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

1.215   ! brouard     1: /* $Id: imach.c,v 1.214 2015/12/16 06:57:54 brouard Exp $
1.126     brouard     2:   $State: Exp $
1.163     brouard     3:   $Log: imach.c,v $
1.215   ! brouard     4:   Revision 1.214  2015/12/16 06:57:54  brouard
        !             5:   Summary: temporary not working
        !             6: 
1.214     brouard     7:   Revision 1.213  2015/12/11 18:22:17  brouard
                      8:   Summary: 0.98r4
                      9: 
1.213     brouard    10:   Revision 1.212  2015/11/21 12:47:24  brouard
                     11:   Summary: minor typo
                     12: 
1.212     brouard    13:   Revision 1.211  2015/11/21 12:41:11  brouard
                     14:   Summary: 0.98r3 with some graph of projected cross-sectional
                     15: 
                     16:   Author: Nicolas Brouard
                     17: 
1.211     brouard    18:   Revision 1.210  2015/11/18 17:41:20  brouard
                     19:   Summary: Start working on projected prevalences
                     20: 
1.210     brouard    21:   Revision 1.209  2015/11/17 22:12:03  brouard
                     22:   Summary: Adding ftolpl parameter
                     23:   Author: N Brouard
                     24: 
                     25:   We had difficulties to get smoothed confidence intervals. It was due
                     26:   to the period prevalence which wasn't computed accurately. The inner
                     27:   parameter ftolpl is now an outer parameter of the .imach parameter
                     28:   file after estepm. If ftolpl is small 1.e-4 and estepm too,
                     29:   computation are long.
                     30: 
1.209     brouard    31:   Revision 1.208  2015/11/17 14:31:57  brouard
                     32:   Summary: temporary
                     33: 
1.208     brouard    34:   Revision 1.207  2015/10/27 17:36:57  brouard
                     35:   *** empty log message ***
                     36: 
1.207     brouard    37:   Revision 1.206  2015/10/24 07:14:11  brouard
                     38:   *** empty log message ***
                     39: 
1.206     brouard    40:   Revision 1.205  2015/10/23 15:50:53  brouard
                     41:   Summary: 0.98r3 some clarification for graphs on likelihood contributions
                     42: 
1.205     brouard    43:   Revision 1.204  2015/10/01 16:20:26  brouard
                     44:   Summary: Some new graphs of contribution to likelihood
                     45: 
1.204     brouard    46:   Revision 1.203  2015/09/30 17:45:14  brouard
                     47:   Summary: looking at better estimation of the hessian
                     48: 
                     49:   Also a better criteria for convergence to the period prevalence And
                     50:   therefore adding the number of years needed to converge. (The
                     51:   prevalence in any alive state shold sum to one
                     52: 
1.203     brouard    53:   Revision 1.202  2015/09/22 19:45:16  brouard
                     54:   Summary: Adding some overall graph on contribution to likelihood. Might change
                     55: 
1.202     brouard    56:   Revision 1.201  2015/09/15 17:34:58  brouard
                     57:   Summary: 0.98r0
                     58: 
                     59:   - Some new graphs like suvival functions
                     60:   - Some bugs fixed like model=1+age+V2.
                     61: 
1.201     brouard    62:   Revision 1.200  2015/09/09 16:53:55  brouard
                     63:   Summary: Big bug thanks to Flavia
                     64: 
                     65:   Even model=1+age+V2. did not work anymore
                     66: 
1.200     brouard    67:   Revision 1.199  2015/09/07 14:09:23  brouard
                     68:   Summary: 0.98q6 changing default small png format for graph to vectorized svg.
                     69: 
1.199     brouard    70:   Revision 1.198  2015/09/03 07:14:39  brouard
                     71:   Summary: 0.98q5 Flavia
                     72: 
1.198     brouard    73:   Revision 1.197  2015/09/01 18:24:39  brouard
                     74:   *** empty log message ***
                     75: 
1.197     brouard    76:   Revision 1.196  2015/08/18 23:17:52  brouard
                     77:   Summary: 0.98q5
                     78: 
1.196     brouard    79:   Revision 1.195  2015/08/18 16:28:39  brouard
                     80:   Summary: Adding a hack for testing purpose
                     81: 
                     82:   After reading the title, ftol and model lines, if the comment line has
                     83:   a q, starting with #q, the answer at the end of the run is quit. It
                     84:   permits to run test files in batch with ctest. The former workaround was
                     85:   $ echo q | imach foo.imach
                     86: 
1.195     brouard    87:   Revision 1.194  2015/08/18 13:32:00  brouard
                     88:   Summary:  Adding error when the covariance matrix doesn't contain the exact number of lines required by the model line.
                     89: 
1.194     brouard    90:   Revision 1.193  2015/08/04 07:17:42  brouard
                     91:   Summary: 0.98q4
                     92: 
1.193     brouard    93:   Revision 1.192  2015/07/16 16:49:02  brouard
                     94:   Summary: Fixing some outputs
                     95: 
1.192     brouard    96:   Revision 1.191  2015/07/14 10:00:33  brouard
                     97:   Summary: Some fixes
                     98: 
1.191     brouard    99:   Revision 1.190  2015/05/05 08:51:13  brouard
                    100:   Summary: Adding digits in output parameters (7 digits instead of 6)
                    101: 
                    102:   Fix 1+age+.
                    103: 
1.190     brouard   104:   Revision 1.189  2015/04/30 14:45:16  brouard
                    105:   Summary: 0.98q2
                    106: 
1.189     brouard   107:   Revision 1.188  2015/04/30 08:27:53  brouard
                    108:   *** empty log message ***
                    109: 
1.188     brouard   110:   Revision 1.187  2015/04/29 09:11:15  brouard
                    111:   *** empty log message ***
                    112: 
1.187     brouard   113:   Revision 1.186  2015/04/23 12:01:52  brouard
                    114:   Summary: V1*age is working now, version 0.98q1
                    115: 
                    116:   Some codes had been disabled in order to simplify and Vn*age was
                    117:   working in the optimization phase, ie, giving correct MLE parameters,
                    118:   but, as usual, outputs were not correct and program core dumped.
                    119: 
1.186     brouard   120:   Revision 1.185  2015/03/11 13:26:42  brouard
                    121:   Summary: Inclusion of compile and links command line for Intel Compiler
                    122: 
1.185     brouard   123:   Revision 1.184  2015/03/11 11:52:39  brouard
                    124:   Summary: Back from Windows 8. Intel Compiler
                    125: 
1.184     brouard   126:   Revision 1.183  2015/03/10 20:34:32  brouard
                    127:   Summary: 0.98q0, trying with directest, mnbrak fixed
                    128: 
                    129:   We use directest instead of original Powell test; probably no
                    130:   incidence on the results, but better justifications;
                    131:   We fixed Numerical Recipes mnbrak routine which was wrong and gave
                    132:   wrong results.
                    133: 
1.183     brouard   134:   Revision 1.182  2015/02/12 08:19:57  brouard
                    135:   Summary: Trying to keep directest which seems simpler and more general
                    136:   Author: Nicolas Brouard
                    137: 
1.182     brouard   138:   Revision 1.181  2015/02/11 23:22:24  brouard
                    139:   Summary: Comments on Powell added
                    140: 
                    141:   Author:
                    142: 
1.181     brouard   143:   Revision 1.180  2015/02/11 17:33:45  brouard
                    144:   Summary: Finishing move from main to function (hpijx and prevalence_limit)
                    145: 
1.180     brouard   146:   Revision 1.179  2015/01/04 09:57:06  brouard
                    147:   Summary: back to OS/X
                    148: 
1.179     brouard   149:   Revision 1.178  2015/01/04 09:35:48  brouard
                    150:   *** empty log message ***
                    151: 
1.178     brouard   152:   Revision 1.177  2015/01/03 18:40:56  brouard
                    153:   Summary: Still testing ilc32 on OSX
                    154: 
1.177     brouard   155:   Revision 1.176  2015/01/03 16:45:04  brouard
                    156:   *** empty log message ***
                    157: 
1.176     brouard   158:   Revision 1.175  2015/01/03 16:33:42  brouard
                    159:   *** empty log message ***
                    160: 
1.175     brouard   161:   Revision 1.174  2015/01/03 16:15:49  brouard
                    162:   Summary: Still in cross-compilation
                    163: 
1.174     brouard   164:   Revision 1.173  2015/01/03 12:06:26  brouard
                    165:   Summary: trying to detect cross-compilation
                    166: 
1.173     brouard   167:   Revision 1.172  2014/12/27 12:07:47  brouard
                    168:   Summary: Back from Visual Studio and Intel, options for compiling for Windows XP
                    169: 
1.172     brouard   170:   Revision 1.171  2014/12/23 13:26:59  brouard
                    171:   Summary: Back from Visual C
                    172: 
                    173:   Still problem with utsname.h on Windows
                    174: 
1.171     brouard   175:   Revision 1.170  2014/12/23 11:17:12  brouard
                    176:   Summary: Cleaning some \%% back to %%
                    177: 
                    178:   The escape was mandatory for a specific compiler (which one?), but too many warnings.
                    179: 
1.170     brouard   180:   Revision 1.169  2014/12/22 23:08:31  brouard
                    181:   Summary: 0.98p
                    182: 
                    183:   Outputs some informations on compiler used, OS etc. Testing on different platforms.
                    184: 
1.169     brouard   185:   Revision 1.168  2014/12/22 15:17:42  brouard
1.170     brouard   186:   Summary: update
1.169     brouard   187: 
1.168     brouard   188:   Revision 1.167  2014/12/22 13:50:56  brouard
                    189:   Summary: Testing uname and compiler version and if compiled 32 or 64
                    190: 
                    191:   Testing on Linux 64
                    192: 
1.167     brouard   193:   Revision 1.166  2014/12/22 11:40:47  brouard
                    194:   *** empty log message ***
                    195: 
1.166     brouard   196:   Revision 1.165  2014/12/16 11:20:36  brouard
                    197:   Summary: After compiling on Visual C
                    198: 
                    199:   * imach.c (Module): Merging 1.61 to 1.162
                    200: 
1.165     brouard   201:   Revision 1.164  2014/12/16 10:52:11  brouard
                    202:   Summary: Merging with Visual C after suppressing some warnings for unused variables. Also fixing Saito's bug 0.98Xn
                    203: 
                    204:   * imach.c (Module): Merging 1.61 to 1.162
                    205: 
1.164     brouard   206:   Revision 1.163  2014/12/16 10:30:11  brouard
                    207:   * imach.c (Module): Merging 1.61 to 1.162
                    208: 
1.163     brouard   209:   Revision 1.162  2014/09/25 11:43:39  brouard
                    210:   Summary: temporary backup 0.99!
                    211: 
1.162     brouard   212:   Revision 1.1  2014/09/16 11:06:58  brouard
                    213:   Summary: With some code (wrong) for nlopt
                    214: 
                    215:   Author:
                    216: 
                    217:   Revision 1.161  2014/09/15 20:41:41  brouard
                    218:   Summary: Problem with macro SQR on Intel compiler
                    219: 
1.161     brouard   220:   Revision 1.160  2014/09/02 09:24:05  brouard
                    221:   *** empty log message ***
                    222: 
1.160     brouard   223:   Revision 1.159  2014/09/01 10:34:10  brouard
                    224:   Summary: WIN32
                    225:   Author: Brouard
                    226: 
1.159     brouard   227:   Revision 1.158  2014/08/27 17:11:51  brouard
                    228:   *** empty log message ***
                    229: 
1.158     brouard   230:   Revision 1.157  2014/08/27 16:26:55  brouard
                    231:   Summary: Preparing windows Visual studio version
                    232:   Author: Brouard
                    233: 
                    234:   In order to compile on Visual studio, time.h is now correct and time_t
                    235:   and tm struct should be used. difftime should be used but sometimes I
                    236:   just make the differences in raw time format (time(&now).
                    237:   Trying to suppress #ifdef LINUX
                    238:   Add xdg-open for __linux in order to open default browser.
                    239: 
1.157     brouard   240:   Revision 1.156  2014/08/25 20:10:10  brouard
                    241:   *** empty log message ***
                    242: 
1.156     brouard   243:   Revision 1.155  2014/08/25 18:32:34  brouard
                    244:   Summary: New compile, minor changes
                    245:   Author: Brouard
                    246: 
1.155     brouard   247:   Revision 1.154  2014/06/20 17:32:08  brouard
                    248:   Summary: Outputs now all graphs of convergence to period prevalence
                    249: 
1.154     brouard   250:   Revision 1.153  2014/06/20 16:45:46  brouard
                    251:   Summary: If 3 live state, convergence to period prevalence on same graph
                    252:   Author: Brouard
                    253: 
1.153     brouard   254:   Revision 1.152  2014/06/18 17:54:09  brouard
                    255:   Summary: open browser, use gnuplot on same dir than imach if not found in the path
                    256: 
1.152     brouard   257:   Revision 1.151  2014/06/18 16:43:30  brouard
                    258:   *** empty log message ***
                    259: 
1.151     brouard   260:   Revision 1.150  2014/06/18 16:42:35  brouard
                    261:   Summary: If gnuplot is not in the path try on same directory than imach binary (OSX)
                    262:   Author: brouard
                    263: 
1.150     brouard   264:   Revision 1.149  2014/06/18 15:51:14  brouard
                    265:   Summary: Some fixes in parameter files errors
                    266:   Author: Nicolas Brouard
                    267: 
1.149     brouard   268:   Revision 1.148  2014/06/17 17:38:48  brouard
                    269:   Summary: Nothing new
                    270:   Author: Brouard
                    271: 
                    272:   Just a new packaging for OS/X version 0.98nS
                    273: 
1.148     brouard   274:   Revision 1.147  2014/06/16 10:33:11  brouard
                    275:   *** empty log message ***
                    276: 
1.147     brouard   277:   Revision 1.146  2014/06/16 10:20:28  brouard
                    278:   Summary: Merge
                    279:   Author: Brouard
                    280: 
                    281:   Merge, before building revised version.
                    282: 
1.146     brouard   283:   Revision 1.145  2014/06/10 21:23:15  brouard
                    284:   Summary: Debugging with valgrind
                    285:   Author: Nicolas Brouard
                    286: 
                    287:   Lot of changes in order to output the results with some covariates
                    288:   After the Edimburgh REVES conference 2014, it seems mandatory to
                    289:   improve the code.
                    290:   No more memory valgrind error but a lot has to be done in order to
                    291:   continue the work of splitting the code into subroutines.
                    292:   Also, decodemodel has been improved. Tricode is still not
                    293:   optimal. nbcode should be improved. Documentation has been added in
                    294:   the source code.
                    295: 
1.144     brouard   296:   Revision 1.143  2014/01/26 09:45:38  brouard
                    297:   Summary: Version 0.98nR (to be improved, but gives same optimization results as 0.98k. Nice, promising
                    298: 
                    299:   * imach.c (Module): Trying to merge old staffs together while being at Tokyo. Not tested...
                    300:   (Module): Version 0.98nR Running ok, but output format still only works for three covariates.
                    301: 
1.143     brouard   302:   Revision 1.142  2014/01/26 03:57:36  brouard
                    303:   Summary: gnuplot changed plot w l 1 has to be changed to plot w l lt 2
                    304: 
                    305:   * imach.c (Module): Trying to merge old staffs together while being at Tokyo. Not tested...
                    306: 
1.142     brouard   307:   Revision 1.141  2014/01/26 02:42:01  brouard
                    308:   * imach.c (Module): Trying to merge old staffs together while being at Tokyo. Not tested...
                    309: 
1.141     brouard   310:   Revision 1.140  2011/09/02 10:37:54  brouard
                    311:   Summary: times.h is ok with mingw32 now.
                    312: 
1.140     brouard   313:   Revision 1.139  2010/06/14 07:50:17  brouard
                    314:   After the theft of my laptop, I probably lost some lines of codes which were not uploaded to the CVS tree.
                    315:   I remember having already fixed agemin agemax which are pointers now but not cvs saved.
                    316: 
1.139     brouard   317:   Revision 1.138  2010/04/30 18:19:40  brouard
                    318:   *** empty log message ***
                    319: 
1.138     brouard   320:   Revision 1.137  2010/04/29 18:11:38  brouard
                    321:   (Module): Checking covariates for more complex models
                    322:   than V1+V2. A lot of change to be done. Unstable.
                    323: 
1.137     brouard   324:   Revision 1.136  2010/04/26 20:30:53  brouard
                    325:   (Module): merging some libgsl code. Fixing computation
                    326:   of likelione (using inter/intrapolation if mle = 0) in order to
                    327:   get same likelihood as if mle=1.
                    328:   Some cleaning of code and comments added.
                    329: 
1.136     brouard   330:   Revision 1.135  2009/10/29 15:33:14  brouard
                    331:   (Module): Now imach stops if date of birth, at least year of birth, is not given. Some cleaning of the code.
                    332: 
1.135     brouard   333:   Revision 1.134  2009/10/29 13:18:53  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.134     brouard   336:   Revision 1.133  2009/07/06 10:21:25  brouard
                    337:   just nforces
                    338: 
1.133     brouard   339:   Revision 1.132  2009/07/06 08:22:05  brouard
                    340:   Many tings
                    341: 
1.132     brouard   342:   Revision 1.131  2009/06/20 16:22:47  brouard
                    343:   Some dimensions resccaled
                    344: 
1.131     brouard   345:   Revision 1.130  2009/05/26 06:44:34  brouard
                    346:   (Module): Max Covariate is now set to 20 instead of 8. A
                    347:   lot of cleaning with variables initialized to 0. Trying to make
                    348:   V2+V3*age+V1+V4 strb=V3*age+V1+V4 working better.
                    349: 
1.130     brouard   350:   Revision 1.129  2007/08/31 13:49:27  lievre
                    351:   Modification of the way of exiting when the covariate is not binary in order to see on the window the error message before exiting
                    352: 
1.129     lievre    353:   Revision 1.128  2006/06/30 13:02:05  brouard
                    354:   (Module): Clarifications on computing e.j
                    355: 
1.128     brouard   356:   Revision 1.127  2006/04/28 18:11:50  brouard
                    357:   (Module): Yes the sum of survivors was wrong since
                    358:   imach-114 because nhstepm was no more computed in the age
                    359:   loop. Now we define nhstepma in the age loop.
                    360:   (Module): In order to speed up (in case of numerous covariates) we
                    361:   compute health expectancies (without variances) in a first step
                    362:   and then all the health expectancies with variances or standard
                    363:   deviation (needs data from the Hessian matrices) which slows the
                    364:   computation.
                    365:   In the future we should be able to stop the program is only health
                    366:   expectancies and graph are needed without standard deviations.
                    367: 
1.127     brouard   368:   Revision 1.126  2006/04/28 17:23:28  brouard
                    369:   (Module): Yes the sum of survivors was wrong since
                    370:   imach-114 because nhstepm was no more computed in the age
                    371:   loop. Now we define nhstepma in the age loop.
                    372:   Version 0.98h
                    373: 
1.126     brouard   374:   Revision 1.125  2006/04/04 15:20:31  lievre
                    375:   Errors in calculation of health expectancies. Age was not initialized.
                    376:   Forecasting file added.
                    377: 
                    378:   Revision 1.124  2006/03/22 17:13:53  lievre
                    379:   Parameters are printed with %lf instead of %f (more numbers after the comma).
                    380:   The log-likelihood is printed in the log file
                    381: 
                    382:   Revision 1.123  2006/03/20 10:52:43  brouard
                    383:   * imach.c (Module): <title> changed, corresponds to .htm file
                    384:   name. <head> headers where missing.
                    385: 
                    386:   * imach.c (Module): Weights can have a decimal point as for
                    387:   English (a comma might work with a correct LC_NUMERIC environment,
                    388:   otherwise the weight is truncated).
                    389:   Modification of warning when the covariates values are not 0 or
                    390:   1.
                    391:   Version 0.98g
                    392: 
                    393:   Revision 1.122  2006/03/20 09:45:41  brouard
                    394:   (Module): Weights can have a decimal point as for
                    395:   English (a comma might work with a correct LC_NUMERIC environment,
                    396:   otherwise the weight is truncated).
                    397:   Modification of warning when the covariates values are not 0 or
                    398:   1.
                    399:   Version 0.98g
                    400: 
                    401:   Revision 1.121  2006/03/16 17:45:01  lievre
                    402:   * imach.c (Module): Comments concerning covariates added
                    403: 
                    404:   * imach.c (Module): refinements in the computation of lli if
                    405:   status=-2 in order to have more reliable computation if stepm is
                    406:   not 1 month. Version 0.98f
                    407: 
                    408:   Revision 1.120  2006/03/16 15:10:38  lievre
                    409:   (Module): refinements in the computation of lli if
                    410:   status=-2 in order to have more reliable computation if stepm is
                    411:   not 1 month. Version 0.98f
                    412: 
                    413:   Revision 1.119  2006/03/15 17:42:26  brouard
                    414:   (Module): Bug if status = -2, the loglikelihood was
                    415:   computed as likelihood omitting the logarithm. Version O.98e
                    416: 
                    417:   Revision 1.118  2006/03/14 18:20:07  brouard
                    418:   (Module): varevsij Comments added explaining the second
                    419:   table of variances if popbased=1 .
                    420:   (Module): Covariances of eij, ekl added, graphs fixed, new html link.
                    421:   (Module): Function pstamp added
                    422:   (Module): Version 0.98d
                    423: 
                    424:   Revision 1.117  2006/03/14 17:16:22  brouard
                    425:   (Module): varevsij Comments added explaining the second
                    426:   table of variances if popbased=1 .
                    427:   (Module): Covariances of eij, ekl added, graphs fixed, new html link.
                    428:   (Module): Function pstamp added
                    429:   (Module): Version 0.98d
                    430: 
                    431:   Revision 1.116  2006/03/06 10:29:27  brouard
                    432:   (Module): Variance-covariance wrong links and
                    433:   varian-covariance of ej. is needed (Saito).
                    434: 
                    435:   Revision 1.115  2006/02/27 12:17:45  brouard
                    436:   (Module): One freematrix added in mlikeli! 0.98c
                    437: 
                    438:   Revision 1.114  2006/02/26 12:57:58  brouard
                    439:   (Module): Some improvements in processing parameter
                    440:   filename with strsep.
                    441: 
                    442:   Revision 1.113  2006/02/24 14:20:24  brouard
                    443:   (Module): Memory leaks checks with valgrind and:
                    444:   datafile was not closed, some imatrix were not freed and on matrix
                    445:   allocation too.
                    446: 
                    447:   Revision 1.112  2006/01/30 09:55:26  brouard
                    448:   (Module): Back to gnuplot.exe instead of wgnuplot.exe
                    449: 
                    450:   Revision 1.111  2006/01/25 20:38:18  brouard
                    451:   (Module): Lots of cleaning and bugs added (Gompertz)
                    452:   (Module): Comments can be added in data file. Missing date values
                    453:   can be a simple dot '.'.
                    454: 
                    455:   Revision 1.110  2006/01/25 00:51:50  brouard
                    456:   (Module): Lots of cleaning and bugs added (Gompertz)
                    457: 
                    458:   Revision 1.109  2006/01/24 19:37:15  brouard
                    459:   (Module): Comments (lines starting with a #) are allowed in data.
                    460: 
                    461:   Revision 1.108  2006/01/19 18:05:42  lievre
                    462:   Gnuplot problem appeared...
                    463:   To be fixed
                    464: 
                    465:   Revision 1.107  2006/01/19 16:20:37  brouard
                    466:   Test existence of gnuplot in imach path
                    467: 
                    468:   Revision 1.106  2006/01/19 13:24:36  brouard
                    469:   Some cleaning and links added in html output
                    470: 
                    471:   Revision 1.105  2006/01/05 20:23:19  lievre
                    472:   *** empty log message ***
                    473: 
                    474:   Revision 1.104  2005/09/30 16:11:43  lievre
                    475:   (Module): sump fixed, loop imx fixed, and simplifications.
                    476:   (Module): If the status is missing at the last wave but we know
                    477:   that the person is alive, then we can code his/her status as -2
                    478:   (instead of missing=-1 in earlier versions) and his/her
                    479:   contributions to the likelihood is 1 - Prob of dying from last
                    480:   health status (= 1-p13= p11+p12 in the easiest case of somebody in
                    481:   the healthy state at last known wave). Version is 0.98
                    482: 
                    483:   Revision 1.103  2005/09/30 15:54:49  lievre
                    484:   (Module): sump fixed, loop imx fixed, and simplifications.
                    485: 
                    486:   Revision 1.102  2004/09/15 17:31:30  brouard
                    487:   Add the possibility to read data file including tab characters.
                    488: 
                    489:   Revision 1.101  2004/09/15 10:38:38  brouard
                    490:   Fix on curr_time
                    491: 
                    492:   Revision 1.100  2004/07/12 18:29:06  brouard
                    493:   Add version for Mac OS X. Just define UNIX in Makefile
                    494: 
                    495:   Revision 1.99  2004/06/05 08:57:40  brouard
                    496:   *** empty log message ***
                    497: 
                    498:   Revision 1.98  2004/05/16 15:05:56  brouard
                    499:   New version 0.97 . First attempt to estimate force of mortality
                    500:   directly from the data i.e. without the need of knowing the health
                    501:   state at each age, but using a Gompertz model: log u =a + b*age .
                    502:   This is the basic analysis of mortality and should be done before any
                    503:   other analysis, in order to test if the mortality estimated from the
                    504:   cross-longitudinal survey is different from the mortality estimated
                    505:   from other sources like vital statistic data.
                    506: 
                    507:   The same imach parameter file can be used but the option for mle should be -3.
                    508: 
1.133     brouard   509:   Agnès, who wrote this part of the code, tried to keep most of the
1.126     brouard   510:   former routines in order to include the new code within the former code.
                    511: 
                    512:   The output is very simple: only an estimate of the intercept and of
                    513:   the slope with 95% confident intervals.
                    514: 
                    515:   Current limitations:
                    516:   A) Even if you enter covariates, i.e. with the
                    517:   model= V1+V2 equation for example, the programm does only estimate a unique global model without covariates.
                    518:   B) There is no computation of Life Expectancy nor Life Table.
                    519: 
                    520:   Revision 1.97  2004/02/20 13:25:42  lievre
                    521:   Version 0.96d. Population forecasting command line is (temporarily)
                    522:   suppressed.
                    523: 
                    524:   Revision 1.96  2003/07/15 15:38:55  brouard
                    525:   * imach.c (Repository): Errors in subdirf, 2, 3 while printing tmpout is
                    526:   rewritten within the same printf. Workaround: many printfs.
                    527: 
                    528:   Revision 1.95  2003/07/08 07:54:34  brouard
                    529:   * imach.c (Repository):
                    530:   (Repository): Using imachwizard code to output a more meaningful covariance
                    531:   matrix (cov(a12,c31) instead of numbers.
                    532: 
                    533:   Revision 1.94  2003/06/27 13:00:02  brouard
                    534:   Just cleaning
                    535: 
                    536:   Revision 1.93  2003/06/25 16:33:55  brouard
                    537:   (Module): On windows (cygwin) function asctime_r doesn't
                    538:   exist so I changed back to asctime which exists.
                    539:   (Module): Version 0.96b
                    540: 
                    541:   Revision 1.92  2003/06/25 16:30:45  brouard
                    542:   (Module): On windows (cygwin) function asctime_r doesn't
                    543:   exist so I changed back to asctime which exists.
                    544: 
                    545:   Revision 1.91  2003/06/25 15:30:29  brouard
                    546:   * imach.c (Repository): Duplicated warning errors corrected.
                    547:   (Repository): Elapsed time after each iteration is now output. It
                    548:   helps to forecast when convergence will be reached. Elapsed time
                    549:   is stamped in powell.  We created a new html file for the graphs
                    550:   concerning matrix of covariance. It has extension -cov.htm.
                    551: 
                    552:   Revision 1.90  2003/06/24 12:34:15  brouard
                    553:   (Module): Some bugs corrected for windows. Also, when
                    554:   mle=-1 a template is output in file "or"mypar.txt with the design
                    555:   of the covariance matrix to be input.
                    556: 
                    557:   Revision 1.89  2003/06/24 12:30:52  brouard
                    558:   (Module): Some bugs corrected for windows. Also, when
                    559:   mle=-1 a template is output in file "or"mypar.txt with the design
                    560:   of the covariance matrix to be input.
                    561: 
                    562:   Revision 1.88  2003/06/23 17:54:56  brouard
                    563:   * 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.
                    564: 
                    565:   Revision 1.87  2003/06/18 12:26:01  brouard
                    566:   Version 0.96
                    567: 
                    568:   Revision 1.86  2003/06/17 20:04:08  brouard
                    569:   (Module): Change position of html and gnuplot routines and added
                    570:   routine fileappend.
                    571: 
                    572:   Revision 1.85  2003/06/17 13:12:43  brouard
                    573:   * imach.c (Repository): Check when date of death was earlier that
                    574:   current date of interview. It may happen when the death was just
                    575:   prior to the death. In this case, dh was negative and likelihood
                    576:   was wrong (infinity). We still send an "Error" but patch by
                    577:   assuming that the date of death was just one stepm after the
                    578:   interview.
                    579:   (Repository): Because some people have very long ID (first column)
                    580:   we changed int to long in num[] and we added a new lvector for
                    581:   memory allocation. But we also truncated to 8 characters (left
                    582:   truncation)
                    583:   (Repository): No more line truncation errors.
                    584: 
                    585:   Revision 1.84  2003/06/13 21:44:43  brouard
                    586:   * imach.c (Repository): Replace "freqsummary" at a correct
                    587:   place. It differs from routine "prevalence" which may be called
                    588:   many times. Probs is memory consuming and must be used with
                    589:   parcimony.
                    590:   Version 0.95a3 (should output exactly the same maximization than 0.8a2)
                    591: 
                    592:   Revision 1.83  2003/06/10 13:39:11  lievre
                    593:   *** empty log message ***
                    594: 
                    595:   Revision 1.82  2003/06/05 15:57:20  brouard
                    596:   Add log in  imach.c and  fullversion number is now printed.
                    597: 
                    598: */
                    599: /*
                    600:    Interpolated Markov Chain
                    601: 
                    602:   Short summary of the programme:
                    603:   
                    604:   This program computes Healthy Life Expectancies from
                    605:   cross-longitudinal data. Cross-longitudinal data consist in: -1- a
                    606:   first survey ("cross") where individuals from different ages are
                    607:   interviewed on their health status or degree of disability (in the
                    608:   case of a health survey which is our main interest) -2- at least a
                    609:   second wave of interviews ("longitudinal") which measure each change
                    610:   (if any) in individual health status.  Health expectancies are
                    611:   computed from the time spent in each health state according to a
                    612:   model. More health states you consider, more time is necessary to reach the
                    613:   Maximum Likelihood of the parameters involved in the model.  The
                    614:   simplest model is the multinomial logistic model where pij is the
                    615:   probability to be observed in state j at the second wave
                    616:   conditional to be observed in state i at the first wave. Therefore
                    617:   the model is: log(pij/pii)= aij + bij*age+ cij*sex + etc , where
                    618:   'age' is age and 'sex' is a covariate. If you want to have a more
                    619:   complex model than "constant and age", you should modify the program
                    620:   where the markup *Covariates have to be included here again* invites
                    621:   you to do it.  More covariates you add, slower the
                    622:   convergence.
                    623: 
                    624:   The advantage of this computer programme, compared to a simple
                    625:   multinomial logistic model, is clear when the delay between waves is not
                    626:   identical for each individual. Also, if a individual missed an
                    627:   intermediate interview, the information is lost, but taken into
                    628:   account using an interpolation or extrapolation.  
                    629: 
                    630:   hPijx is the probability to be observed in state i at age x+h
                    631:   conditional to the observed state i at age x. The delay 'h' can be
                    632:   split into an exact number (nh*stepm) of unobserved intermediate
                    633:   states. This elementary transition (by month, quarter,
                    634:   semester or year) is modelled as a multinomial logistic.  The hPx
                    635:   matrix is simply the matrix product of nh*stepm elementary matrices
                    636:   and the contribution of each individual to the likelihood is simply
                    637:   hPijx.
                    638: 
                    639:   Also this programme outputs the covariance matrix of the parameters but also
                    640:   of the life expectancies. It also computes the period (stable) prevalence. 
                    641:   
1.133     brouard   642:   Authors: Nicolas Brouard (brouard@ined.fr) and Agnès Lièvre (lievre@ined.fr).
                    643:            Institut national d'études démographiques, Paris.
1.126     brouard   644:   This software have been partly granted by Euro-REVES, a concerted action
                    645:   from the European Union.
                    646:   It is copyrighted identically to a GNU software product, ie programme and
                    647:   software can be distributed freely for non commercial use. Latest version
                    648:   can be accessed at http://euroreves.ined.fr/imach .
                    649: 
                    650:   Help to debug: LD_PRELOAD=/usr/local/lib/libnjamd.so ./imach foo.imach
                    651:   or better on gdb : set env LD_PRELOAD=/usr/local/lib/libnjamd.so
                    652:   
                    653:   **********************************************************************/
                    654: /*
                    655:   main
                    656:   read parameterfile
                    657:   read datafile
                    658:   concatwav
                    659:   freqsummary
                    660:   if (mle >= 1)
                    661:     mlikeli
                    662:   print results files
                    663:   if mle==1 
                    664:      computes hessian
                    665:   read end of parameter file: agemin, agemax, bage, fage, estepm
                    666:       begin-prev-date,...
                    667:   open gnuplot file
                    668:   open html file
1.145     brouard   669:   period (stable) prevalence      | pl_nom    1-1 2-2 etc by covariate
                    670:    for age prevalim()             | #****** V1=0  V2=1  V3=1  V4=0 ******
                    671:                                   | 65 1 0 2 1 3 1 4 0  0.96326 0.03674
                    672:     freexexit2 possible for memory heap.
                    673: 
                    674:   h Pij x                         | pij_nom  ficrestpij
                    675:    # Cov Agex agex+h hpijx with i,j= 1-1 1-2     1-3     2-1     2-2     2-3
                    676:        1  85   85    1.00000             0.00000 0.00000 0.00000 1.00000 0.00000
                    677:        1  85   86    0.68299             0.22291 0.09410 0.71093 0.00000 0.28907
                    678: 
                    679:        1  65   99    0.00364             0.00322 0.99314 0.00350 0.00310 0.99340
                    680:        1  65  100    0.00214             0.00204 0.99581 0.00206 0.00196 0.99597
                    681:   variance of p one-step probabilities varprob  | prob_nom   ficresprob #One-step probabilities and stand. devi in ()
                    682:    Standard deviation of one-step probabilities | probcor_nom   ficresprobcor #One-step probabilities and correlation matrix
                    683:    Matrix of variance covariance of one-step probabilities |  probcov_nom ficresprobcov #One-step probabilities and covariance matrix
                    684: 
1.126     brouard   685:   forecasting if prevfcast==1 prevforecast call prevalence()
                    686:   health expectancies
                    687:   Variance-covariance of DFLE
                    688:   prevalence()
                    689:    movingaverage()
                    690:   varevsij() 
                    691:   if popbased==1 varevsij(,popbased)
                    692:   total life expectancies
                    693:   Variance of period (stable) prevalence
                    694:  end
                    695: */
                    696: 
1.187     brouard   697: /* #define DEBUG */
                    698: /* #define DEBUGBRENT */
1.203     brouard   699: /* #define DEBUGLINMIN */
                    700: /* #define DEBUGHESS */
                    701: #define DEBUGHESSIJ
                    702: /* #define LINMINORIGINAL  /\* Don't use loop on scale in linmin (accepting nan)*\/ */
1.165     brouard   703: #define POWELL /* Instead of NLOPT */
1.192     brouard   704: #define POWELLF1F3 /* Skip test */
1.186     brouard   705: /* #define POWELLORIGINAL /\* Don't use Directest to decide new direction but original Powell test *\/ */
                    706: /* #define MNBRAKORIGINAL /\* Don't use mnbrak fix *\/ */
1.126     brouard   707: 
                    708: #include <math.h>
                    709: #include <stdio.h>
                    710: #include <stdlib.h>
                    711: #include <string.h>
1.159     brouard   712: 
                    713: #ifdef _WIN32
                    714: #include <io.h>
1.172     brouard   715: #include <windows.h>
                    716: #include <tchar.h>
1.159     brouard   717: #else
1.126     brouard   718: #include <unistd.h>
1.159     brouard   719: #endif
1.126     brouard   720: 
                    721: #include <limits.h>
                    722: #include <sys/types.h>
1.171     brouard   723: 
                    724: #if defined(__GNUC__)
                    725: #include <sys/utsname.h> /* Doesn't work on Windows */
                    726: #endif
                    727: 
1.126     brouard   728: #include <sys/stat.h>
                    729: #include <errno.h>
1.159     brouard   730: /* extern int errno; */
1.126     brouard   731: 
1.157     brouard   732: /* #ifdef LINUX */
                    733: /* #include <time.h> */
                    734: /* #include "timeval.h" */
                    735: /* #else */
                    736: /* #include <sys/time.h> */
                    737: /* #endif */
                    738: 
1.126     brouard   739: #include <time.h>
                    740: 
1.136     brouard   741: #ifdef GSL
                    742: #include <gsl/gsl_errno.h>
                    743: #include <gsl/gsl_multimin.h>
                    744: #endif
                    745: 
1.167     brouard   746: 
1.162     brouard   747: #ifdef NLOPT
                    748: #include <nlopt.h>
                    749: typedef struct {
                    750:   double (* function)(double [] );
                    751: } myfunc_data ;
                    752: #endif
                    753: 
1.126     brouard   754: /* #include <libintl.h> */
                    755: /* #define _(String) gettext (String) */
                    756: 
1.141     brouard   757: #define MAXLINE 1024 /* Was 256. Overflow with 312 with 2 states and 4 covariates. Should be ok */
1.126     brouard   758: 
                    759: #define GNUPLOTPROGRAM "gnuplot"
                    760: /*#define GNUPLOTPROGRAM "..\\gp37mgw\\wgnuplot"*/
                    761: #define FILENAMELENGTH 132
                    762: 
                    763: #define        GLOCK_ERROR_NOPATH              -1      /* empty path */
                    764: #define        GLOCK_ERROR_GETCWD              -2      /* cannot get cwd */
                    765: 
1.144     brouard   766: #define MAXPARM 128 /**< Maximum number of parameters for the optimization */
                    767: #define NPARMAX 64 /**< (nlstate+ndeath-1)*nlstate*ncovmodel */
1.126     brouard   768: 
                    769: #define NINTERVMAX 8
1.144     brouard   770: #define NLSTATEMAX 8 /**< Maximum number of live states (for func) */
                    771: #define NDEATHMAX 8 /**< Maximum number of dead states (for func) */
                    772: #define NCOVMAX 20 /**< Maximum number of covariates, including generated covariates V1*V2 */
1.197     brouard   773: #define codtabm(h,k)  (1 & (h-1) >> (k-1))+1
1.211     brouard   774: /*#define decodtabm(h,k,cptcoveff)= (h <= (1<<cptcoveff)?(((h-1) >> (k-1)) & 1) +1 : -1)*/
                    775: #define decodtabm(h,k,cptcoveff) (((h-1) >> (k-1)) & 1) +1 
1.126     brouard   776: #define MAXN 20000
1.144     brouard   777: #define YEARM 12. /**< Number of months per year */
1.126     brouard   778: #define AGESUP 130
                    779: #define AGEBASE 40
1.194     brouard   780: #define AGEOVERFLOW 1.e20
1.164     brouard   781: #define AGEGOMP 10 /**< Minimal age for Gompertz adjustment */
1.157     brouard   782: #ifdef _WIN32
                    783: #define DIRSEPARATOR '\\'
                    784: #define CHARSEPARATOR "\\"
                    785: #define ODIRSEPARATOR '/'
                    786: #else
1.126     brouard   787: #define DIRSEPARATOR '/'
                    788: #define CHARSEPARATOR "/"
                    789: #define ODIRSEPARATOR '\\'
                    790: #endif
                    791: 
1.215   ! brouard   792: /* $Id: imach.c,v 1.214 2015/12/16 06:57:54 brouard Exp $ */
1.126     brouard   793: /* $State: Exp $ */
1.196     brouard   794: #include "version.h"
                    795: char version[]=__IMACH_VERSION__;
1.204     brouard   796: 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.215   ! brouard   797: char fullversion[]="$Revision: 1.214 $ $Date: 2015/12/16 06:57:54 $"; 
1.126     brouard   798: char strstart[80];
                    799: char optionfilext[10], optionfilefiname[FILENAMELENGTH];
1.130     brouard   800: int erreur=0, nberr=0, nbwarn=0; /* Error number, number of errors number of warnings  */
1.187     brouard   801: int nagesqr=0, nforce=0; /* nagesqr=1 if model is including age*age, number of forces */
1.145     brouard   802: /* Number of covariates model=V2+V1+ V3*age+V2*V4 */
                    803: int cptcovn=0; /**< cptcovn number of covariates added in the model (excepting constant and age and age*product) */
                    804: int cptcovt=0; /**< cptcovt number of covariates added in the model (excepting constant and age) */
                    805: int cptcovs=0; /**< cptcovs number of simple covariates V2+V1 =2 */
                    806: int cptcovage=0; /**< Number of covariates with age: V3*age only =1 */
                    807: int cptcovprodnoage=0; /**< Number of covariate products without age */   
                    808: int cptcoveff=0; /* Total number of covariates to vary for printing results */
                    809: int cptcov=0; /* Working variable */
1.126     brouard   810: int npar=NPARMAX;
                    811: int nlstate=2; /* Number of live states */
                    812: int ndeath=1; /* Number of dead states */
1.130     brouard   813: int ncovmodel=0, ncovcol=0;     /* Total number of covariables including constant a12*1 +b12*x ncovmodel=2 */
1.126     brouard   814: int popbased=0;
                    815: 
                    816: int *wav; /* Number of waves for this individuual 0 is possible */
1.130     brouard   817: int maxwav=0; /* Maxim number of waves */
                    818: int jmin=0, jmax=0; /* min, max spacing between 2 waves */
                    819: int ijmin=0, ijmax=0; /* Individuals having jmin and jmax */ 
                    820: int gipmx=0, gsw=0; /* Global variables on the number of contributions 
1.126     brouard   821:                   to the likelihood and the sum of weights (done by funcone)*/
1.130     brouard   822: int mle=1, weightopt=0;
1.126     brouard   823: int **mw; /* mw[mi][i] is number of the mi wave for this individual */
                    824: int **dh; /* dh[mi][i] is number of steps between mi,mi+1 for this individual */
                    825: int **bh; /* bh[mi][i] is the bias (+ or -) for this individual if the delay between
                    826:           * wave mi and wave mi+1 is not an exact multiple of stepm. */
1.162     brouard   827: int countcallfunc=0;  /* Count the number of calls to func */
1.130     brouard   828: double jmean=1; /* Mean space between 2 waves */
1.145     brouard   829: double **matprod2(); /* test */
1.126     brouard   830: double **oldm, **newm, **savm; /* Working pointers to matrices */
                    831: double **oldms, **newms, **savms; /* Fixed working pointers to matrices */
1.136     brouard   832: /*FILE *fic ; */ /* Used in readdata only */
1.214     brouard   833: FILE *ficpar, *ficparo,*ficres, *ficresp, *ficresphtm, *ficresphtmfr, *ficrespl, *ficrespij, *ficrest,*ficresf,*ficrespop;
1.126     brouard   834: FILE *ficlog, *ficrespow;
1.130     brouard   835: int globpr=0; /* Global variable for printing or not */
1.126     brouard   836: double fretone; /* Only one call to likelihood */
1.130     brouard   837: long ipmx=0; /* Number of contributions */
1.126     brouard   838: double sw; /* Sum of weights */
                    839: char filerespow[FILENAMELENGTH];
                    840: char fileresilk[FILENAMELENGTH]; /* File of individual contributions to the likelihood */
                    841: FILE *ficresilk;
                    842: FILE *ficgp,*ficresprob,*ficpop, *ficresprobcov, *ficresprobcor;
                    843: FILE *ficresprobmorprev;
                    844: FILE *fichtm, *fichtmcov; /* Html File */
                    845: FILE *ficreseij;
                    846: char filerese[FILENAMELENGTH];
                    847: FILE *ficresstdeij;
                    848: char fileresstde[FILENAMELENGTH];
                    849: FILE *ficrescveij;
                    850: char filerescve[FILENAMELENGTH];
                    851: FILE  *ficresvij;
                    852: char fileresv[FILENAMELENGTH];
                    853: FILE  *ficresvpl;
                    854: char fileresvpl[FILENAMELENGTH];
                    855: char title[MAXLINE];
                    856: char optionfile[FILENAMELENGTH], datafile[FILENAMELENGTH],  filerespl[FILENAMELENGTH];
                    857: char plotcmd[FILENAMELENGTH], pplotcmd[FILENAMELENGTH];
                    858: char tmpout[FILENAMELENGTH],  tmpout2[FILENAMELENGTH]; 
                    859: char command[FILENAMELENGTH];
                    860: int  outcmd=0;
                    861: 
                    862: char fileres[FILENAMELENGTH], filerespij[FILENAMELENGTH], filereso[FILENAMELENGTH], rfileres[FILENAMELENGTH];
1.202     brouard   863: char fileresu[FILENAMELENGTH]; /* fileres without r in front */
1.126     brouard   864: char filelog[FILENAMELENGTH]; /* Log file */
                    865: char filerest[FILENAMELENGTH];
                    866: char fileregp[FILENAMELENGTH];
                    867: char popfile[FILENAMELENGTH];
                    868: 
                    869: char optionfilegnuplot[FILENAMELENGTH], optionfilehtm[FILENAMELENGTH], optionfilehtmcov[FILENAMELENGTH] ;
                    870: 
1.157     brouard   871: /* struct timeval start_time, end_time, curr_time, last_time, forecast_time; */
                    872: /* struct timezone tzp; */
                    873: /* extern int gettimeofday(); */
                    874: struct tm tml, *gmtime(), *localtime();
                    875: 
                    876: extern time_t time();
                    877: 
                    878: struct tm start_time, end_time, curr_time, last_time, forecast_time;
                    879: time_t  rstart_time, rend_time, rcurr_time, rlast_time, rforecast_time; /* raw time */
                    880: struct tm tm;
                    881: 
1.126     brouard   882: char strcurr[80], strfor[80];
                    883: 
                    884: char *endptr;
                    885: long lval;
                    886: double dval;
                    887: 
                    888: #define NR_END 1
                    889: #define FREE_ARG char*
                    890: #define FTOL 1.0e-10
                    891: 
                    892: #define NRANSI 
                    893: #define ITMAX 200 
                    894: 
                    895: #define TOL 2.0e-4 
                    896: 
                    897: #define CGOLD 0.3819660 
                    898: #define ZEPS 1.0e-10 
                    899: #define SHFT(a,b,c,d) (a)=(b);(b)=(c);(c)=(d); 
                    900: 
                    901: #define GOLD 1.618034 
                    902: #define GLIMIT 100.0 
                    903: #define TINY 1.0e-20 
                    904: 
                    905: static double maxarg1,maxarg2;
                    906: #define FMAX(a,b) (maxarg1=(a),maxarg2=(b),(maxarg1)>(maxarg2)? (maxarg1):(maxarg2))
                    907: #define FMIN(a,b) (maxarg1=(a),maxarg2=(b),(maxarg1)<(maxarg2)? (maxarg1):(maxarg2))
                    908:   
                    909: #define SIGN(a,b) ((b)>0.0 ? fabs(a) : -fabs(a))
                    910: #define rint(a) floor(a+0.5)
1.166     brouard   911: /* http://www.thphys.uni-heidelberg.de/~robbers/cmbeasy/doc/html/myutils_8h-source.html */
1.183     brouard   912: #define mytinydouble 1.0e-16
1.166     brouard   913: /* #define DEQUAL(a,b) (fabs((a)-(b))<mytinydouble) */
                    914: /* http://www.thphys.uni-heidelberg.de/~robbers/cmbeasy/doc/html/mynrutils_8h-source.html */
                    915: /* static double dsqrarg; */
                    916: /* #define DSQR(a) (DEQUAL((dsqrarg=(a)),0.0) ? 0.0 : dsqrarg*dsqrarg) */
1.126     brouard   917: static double sqrarg;
                    918: #define SQR(a) ((sqrarg=(a)) == 0.0 ? 0.0 :sqrarg*sqrarg)
                    919: #define SWAP(a,b) {temp=(a);(a)=(b);(b)=temp;} 
                    920: int agegomp= AGEGOMP;
                    921: 
                    922: int imx; 
                    923: int stepm=1;
                    924: /* Stepm, step in month: minimum step interpolation*/
                    925: 
                    926: int estepm;
                    927: /* Estepm, step in month to interpolate survival function in order to approximate Life Expectancy*/
                    928: 
                    929: int m,nb;
                    930: long *num;
1.197     brouard   931: int firstpass=0, lastpass=4,*cod, *cens;
1.192     brouard   932: int *ncodemax;  /* ncodemax[j]= Number of modalities of the j th
                    933:                   covariate for which somebody answered excluding 
                    934:                   undefined. Usually 2: 0 and 1. */
                    935: int *ncodemaxwundef;  /* ncodemax[j]= Number of modalities of the j th
                    936:                             covariate for which somebody answered including 
                    937:                             undefined. Usually 3: -1, 0 and 1. */
1.126     brouard   938: double **agev,*moisnais, *annais, *moisdc, *andc,**mint, **anint;
                    939: double **pmmij, ***probs;
                    940: double *ageexmed,*agecens;
                    941: double dateintmean=0;
                    942: 
                    943: double *weight;
                    944: int **s; /* Status */
1.141     brouard   945: double *agedc;
1.145     brouard   946: double  **covar; /**< covar[j,i], value of jth covariate for individual i,
1.141     brouard   947:                  * covar=matrix(0,NCOVMAX,1,n); 
1.187     brouard   948:                  * cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*age; */
1.141     brouard   949: double  idx; 
                    950: int **nbcode, *Tvar; /**< model=V2 => Tvar[1]= 2 */
1.197     brouard   951: int *Tage;
1.145     brouard   952: int *Ndum; /** Freq of modality (tricode */
1.200     brouard   953: /* int **codtab;*/ /**< codtab=imatrix(1,100,1,10); */
1.141     brouard   954: int **Tvard, *Tprod, cptcovprod, *Tvaraff;
1.126     brouard   955: double *lsurv, *lpop, *tpop;
                    956: 
1.143     brouard   957: double ftol=FTOL; /**< Tolerance for computing Max Likelihood */
                    958: double ftolhess; /**< Tolerance for computing hessian */
1.126     brouard   959: 
                    960: /**************** split *************************/
                    961: static int split( char *path, char *dirc, char *name, char *ext, char *finame )
                    962: {
                    963:   /* From a file name with (full) path (either Unix or Windows) we extract the directory (dirc)
                    964:      the name of the file (name), its extension only (ext) and its first part of the name (finame)
                    965:   */ 
                    966:   char *ss;                            /* pointer */
1.186     brouard   967:   int  l1=0, l2=0;                             /* length counters */
1.126     brouard   968: 
                    969:   l1 = strlen(path );                  /* length of path */
                    970:   if ( l1 == 0 ) return( GLOCK_ERROR_NOPATH );
                    971:   ss= strrchr( path, DIRSEPARATOR );           /* find last / */
                    972:   if ( ss == NULL ) {                  /* no directory, so determine current directory */
                    973:     strcpy( name, path );              /* we got the fullname name because no directory */
                    974:     /*if(strrchr(path, ODIRSEPARATOR )==NULL)
                    975:       printf("Warning you should use %s as a separator\n",DIRSEPARATOR);*/
                    976:     /* get current working directory */
                    977:     /*    extern  char* getcwd ( char *buf , int len);*/
1.184     brouard   978: #ifdef WIN32
                    979:     if (_getcwd( dirc, FILENAME_MAX ) == NULL ) {
                    980: #else
                    981:        if (getcwd(dirc, FILENAME_MAX) == NULL) {
                    982: #endif
1.126     brouard   983:       return( GLOCK_ERROR_GETCWD );
                    984:     }
                    985:     /* got dirc from getcwd*/
                    986:     printf(" DIRC = %s \n",dirc);
1.205     brouard   987:   } else {                             /* strip directory from path */
1.126     brouard   988:     ss++;                              /* after this, the filename */
                    989:     l2 = strlen( ss );                 /* length of filename */
                    990:     if ( l2 == 0 ) return( GLOCK_ERROR_NOPATH );
                    991:     strcpy( name, ss );                /* save file name */
                    992:     strncpy( dirc, path, l1 - l2 );    /* now the directory */
1.186     brouard   993:     dirc[l1-l2] = '\0';                        /* add zero */
1.126     brouard   994:     printf(" DIRC2 = %s \n",dirc);
                    995:   }
                    996:   /* We add a separator at the end of dirc if not exists */
                    997:   l1 = strlen( dirc );                 /* length of directory */
                    998:   if( dirc[l1-1] != DIRSEPARATOR ){
                    999:     dirc[l1] =  DIRSEPARATOR;
                   1000:     dirc[l1+1] = 0; 
                   1001:     printf(" DIRC3 = %s \n",dirc);
                   1002:   }
                   1003:   ss = strrchr( name, '.' );           /* find last / */
                   1004:   if (ss >0){
                   1005:     ss++;
                   1006:     strcpy(ext,ss);                    /* save extension */
                   1007:     l1= strlen( name);
                   1008:     l2= strlen(ss)+1;
                   1009:     strncpy( finame, name, l1-l2);
                   1010:     finame[l1-l2]= 0;
                   1011:   }
                   1012: 
                   1013:   return( 0 );                         /* we're done */
                   1014: }
                   1015: 
                   1016: 
                   1017: /******************************************/
                   1018: 
                   1019: void replace_back_to_slash(char *s, char*t)
                   1020: {
                   1021:   int i;
                   1022:   int lg=0;
                   1023:   i=0;
                   1024:   lg=strlen(t);
                   1025:   for(i=0; i<= lg; i++) {
                   1026:     (s[i] = t[i]);
                   1027:     if (t[i]== '\\') s[i]='/';
                   1028:   }
                   1029: }
                   1030: 
1.132     brouard  1031: char *trimbb(char *out, char *in)
1.137     brouard  1032: { /* Trim multiple blanks in line but keeps first blanks if line starts with blanks */
1.132     brouard  1033:   char *s;
                   1034:   s=out;
                   1035:   while (*in != '\0'){
1.137     brouard  1036:     while( *in == ' ' && *(in+1) == ' '){ /* && *(in+1) != '\0'){*/
1.132     brouard  1037:       in++;
                   1038:     }
                   1039:     *out++ = *in++;
                   1040:   }
                   1041:   *out='\0';
                   1042:   return s;
                   1043: }
                   1044: 
1.187     brouard  1045: /* char *substrchaine(char *out, char *in, char *chain) */
                   1046: /* { */
                   1047: /*   /\* Substract chain 'chain' from 'in', return and output 'out' *\/ */
                   1048: /*   char *s, *t; */
                   1049: /*   t=in;s=out; */
                   1050: /*   while ((*in != *chain) && (*in != '\0')){ */
                   1051: /*     *out++ = *in++; */
                   1052: /*   } */
                   1053: 
                   1054: /*   /\* *in matches *chain *\/ */
                   1055: /*   while ((*in++ == *chain++) && (*in != '\0')){ */
                   1056: /*     printf("*in = %c, *out= %c *chain= %c \n", *in, *out, *chain);  */
                   1057: /*   } */
                   1058: /*   in--; chain--; */
                   1059: /*   while ( (*in != '\0')){ */
                   1060: /*     printf("Bef *in = %c, *out= %c *chain= %c \n", *in, *out, *chain);  */
                   1061: /*     *out++ = *in++; */
                   1062: /*     printf("Aft *in = %c, *out= %c *chain= %c \n", *in, *out, *chain);  */
                   1063: /*   } */
                   1064: /*   *out='\0'; */
                   1065: /*   out=s; */
                   1066: /*   return out; */
                   1067: /* } */
                   1068: char *substrchaine(char *out, char *in, char *chain)
                   1069: {
                   1070:   /* Substract chain 'chain' from 'in', return and output 'out' */
                   1071:   /* in="V1+V1*age+age*age+V2", chain="age*age" */
                   1072: 
                   1073:   char *strloc;
                   1074: 
                   1075:   strcpy (out, in); 
                   1076:   strloc = strstr(out, chain); /* strloc points to out at age*age+V2 */
                   1077:   printf("Bef strloc=%s chain=%s out=%s \n", strloc, chain, out);
                   1078:   if(strloc != NULL){ 
                   1079:     /* will affect out */ /* strloc+strlenc(chain)=+V2 */ /* Will also work in Unicode */
                   1080:     memmove(strloc,strloc+strlen(chain), strlen(strloc+strlen(chain))+1);
                   1081:     /* strcpy (strloc, strloc +strlen(chain));*/
                   1082:   }
                   1083:   printf("Aft strloc=%s chain=%s in=%s out=%s \n", strloc, chain, in, out);
                   1084:   return out;
                   1085: }
                   1086: 
                   1087: 
1.145     brouard  1088: char *cutl(char *blocc, char *alocc, char *in, char occ)
                   1089: {
1.187     brouard  1090:   /* cuts string in into blocc and alocc where blocc ends before FIRST occurence of char 'occ' 
1.145     brouard  1091:      and alocc starts after first occurence of char 'occ' : ex cutv(blocc,alocc,"abcdef2ghi2j",'2')
1.187     brouard  1092:      gives blocc="abcdef" and alocc="ghi2j".
1.145     brouard  1093:      If occ is not found blocc is null and alocc is equal to in. Returns blocc
                   1094:   */
1.160     brouard  1095:   char *s, *t;
1.145     brouard  1096:   t=in;s=in;
                   1097:   while ((*in != occ) && (*in != '\0')){
                   1098:     *alocc++ = *in++;
                   1099:   }
                   1100:   if( *in == occ){
                   1101:     *(alocc)='\0';
                   1102:     s=++in;
                   1103:   }
                   1104:  
                   1105:   if (s == t) {/* occ not found */
                   1106:     *(alocc-(in-s))='\0';
                   1107:     in=s;
                   1108:   }
                   1109:   while ( *in != '\0'){
                   1110:     *blocc++ = *in++;
                   1111:   }
                   1112: 
                   1113:   *blocc='\0';
                   1114:   return t;
                   1115: }
1.137     brouard  1116: char *cutv(char *blocc, char *alocc, char *in, char occ)
                   1117: {
1.187     brouard  1118:   /* cuts string in into blocc and alocc where blocc ends before LAST occurence of char 'occ' 
1.137     brouard  1119:      and alocc starts after last occurence of char 'occ' : ex cutv(blocc,alocc,"abcdef2ghi2j",'2')
                   1120:      gives blocc="abcdef2ghi" and alocc="j".
                   1121:      If occ is not found blocc is null and alocc is equal to in. Returns alocc
                   1122:   */
                   1123:   char *s, *t;
                   1124:   t=in;s=in;
                   1125:   while (*in != '\0'){
                   1126:     while( *in == occ){
                   1127:       *blocc++ = *in++;
                   1128:       s=in;
                   1129:     }
                   1130:     *blocc++ = *in++;
                   1131:   }
                   1132:   if (s == t) /* occ not found */
                   1133:     *(blocc-(in-s))='\0';
                   1134:   else
                   1135:     *(blocc-(in-s)-1)='\0';
                   1136:   in=s;
                   1137:   while ( *in != '\0'){
                   1138:     *alocc++ = *in++;
                   1139:   }
                   1140: 
                   1141:   *alocc='\0';
                   1142:   return s;
                   1143: }
                   1144: 
1.126     brouard  1145: int nbocc(char *s, char occ)
                   1146: {
                   1147:   int i,j=0;
                   1148:   int lg=20;
                   1149:   i=0;
                   1150:   lg=strlen(s);
                   1151:   for(i=0; i<= lg; i++) {
                   1152:   if  (s[i] == occ ) j++;
                   1153:   }
                   1154:   return j;
                   1155: }
                   1156: 
1.137     brouard  1157: /* void cutv(char *u,char *v, char*t, char occ) */
                   1158: /* { */
                   1159: /*   /\* cuts string t into u and v where u ends before last occurence of char 'occ'  */
                   1160: /*      and v starts after last occurence of char 'occ' : ex cutv(u,v,"abcdef2ghi2j",'2') */
                   1161: /*      gives u="abcdef2ghi" and v="j" *\/ */
                   1162: /*   int i,lg,j,p=0; */
                   1163: /*   i=0; */
                   1164: /*   lg=strlen(t); */
                   1165: /*   for(j=0; j<=lg-1; j++) { */
                   1166: /*     if((t[j]!= occ) && (t[j+1]== occ)) p=j+1; */
                   1167: /*   } */
1.126     brouard  1168: 
1.137     brouard  1169: /*   for(j=0; j<p; j++) { */
                   1170: /*     (u[j] = t[j]); */
                   1171: /*   } */
                   1172: /*      u[p]='\0'; */
1.126     brouard  1173: 
1.137     brouard  1174: /*    for(j=0; j<= lg; j++) { */
                   1175: /*     if (j>=(p+1))(v[j-p-1] = t[j]); */
                   1176: /*   } */
                   1177: /* } */
1.126     brouard  1178: 
1.160     brouard  1179: #ifdef _WIN32
                   1180: char * strsep(char **pp, const char *delim)
                   1181: {
                   1182:   char *p, *q;
                   1183:          
                   1184:   if ((p = *pp) == NULL)
                   1185:     return 0;
                   1186:   if ((q = strpbrk (p, delim)) != NULL)
                   1187:   {
                   1188:     *pp = q + 1;
                   1189:     *q = '\0';
                   1190:   }
                   1191:   else
                   1192:     *pp = 0;
                   1193:   return p;
                   1194: }
                   1195: #endif
                   1196: 
1.126     brouard  1197: /********************** nrerror ********************/
                   1198: 
                   1199: void nrerror(char error_text[])
                   1200: {
                   1201:   fprintf(stderr,"ERREUR ...\n");
                   1202:   fprintf(stderr,"%s\n",error_text);
                   1203:   exit(EXIT_FAILURE);
                   1204: }
                   1205: /*********************** vector *******************/
                   1206: double *vector(int nl, int nh)
                   1207: {
                   1208:   double *v;
                   1209:   v=(double *) malloc((size_t)((nh-nl+1+NR_END)*sizeof(double)));
                   1210:   if (!v) nrerror("allocation failure in vector");
                   1211:   return v-nl+NR_END;
                   1212: }
                   1213: 
                   1214: /************************ free vector ******************/
                   1215: void free_vector(double*v, int nl, int nh)
                   1216: {
                   1217:   free((FREE_ARG)(v+nl-NR_END));
                   1218: }
                   1219: 
                   1220: /************************ivector *******************************/
                   1221: int *ivector(long nl,long nh)
                   1222: {
                   1223:   int *v;
                   1224:   v=(int *) malloc((size_t)((nh-nl+1+NR_END)*sizeof(int)));
                   1225:   if (!v) nrerror("allocation failure in ivector");
                   1226:   return v-nl+NR_END;
                   1227: }
                   1228: 
                   1229: /******************free ivector **************************/
                   1230: void free_ivector(int *v, long nl, long nh)
                   1231: {
                   1232:   free((FREE_ARG)(v+nl-NR_END));
                   1233: }
                   1234: 
                   1235: /************************lvector *******************************/
                   1236: long *lvector(long nl,long nh)
                   1237: {
                   1238:   long *v;
                   1239:   v=(long *) malloc((size_t)((nh-nl+1+NR_END)*sizeof(long)));
                   1240:   if (!v) nrerror("allocation failure in ivector");
                   1241:   return v-nl+NR_END;
                   1242: }
                   1243: 
                   1244: /******************free lvector **************************/
                   1245: void free_lvector(long *v, long nl, long nh)
                   1246: {
                   1247:   free((FREE_ARG)(v+nl-NR_END));
                   1248: }
                   1249: 
                   1250: /******************* imatrix *******************************/
                   1251: int **imatrix(long nrl, long nrh, long ncl, long nch) 
                   1252:      /* allocate a int matrix with subscript range m[nrl..nrh][ncl..nch] */ 
                   1253: { 
                   1254:   long i, nrow=nrh-nrl+1,ncol=nch-ncl+1; 
                   1255:   int **m; 
                   1256:   
                   1257:   /* allocate pointers to rows */ 
                   1258:   m=(int **) malloc((size_t)((nrow+NR_END)*sizeof(int*))); 
                   1259:   if (!m) nrerror("allocation failure 1 in matrix()"); 
                   1260:   m += NR_END; 
                   1261:   m -= nrl; 
                   1262:   
                   1263:   
                   1264:   /* allocate rows and set pointers to them */ 
                   1265:   m[nrl]=(int *) malloc((size_t)((nrow*ncol+NR_END)*sizeof(int))); 
                   1266:   if (!m[nrl]) nrerror("allocation failure 2 in matrix()"); 
                   1267:   m[nrl] += NR_END; 
                   1268:   m[nrl] -= ncl; 
                   1269:   
                   1270:   for(i=nrl+1;i<=nrh;i++) m[i]=m[i-1]+ncol; 
                   1271:   
                   1272:   /* return pointer to array of pointers to rows */ 
                   1273:   return m; 
                   1274: } 
                   1275: 
                   1276: /****************** free_imatrix *************************/
                   1277: void free_imatrix(m,nrl,nrh,ncl,nch)
                   1278:       int **m;
                   1279:       long nch,ncl,nrh,nrl; 
                   1280:      /* free an int matrix allocated by imatrix() */ 
                   1281: { 
                   1282:   free((FREE_ARG) (m[nrl]+ncl-NR_END)); 
                   1283:   free((FREE_ARG) (m+nrl-NR_END)); 
                   1284: } 
                   1285: 
                   1286: /******************* matrix *******************************/
                   1287: double **matrix(long nrl, long nrh, long ncl, long nch)
                   1288: {
                   1289:   long i, nrow=nrh-nrl+1, ncol=nch-ncl+1;
                   1290:   double **m;
                   1291: 
                   1292:   m=(double **) malloc((size_t)((nrow+NR_END)*sizeof(double*)));
                   1293:   if (!m) nrerror("allocation failure 1 in matrix()");
                   1294:   m += NR_END;
                   1295:   m -= nrl;
                   1296: 
                   1297:   m[nrl]=(double *) malloc((size_t)((nrow*ncol+NR_END)*sizeof(double)));
                   1298:   if (!m[nrl]) nrerror("allocation failure 2 in matrix()");
                   1299:   m[nrl] += NR_END;
                   1300:   m[nrl] -= ncl;
                   1301: 
                   1302:   for (i=nrl+1; i<=nrh; i++) m[i]=m[i-1]+ncol;
                   1303:   return m;
1.145     brouard  1304:   /* print *(*(m+1)+70) or print m[1][70]; print m+1 or print &(m[1]) or &(m[1][0])
                   1305: m[i] = address of ith row of the table. &(m[i]) is its value which is another adress
                   1306: that of m[i][0]. In order to get the value p m[i][0] but it is unitialized.
1.126     brouard  1307:    */
                   1308: }
                   1309: 
                   1310: /*************************free matrix ************************/
                   1311: void free_matrix(double **m, long nrl, long nrh, long ncl, long nch)
                   1312: {
                   1313:   free((FREE_ARG)(m[nrl]+ncl-NR_END));
                   1314:   free((FREE_ARG)(m+nrl-NR_END));
                   1315: }
                   1316: 
                   1317: /******************* ma3x *******************************/
                   1318: double ***ma3x(long nrl, long nrh, long ncl, long nch, long nll, long nlh)
                   1319: {
                   1320:   long i, j, nrow=nrh-nrl+1, ncol=nch-ncl+1, nlay=nlh-nll+1;
                   1321:   double ***m;
                   1322: 
                   1323:   m=(double ***) malloc((size_t)((nrow+NR_END)*sizeof(double*)));
                   1324:   if (!m) nrerror("allocation failure 1 in matrix()");
                   1325:   m += NR_END;
                   1326:   m -= nrl;
                   1327: 
                   1328:   m[nrl]=(double **) malloc((size_t)((nrow*ncol+NR_END)*sizeof(double)));
                   1329:   if (!m[nrl]) nrerror("allocation failure 2 in matrix()");
                   1330:   m[nrl] += NR_END;
                   1331:   m[nrl] -= ncl;
                   1332: 
                   1333:   for (i=nrl+1; i<=nrh; i++) m[i]=m[i-1]+ncol;
                   1334: 
                   1335:   m[nrl][ncl]=(double *) malloc((size_t)((nrow*ncol*nlay+NR_END)*sizeof(double)));
                   1336:   if (!m[nrl][ncl]) nrerror("allocation failure 3 in matrix()");
                   1337:   m[nrl][ncl] += NR_END;
                   1338:   m[nrl][ncl] -= nll;
                   1339:   for (j=ncl+1; j<=nch; j++) 
                   1340:     m[nrl][j]=m[nrl][j-1]+nlay;
                   1341:   
                   1342:   for (i=nrl+1; i<=nrh; i++) {
                   1343:     m[i][ncl]=m[i-1l][ncl]+ncol*nlay;
                   1344:     for (j=ncl+1; j<=nch; j++) 
                   1345:       m[i][j]=m[i][j-1]+nlay;
                   1346:   }
                   1347:   return m; 
                   1348:   /*  gdb: p *(m+1) <=> p m[1] and p (m+1) <=> p (m+1) <=> p &(m[1])
                   1349:            &(m[i][j][k]) <=> *((*(m+i) + j)+k)
                   1350:   */
                   1351: }
                   1352: 
                   1353: /*************************free ma3x ************************/
                   1354: void free_ma3x(double ***m, long nrl, long nrh, long ncl, long nch,long nll, long nlh)
                   1355: {
                   1356:   free((FREE_ARG)(m[nrl][ncl]+ nll-NR_END));
                   1357:   free((FREE_ARG)(m[nrl]+ncl-NR_END));
                   1358:   free((FREE_ARG)(m+nrl-NR_END));
                   1359: }
                   1360: 
                   1361: /*************** function subdirf ***********/
                   1362: char *subdirf(char fileres[])
                   1363: {
                   1364:   /* Caution optionfilefiname is hidden */
                   1365:   strcpy(tmpout,optionfilefiname);
                   1366:   strcat(tmpout,"/"); /* Add to the right */
                   1367:   strcat(tmpout,fileres);
                   1368:   return tmpout;
                   1369: }
                   1370: 
                   1371: /*************** function subdirf2 ***********/
                   1372: char *subdirf2(char fileres[], char *preop)
                   1373: {
                   1374:   
                   1375:   /* Caution optionfilefiname is hidden */
                   1376:   strcpy(tmpout,optionfilefiname);
                   1377:   strcat(tmpout,"/");
                   1378:   strcat(tmpout,preop);
                   1379:   strcat(tmpout,fileres);
                   1380:   return tmpout;
                   1381: }
                   1382: 
                   1383: /*************** function subdirf3 ***********/
                   1384: char *subdirf3(char fileres[], char *preop, char *preop2)
                   1385: {
                   1386:   
                   1387:   /* Caution optionfilefiname is hidden */
                   1388:   strcpy(tmpout,optionfilefiname);
                   1389:   strcat(tmpout,"/");
                   1390:   strcat(tmpout,preop);
                   1391:   strcat(tmpout,preop2);
                   1392:   strcat(tmpout,fileres);
                   1393:   return tmpout;
                   1394: }
1.213     brouard  1395:  
                   1396: /*************** function subdirfext ***********/
                   1397: char *subdirfext(char fileres[], char *preop, char *postop)
                   1398: {
                   1399:   
                   1400:   strcpy(tmpout,preop);
                   1401:   strcat(tmpout,fileres);
                   1402:   strcat(tmpout,postop);
                   1403:   return tmpout;
                   1404: }
1.126     brouard  1405: 
1.213     brouard  1406: /*************** function subdirfext3 ***********/
                   1407: char *subdirfext3(char fileres[], char *preop, char *postop)
                   1408: {
                   1409:   
                   1410:   /* Caution optionfilefiname is hidden */
                   1411:   strcpy(tmpout,optionfilefiname);
                   1412:   strcat(tmpout,"/");
                   1413:   strcat(tmpout,preop);
                   1414:   strcat(tmpout,fileres);
                   1415:   strcat(tmpout,postop);
                   1416:   return tmpout;
                   1417: }
                   1418:  
1.162     brouard  1419: char *asc_diff_time(long time_sec, char ascdiff[])
                   1420: {
                   1421:   long sec_left, days, hours, minutes;
                   1422:   days = (time_sec) / (60*60*24);
                   1423:   sec_left = (time_sec) % (60*60*24);
                   1424:   hours = (sec_left) / (60*60) ;
                   1425:   sec_left = (sec_left) %(60*60);
                   1426:   minutes = (sec_left) /60;
                   1427:   sec_left = (sec_left) % (60);
                   1428:   sprintf(ascdiff,"%ld day(s) %ld hour(s) %ld minute(s) %ld second(s)",days, hours, minutes, sec_left);  
                   1429:   return ascdiff;
                   1430: }
                   1431: 
1.126     brouard  1432: /***************** f1dim *************************/
                   1433: extern int ncom; 
                   1434: extern double *pcom,*xicom;
                   1435: extern double (*nrfunc)(double []); 
                   1436:  
                   1437: double f1dim(double x) 
                   1438: { 
                   1439:   int j; 
                   1440:   double f;
                   1441:   double *xt; 
                   1442:  
                   1443:   xt=vector(1,ncom); 
                   1444:   for (j=1;j<=ncom;j++) xt[j]=pcom[j]+x*xicom[j]; 
                   1445:   f=(*nrfunc)(xt); 
                   1446:   free_vector(xt,1,ncom); 
                   1447:   return f; 
                   1448: } 
                   1449: 
                   1450: /*****************brent *************************/
                   1451: double brent(double ax, double bx, double cx, double (*f)(double), double tol,         double *xmin) 
1.187     brouard  1452: {
                   1453:   /* Given a function f, and given a bracketing triplet of abscissas ax, bx, cx (such that bx is
                   1454:    * between ax and cx, and f(bx) is less than both f(ax) and f(cx) ), this routine isolates
                   1455:    * the minimum to a fractional precision of about tol using Brent’s method. The abscissa of
                   1456:    * the minimum is returned as xmin, and the minimum function value is returned as brent , the
                   1457:    * returned function value. 
                   1458:   */
1.126     brouard  1459:   int iter; 
                   1460:   double a,b,d,etemp;
1.159     brouard  1461:   double fu=0,fv,fw,fx;
1.164     brouard  1462:   double ftemp=0.;
1.126     brouard  1463:   double p,q,r,tol1,tol2,u,v,w,x,xm; 
                   1464:   double e=0.0; 
                   1465:  
                   1466:   a=(ax < cx ? ax : cx); 
                   1467:   b=(ax > cx ? ax : cx); 
                   1468:   x=w=v=bx; 
                   1469:   fw=fv=fx=(*f)(x); 
                   1470:   for (iter=1;iter<=ITMAX;iter++) { 
                   1471:     xm=0.5*(a+b); 
                   1472:     tol2=2.0*(tol1=tol*fabs(x)+ZEPS); 
                   1473:     /*         if (2.0*fabs(fp-(*fret)) <= ftol*(fabs(fp)+fabs(*fret)))*/
                   1474:     printf(".");fflush(stdout);
                   1475:     fprintf(ficlog,".");fflush(ficlog);
1.162     brouard  1476: #ifdef DEBUGBRENT
1.126     brouard  1477:     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);
                   1478:     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);
                   1479:     /*         if ((fabs(x-xm) <= (tol2-0.5*(b-a)))||(2.0*fabs(fu-ftemp) <= ftol*1.e-2*(fabs(fu)+fabs(ftemp)))) { */
                   1480: #endif
                   1481:     if (fabs(x-xm) <= (tol2-0.5*(b-a))){ 
                   1482:       *xmin=x; 
                   1483:       return fx; 
                   1484:     } 
                   1485:     ftemp=fu;
                   1486:     if (fabs(e) > tol1) { 
                   1487:       r=(x-w)*(fx-fv); 
                   1488:       q=(x-v)*(fx-fw); 
                   1489:       p=(x-v)*q-(x-w)*r; 
                   1490:       q=2.0*(q-r); 
                   1491:       if (q > 0.0) p = -p; 
                   1492:       q=fabs(q); 
                   1493:       etemp=e; 
                   1494:       e=d; 
                   1495:       if (fabs(p) >= fabs(0.5*q*etemp) || p <= q*(a-x) || p >= q*(b-x)) 
                   1496:        d=CGOLD*(e=(x >= xm ? a-x : b-x)); 
                   1497:       else { 
                   1498:        d=p/q; 
                   1499:        u=x+d; 
                   1500:        if (u-a < tol2 || b-u < tol2) 
                   1501:          d=SIGN(tol1,xm-x); 
                   1502:       } 
                   1503:     } else { 
                   1504:       d=CGOLD*(e=(x >= xm ? a-x : b-x)); 
                   1505:     } 
                   1506:     u=(fabs(d) >= tol1 ? x+d : x+SIGN(tol1,d)); 
                   1507:     fu=(*f)(u); 
                   1508:     if (fu <= fx) { 
                   1509:       if (u >= x) a=x; else b=x; 
                   1510:       SHFT(v,w,x,u) 
1.183     brouard  1511:       SHFT(fv,fw,fx,fu) 
                   1512:     } else { 
                   1513:       if (u < x) a=u; else b=u; 
                   1514:       if (fu <= fw || w == x) { 
                   1515:        v=w; 
                   1516:        w=u; 
                   1517:        fv=fw; 
                   1518:        fw=fu; 
                   1519:       } else if (fu <= fv || v == x || v == w) { 
                   1520:        v=u; 
                   1521:        fv=fu; 
                   1522:       } 
                   1523:     } 
1.126     brouard  1524:   } 
                   1525:   nrerror("Too many iterations in brent"); 
                   1526:   *xmin=x; 
                   1527:   return fx; 
                   1528: } 
                   1529: 
                   1530: /****************** mnbrak ***********************/
                   1531: 
                   1532: void mnbrak(double *ax, double *bx, double *cx, double *fa, double *fb, double *fc, 
                   1533:            double (*func)(double)) 
1.183     brouard  1534: { /* Given a function func , and given distinct initial points ax and bx , this routine searches in
                   1535: the downhill direction (defined by the function as evaluated at the initial points) and returns
                   1536: new points ax , bx , cx that bracket a minimum of the function. Also returned are the function
                   1537: values at the three points, fa, fb , and fc such that fa > fb and fb < fc.
                   1538:    */
1.126     brouard  1539:   double ulim,u,r,q, dum;
                   1540:   double fu; 
1.187     brouard  1541: 
                   1542:   double scale=10.;
                   1543:   int iterscale=0;
                   1544: 
                   1545:   *fa=(*func)(*ax); /*  xta[j]=pcom[j]+(*ax)*xicom[j]; fa=f(xta[j])*/
                   1546:   *fb=(*func)(*bx); /*  xtb[j]=pcom[j]+(*bx)*xicom[j]; fb=f(xtb[j]) */
                   1547: 
                   1548: 
                   1549:   /* while(*fb != *fb){ /\* *ax should be ok, reducing distance to *ax *\/ */
                   1550:   /*   printf("Warning mnbrak *fb = %lf, *bx=%lf *ax=%lf *fa==%lf iter=%d\n",*fb, *bx, *ax, *fa, iterscale++); */
                   1551:   /*   *bx = *ax - (*ax - *bx)/scale; */
                   1552:   /*   *fb=(*func)(*bx);  /\*  xtb[j]=pcom[j]+(*bx)*xicom[j]; fb=f(xtb[j]) *\/ */
                   1553:   /* } */
                   1554: 
1.126     brouard  1555:   if (*fb > *fa) { 
                   1556:     SHFT(dum,*ax,*bx,dum) 
1.183     brouard  1557:     SHFT(dum,*fb,*fa,dum) 
                   1558:   } 
1.126     brouard  1559:   *cx=(*bx)+GOLD*(*bx-*ax); 
                   1560:   *fc=(*func)(*cx); 
1.183     brouard  1561: #ifdef DEBUG
                   1562:   printf("mnbrak0 *fb=%.12e *fc=%.12e\n",*fb,*fc);
                   1563:   fprintf(ficlog,"mnbrak0 *fb=%.12e *fc=%.12e\n",*fb,*fc);
                   1564: #endif
                   1565:   while (*fb > *fc) { /* Declining a,b,c with fa> fb > fc */
1.126     brouard  1566:     r=(*bx-*ax)*(*fb-*fc); 
                   1567:     q=(*bx-*cx)*(*fb-*fa); 
                   1568:     u=(*bx)-((*bx-*cx)*q-(*bx-*ax)*r)/ 
1.183     brouard  1569:       (2.0*SIGN(FMAX(fabs(q-r),TINY),q-r)); /* Minimum abscissa of a parabolic estimated from (a,fa), (b,fb) and (c,fc). */
                   1570:     ulim=(*bx)+GLIMIT*(*cx-*bx); /* Maximum abscissa where function should be evaluated */
                   1571:     if ((*bx-u)*(u-*cx) > 0.0) { /* if u_p is between b and c */
1.126     brouard  1572:       fu=(*func)(u); 
1.163     brouard  1573: #ifdef DEBUG
                   1574:       /* f(x)=A(x-u)**2+f(u) */
                   1575:       double A, fparabu; 
                   1576:       A= (*fb - *fa)/(*bx-*ax)/(*bx+*ax-2*u);
                   1577:       fparabu= *fa - A*(*ax-u)*(*ax-u);
                   1578:       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);
                   1579:       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  1580:       /* And thus,it can be that fu > *fc even if fparabu < *fc */
                   1581:       /* mnbrak (*ax=7.666299858533, *fa=299039.693133272231), (*bx=8.595447774979, *fb=298976.598289369489),
                   1582:         (*cx=10.098840694817, *fc=298946.631474258087),  (*u=9.852501168332, fu=298948.773013752128, fparabu=298945.434711494134) */
                   1583:       /* In that case, there is no bracket in the output! Routine is wrong with many consequences.*/
1.163     brouard  1584: #endif 
1.184     brouard  1585: #ifdef MNBRAKORIGINAL
1.183     brouard  1586: #else
1.191     brouard  1587: /*       if (fu > *fc) { */
                   1588: /* #ifdef DEBUG */
                   1589: /*       printf("mnbrak4  fu > fc \n"); */
                   1590: /*       fprintf(ficlog, "mnbrak4 fu > fc\n"); */
                   1591: /* #endif */
                   1592: /*     /\* 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 *\\/  *\/ */
                   1593: /*     /\* SHFT(*fa,*fc,fu,*fc) /\\* (b, u, c) is a bracket while test fb > fc will be fu > fc  will exit *\\/ *\/ */
                   1594: /*     dum=u; /\* Shifting c and u *\/ */
                   1595: /*     u = *cx; */
                   1596: /*     *cx = dum; */
                   1597: /*     dum = fu; */
                   1598: /*     fu = *fc; */
                   1599: /*     *fc =dum; */
                   1600: /*       } else { /\* end *\/ */
                   1601: /* #ifdef DEBUG */
                   1602: /*       printf("mnbrak3  fu < fc \n"); */
                   1603: /*       fprintf(ficlog, "mnbrak3 fu < fc\n"); */
                   1604: /* #endif */
                   1605: /*     dum=u; /\* Shifting c and u *\/ */
                   1606: /*     u = *cx; */
                   1607: /*     *cx = dum; */
                   1608: /*     dum = fu; */
                   1609: /*     fu = *fc; */
                   1610: /*     *fc =dum; */
                   1611: /*       } */
1.183     brouard  1612: #ifdef DEBUG
1.191     brouard  1613:       printf("mnbrak34  fu < or >= fc \n");
                   1614:       fprintf(ficlog, "mnbrak34 fu < fc\n");
1.183     brouard  1615: #endif
1.191     brouard  1616:       dum=u; /* Shifting c and u */
                   1617:       u = *cx;
                   1618:       *cx = dum;
                   1619:       dum = fu;
                   1620:       fu = *fc;
                   1621:       *fc =dum;
1.183     brouard  1622: #endif
1.162     brouard  1623:     } else if ((*cx-u)*(u-ulim) > 0.0) { /* u is after c but before ulim */
1.183     brouard  1624: #ifdef DEBUG
                   1625:       printf("mnbrak2  u after c but before ulim\n");
                   1626:       fprintf(ficlog, "mnbrak2 u after c but before ulim\n");
                   1627: #endif
1.126     brouard  1628:       fu=(*func)(u); 
                   1629:       if (fu < *fc) { 
1.183     brouard  1630: #ifdef DEBUG
                   1631:       printf("mnbrak2  u after c but before ulim AND fu < fc\n");
                   1632:       fprintf(ficlog, "mnbrak2 u after c but before ulim AND fu <fc \n");
                   1633: #endif
1.126     brouard  1634:        SHFT(*bx,*cx,u,*cx+GOLD*(*cx-*bx)) 
1.183     brouard  1635:        SHFT(*fb,*fc,fu,(*func)(u)) 
                   1636:       } 
1.162     brouard  1637:     } else if ((u-ulim)*(ulim-*cx) >= 0.0) { /* u outside ulim (verifying that ulim is beyond c) */
1.183     brouard  1638: #ifdef DEBUG
                   1639:       printf("mnbrak2  u outside ulim (verifying that ulim is beyond c)\n");
                   1640:       fprintf(ficlog, "mnbrak2 u outside ulim (verifying that ulim is beyond c)\n");
                   1641: #endif
1.126     brouard  1642:       u=ulim; 
                   1643:       fu=(*func)(u); 
1.183     brouard  1644:     } else { /* u could be left to b (if r > q parabola has a maximum) */
                   1645: #ifdef DEBUG
                   1646:       printf("mnbrak2  u could be left to b (if r > q parabola has a maximum)\n");
                   1647:       fprintf(ficlog, "mnbrak2  u could be left to b (if r > q parabola has a maximum)\n");
                   1648: #endif
1.126     brouard  1649:       u=(*cx)+GOLD*(*cx-*bx); 
                   1650:       fu=(*func)(u); 
1.183     brouard  1651:     } /* end tests */
1.126     brouard  1652:     SHFT(*ax,*bx,*cx,u) 
1.183     brouard  1653:     SHFT(*fa,*fb,*fc,fu) 
                   1654: #ifdef DEBUG
                   1655:       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);
                   1656:       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);
                   1657: #endif
                   1658:   } /* 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  1659: } 
                   1660: 
                   1661: /*************** linmin ************************/
1.162     brouard  1662: /* Given an n -dimensional point p[1..n] and an n -dimensional direction xi[1..n] , moves and
                   1663: resets p to where the function func(p) takes on a minimum along the direction xi from p ,
                   1664: and replaces xi by the actual vector displacement that p was moved. Also returns as fret
                   1665: the value of func at the returned location p . This is actually all accomplished by calling the
                   1666: routines mnbrak and brent .*/
1.126     brouard  1667: int ncom; 
                   1668: double *pcom,*xicom;
                   1669: double (*nrfunc)(double []); 
                   1670:  
                   1671: void linmin(double p[], double xi[], int n, double *fret,double (*func)(double [])) 
                   1672: { 
                   1673:   double brent(double ax, double bx, double cx, 
                   1674:               double (*f)(double), double tol, double *xmin); 
                   1675:   double f1dim(double x); 
                   1676:   void mnbrak(double *ax, double *bx, double *cx, double *fa, double *fb, 
                   1677:              double *fc, double (*func)(double)); 
                   1678:   int j; 
                   1679:   double xx,xmin,bx,ax; 
                   1680:   double fx,fb,fa;
1.187     brouard  1681: 
1.203     brouard  1682: #ifdef LINMINORIGINAL
                   1683: #else
                   1684:   double scale=10., axs, xxs; /* Scale added for infinity */
                   1685: #endif
                   1686:   
1.126     brouard  1687:   ncom=n; 
                   1688:   pcom=vector(1,n); 
                   1689:   xicom=vector(1,n); 
                   1690:   nrfunc=func; 
                   1691:   for (j=1;j<=n;j++) { 
                   1692:     pcom[j]=p[j]; 
1.202     brouard  1693:     xicom[j]=xi[j]; /* Former scale xi[j] of currrent direction i */
1.126     brouard  1694:   } 
1.187     brouard  1695: 
1.203     brouard  1696: #ifdef LINMINORIGINAL
                   1697:   xx=1.;
                   1698: #else
                   1699:   axs=0.0;
                   1700:   xxs=1.;
                   1701:   do{
                   1702:     xx= xxs;
                   1703: #endif
1.187     brouard  1704:     ax=0.;
                   1705:     mnbrak(&ax,&xx,&bx,&fa,&fx,&fb,f1dim);  /* Outputs: xtx[j]=pcom[j]+(*xx)*xicom[j]; fx=f(xtx[j]) */
                   1706:     /* brackets with inputs ax=0 and xx=1, but points, pcom=p, and directions values, xicom=xi, are sent via f1dim(x) */
                   1707:     /* 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))   */
                   1708:     /* Outputs: fa=f(p(j)) and fx=f(p(j) + xxs * xi(j) ) and f(bx)= f(p(j)+ bx* xi(j)) */
                   1709:     /* Given input ax=axs and xx=xxs, xx might be too far from ax to get a finite f(xx) */
                   1710:     /* Searches on line, outputs (ax, xx, bx) such that fx < min(fa and fb) */
                   1711:     /* 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  1712: #ifdef LINMINORIGINAL
                   1713: #else
                   1714:     if (fx != fx){
                   1715:        xxs=xxs/scale; /* Trying a smaller xx, closer to initial ax=0 */
                   1716:        printf("|");
                   1717:        fprintf(ficlog,"|");
                   1718: #ifdef DEBUGLINMIN
                   1719:        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);
                   1720: #endif
                   1721:     }
                   1722:   }while(fx != fx);
                   1723: #endif
                   1724:   
1.191     brouard  1725: #ifdef DEBUGLINMIN
                   1726:   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  1727:   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  1728: #endif
1.187     brouard  1729:   *fret=brent(ax,xx,bx,f1dim,TOL,&xmin); /* Giving a bracketting triplet (ax, xx, bx), find a minimum, xmin, according to f1dim, *fret(xmin),*/
                   1730:   /* fa = f(p[j] + ax * xi[j]), fx = f(p[j] + xx * xi[j]), fb = f(p[j] + bx * xi[j]) */
                   1731:   /* fmin = f(p[j] + xmin * xi[j]) */
                   1732:   /* P+lambda n in that direction (lambdamin), with TOL between abscisses */
                   1733:   /* f1dim(xmin): for (j=1;j<=ncom;j++) xt[j]=pcom[j]+xmin*xicom[j]; */
1.126     brouard  1734: #ifdef DEBUG
                   1735:   printf("retour brent fret=%.12e xmin=%.12e\n",*fret,xmin);
                   1736:   fprintf(ficlog,"retour brent fret=%.12e xmin=%.12e\n",*fret,xmin);
                   1737: #endif
1.191     brouard  1738: #ifdef DEBUGLINMIN
                   1739:   printf("linmin end ");
1.202     brouard  1740:   fprintf(ficlog,"linmin end ");
1.191     brouard  1741: #endif
1.126     brouard  1742:   for (j=1;j<=n;j++) { 
1.203     brouard  1743: #ifdef LINMINORIGINAL
                   1744:     xi[j] *= xmin; 
                   1745: #else
                   1746: #ifdef DEBUGLINMIN
                   1747:     if(xxs <1.0)
                   1748:       printf(" before xi[%d]=%12.8f", j,xi[j]);
                   1749: #endif
                   1750:     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) */
                   1751: #ifdef DEBUGLINMIN
                   1752:     if(xxs <1.0)
                   1753:       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 );
                   1754: #endif
                   1755: #endif
1.187     brouard  1756:     p[j] += xi[j]; /* Parameters values are updated accordingly */
1.126     brouard  1757:   } 
1.191     brouard  1758: #ifdef DEBUGLINMIN
1.203     brouard  1759:   printf("\n");
1.191     brouard  1760:   printf("Comparing last *frec(xmin=%12.8f)=%12.8f from Brent and frec(0.)=%12.8f \n", xmin, *fret, (*func)(p));
1.202     brouard  1761:   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  1762:   for (j=1;j<=n;j++) { 
1.202     brouard  1763:     printf(" xi[%d]= %14.10f p[%d]= %12.7f",j,xi[j],j,p[j]);
                   1764:     fprintf(ficlog," xi[%d]= %14.10f p[%d]= %12.7f",j,xi[j],j,p[j]);
                   1765:     if(j % ncovmodel == 0){
1.191     brouard  1766:       printf("\n");
1.202     brouard  1767:       fprintf(ficlog,"\n");
                   1768:     }
1.191     brouard  1769:   }
1.203     brouard  1770: #else
1.191     brouard  1771: #endif
1.126     brouard  1772:   free_vector(xicom,1,n); 
                   1773:   free_vector(pcom,1,n); 
                   1774: } 
                   1775: 
                   1776: 
                   1777: /*************** powell ************************/
1.162     brouard  1778: /*
                   1779: Minimization of a function func of n variables. Input consists of an initial starting point
                   1780: p[1..n] ; an initial matrix xi[1..n][1..n] , whose columns contain the initial set of di-
                   1781: rections (usually the n unit vectors); and ftol , the fractional tolerance in the function value
                   1782: such that failure to decrease by more than this amount on one iteration signals doneness. On
                   1783: output, p is set to the best point found, xi is the then-current direction set, fret is the returned
                   1784: function value at p , and iter is the number of iterations taken. The routine linmin is used.
                   1785:  */
1.126     brouard  1786: void powell(double p[], double **xi, int n, double ftol, int *iter, double *fret, 
                   1787:            double (*func)(double [])) 
                   1788: { 
                   1789:   void linmin(double p[], double xi[], int n, double *fret, 
                   1790:              double (*func)(double [])); 
                   1791:   int i,ibig,j; 
                   1792:   double del,t,*pt,*ptt,*xit;
1.181     brouard  1793:   double directest;
1.126     brouard  1794:   double fp,fptt;
                   1795:   double *xits;
                   1796:   int niterf, itmp;
                   1797: 
                   1798:   pt=vector(1,n); 
                   1799:   ptt=vector(1,n); 
                   1800:   xit=vector(1,n); 
                   1801:   xits=vector(1,n); 
                   1802:   *fret=(*func)(p); 
                   1803:   for (j=1;j<=n;j++) pt[j]=p[j]; 
1.202     brouard  1804:   rcurr_time = time(NULL);  
1.126     brouard  1805:   for (*iter=1;;++(*iter)) { 
1.187     brouard  1806:     fp=(*fret); /* From former iteration or initial value */
1.126     brouard  1807:     ibig=0; 
                   1808:     del=0.0; 
1.157     brouard  1809:     rlast_time=rcurr_time;
                   1810:     /* (void) gettimeofday(&curr_time,&tzp); */
                   1811:     rcurr_time = time(NULL);  
                   1812:     curr_time = *localtime(&rcurr_time);
                   1813:     printf("\nPowell iter=%d -2*LL=%.12f %ld sec. %ld sec.",*iter,*fret, rcurr_time-rlast_time, rcurr_time-rstart_time);fflush(stdout);
                   1814:     fprintf(ficlog,"\nPowell iter=%d -2*LL=%.12f %ld sec. %ld sec.",*iter,*fret,rcurr_time-rlast_time, rcurr_time-rstart_time); fflush(ficlog);
                   1815: /*     fprintf(ficrespow,"%d %.12f %ld",*iter,*fret,curr_time.tm_sec-start_time.tm_sec); */
1.192     brouard  1816:     for (i=1;i<=n;i++) {
1.126     brouard  1817:       printf(" %d %.12f",i, p[i]);
                   1818:       fprintf(ficlog," %d %.12lf",i, p[i]);
                   1819:       fprintf(ficrespow," %.12lf", p[i]);
                   1820:     }
                   1821:     printf("\n");
                   1822:     fprintf(ficlog,"\n");
                   1823:     fprintf(ficrespow,"\n");fflush(ficrespow);
                   1824:     if(*iter <=3){
1.157     brouard  1825:       tml = *localtime(&rcurr_time);
                   1826:       strcpy(strcurr,asctime(&tml));
                   1827:       rforecast_time=rcurr_time; 
1.126     brouard  1828:       itmp = strlen(strcurr);
                   1829:       if(strcurr[itmp-1]=='\n')  /* Windows outputs with a new line */
                   1830:        strcurr[itmp-1]='\0';
1.162     brouard  1831:       printf("\nConsidering the time needed for the last iteration #%d: %ld seconds,\n",*iter,rcurr_time-rlast_time);
1.157     brouard  1832:       fprintf(ficlog,"\nConsidering the time needed for this last iteration #%d: %ld seconds,\n",*iter,rcurr_time-rlast_time);
1.126     brouard  1833:       for(niterf=10;niterf<=30;niterf+=10){
1.157     brouard  1834:        rforecast_time=rcurr_time+(niterf-*iter)*(rcurr_time-rlast_time);
                   1835:        forecast_time = *localtime(&rforecast_time);
                   1836:        strcpy(strfor,asctime(&forecast_time));
1.126     brouard  1837:        itmp = strlen(strfor);
                   1838:        if(strfor[itmp-1]=='\n')
                   1839:        strfor[itmp-1]='\0';
1.157     brouard  1840:        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);
                   1841:        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  1842:       }
                   1843:     }
1.187     brouard  1844:     for (i=1;i<=n;i++) { /* For each direction i */
                   1845:       for (j=1;j<=n;j++) xit[j]=xi[j][i]; /* Directions stored from previous iteration with previous scales */
1.126     brouard  1846:       fptt=(*fret); 
                   1847: #ifdef DEBUG
1.203     brouard  1848:       printf("fret=%lf, %lf, %lf \n", *fret, *fret, *fret);
                   1849:       fprintf(ficlog, "fret=%lf, %lf, %lf \n", *fret, *fret, *fret);
1.126     brouard  1850: #endif
1.203     brouard  1851:       printf("%d",i);fflush(stdout); /* print direction (parameter) i */
1.126     brouard  1852:       fprintf(ficlog,"%d",i);fflush(ficlog);
1.188     brouard  1853:       linmin(p,xit,n,fret,func); /* Point p[n]. xit[n] has been loaded for direction i as input.*/
                   1854:                                    /* Outputs are fret(new point p) p is updated and xit rescaled */
                   1855:       if (fabs(fptt-(*fret)) > del) { /* We are keeping the max gain on each of the n directions */
                   1856:        /* because that direction will be replaced unless the gain del is small */
                   1857:        /* in comparison with the 'probable' gain, mu^2, with the last average direction. */
                   1858:        /* Unless the n directions are conjugate some gain in the determinant may be obtained */
                   1859:        /* with the new direction. */
1.126     brouard  1860:        del=fabs(fptt-(*fret)); 
                   1861:        ibig=i; 
                   1862:       } 
                   1863: #ifdef DEBUG
                   1864:       printf("%d %.12e",i,(*fret));
                   1865:       fprintf(ficlog,"%d %.12e",i,(*fret));
                   1866:       for (j=1;j<=n;j++) {
                   1867:        xits[j]=FMAX(fabs(p[j]-pt[j]),1.e-5);
                   1868:        printf(" x(%d)=%.12e",j,xit[j]);
                   1869:        fprintf(ficlog," x(%d)=%.12e",j,xit[j]);
                   1870:       }
                   1871:       for(j=1;j<=n;j++) {
1.162     brouard  1872:        printf(" p(%d)=%.12e",j,p[j]);
                   1873:        fprintf(ficlog," p(%d)=%.12e",j,p[j]);
1.126     brouard  1874:       }
                   1875:       printf("\n");
                   1876:       fprintf(ficlog,"\n");
                   1877: #endif
1.187     brouard  1878:     } /* end loop on each direction i */
                   1879:     /* Convergence test will use last linmin estimation (fret) and compare former iteration (fp) */ 
1.188     brouard  1880:     /* But p and xit have been updated at the end of linmin, *fret corresponds to new p, xit  */
1.187     brouard  1881:     /* New value of last point Pn is not computed, P(n-1) */
1.182     brouard  1882:     if (2.0*fabs(fp-(*fret)) <= ftol*(fabs(fp)+fabs(*fret))) { /* Did we reach enough precision? */
1.188     brouard  1883:       /* We could compare with a chi^2. chisquare(0.95,ddl=1)=3.84 */
                   1884:       /* By adding age*age in a model, the new -2LL should be lower and the difference follows a */
                   1885:       /* a chisquare statistics with 1 degree. To be significant at the 95% level, it should have */
                   1886:       /* decreased of more than 3.84  */
                   1887:       /* By adding age*age and V1*age the gain (-2LL) should be more than 5.99 (ddl=2) */
                   1888:       /* By using V1+V2+V3, the gain should be  7.82, compared with basic 1+age. */
                   1889:       /* By adding 10 parameters more the gain should be 18.31 */
                   1890: 
                   1891:       /* Starting the program with initial values given by a former maximization will simply change */
                   1892:       /* the scales of the directions and the directions, because the are reset to canonical directions */
                   1893:       /* Thus the first calls to linmin will give new points and better maximizations until fp-(*fret) is */
                   1894:       /* under the tolerance value. If the tolerance is very small 1.e-9, it could last long.  */
1.126     brouard  1895: #ifdef DEBUG
                   1896:       int k[2],l;
                   1897:       k[0]=1;
                   1898:       k[1]=-1;
                   1899:       printf("Max: %.12e",(*func)(p));
                   1900:       fprintf(ficlog,"Max: %.12e",(*func)(p));
                   1901:       for (j=1;j<=n;j++) {
                   1902:        printf(" %.12e",p[j]);
                   1903:        fprintf(ficlog," %.12e",p[j]);
                   1904:       }
                   1905:       printf("\n");
                   1906:       fprintf(ficlog,"\n");
                   1907:       for(l=0;l<=1;l++) {
                   1908:        for (j=1;j<=n;j++) {
                   1909:          ptt[j]=p[j]+(p[j]-pt[j])*k[l];
                   1910:          printf("l=%d j=%d ptt=%.12e, xits=%.12e, p=%.12e, xit=%.12e", l,j,ptt[j],xits[j],p[j],xit[j]);
                   1911:          fprintf(ficlog,"l=%d j=%d ptt=%.12e, xits=%.12e, p=%.12e, xit=%.12e", l,j,ptt[j],xits[j],p[j],xit[j]);
                   1912:        }
                   1913:        printf("func(ptt)=%.12e, deriv=%.12e\n",(*func)(ptt),(ptt[j]-p[j])/((*func)(ptt)-(*func)(p)));
                   1914:        fprintf(ficlog,"func(ptt)=%.12e, deriv=%.12e\n",(*func)(ptt),(ptt[j]-p[j])/((*func)(ptt)-(*func)(p)));
                   1915:       }
                   1916: #endif
                   1917: 
                   1918: 
                   1919:       free_vector(xit,1,n); 
                   1920:       free_vector(xits,1,n); 
                   1921:       free_vector(ptt,1,n); 
                   1922:       free_vector(pt,1,n); 
                   1923:       return; 
1.192     brouard  1924:     } /* enough precision */ 
1.126     brouard  1925:     if (*iter == ITMAX) nrerror("powell exceeding maximum iterations."); 
1.181     brouard  1926:     for (j=1;j<=n;j++) { /* Computes the extrapolated point P_0 + 2 (P_n-P_0) */
1.126     brouard  1927:       ptt[j]=2.0*p[j]-pt[j]; 
                   1928:       xit[j]=p[j]-pt[j]; 
                   1929:       pt[j]=p[j]; 
                   1930:     } 
1.181     brouard  1931:     fptt=(*func)(ptt); /* f_3 */
1.192     brouard  1932: #ifdef POWELLF1F3
                   1933: #else
1.161     brouard  1934:     if (fptt < fp) { /* If extrapolated point is better, decide if we keep that new direction or not */
1.192     brouard  1935: #endif
1.162     brouard  1936:       /* (x1 f1=fp), (x2 f2=*fret), (x3 f3=fptt), (xm fm) */
1.161     brouard  1937:       /* From x1 (P0) distance of x2 is at h and x3 is 2h */
1.162     brouard  1938:       /* Let f"(x2) be the 2nd derivative equal everywhere.  */
                   1939:       /* Then the parabolic through (x1,f1), (x2,f2) and (x3,f3) */
                   1940:       /* will reach at f3 = fm + h^2/2 f"m  ; f" = (f1 -2f2 +f3 ) / h**2 */
1.181     brouard  1941:       /* Conditional for using this new direction is that mu^2 = (f1-2f2+f3)^2 /2 < del */
1.161     brouard  1942:       /* t=2.0*(fp-2.0*(*fret)+fptt)*SQR(fp-(*fret)-del)-del*SQR(fp-fptt); */
1.183     brouard  1943: #ifdef NRCORIGINAL
                   1944:       t=2.0*(fp-2.0*(*fret)+fptt)*SQR(fp-(*fret)-del)- del*SQR(fp-fptt); /* Original Numerical Recipes in C*/
                   1945: #else
                   1946:       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  1947:       t= t- del*SQR(fp-fptt);
1.183     brouard  1948: #endif
1.202     brouard  1949:       directest = fp-2.0*(*fret)+fptt - 2.0 * del; /* If delta was big enough we change it for a new direction */
1.161     brouard  1950: #ifdef DEBUG
1.181     brouard  1951:       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);
                   1952:       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  1953:       printf("t3= %.12lf, t4= %.12lf, t3*= %.12lf, t4*= %.12lf\n",SQR(fp-(*fret)-del),SQR(fp-fptt),
                   1954:             (fp-(*fret)-del)*(fp-(*fret)-del),(fp-fptt)*(fp-fptt));
                   1955:       fprintf(ficlog,"t3= %.12lf, t4= %.12lf, t3*= %.12lf, t4*= %.12lf\n",SQR(fp-(*fret)-del),SQR(fp-fptt),
                   1956:             (fp-(*fret)-del)*(fp-(*fret)-del),(fp-fptt)*(fp-fptt));
                   1957:       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);
                   1958:       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);
                   1959: #endif
1.183     brouard  1960: #ifdef POWELLORIGINAL
                   1961:       if (t < 0.0) { /* Then we use it for new direction */
                   1962: #else
1.182     brouard  1963:       if (directest*t < 0.0) { /* Contradiction between both tests */
1.202     brouard  1964:        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  1965:         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  1966:         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  1967:         fprintf(ficlog,"f1-2f2+f3= %.12lf, f1-f2-del= %.12lf, f1-f3= %.12lf\n",fp-2.0*(*fret)+fptt, fp -(*fret) -del, fp-fptt);
                   1968:       } 
1.181     brouard  1969:       if (directest < 0.0) { /* Then we use it for new direction */
                   1970: #endif
1.191     brouard  1971: #ifdef DEBUGLINMIN
                   1972:        printf("Before linmin in direction P%d-P0\n",n);
                   1973:        for (j=1;j<=n;j++) { 
1.202     brouard  1974:          printf(" Before xit[%d]= %12.7f p[%d]= %12.7f",j,xit[j],j,p[j]);
                   1975:          fprintf(ficlog," Before xit[%d]= %12.7f p[%d]= %12.7f",j,xit[j],j,p[j]);
                   1976:          if(j % ncovmodel == 0){
1.191     brouard  1977:            printf("\n");
1.202     brouard  1978:            fprintf(ficlog,"\n");
                   1979:          }
1.191     brouard  1980:        }
                   1981: #endif
1.187     brouard  1982:        linmin(p,xit,n,fret,func); /* computes minimum on the extrapolated direction: changes p and rescales xit.*/
1.191     brouard  1983: #ifdef DEBUGLINMIN
                   1984:        for (j=1;j<=n;j++) { 
                   1985:          printf("After xit[%d]= %12.7f p[%d]= %12.7f",j,xit[j],j,p[j]);
1.202     brouard  1986:          fprintf(ficlog,"After xit[%d]= %12.7f p[%d]= %12.7f",j,xit[j],j,p[j]);
                   1987:          if(j % ncovmodel == 0){
1.191     brouard  1988:            printf("\n");
1.202     brouard  1989:            fprintf(ficlog,"\n");
                   1990:          }
1.191     brouard  1991:        }
                   1992: #endif
1.126     brouard  1993:        for (j=1;j<=n;j++) { 
1.181     brouard  1994:          xi[j][ibig]=xi[j][n]; /* Replace direction with biggest decrease by last direction n */
                   1995:          xi[j][n]=xit[j];      /* and this nth direction by the by the average p_0 p_n */
1.126     brouard  1996:        }
1.181     brouard  1997:        printf("Gaining to use new average direction of P0 P%d instead of biggest increase direction %d :\n",n,ibig);
                   1998:        fprintf(ficlog,"Gaining to use new average direction of P0 P%d instead of biggest increase direction %d :\n",n,ibig);
1.161     brouard  1999: 
1.126     brouard  2000: #ifdef DEBUG
1.164     brouard  2001:        printf("Direction changed  last moved %d in place of ibig=%d, new last is the average:\n",n,ibig);
                   2002:        fprintf(ficlog,"Direction changed  last moved %d in place of ibig=%d, new last is the average:\n",n,ibig);
1.126     brouard  2003:        for(j=1;j<=n;j++){
                   2004:          printf(" %.12e",xit[j]);
                   2005:          fprintf(ficlog," %.12e",xit[j]);
                   2006:        }
                   2007:        printf("\n");
                   2008:        fprintf(ficlog,"\n");
                   2009: #endif
1.192     brouard  2010:       } /* end of t or directest negative */
                   2011: #ifdef POWELLF1F3
                   2012: #else
1.162     brouard  2013:     } /* end if (fptt < fp)  */
1.192     brouard  2014: #endif
                   2015:   } /* loop iteration */ 
1.126     brouard  2016: } 
                   2017: 
                   2018: /**** Prevalence limit (stable or period prevalence)  ****************/
                   2019: 
1.203     brouard  2020: double **prevalim(double **prlim, int nlstate, double x[], double age, double **oldm, double **savm, double ftolpl, int *ncvyear, int ij)
1.126     brouard  2021: {
                   2022:   /* Computes the prevalence limit in each live state at age x by left multiplying the unit
1.203     brouard  2023:      matrix by transitions matrix until convergence is reached with precision ftolpl */
1.206     brouard  2024:   /* Wx= Wx-1 Px-1= Wx-2 Px-2 Px-1  = Wx-n Px-n ... Px-2 Px-1 I */
                   2025:   /* Wx is row vector: population in state 1, population in state 2, population dead */
                   2026:   /* or prevalence in state 1, prevalence in state 2, 0 */
                   2027:   /* newm is the matrix after multiplications, its rows are identical at a factor */
                   2028:   /* Initial matrix pimij */
                   2029:   /* {0.85204250825084937, 0.13044499163996345, 0.017512500109187184, */
                   2030:   /* 0.090851990222114765, 0.88271245433047185, 0.026435555447413338, */
                   2031:   /*  0,                   0                  , 1} */
                   2032:   /*
                   2033:    * and after some iteration: */
                   2034:   /* {0.45504275246439968, 0.42731458730878791, 0.11764266022681241, */
                   2035:   /*  0.45201005341706885, 0.42865420071559901, 0.11933574586733192, */
                   2036:   /*  0,                   0                  , 1} */
                   2037:   /* And prevalence by suppressing the deaths are close to identical rows in prlim: */
                   2038:   /* {0.51571254859325999, 0.4842874514067399, */
                   2039:   /*  0.51326036147820708, 0.48673963852179264} */
                   2040:   /* If we start from prlim again, prlim tends to a constant matrix */
                   2041: 
1.126     brouard  2042:   int i, ii,j,k;
1.209     brouard  2043:   double *min, *max, *meandiff, maxmax,sumnew=0.;
1.145     brouard  2044:   /* double **matprod2(); */ /* test */
1.131     brouard  2045:   double **out, cov[NCOVMAX+1], **pmij();
1.126     brouard  2046:   double **newm;
1.209     brouard  2047:   double agefin, delaymax=200. ; /* 100 Max number of years to converge */
1.203     brouard  2048:   int ncvloop=0;
1.169     brouard  2049:   
1.209     brouard  2050:   min=vector(1,nlstate);
                   2051:   max=vector(1,nlstate);
                   2052:   meandiff=vector(1,nlstate);
                   2053: 
1.126     brouard  2054:   for (ii=1;ii<=nlstate+ndeath;ii++)
                   2055:     for (j=1;j<=nlstate+ndeath;j++){
                   2056:       oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   2057:     }
1.169     brouard  2058:   
                   2059:   cov[1]=1.;
                   2060:   
                   2061:   /* Even if hstepm = 1, at least one multiplication by the unit matrix */
1.202     brouard  2062:   /* Start at agefin= age, computes the matrix of passage and loops decreasing agefin until convergence is reached */
1.126     brouard  2063:   for(agefin=age-stepm/YEARM; agefin>=age-delaymax; agefin=agefin-stepm/YEARM){
1.202     brouard  2064:     ncvloop++;
1.126     brouard  2065:     newm=savm;
                   2066:     /* Covariates have to be included here again */
1.138     brouard  2067:     cov[2]=agefin;
1.187     brouard  2068:     if(nagesqr==1)
                   2069:       cov[3]= agefin*agefin;;
1.138     brouard  2070:     for (k=1; k<=cptcovn;k++) {
1.200     brouard  2071:       /* cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(ij,Tvar[k])]; */
                   2072:       cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(ij,k)];
1.198     brouard  2073:       /* 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  2074:     }
1.186     brouard  2075:     /*wrong? for (k=1; k<=cptcovage;k++) cov[2+Tage[k]]=cov[2+Tage[k]]*cov[2]; */
1.200     brouard  2076:     /* for (k=1; k<=cptcovage;k++) cov[2+nagesqr+Tage[k]]=nbcode[Tvar[k]][codtabm(ij,Tvar[k])]*cov[2]; */
                   2077:     for (k=1; k<=cptcovage;k++) cov[2+nagesqr+Tage[k]]=nbcode[Tvar[k]][codtabm(ij,k)]*cov[2];
1.186     brouard  2078:     for (k=1; k<=cptcovprod;k++) /* Useless */
1.200     brouard  2079:       /* cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,Tvard[k][1])] * nbcode[Tvard[k][2]][codtabm(ij,Tvard[k][2])]; */
                   2080:       cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,k)] * nbcode[Tvard[k][2]][codtabm(ij,k)];
1.138     brouard  2081:     
                   2082:     /*printf("ij=%d cptcovprod=%d tvar=%d ", ij, cptcovprod, Tvar[1]);*/
                   2083:     /*printf("ij=%d cov[3]=%lf cov[4]=%lf \n",ij, cov[3],cov[4]);*/
                   2084:     /*printf("ij=%d cov[3]=%lf \n",ij, cov[3]);*/
1.145     brouard  2085:     /* savm=pmij(pmmij,cov,ncovmodel,x,nlstate); */
                   2086:     /* out=matprod2(newm, pmij(pmmij,cov,ncovmodel,x,nlstate),1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, oldm); /\* Bug Valgrind *\/ */
1.142     brouard  2087:     out=matprod2(newm, pmij(pmmij,cov,ncovmodel,x,nlstate),1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, oldm); /* Bug Valgrind */
1.138     brouard  2088:     
1.126     brouard  2089:     savm=oldm;
                   2090:     oldm=newm;
1.209     brouard  2091: 
                   2092:     for(j=1; j<=nlstate; j++){
                   2093:       max[j]=0.;
                   2094:       min[j]=1.;
                   2095:     }
                   2096:     for(i=1;i<=nlstate;i++){
                   2097:       sumnew=0;
                   2098:       for(k=1; k<=ndeath; k++) sumnew+=newm[i][nlstate+k];
                   2099:       for(j=1; j<=nlstate; j++){ 
                   2100:        prlim[i][j]= newm[i][j]/(1-sumnew);
                   2101:        max[j]=FMAX(max[j],prlim[i][j]);
                   2102:        min[j]=FMIN(min[j],prlim[i][j]);
                   2103:       }
                   2104:     }
                   2105: 
1.126     brouard  2106:     maxmax=0.;
1.209     brouard  2107:     for(j=1; j<=nlstate; j++){
                   2108:       meandiff[j]=(max[j]-min[j])/(max[j]+min[j])*2.; /* mean difference for each column */
                   2109:       maxmax=FMAX(maxmax,meandiff[j]);
                   2110:       /* 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  2111:     } /* j loop */
1.203     brouard  2112:     *ncvyear= (int)age- (int)agefin;
1.208     brouard  2113:     /* 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  2114:     if(maxmax < ftolpl){
1.209     brouard  2115:       /* printf("maxmax=%lf ncvloop=%ld, age=%d, agefin=%d ncvyear=%d \n", maxmax, ncvloop, (int)age, (int)agefin, *ncvyear); */
                   2116:       free_vector(min,1,nlstate);
                   2117:       free_vector(max,1,nlstate);
                   2118:       free_vector(meandiff,1,nlstate);
1.126     brouard  2119:       return prlim;
                   2120:     }
1.169     brouard  2121:   } /* age loop */
1.208     brouard  2122:     /* After some age loop it doesn't converge */
1.209     brouard  2123:   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  2124: 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  2125:   /* 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); */
                   2126:   free_vector(min,1,nlstate);
                   2127:   free_vector(max,1,nlstate);
                   2128:   free_vector(meandiff,1,nlstate);
1.208     brouard  2129:   
1.169     brouard  2130:   return prlim; /* should not reach here */
1.126     brouard  2131: }
                   2132: 
                   2133: /*************** transition probabilities ***************/ 
                   2134: 
                   2135: double **pmij(double **ps, double *cov, int ncovmodel, double *x, int nlstate )
                   2136: {
1.138     brouard  2137:   /* According to parameters values stored in x and the covariate's values stored in cov,
                   2138:      computes the probability to be observed in state j being in state i by appying the
                   2139:      model to the ncovmodel covariates (including constant and age).
                   2140:      lnpijopii=ln(pij/pii)= aij+bij*age+cij*v1+dij*v2+... = sum_nc=1^ncovmodel xij(nc)*cov[nc]
                   2141:      and, according on how parameters are entered, the position of the coefficient xij(nc) of the
                   2142:      ncth covariate in the global vector x is given by the formula:
                   2143:      j<i nc+((i-1)*(nlstate+ndeath-1)+j-1)*ncovmodel
                   2144:      j>=i nc + ((i-1)*(nlstate+ndeath-1)+(j-2))*ncovmodel
                   2145:      Computes ln(pij/pii) (lnpijopii), deduces pij/pii by exponentiation,
                   2146:      sums on j different of i to get 1-pii/pii, deduces pii, and then all pij.
                   2147:      Outputs ps[i][j] the probability to be observed in j being in j according to
                   2148:      the values of the covariates cov[nc] and corresponding parameter values x[nc+shiftij]
                   2149:   */
                   2150:   double s1, lnpijopii;
1.126     brouard  2151:   /*double t34;*/
1.164     brouard  2152:   int i,j, nc, ii, jj;
1.126     brouard  2153: 
                   2154:     for(i=1; i<= nlstate; i++){
                   2155:       for(j=1; j<i;j++){
1.138     brouard  2156:        for (nc=1, lnpijopii=0.;nc <=ncovmodel; nc++){
                   2157:          /*lnpijopii += param[i][j][nc]*cov[nc];*/
                   2158:          lnpijopii += x[nc+((i-1)*(nlstate+ndeath-1)+j-1)*ncovmodel]*cov[nc];
                   2159: /*      printf("Int j<i s1=%.17e, lnpijopii=%.17e\n",s1,lnpijopii); */
1.126     brouard  2160:        }
1.138     brouard  2161:        ps[i][j]=lnpijopii; /* In fact ln(pij/pii) */
                   2162: /*     printf("s1=%.17e, lnpijopii=%.17e\n",s1,lnpijopii); */
1.126     brouard  2163:       }
                   2164:       for(j=i+1; j<=nlstate+ndeath;j++){
1.138     brouard  2165:        for (nc=1, lnpijopii=0.;nc <=ncovmodel; nc++){
                   2166:          /*lnpijopii += x[(i-1)*nlstate*ncovmodel+(j-2)*ncovmodel+nc+(i-1)*(ndeath-1)*ncovmodel]*cov[nc];*/
                   2167:          lnpijopii += x[nc + ((i-1)*(nlstate+ndeath-1)+(j-2))*ncovmodel]*cov[nc];
                   2168: /*       printf("Int j>i s1=%.17e, lnpijopii=%.17e %lx %lx\n",s1,lnpijopii,s1,lnpijopii); */
1.126     brouard  2169:        }
1.138     brouard  2170:        ps[i][j]=lnpijopii; /* In fact ln(pij/pii) */
1.126     brouard  2171:       }
                   2172:     }
                   2173:     
                   2174:     for(i=1; i<= nlstate; i++){
                   2175:       s1=0;
1.131     brouard  2176:       for(j=1; j<i; j++){
1.138     brouard  2177:        s1+=exp(ps[i][j]); /* In fact sums pij/pii */
1.131     brouard  2178:        /*printf("debug1 %d %d ps=%lf exp(ps)=%lf s1+=%lf\n",i,j,ps[i][j],exp(ps[i][j]),s1); */
                   2179:       }
                   2180:       for(j=i+1; j<=nlstate+ndeath; j++){
1.138     brouard  2181:        s1+=exp(ps[i][j]); /* In fact sums pij/pii */
1.131     brouard  2182:        /*printf("debug2 %d %d ps=%lf exp(ps)=%lf s1+=%lf\n",i,j,ps[i][j],exp(ps[i][j]),s1); */
                   2183:       }
1.138     brouard  2184:       /* s1= sum_{j<>i} pij/pii=(1-pii)/pii and thus pii is known from s1 */
1.126     brouard  2185:       ps[i][i]=1./(s1+1.);
1.138     brouard  2186:       /* Computing other pijs */
1.126     brouard  2187:       for(j=1; j<i; j++)
                   2188:        ps[i][j]= exp(ps[i][j])*ps[i][i];
                   2189:       for(j=i+1; j<=nlstate+ndeath; j++)
                   2190:        ps[i][j]= exp(ps[i][j])*ps[i][i];
                   2191:       /* ps[i][nlstate+1]=1.-s1- ps[i][i];*/ /* Sum should be 1 */
                   2192:     } /* end i */
                   2193:     
                   2194:     for(ii=nlstate+1; ii<= nlstate+ndeath; ii++){
                   2195:       for(jj=1; jj<= nlstate+ndeath; jj++){
                   2196:        ps[ii][jj]=0;
                   2197:        ps[ii][ii]=1;
                   2198:       }
                   2199:     }
                   2200:     
1.145     brouard  2201:     
                   2202:     /* for(ii=1; ii<= nlstate+ndeath; ii++){ */
                   2203:     /*   for(jj=1; jj<= nlstate+ndeath; jj++){ */
                   2204:     /*         printf(" pmij  ps[%d][%d]=%lf ",ii,jj,ps[ii][jj]); */
                   2205:     /*   } */
                   2206:     /*   printf("\n "); */
                   2207:     /* } */
                   2208:     /* printf("\n ");printf("%lf ",cov[2]);*/
                   2209:     /*
1.126     brouard  2210:       for(i=1; i<= npar; i++) printf("%f ",x[i]);
                   2211:       goto end;*/
                   2212:     return ps;
                   2213: }
                   2214: 
                   2215: /**************** Product of 2 matrices ******************/
                   2216: 
1.145     brouard  2217: double **matprod2(double **out, double **in,int nrl, int nrh, int ncl, int nch, int ncolol, int ncoloh, double **b)
1.126     brouard  2218: {
                   2219:   /* Computes the matrix product of in(1,nrh-nrl+1)(1,nch-ncl+1) times
                   2220:      b(1,nch-ncl+1)(1,ncoloh-ncolol+1) into out(...) */
                   2221:   /* in, b, out are matrice of pointers which should have been initialized 
                   2222:      before: only the contents of out is modified. The function returns
                   2223:      a pointer to pointers identical to out */
1.145     brouard  2224:   int i, j, k;
1.126     brouard  2225:   for(i=nrl; i<= nrh; i++)
1.145     brouard  2226:     for(k=ncolol; k<=ncoloh; k++){
                   2227:       out[i][k]=0.;
                   2228:       for(j=ncl; j<=nch; j++)
                   2229:        out[i][k] +=in[i][j]*b[j][k];
                   2230:     }
1.126     brouard  2231:   return out;
                   2232: }
                   2233: 
                   2234: 
                   2235: /************* Higher Matrix Product ***************/
                   2236: 
                   2237: double ***hpxij(double ***po, int nhstepm, double age, int hstepm, double *x, int nlstate, int stepm, double **oldm, double **savm, int ij )
                   2238: {
                   2239:   /* Computes the transition matrix starting at age 'age' over 
                   2240:      'nhstepm*hstepm*stepm' months (i.e. until
                   2241:      age (in years)  age+nhstepm*hstepm*stepm/12) by multiplying 
                   2242:      nhstepm*hstepm matrices. 
                   2243:      Output is stored in matrix po[i][j][h] for h every 'hstepm' step 
                   2244:      (typically every 2 years instead of every month which is too big 
                   2245:      for the memory).
                   2246:      Model is determined by parameters x and covariates have to be 
                   2247:      included manually here. 
                   2248: 
                   2249:      */
                   2250: 
                   2251:   int i, j, d, h, k;
1.131     brouard  2252:   double **out, cov[NCOVMAX+1];
1.126     brouard  2253:   double **newm;
1.187     brouard  2254:   double agexact;
1.214     brouard  2255:   double agebegin, ageend;
1.126     brouard  2256: 
                   2257:   /* Hstepm could be zero and should return the unit matrix */
                   2258:   for (i=1;i<=nlstate+ndeath;i++)
                   2259:     for (j=1;j<=nlstate+ndeath;j++){
                   2260:       oldm[i][j]=(i==j ? 1.0 : 0.0);
                   2261:       po[i][j][0]=(i==j ? 1.0 : 0.0);
                   2262:     }
                   2263:   /* Even if hstepm = 1, at least one multiplication by the unit matrix */
                   2264:   for(h=1; h <=nhstepm; h++){
                   2265:     for(d=1; d <=hstepm; d++){
                   2266:       newm=savm;
                   2267:       /* Covariates have to be included here again */
                   2268:       cov[1]=1.;
1.214     brouard  2269:       agexact=age+((h-1)*hstepm + (d-1))*stepm/YEARM; /* age just before transition */
1.187     brouard  2270:       cov[2]=agexact;
                   2271:       if(nagesqr==1)
                   2272:        cov[3]= agexact*agexact;
1.131     brouard  2273:       for (k=1; k<=cptcovn;k++) 
1.200     brouard  2274:        cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(ij,k)];
                   2275:        /* cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(ij,Tvar[k])]; */
1.186     brouard  2276:       for (k=1; k<=cptcovage;k++) /* Should start at cptcovn+1 */
                   2277:        /* cov[2+Tage[k]]=cov[2+Tage[k]]*cov[2]; */
1.200     brouard  2278:        cov[2+nagesqr+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(ij,k)]*cov[2];
                   2279:        /* cov[2+nagesqr+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(ij,Tvar[Tage[k]])]*cov[2]; */
1.145     brouard  2280:       for (k=1; k<=cptcovprod;k++) /* Useless because included in cptcovn */
1.200     brouard  2281:        cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,k)]*nbcode[Tvard[k][2]][codtabm(ij,k)];
                   2282:        /* 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  2283: 
                   2284: 
                   2285:       /*printf("hxi cptcov=%d cptcode=%d\n",cptcov,cptcode);*/
                   2286:       /*printf("h=%d d=%d age=%f cov=%f\n",h,d,age,cov[2]);*/
                   2287:       out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, 
                   2288:                   pmij(pmmij,cov,ncovmodel,x,nlstate));
                   2289:       savm=oldm;
                   2290:       oldm=newm;
                   2291:     }
                   2292:     for(i=1; i<=nlstate+ndeath; i++)
                   2293:       for(j=1;j<=nlstate+ndeath;j++) {
                   2294:        po[i][j][h]=newm[i][j];
1.128     brouard  2295:        /*if(h==nhstepm) printf("po[%d][%d][%d]=%f ",i,j,h,po[i][j][h]);*/
1.126     brouard  2296:       }
1.128     brouard  2297:     /*printf("h=%d ",h);*/
1.126     brouard  2298:   } /* end h */
1.128     brouard  2299: /*     printf("\n H=%d \n",h); */
1.126     brouard  2300:   return po;
                   2301: }
                   2302: 
1.162     brouard  2303: #ifdef NLOPT
                   2304:   double  myfunc(unsigned n, const double *p1, double *grad, void *pd){
                   2305:   double fret;
                   2306:   double *xt;
                   2307:   int j;
                   2308:   myfunc_data *d2 = (myfunc_data *) pd;
                   2309: /* xt = (p1-1); */
                   2310:   xt=vector(1,n); 
                   2311:   for (j=1;j<=n;j++)   xt[j]=p1[j-1]; /* xt[1]=p1[0] */
                   2312: 
                   2313:   fret=(d2->function)(xt); /*  p xt[1]@8 is fine */
                   2314:   /* fret=(*func)(xt); /\*  p xt[1]@8 is fine *\/ */
                   2315:   printf("Function = %.12lf ",fret);
                   2316:   for (j=1;j<=n;j++) printf(" %d %.8lf", j, xt[j]); 
                   2317:   printf("\n");
                   2318:  free_vector(xt,1,n);
                   2319:   return fret;
                   2320: }
                   2321: #endif
1.126     brouard  2322: 
                   2323: /*************** log-likelihood *************/
                   2324: double func( double *x)
                   2325: {
                   2326:   int i, ii, j, k, mi, d, kk;
1.131     brouard  2327:   double l, ll[NLSTATEMAX+1], cov[NCOVMAX+1];
1.126     brouard  2328:   double **out;
                   2329:   double sw; /* Sum of weights */
                   2330:   double lli; /* Individual log likelihood */
                   2331:   int s1, s2;
                   2332:   double bbh, survp;
                   2333:   long ipmx;
1.187     brouard  2334:   double agexact;
1.126     brouard  2335:   /*extern weight */
                   2336:   /* We are differentiating ll according to initial status */
                   2337:   /*  for (i=1;i<=npar;i++) printf("%f ", x[i]);*/
                   2338:   /*for(i=1;i<imx;i++) 
                   2339:     printf(" %d\n",s[4][i]);
                   2340:   */
1.162     brouard  2341: 
                   2342:   ++countcallfunc;
                   2343: 
1.126     brouard  2344:   cov[1]=1.;
                   2345: 
                   2346:   for(k=1; k<=nlstate; k++) ll[k]=0.;
                   2347: 
                   2348:   if(mle==1){
                   2349:     for (i=1,ipmx=0, sw=0.; i<=imx; i++){
1.138     brouard  2350:       /* Computes the values of the ncovmodel covariates of the model
                   2351:         depending if the covariates are fixed or variying (age dependent) and stores them in cov[]
                   2352:         Then computes with function pmij which return a matrix p[i][j] giving the elementary probability
                   2353:         to be observed in j being in i according to the model.
                   2354:        */
1.145     brouard  2355:       for (k=1; k<=cptcovn;k++){ /* Simple and product covariates without age* products */
1.187     brouard  2356:          cov[2+nagesqr+k]=covar[Tvar[k]][i];
1.145     brouard  2357:       }
1.137     brouard  2358:       /* In model V2+V1*V4+age*V3+V3*V2 Tvar[1] is V2, Tvar[2=V1*V4] 
1.138     brouard  2359:         is 6, Tvar[3=age*V3] should not be computed because of age Tvar[4=V3*V2] 
1.137     brouard  2360:         has been calculated etc */
1.126     brouard  2361:       for(mi=1; mi<= wav[i]-1; mi++){
                   2362:        for (ii=1;ii<=nlstate+ndeath;ii++)
                   2363:          for (j=1;j<=nlstate+ndeath;j++){
                   2364:            oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   2365:            savm[ii][j]=(ii==j ? 1.0 : 0.0);
                   2366:          }
                   2367:        for(d=0; d<dh[mi][i]; d++){
                   2368:          newm=savm;
1.187     brouard  2369:          agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;
                   2370:          cov[2]=agexact;
                   2371:          if(nagesqr==1)
                   2372:            cov[3]= agexact*agexact;
1.126     brouard  2373:          for (kk=1; kk<=cptcovage;kk++) {
1.187     brouard  2374:            cov[Tage[kk]+2+nagesqr]=covar[Tvar[Tage[kk]]][i]*agexact; /* Tage[kk] gives the data-covariate associated with age */
1.126     brouard  2375:          }
                   2376:          out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
                   2377:                       1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
                   2378:          savm=oldm;
                   2379:          oldm=newm;
                   2380:        } /* end mult */
                   2381:       
                   2382:        /*lli=log(out[s[mw[mi][i]][i]][s[mw[mi+1][i]][i]]);*/ /* Original formula */
                   2383:        /* But now since version 0.9 we anticipate for bias at large stepm.
                   2384:         * If stepm is larger than one month (smallest stepm) and if the exact delay 
                   2385:         * (in months) between two waves is not a multiple of stepm, we rounded to 
                   2386:         * the nearest (and in case of equal distance, to the lowest) interval but now
                   2387:         * we keep into memory the bias bh[mi][i] and also the previous matrix product
                   2388:         * (i.e to dh[mi][i]-1) saved in 'savm'. Then we inter(extra)polate the
                   2389:         * probability in order to take into account the bias as a fraction of the way
                   2390:         * from savm to out if bh is negative or even beyond if bh is positive. bh varies
                   2391:         * -stepm/2 to stepm/2 .
                   2392:         * For stepm=1 the results are the same as for previous versions of Imach.
                   2393:         * For stepm > 1 the results are less biased than in previous versions. 
                   2394:         */
                   2395:        s1=s[mw[mi][i]][i];
                   2396:        s2=s[mw[mi+1][i]][i];
                   2397:        bbh=(double)bh[mi][i]/(double)stepm; 
                   2398:        /* bias bh is positive if real duration
                   2399:         * is higher than the multiple of stepm and negative otherwise.
                   2400:         */
                   2401:        /* lli= (savm[s1][s2]>1.e-8 ?(1.+bbh)*log(out[s1][s2])- bbh*log(savm[s1][s2]):log((1.+bbh)*out[s1][s2]));*/
                   2402:        if( s2 > nlstate){ 
                   2403:          /* i.e. if s2 is a death state and if the date of death is known 
                   2404:             then the contribution to the likelihood is the probability to 
                   2405:             die between last step unit time and current  step unit time, 
                   2406:             which is also equal to probability to die before dh 
                   2407:             minus probability to die before dh-stepm . 
                   2408:             In version up to 0.92 likelihood was computed
                   2409:        as if date of death was unknown. Death was treated as any other
                   2410:        health state: the date of the interview describes the actual state
                   2411:        and not the date of a change in health state. The former idea was
                   2412:        to consider that at each interview the state was recorded
                   2413:        (healthy, disable or death) and IMaCh was corrected; but when we
                   2414:        introduced the exact date of death then we should have modified
                   2415:        the contribution of an exact death to the likelihood. This new
                   2416:        contribution is smaller and very dependent of the step unit
                   2417:        stepm. It is no more the probability to die between last interview
                   2418:        and month of death but the probability to survive from last
                   2419:        interview up to one month before death multiplied by the
                   2420:        probability to die within a month. Thanks to Chris
                   2421:        Jackson for correcting this bug.  Former versions increased
                   2422:        mortality artificially. The bad side is that we add another loop
                   2423:        which slows down the processing. The difference can be up to 10%
                   2424:        lower mortality.
                   2425:          */
1.183     brouard  2426:        /* If, at the beginning of the maximization mostly, the
                   2427:           cumulative probability or probability to be dead is
                   2428:           constant (ie = 1) over time d, the difference is equal to
                   2429:           0.  out[s1][3] = savm[s1][3]: probability, being at state
                   2430:           s1 at precedent wave, to be dead a month before current
                   2431:           wave is equal to probability, being at state s1 at
                   2432:           precedent wave, to be dead at mont of the current
                   2433:           wave. Then the observed probability (that this person died)
                   2434:           is null according to current estimated parameter. In fact,
                   2435:           it should be very low but not zero otherwise the log go to
                   2436:           infinity.
                   2437:        */
                   2438: /* #ifdef INFINITYORIGINAL */
                   2439: /*         lli=log(out[s1][s2] - savm[s1][s2]); */
                   2440: /* #else */
                   2441: /*       if ((out[s1][s2] - savm[s1][s2]) < mytinydouble)  */
                   2442: /*         lli=log(mytinydouble); */
                   2443: /*       else */
                   2444: /*         lli=log(out[s1][s2] - savm[s1][s2]); */
                   2445: /* #endif */
                   2446:            lli=log(out[s1][s2] - savm[s1][s2]);
1.126     brouard  2447: 
                   2448:        } else if  (s2==-2) {
                   2449:          for (j=1,survp=0. ; j<=nlstate; j++) 
                   2450:            survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j];
                   2451:          /*survp += out[s1][j]; */
                   2452:          lli= log(survp);
                   2453:        }
                   2454:        
                   2455:        else if  (s2==-4) { 
                   2456:          for (j=3,survp=0. ; j<=nlstate; j++)  
                   2457:            survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j];
                   2458:          lli= log(survp); 
                   2459:        } 
                   2460: 
                   2461:        else if  (s2==-5) { 
                   2462:          for (j=1,survp=0. ; j<=2; j++)  
                   2463:            survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j];
                   2464:          lli= log(survp); 
                   2465:        } 
                   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]);
                   2578:        }else{
                   2579:          lli=log(out[s[mw[mi][i]][i]][s[mw[mi+1][i]][i]]); /* Original formula */
                   2580:        }
                   2581:        ipmx +=1;
                   2582:        sw += weight[i];
                   2583:        ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
                   2584: /*     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]); */
                   2585:       } /* end of wave */
                   2586:     } /* end of individual */
                   2587:   }else{  /* ml=5 no inter-extrapolation no jackson =0.8a */
                   2588:     for (i=1,ipmx=0, sw=0.; i<=imx; i++){
1.187     brouard  2589:       for (k=1; k<=cptcovn;k++) cov[2+nagesqr+k]=covar[Tvar[k]][i];
1.126     brouard  2590:       for(mi=1; mi<= wav[i]-1; mi++){
                   2591:        for (ii=1;ii<=nlstate+ndeath;ii++)
                   2592:          for (j=1;j<=nlstate+ndeath;j++){
                   2593:            oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   2594:            savm[ii][j]=(ii==j ? 1.0 : 0.0);
                   2595:          }
                   2596:        for(d=0; d<dh[mi][i]; d++){
                   2597:          newm=savm;
1.187     brouard  2598:          agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;
                   2599:          cov[2]=agexact;
                   2600:          if(nagesqr==1)
                   2601:            cov[3]= agexact*agexact;
1.126     brouard  2602:          for (kk=1; kk<=cptcovage;kk++) {
1.187     brouard  2603:            cov[Tage[kk]+2+nagesqr]=covar[Tvar[Tage[kk]]][i]*agexact;
1.126     brouard  2604:          }
                   2605:        
                   2606:          out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
                   2607:                       1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
                   2608:          savm=oldm;
                   2609:          oldm=newm;
                   2610:        } /* end mult */
                   2611:       
                   2612:        s1=s[mw[mi][i]][i];
                   2613:        s2=s[mw[mi+1][i]][i];
                   2614:        lli=log(out[s[mw[mi][i]][i]][s[mw[mi+1][i]][i]]); /* Original formula */
                   2615:        ipmx +=1;
                   2616:        sw += weight[i];
                   2617:        ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
                   2618:        /*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]);*/
                   2619:       } /* end of wave */
                   2620:     } /* end of individual */
                   2621:   } /* End of if */
                   2622:   for(k=1,l=0.; k<=nlstate; k++) l += ll[k];
                   2623:   /* printf("l1=%f l2=%f ",ll[1],ll[2]); */
                   2624:   l= l*ipmx/sw; /* To get the same order of magnitude as if weight=1 for every body */
                   2625:   return -l;
                   2626: }
                   2627: 
                   2628: /*************** log-likelihood *************/
                   2629: double funcone( double *x)
                   2630: {
                   2631:   /* Same as likeli but slower because of a lot of printf and if */
                   2632:   int i, ii, j, k, mi, d, kk;
1.131     brouard  2633:   double l, ll[NLSTATEMAX+1], cov[NCOVMAX+1];
1.126     brouard  2634:   double **out;
                   2635:   double lli; /* Individual log likelihood */
                   2636:   double llt;
                   2637:   int s1, s2;
                   2638:   double bbh, survp;
1.187     brouard  2639:   double agexact;
1.214     brouard  2640:   double agebegin, ageend;
1.126     brouard  2641:   /*extern weight */
                   2642:   /* We are differentiating ll according to initial status */
                   2643:   /*  for (i=1;i<=npar;i++) printf("%f ", x[i]);*/
                   2644:   /*for(i=1;i<imx;i++) 
                   2645:     printf(" %d\n",s[4][i]);
                   2646:   */
                   2647:   cov[1]=1.;
                   2648: 
                   2649:   for(k=1; k<=nlstate; k++) ll[k]=0.;
                   2650: 
                   2651:   for (i=1,ipmx=0, sw=0.; i<=imx; i++){
1.187     brouard  2652:     for (k=1; k<=cptcovn;k++) cov[2+nagesqr+k]=covar[Tvar[k]][i];
1.126     brouard  2653:     for(mi=1; mi<= wav[i]-1; mi++){
                   2654:       for (ii=1;ii<=nlstate+ndeath;ii++)
                   2655:        for (j=1;j<=nlstate+ndeath;j++){
                   2656:          oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   2657:          savm[ii][j]=(ii==j ? 1.0 : 0.0);
                   2658:        }
1.214     brouard  2659:       
                   2660:       agebegin=agev[mw[mi][i]][i]; /* Age at beginning of effective wave */
                   2661:       ageend=agev[mw[mi][i]][i] + (dh[mi][i])*stepm/YEARM; /* Age at end of effective wave and at the end of transition */
                   2662:       for(d=0; d<dh[mi][i]; d++){  /* Delay between two effective waves */
                   2663:        /*dh[m][i] or dh[mw[mi][i]][i] is the delay between two effective waves m=mw[mi][i]
                   2664:          and mw[mi+1][i]. dh depends on stepm.*/
1.126     brouard  2665:        newm=savm;
1.187     brouard  2666:        agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;
                   2667:        cov[2]=agexact;
                   2668:        if(nagesqr==1)
                   2669:          cov[3]= agexact*agexact;
1.126     brouard  2670:        for (kk=1; kk<=cptcovage;kk++) {
1.187     brouard  2671:          cov[Tage[kk]+2+nagesqr]=covar[Tvar[Tage[kk]]][i]*agexact;
1.126     brouard  2672:        }
1.187     brouard  2673: 
1.145     brouard  2674:        /* savm=pmij(pmmij,cov,ncovmodel,x,nlstate); */
1.126     brouard  2675:        out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
                   2676:                     1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
1.145     brouard  2677:        /* out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath, */
                   2678:        /*           1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate)); */
1.126     brouard  2679:        savm=oldm;
                   2680:        oldm=newm;
                   2681:       } /* end mult */
                   2682:       
                   2683:       s1=s[mw[mi][i]][i];
                   2684:       s2=s[mw[mi+1][i]][i];
                   2685:       bbh=(double)bh[mi][i]/(double)stepm; 
                   2686:       /* bias is positive if real duration
                   2687:        * is higher than the multiple of stepm and negative otherwise.
                   2688:        */
                   2689:       if( s2 > nlstate && (mle <5) ){  /* Jackson */
                   2690:        lli=log(out[s1][s2] - savm[s1][s2]);
                   2691:       } else if  (s2==-2) {
                   2692:        for (j=1,survp=0. ; j<=nlstate; j++) 
                   2693:          survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j];
                   2694:        lli= log(survp);
                   2695:       }else if (mle==1){
                   2696:        lli= log((1.+bbh)*out[s1][s2]- bbh*savm[s1][s2]); /* linear interpolation */
                   2697:       } else if(mle==2){
                   2698:        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 */
                   2699:       } else if(mle==3){  /* exponential inter-extrapolation */
                   2700:        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 */
                   2701:       } else if (mle==4){  /* mle=4 no inter-extrapolation */
                   2702:        lli=log(out[s1][s2]); /* Original formula */
1.136     brouard  2703:       } else{  /* mle=0 back to 1 */
                   2704:        lli= log((1.+bbh)*out[s1][s2]- bbh*savm[s1][s2]); /* linear interpolation */
                   2705:        /*lli=log(out[s1][s2]); */ /* Original formula */
1.126     brouard  2706:       } /* End of if */
                   2707:       ipmx +=1;
                   2708:       sw += weight[i];
                   2709:       ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
1.132     brouard  2710:       /*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  2711:       if(globpr){
1.214     brouard  2712:        fprintf(ficresilk,"%9ld %6.1f %6.1f %6d %2d %2d %2d %2d %3d %11.6f %8.4f %8.3f\
1.126     brouard  2713:  %11.6f %11.6f %11.6f ", \
1.214     brouard  2714:                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  2715:                2*weight[i]*lli,out[s1][s2],savm[s1][s2]);
                   2716:        for(k=1,llt=0.,l=0.; k<=nlstate; k++){
                   2717:          llt +=ll[k]*gipmx/gsw;
                   2718:          fprintf(ficresilk," %10.6f",-ll[k]*gipmx/gsw);
                   2719:        }
                   2720:        fprintf(ficresilk," %10.6f\n", -llt);
                   2721:       }
                   2722:     } /* end of wave */
                   2723:   } /* end of individual */
                   2724:   for(k=1,l=0.; k<=nlstate; k++) l += ll[k];
                   2725:   /* printf("l1=%f l2=%f ",ll[1],ll[2]); */
                   2726:   l= l*ipmx/sw; /* To get the same order of magnitude as if weight=1 for every body */
                   2727:   if(globpr==0){ /* First time we count the contributions and weights */
                   2728:     gipmx=ipmx;
                   2729:     gsw=sw;
                   2730:   }
                   2731:   return -l;
                   2732: }
                   2733: 
                   2734: 
                   2735: /*************** function likelione ***********/
                   2736: void likelione(FILE *ficres,double p[], int npar, int nlstate, int *globpri, long *ipmx, double *sw, double *fretone, double (*funcone)(double []))
                   2737: {
                   2738:   /* This routine should help understanding what is done with 
                   2739:      the selection of individuals/waves and
                   2740:      to check the exact contribution to the likelihood.
                   2741:      Plotting could be done.
                   2742:    */
                   2743:   int k;
                   2744: 
                   2745:   if(*globpri !=0){ /* Just counts and sums, no printings */
1.201     brouard  2746:     strcpy(fileresilk,"ILK_"); 
1.202     brouard  2747:     strcat(fileresilk,fileresu);
1.126     brouard  2748:     if((ficresilk=fopen(fileresilk,"w"))==NULL) {
                   2749:       printf("Problem with resultfile: %s\n", fileresilk);
                   2750:       fprintf(ficlog,"Problem with resultfile: %s\n", fileresilk);
                   2751:     }
1.214     brouard  2752:     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");
                   2753:     fprintf(ficresilk, "#num_i ageb agend i s1 s2 mi mw dh likeli weight %%weight 2wlli out sav ");
1.126     brouard  2754:     /*         i,s1,s2,mi,mw[mi][i],dh[mi][i],exp(lli),weight[i],2*weight[i]*lli,out[s1][s2],savm[s1][s2]); */
                   2755:     for(k=1; k<=nlstate; k++) 
                   2756:       fprintf(ficresilk," -2*gipw/gsw*weight*ll[%d]++",k);
                   2757:     fprintf(ficresilk," -2*gipw/gsw*weight*ll(total)\n");
                   2758:   }
                   2759: 
                   2760:   *fretone=(*funcone)(p);
                   2761:   if(*globpri !=0){
                   2762:     fclose(ficresilk);
1.205     brouard  2763:     if (mle ==0)
                   2764:       fprintf(fichtm,"\n<br>File of contributions to the likelihood computed with initial parameters and mle = %d.",mle);
                   2765:     else if(mle >=1)
                   2766:       fprintf(fichtm,"\n<br>File of contributions to the likelihood computed with optimized parameters mle = %d.",mle);
                   2767:     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  2768:     
1.208     brouard  2769:       
                   2770:     for (k=1; k<= nlstate ; k++) {
1.211     brouard  2771:       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  2772: <img src=\"%s-p%dj.png\">",k,k,subdirf2(optionfilefiname,"ILK_"),k,subdirf2(optionfilefiname,"ILK_"),k,subdirf2(optionfilefiname,"ILK_"),k);
                   2773:     }
1.207     brouard  2774:     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  2775: <img src=\"%s-ori.png\">",subdirf2(optionfilefiname,"ILK_"),subdirf2(optionfilefiname,"ILK_"),subdirf2(optionfilefiname,"ILK_"));
1.207     brouard  2776:     fprintf(fichtm,"<br>- and by state of destination <a href=\"%s-dest.png\">%s-dest.png</a><br> \
1.204     brouard  2777: <img src=\"%s-dest.png\">",subdirf2(optionfilefiname,"ILK_"),subdirf2(optionfilefiname,"ILK_"),subdirf2(optionfilefiname,"ILK_"));
1.207     brouard  2778:     fflush(fichtm);
1.205     brouard  2779:   }
1.126     brouard  2780:   return;
                   2781: }
                   2782: 
                   2783: 
                   2784: /*********** Maximum Likelihood Estimation ***************/
                   2785: 
                   2786: void mlikeli(FILE *ficres,double p[], int npar, int ncovmodel, int nlstate, double ftol, double (*func)(double []))
                   2787: {
1.165     brouard  2788:   int i,j, iter=0;
1.126     brouard  2789:   double **xi;
                   2790:   double fret;
                   2791:   double fretone; /* Only one call to likelihood */
                   2792:   /*  char filerespow[FILENAMELENGTH];*/
1.162     brouard  2793: 
                   2794: #ifdef NLOPT
                   2795:   int creturn;
                   2796:   nlopt_opt opt;
                   2797:   /* double lb[9] = { -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL }; /\* lower bounds *\/ */
                   2798:   double *lb;
                   2799:   double minf; /* the minimum objective value, upon return */
                   2800:   double * p1; /* Shifted parameters from 0 instead of 1 */
                   2801:   myfunc_data dinst, *d = &dinst;
                   2802: #endif
                   2803: 
                   2804: 
1.126     brouard  2805:   xi=matrix(1,npar,1,npar);
                   2806:   for (i=1;i<=npar;i++)
                   2807:     for (j=1;j<=npar;j++)
                   2808:       xi[i][j]=(i==j ? 1.0 : 0.0);
                   2809:   printf("Powell\n");  fprintf(ficlog,"Powell\n");
1.201     brouard  2810:   strcpy(filerespow,"POW_"); 
1.126     brouard  2811:   strcat(filerespow,fileres);
                   2812:   if((ficrespow=fopen(filerespow,"w"))==NULL) {
                   2813:     printf("Problem with resultfile: %s\n", filerespow);
                   2814:     fprintf(ficlog,"Problem with resultfile: %s\n", filerespow);
                   2815:   }
                   2816:   fprintf(ficrespow,"# Powell\n# iter -2*LL");
                   2817:   for (i=1;i<=nlstate;i++)
                   2818:     for(j=1;j<=nlstate+ndeath;j++)
                   2819:       if(j!=i)fprintf(ficrespow," p%1d%1d",i,j);
                   2820:   fprintf(ficrespow,"\n");
1.162     brouard  2821: #ifdef POWELL
1.126     brouard  2822:   powell(p,xi,npar,ftol,&iter,&fret,func);
1.162     brouard  2823: #endif
1.126     brouard  2824: 
1.162     brouard  2825: #ifdef NLOPT
                   2826: #ifdef NEWUOA
                   2827:   opt = nlopt_create(NLOPT_LN_NEWUOA,npar);
                   2828: #else
                   2829:   opt = nlopt_create(NLOPT_LN_BOBYQA,npar);
                   2830: #endif
                   2831:   lb=vector(0,npar-1);
                   2832:   for (i=0;i<npar;i++) lb[i]= -HUGE_VAL;
                   2833:   nlopt_set_lower_bounds(opt, lb);
                   2834:   nlopt_set_initial_step1(opt, 0.1);
                   2835:   
                   2836:   p1= (p+1); /*  p *(p+1)@8 and p *(p1)@8 are equal p1[0]=p[1] */
                   2837:   d->function = func;
                   2838:   printf(" Func %.12lf \n",myfunc(npar,p1,NULL,d));
                   2839:   nlopt_set_min_objective(opt, myfunc, d);
                   2840:   nlopt_set_xtol_rel(opt, ftol);
                   2841:   if ((creturn=nlopt_optimize(opt, p1, &minf)) < 0) {
                   2842:     printf("nlopt failed! %d\n",creturn); 
                   2843:   }
                   2844:   else {
                   2845:     printf("found minimum after %d evaluations (NLOPT=%d)\n", countcallfunc ,NLOPT);
                   2846:     printf("found minimum at f(%g,%g) = %0.10g\n", p[0], p[1], minf);
                   2847:     iter=1; /* not equal */
                   2848:   }
                   2849:   nlopt_destroy(opt);
                   2850: #endif
1.126     brouard  2851:   free_matrix(xi,1,npar,1,npar);
                   2852:   fclose(ficrespow);
1.203     brouard  2853:   printf("\n#Number of iterations & function calls = %d & %d, -2 Log likelihood = %.12f\n",iter, countcallfunc,func(p));
                   2854:   fprintf(ficlog,"\n#Number of iterations & function calls = %d & %d, -2 Log likelihood = %.12f\n",iter, countcallfunc,func(p));
1.180     brouard  2855:   fprintf(ficres,"#Number of iterations & function calls = %d & %d, -2 Log likelihood = %.12f\n",iter, countcallfunc,func(p));
1.126     brouard  2856: 
                   2857: }
                   2858: 
                   2859: /**** Computes Hessian and covariance matrix ***/
1.203     brouard  2860: void hesscov(double **matcov, double **hess, double p[], int npar, double delti[], double ftolhess, double (*func)(double []))
1.126     brouard  2861: {
                   2862:   double  **a,**y,*x,pd;
1.203     brouard  2863:   /* double **hess; */
1.164     brouard  2864:   int i, j;
1.126     brouard  2865:   int *indx;
                   2866: 
                   2867:   double hessii(double p[], double delta, int theta, double delti[],double (*func)(double []),int npar);
1.203     brouard  2868:   double hessij(double p[], double **hess, double delti[], int i, int j,double (*func)(double []),int npar);
1.126     brouard  2869:   void lubksb(double **a, int npar, int *indx, double b[]) ;
                   2870:   void ludcmp(double **a, int npar, int *indx, double *d) ;
                   2871:   double gompertz(double p[]);
1.203     brouard  2872:   /* hess=matrix(1,npar,1,npar); */
1.126     brouard  2873: 
                   2874:   printf("\nCalculation of the hessian matrix. Wait...\n");
                   2875:   fprintf(ficlog,"\nCalculation of the hessian matrix. Wait...\n");
                   2876:   for (i=1;i<=npar;i++){
1.203     brouard  2877:     printf("%d-",i);fflush(stdout);
                   2878:     fprintf(ficlog,"%d-",i);fflush(ficlog);
1.126     brouard  2879:    
                   2880:      hess[i][i]=hessii(p,ftolhess,i,delti,func,npar);
                   2881:     
                   2882:     /*  printf(" %f ",p[i]);
                   2883:        printf(" %lf %lf %lf",hess[i][i],ftolhess,delti[i]);*/
                   2884:   }
                   2885:   
                   2886:   for (i=1;i<=npar;i++) {
                   2887:     for (j=1;j<=npar;j++)  {
                   2888:       if (j>i) { 
1.203     brouard  2889:        printf(".%d-%d",i,j);fflush(stdout);
                   2890:        fprintf(ficlog,".%d-%d",i,j);fflush(ficlog);
                   2891:        hess[i][j]=hessij(p,hess, delti,i,j,func,npar);
1.126     brouard  2892:        
                   2893:        hess[j][i]=hess[i][j];    
                   2894:        /*printf(" %lf ",hess[i][j]);*/
                   2895:       }
                   2896:     }
                   2897:   }
                   2898:   printf("\n");
                   2899:   fprintf(ficlog,"\n");
                   2900: 
                   2901:   printf("\nInverting the hessian to get the covariance matrix. Wait...\n");
                   2902:   fprintf(ficlog,"\nInverting the hessian to get the covariance matrix. Wait...\n");
                   2903:   
                   2904:   a=matrix(1,npar,1,npar);
                   2905:   y=matrix(1,npar,1,npar);
                   2906:   x=vector(1,npar);
                   2907:   indx=ivector(1,npar);
                   2908:   for (i=1;i<=npar;i++)
                   2909:     for (j=1;j<=npar;j++) a[i][j]=hess[i][j];
                   2910:   ludcmp(a,npar,indx,&pd);
                   2911: 
                   2912:   for (j=1;j<=npar;j++) {
                   2913:     for (i=1;i<=npar;i++) x[i]=0;
                   2914:     x[j]=1;
                   2915:     lubksb(a,npar,indx,x);
                   2916:     for (i=1;i<=npar;i++){ 
                   2917:       matcov[i][j]=x[i];
                   2918:     }
                   2919:   }
                   2920: 
                   2921:   printf("\n#Hessian matrix#\n");
                   2922:   fprintf(ficlog,"\n#Hessian matrix#\n");
                   2923:   for (i=1;i<=npar;i++) { 
                   2924:     for (j=1;j<=npar;j++) { 
1.203     brouard  2925:       printf("%.6e ",hess[i][j]);
                   2926:       fprintf(ficlog,"%.6e ",hess[i][j]);
1.126     brouard  2927:     }
                   2928:     printf("\n");
                   2929:     fprintf(ficlog,"\n");
                   2930:   }
                   2931: 
1.203     brouard  2932:   /* printf("\n#Covariance matrix#\n"); */
                   2933:   /* fprintf(ficlog,"\n#Covariance matrix#\n"); */
                   2934:   /* for (i=1;i<=npar;i++) {  */
                   2935:   /*   for (j=1;j<=npar;j++) {  */
                   2936:   /*     printf("%.6e ",matcov[i][j]); */
                   2937:   /*     fprintf(ficlog,"%.6e ",matcov[i][j]); */
                   2938:   /*   } */
                   2939:   /*   printf("\n"); */
                   2940:   /*   fprintf(ficlog,"\n"); */
                   2941:   /* } */
                   2942: 
1.126     brouard  2943:   /* Recompute Inverse */
1.203     brouard  2944:   /* for (i=1;i<=npar;i++) */
                   2945:   /*   for (j=1;j<=npar;j++) a[i][j]=matcov[i][j]; */
                   2946:   /* ludcmp(a,npar,indx,&pd); */
                   2947: 
                   2948:   /*  printf("\n#Hessian matrix recomputed#\n"); */
                   2949: 
                   2950:   /* for (j=1;j<=npar;j++) { */
                   2951:   /*   for (i=1;i<=npar;i++) x[i]=0; */
                   2952:   /*   x[j]=1; */
                   2953:   /*   lubksb(a,npar,indx,x); */
                   2954:   /*   for (i=1;i<=npar;i++){  */
                   2955:   /*     y[i][j]=x[i]; */
                   2956:   /*     printf("%.3e ",y[i][j]); */
                   2957:   /*     fprintf(ficlog,"%.3e ",y[i][j]); */
                   2958:   /*   } */
                   2959:   /*   printf("\n"); */
                   2960:   /*   fprintf(ficlog,"\n"); */
                   2961:   /* } */
                   2962: 
                   2963:   /* Verifying the inverse matrix */
                   2964: #ifdef DEBUGHESS
                   2965:   y=matprod2(y,hess,1,npar,1,npar,1,npar,matcov);
1.126     brouard  2966: 
1.203     brouard  2967:    printf("\n#Verification: multiplying the matrix of covariance by the Hessian matrix, should be unity:#\n");
                   2968:    fprintf(ficlog,"\n#Verification: multiplying the matrix of covariance by the Hessian matrix. Should be unity:#\n");
1.126     brouard  2969: 
                   2970:   for (j=1;j<=npar;j++) {
                   2971:     for (i=1;i<=npar;i++){ 
1.203     brouard  2972:       printf("%.2f ",y[i][j]);
                   2973:       fprintf(ficlog,"%.2f ",y[i][j]);
1.126     brouard  2974:     }
                   2975:     printf("\n");
                   2976:     fprintf(ficlog,"\n");
                   2977:   }
1.203     brouard  2978: #endif
1.126     brouard  2979: 
                   2980:   free_matrix(a,1,npar,1,npar);
                   2981:   free_matrix(y,1,npar,1,npar);
                   2982:   free_vector(x,1,npar);
                   2983:   free_ivector(indx,1,npar);
1.203     brouard  2984:   /* free_matrix(hess,1,npar,1,npar); */
1.126     brouard  2985: 
                   2986: 
                   2987: }
                   2988: 
                   2989: /*************** hessian matrix ****************/
                   2990: double hessii(double x[], double delta, int theta, double delti[], double (*func)(double []), int npar)
1.203     brouard  2991: { /* Around values of x, computes the function func and returns the scales delti and hessian */
1.126     brouard  2992:   int i;
                   2993:   int l=1, lmax=20;
1.203     brouard  2994:   double k1,k2, res, fx;
1.132     brouard  2995:   double p2[MAXPARM+1]; /* identical to x */
1.126     brouard  2996:   double delt=0.0001, delts, nkhi=10.,nkhif=1., khi=1.e-4;
                   2997:   int k=0,kmax=10;
                   2998:   double l1;
                   2999: 
                   3000:   fx=func(x);
                   3001:   for (i=1;i<=npar;i++) p2[i]=x[i];
1.145     brouard  3002:   for(l=0 ; l <=lmax; l++){  /* Enlarging the zone around the Maximum */
1.126     brouard  3003:     l1=pow(10,l);
                   3004:     delts=delt;
                   3005:     for(k=1 ; k <kmax; k=k+1){
                   3006:       delt = delta*(l1*k);
                   3007:       p2[theta]=x[theta] +delt;
1.145     brouard  3008:       k1=func(p2)-fx;   /* Might be negative if too close to the theoretical maximum */
1.126     brouard  3009:       p2[theta]=x[theta]-delt;
                   3010:       k2=func(p2)-fx;
                   3011:       /*res= (k1-2.0*fx+k2)/delt/delt; */
1.203     brouard  3012:       res= (k1+k2)/delt/delt/2.; /* Divided by 2 because L and not 2*L */
1.126     brouard  3013:       
1.203     brouard  3014: #ifdef DEBUGHESSII
1.126     brouard  3015:       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);
                   3016:       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);
                   3017: #endif
                   3018:       /*if(fabs(k1-2.0*fx+k2) <1.e-13){ */
                   3019:       if((k1 <khi/nkhi/2.) || (k2 <khi/nkhi/2.)){
                   3020:        k=kmax;
                   3021:       }
                   3022:       else if((k1 >khi/nkhif) || (k2 >khi/nkhif)){ /* Keeps lastvalue before 3.84/2 KHI2 5% 1d.f. */
1.164     brouard  3023:        k=kmax; l=lmax*10;
1.126     brouard  3024:       }
                   3025:       else if((k1 >khi/nkhi) || (k2 >khi/nkhi)){ 
                   3026:        delts=delt;
                   3027:       }
1.203     brouard  3028:     } /* End loop k */
1.126     brouard  3029:   }
                   3030:   delti[theta]=delts;
                   3031:   return res; 
                   3032:   
                   3033: }
                   3034: 
1.203     brouard  3035: double hessij( double x[], double **hess, double delti[], int thetai,int thetaj,double (*func)(double []),int npar)
1.126     brouard  3036: {
                   3037:   int i;
1.164     brouard  3038:   int l=1, lmax=20;
1.126     brouard  3039:   double k1,k2,k3,k4,res,fx;
1.132     brouard  3040:   double p2[MAXPARM+1];
1.203     brouard  3041:   int k, kmax=1;
                   3042:   double v1, v2, cv12, lc1, lc2;
1.208     brouard  3043: 
                   3044:   int firstime=0;
1.203     brouard  3045:   
1.126     brouard  3046:   fx=func(x);
1.203     brouard  3047:   for (k=1; k<=kmax; k=k+10) {
1.126     brouard  3048:     for (i=1;i<=npar;i++) p2[i]=x[i];
1.203     brouard  3049:     p2[thetai]=x[thetai]+delti[thetai]*k;
                   3050:     p2[thetaj]=x[thetaj]+delti[thetaj]*k;
1.126     brouard  3051:     k1=func(p2)-fx;
                   3052:   
1.203     brouard  3053:     p2[thetai]=x[thetai]+delti[thetai]*k;
                   3054:     p2[thetaj]=x[thetaj]-delti[thetaj]*k;
1.126     brouard  3055:     k2=func(p2)-fx;
                   3056:   
1.203     brouard  3057:     p2[thetai]=x[thetai]-delti[thetai]*k;
                   3058:     p2[thetaj]=x[thetaj]+delti[thetaj]*k;
1.126     brouard  3059:     k3=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:     k4=func(p2)-fx;
1.203     brouard  3064:     res=(k1-k2-k3+k4)/4.0/delti[thetai]/k/delti[thetaj]/k/2.; /* Because of L not 2*L */
                   3065:     if(k1*k2*k3*k4 <0.){
1.208     brouard  3066:       firstime=1;
1.203     brouard  3067:       kmax=kmax+10;
1.208     brouard  3068:     }
                   3069:     if(kmax >=10 || firstime ==1){
1.203     brouard  3070:       printf("Warning: directions %d-%d, you are not estimating the Hessian at the exact maximum likelihood; increase ftol=%.2e\n",thetai,thetaj, ftol);
                   3071:       fprintf(ficlog,"Warning: directions %d-%d, you are not estimating the Hessian at the exact maximum likelihood; increase ftol=%.2e\n",thetai,thetaj, ftol);
                   3072:       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);
                   3073:       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);
                   3074:     }
                   3075: #ifdef DEBUGHESSIJ
                   3076:     v1=hess[thetai][thetai];
                   3077:     v2=hess[thetaj][thetaj];
                   3078:     cv12=res;
                   3079:     /* Computing eigen value of Hessian matrix */
                   3080:     lc1=((v1+v2)+sqrt((v1+v2)*(v1+v2) - 4*(v1*v2-cv12*cv12)))/2.;
                   3081:     lc2=((v1+v2)-sqrt((v1+v2)*(v1+v2) - 4*(v1*v2-cv12*cv12)))/2.;
                   3082:     if ((lc2 <0) || (lc1 <0) ){
                   3083:       printf("Warning: sub Hessian matrix '%d%d' does not have positive eigen values \n",thetai,thetaj);
                   3084:       fprintf(ficlog, "Warning: sub Hessian matrix '%d%d' does not have positive eigen values \n",thetai,thetaj);
                   3085:       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);
                   3086:       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);
                   3087:     }
1.126     brouard  3088: #endif
                   3089:   }
                   3090:   return res;
                   3091: }
                   3092: 
1.203     brouard  3093:     /* Not done yet: Was supposed to fix if not exactly at the maximum */
                   3094: /* double hessij( double x[], double delti[], int thetai,int thetaj,double (*func)(double []),int npar) */
                   3095: /* { */
                   3096: /*   int i; */
                   3097: /*   int l=1, lmax=20; */
                   3098: /*   double k1,k2,k3,k4,res,fx; */
                   3099: /*   double p2[MAXPARM+1]; */
                   3100: /*   double delt=0.0001, delts, nkhi=10.,nkhif=1., khi=1.e-4; */
                   3101: /*   int k=0,kmax=10; */
                   3102: /*   double l1; */
                   3103:   
                   3104: /*   fx=func(x); */
                   3105: /*   for(l=0 ; l <=lmax; l++){  /\* Enlarging the zone around the Maximum *\/ */
                   3106: /*     l1=pow(10,l); */
                   3107: /*     delts=delt; */
                   3108: /*     for(k=1 ; k <kmax; k=k+1){ */
                   3109: /*       delt = delti*(l1*k); */
                   3110: /*       for (i=1;i<=npar;i++) p2[i]=x[i]; */
                   3111: /*       p2[thetai]=x[thetai]+delti[thetai]/k; */
                   3112: /*       p2[thetaj]=x[thetaj]+delti[thetaj]/k; */
                   3113: /*       k1=func(p2)-fx; */
                   3114:       
                   3115: /*       p2[thetai]=x[thetai]+delti[thetai]/k; */
                   3116: /*       p2[thetaj]=x[thetaj]-delti[thetaj]/k; */
                   3117: /*       k2=func(p2)-fx; */
                   3118:       
                   3119: /*       p2[thetai]=x[thetai]-delti[thetai]/k; */
                   3120: /*       p2[thetaj]=x[thetaj]+delti[thetaj]/k; */
                   3121: /*       k3=func(p2)-fx; */
                   3122:       
                   3123: /*       p2[thetai]=x[thetai]-delti[thetai]/k; */
                   3124: /*       p2[thetaj]=x[thetaj]-delti[thetaj]/k; */
                   3125: /*       k4=func(p2)-fx; */
                   3126: /*       res=(k1-k2-k3+k4)/4.0/delti[thetai]*k/delti[thetaj]*k/2.; /\* Because of L not 2*L *\/ */
                   3127: /* #ifdef DEBUGHESSIJ */
                   3128: /*       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); */
                   3129: /*       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); */
                   3130: /* #endif */
                   3131: /*       if((k1 <khi/nkhi/2.) || (k2 <khi/nkhi/2.)|| (k4 <khi/nkhi/2.)|| (k4 <khi/nkhi/2.)){ */
                   3132: /*     k=kmax; */
                   3133: /*       } */
                   3134: /*       else if((k1 >khi/nkhif) || (k2 >khi/nkhif) || (k4 >khi/nkhif) || (k4 >khi/nkhif)){ /\* Keeps lastvalue before 3.84/2 KHI2 5% 1d.f. *\/ */
                   3135: /*     k=kmax; l=lmax*10; */
                   3136: /*       } */
                   3137: /*       else if((k1 >khi/nkhi) || (k2 >khi/nkhi)){  */
                   3138: /*     delts=delt; */
                   3139: /*       } */
                   3140: /*     } /\* End loop k *\/ */
                   3141: /*   } */
                   3142: /*   delti[theta]=delts; */
                   3143: /*   return res;  */
                   3144: /* } */
                   3145: 
                   3146: 
1.126     brouard  3147: /************** Inverse of matrix **************/
                   3148: void ludcmp(double **a, int n, int *indx, double *d) 
                   3149: { 
                   3150:   int i,imax,j,k; 
                   3151:   double big,dum,sum,temp; 
                   3152:   double *vv; 
                   3153:  
                   3154:   vv=vector(1,n); 
                   3155:   *d=1.0; 
                   3156:   for (i=1;i<=n;i++) { 
                   3157:     big=0.0; 
                   3158:     for (j=1;j<=n;j++) 
                   3159:       if ((temp=fabs(a[i][j])) > big) big=temp; 
                   3160:     if (big == 0.0) nrerror("Singular matrix in routine ludcmp"); 
                   3161:     vv[i]=1.0/big; 
                   3162:   } 
                   3163:   for (j=1;j<=n;j++) { 
                   3164:     for (i=1;i<j;i++) { 
                   3165:       sum=a[i][j]; 
                   3166:       for (k=1;k<i;k++) sum -= a[i][k]*a[k][j]; 
                   3167:       a[i][j]=sum; 
                   3168:     } 
                   3169:     big=0.0; 
                   3170:     for (i=j;i<=n;i++) { 
                   3171:       sum=a[i][j]; 
                   3172:       for (k=1;k<j;k++) 
                   3173:        sum -= a[i][k]*a[k][j]; 
                   3174:       a[i][j]=sum; 
                   3175:       if ( (dum=vv[i]*fabs(sum)) >= big) { 
                   3176:        big=dum; 
                   3177:        imax=i; 
                   3178:       } 
                   3179:     } 
                   3180:     if (j != imax) { 
                   3181:       for (k=1;k<=n;k++) { 
                   3182:        dum=a[imax][k]; 
                   3183:        a[imax][k]=a[j][k]; 
                   3184:        a[j][k]=dum; 
                   3185:       } 
                   3186:       *d = -(*d); 
                   3187:       vv[imax]=vv[j]; 
                   3188:     } 
                   3189:     indx[j]=imax; 
                   3190:     if (a[j][j] == 0.0) a[j][j]=TINY; 
                   3191:     if (j != n) { 
                   3192:       dum=1.0/(a[j][j]); 
                   3193:       for (i=j+1;i<=n;i++) a[i][j] *= dum; 
                   3194:     } 
                   3195:   } 
                   3196:   free_vector(vv,1,n);  /* Doesn't work */
                   3197: ;
                   3198: } 
                   3199: 
                   3200: void lubksb(double **a, int n, int *indx, double b[]) 
                   3201: { 
                   3202:   int i,ii=0,ip,j; 
                   3203:   double sum; 
                   3204:  
                   3205:   for (i=1;i<=n;i++) { 
                   3206:     ip=indx[i]; 
                   3207:     sum=b[ip]; 
                   3208:     b[ip]=b[i]; 
                   3209:     if (ii) 
                   3210:       for (j=ii;j<=i-1;j++) sum -= a[i][j]*b[j]; 
                   3211:     else if (sum) ii=i; 
                   3212:     b[i]=sum; 
                   3213:   } 
                   3214:   for (i=n;i>=1;i--) { 
                   3215:     sum=b[i]; 
                   3216:     for (j=i+1;j<=n;j++) sum -= a[i][j]*b[j]; 
                   3217:     b[i]=sum/a[i][i]; 
                   3218:   } 
                   3219: } 
                   3220: 
                   3221: void pstamp(FILE *fichier)
                   3222: {
1.196     brouard  3223:   fprintf(fichier,"# %s.%s\n#IMaCh version %s, %s\n#%s\n# %s", optionfilefiname,optionfilext,version,copyright, fullversion, strstart);
1.126     brouard  3224: }
                   3225: 
                   3226: /************ Frequencies ********************/
1.214     brouard  3227: void  freqsummary(char fileres[], int iagemin, int iagemax, int **s, double **agev, int nlstate, int imx, \
                   3228:                  int *Tvaraff, int **nbcode, int *ncodemax,double **mint,double **anint, char strstart[],\
                   3229:                  int firstpass,  int lastpass, int stepm, int weightopt, char model[])
1.126     brouard  3230: {  /* Some frequencies */
                   3231:   
1.164     brouard  3232:   int i, m, jk, j1, bool, z1,j;
1.214     brouard  3233:   int mi; /* Effective wave */
1.126     brouard  3234:   int first;
                   3235:   double ***freq; /* Frequencies */
                   3236:   double *pp, **prop;
                   3237:   double pos,posprop, k2, dateintsum=0,k2cpt=0;
1.214     brouard  3238:   char fileresp[FILENAMELENGTH], fileresphtm[FILENAMELENGTH], fileresphtmfr[FILENAMELENGTH];
                   3239:   double agebegin, ageend;
                   3240:     
1.126     brouard  3241:   pp=vector(1,nlstate);
                   3242:   prop=matrix(1,nlstate,iagemin,iagemax+3);
1.201     brouard  3243:   strcpy(fileresp,"P_");
                   3244:   strcat(fileresp,fileresu);
1.213     brouard  3245:   /*strcat(fileresphtm,fileresu);*/
1.126     brouard  3246:   if((ficresp=fopen(fileresp,"w"))==NULL) {
                   3247:     printf("Problem with prevalence resultfile: %s\n", fileresp);
                   3248:     fprintf(ficlog,"Problem with prevalence resultfile: %s\n", fileresp);
                   3249:     exit(0);
                   3250:   }
1.214     brouard  3251: 
1.213     brouard  3252:   strcpy(fileresphtm,subdirfext(optionfilefiname,"PHTM_",".htm"));
                   3253:   if((ficresphtm=fopen(fileresphtm,"w"))==NULL) {
                   3254:     printf("Problem with prevalence HTM resultfile '%s' with errno='%s'\n",fileresphtm,strerror(errno));
                   3255:     fprintf(ficlog,"Problem with prevalence HTM resultfile '%s' with errno='%s'\n",fileresphtm,strerror(errno));
                   3256:     fflush(ficlog);
                   3257:     exit(70); 
                   3258:   }
1.214     brouard  3259:   else{
                   3260:     fprintf(ficresphtm,"<html><head>\n<title>IMaCh PHTM_ %s</title></head>\n <body><font size=\"2\">%s <br> %s</font> \
                   3261: <hr size=\"2\" color=\"#EC5E5E\"> \n\
                   3262: Title=%s <br>Datafile=%s Firstpass=%d Lastpass=%d Stepm=%d Weight=%d Model=1+age+%s<br>\n",\
                   3263:          fileresphtm,version,fullversion,title,datafile,firstpass,lastpass,stepm, weightopt, model);
                   3264:   }
                   3265:     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);
                   3266:     
                   3267:   strcpy(fileresphtmfr,subdirfext(optionfilefiname,"PHTMFR_",".htm"));
                   3268:   if((ficresphtmfr=fopen(fileresphtmfr,"w"))==NULL) {
                   3269:     printf("Problem with frequency table HTM resultfile '%s' with errno='%s'\n",fileresphtmfr,strerror(errno));
                   3270:     fprintf(ficlog,"Problem with frequency table HTM resultfile '%s' with errno='%s'\n",fileresphtmfr,strerror(errno));
                   3271:     fflush(ficlog);
                   3272:     exit(70); 
                   3273:   }
                   3274:   else{
                   3275:     fprintf(ficresphtmfr,"<html><head>\n<title>IMaCh PHTM_Frequency table %s</title></head>\n <body><font size=\"2\">%s <br> %s</font> \
                   3276: <hr size=\"2\" color=\"#EC5E5E\"> \n\
                   3277: Title=%s <br>Datafile=%s Firstpass=%d Lastpass=%d Stepm=%d Weight=%d Model=1+age+%s<br>\n",\
                   3278:          fileresphtmfr,version,fullversion,title,datafile,firstpass,lastpass,stepm, weightopt, model);
                   3279:   }
                   3280:   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);
                   3281: 
1.126     brouard  3282:   freq= ma3x(-5,nlstate+ndeath,-5,nlstate+ndeath,iagemin,iagemax+3);
                   3283:   j1=0;
                   3284:   
                   3285:   j=cptcoveff;
                   3286:   if (cptcovn<1) {j=1;ncodemax[1]=1;}
                   3287: 
                   3288:   first=1;
                   3289: 
1.214     brouard  3290:   for (j1 = 1; j1 <= (int) pow(2,cptcoveff); j1++){ /* Loop on covariates combination */
1.126     brouard  3291:       /*printf("cptcoveff=%d Tvaraff=%d", cptcoveff,Tvaraff[1]);
                   3292:        scanf("%d", i);*/
                   3293:       for (i=-5; i<=nlstate+ndeath; i++)  
                   3294:        for (jk=-5; jk<=nlstate+ndeath; jk++)  
                   3295:          for(m=iagemin; m <= iagemax+3; m++)
                   3296:            freq[i][jk][m]=0;
1.143     brouard  3297:       
                   3298:       for (i=1; i<=nlstate; i++)  
                   3299:        for(m=iagemin; m <= iagemax+3; m++)
                   3300:          prop[i][m]=0;
1.126     brouard  3301:       
                   3302:       dateintsum=0;
                   3303:       k2cpt=0;
1.214     brouard  3304:       for (i=1; i<=imx; i++) { /* For each individual i */
1.126     brouard  3305:        bool=1;
1.210     brouard  3306:        if (cptcovn>0) { /* Filter is here: Must be looked at for model=V1+V2+V3+V4 */
1.144     brouard  3307:          for (z1=1; z1<=cptcoveff; z1++)       
1.198     brouard  3308:             if (covar[Tvaraff[z1]][i]!= nbcode[Tvaraff[z1]][codtabm(j1,z1)]){
1.145     brouard  3309:                 /* Tests if the value of each of the covariates of i is equal to filter j1 */
1.144     brouard  3310:               bool=0;
1.198     brouard  3311:               /* 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", 
                   3312:                 bool,i,z1, z1, Tvaraff[z1],i,covar[Tvaraff[z1]][i],j1,z1,codtabm(j1,z1),
                   3313:                 j1,z1,nbcode[Tvaraff[z1]][codtabm(j1,z1)],j1);*/
                   3314:               /* For j1=7 in V1+V2+V3+V4 = 0 1 1 0 and codtabm(7,3)=1 and nbcde[3][?]=1*/
1.144     brouard  3315:             } 
1.210     brouard  3316:        } /* cptcovn > 0 */
1.214     brouard  3317: 
1.126     brouard  3318:        if (bool==1){
1.214     brouard  3319:          /* for(m=firstpass; m<=lastpass; m++){ */
                   3320:          for(mi=1; mi<wav[i];mi++){
                   3321:            m=mw[mi][i];
                   3322:            /* dh[m][i] or dh[mw[mi][i]][i] is the delay between two effective (mi) waves m=mw[mi][i]
                   3323:               and mw[mi+1][i]. dh depends on stepm. */
                   3324:            agebegin=agev[m][i]; /* Age at beginning of wave before transition*/
                   3325:            ageend=agev[m][i]+(dh[m][i])*stepm/YEARM; /* Age at end of wave and transition */
                   3326:            if(m >=firstpass && m <=lastpass){
                   3327:              k2=anint[m][i]+(mint[m][i]/12.);
                   3328:              /*if ((k2>=dateprev1) && (k2<=dateprev2)) {*/
                   3329:              if(agev[m][i]==0) agev[m][i]=iagemax+1;  /* All ages equal to 0 are in iagemax+1 */
                   3330:              if(agev[m][i]==1) agev[m][i]=iagemax+2;  /* All ages equal to 1 are in iagemax+2 */
                   3331:              if (s[m][i]>0 && s[m][i]<=nlstate)  /* If status at wave m is known and a live state */
                   3332:                prop[s[m][i]][(int)agev[m][i]] += weight[i];  /* At age of beginning of transition, where status is known */
1.126     brouard  3333:              if (m<lastpass) {
1.214     brouard  3334:                /* if(s[m][i]==4 && s[m+1][i]==4) */
                   3335:                /*   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]); */
                   3336:                if(s[m][i]==-1)
                   3337:                  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.));
                   3338:                freq[s[m][i]][s[m+1][i]][(int)agev[m][i]] += weight[i]; /* At age of beginning of transition, where status is known */
                   3339:                /* freq[s[m][i]][s[m+1][i]][(int)((agebegin+ageend)/2.)] += weight[i]; */
                   3340:                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  3341:              }
1.214     brouard  3342:            }  
                   3343:            if ((agev[m][i]>1) && (agev[m][i]< (iagemax+3)) && (anint[m][i]!=9999) && (mint[m][i]!=99)) {
                   3344:              dateintsum=dateintsum+k2;
                   3345:              k2cpt++;
                   3346:              /* printf("i=%ld dateintmean = %lf dateintsum=%lf k2cpt=%lf k2=%lf\n",i, dateintsum/k2cpt, dateintsum,k2cpt, k2); */
                   3347:            }
                   3348:            /*}*/
1.210     brouard  3349:          } /* end m */
                   3350:        } /* end bool */
                   3351:       } /* end i = 1 to imx */
1.126     brouard  3352:        
                   3353:       /*      fprintf(ficresp, "#Count between %.lf/%.lf/%.lf and %.lf/%.lf/%.lf\n",jprev1, mprev1,anprev1,jprev2, mprev2,anprev2);*/
                   3354:       pstamp(ficresp);
                   3355:       if  (cptcovn>0) {
                   3356:        fprintf(ficresp, "\n#********** Variable "); 
1.214     brouard  3357:        fprintf(ficresphtm, "\n<br/><br/><h3>********** Variable "); 
                   3358:        fprintf(ficresphtmfr, "\n<br/><br/><h3>********** Variable "); 
1.213     brouard  3359:        for (z1=1; z1<=cptcoveff; z1++){
                   3360:          fprintf(ficresp, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
                   3361:          fprintf(ficresphtm, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
1.214     brouard  3362:          fprintf(ficresphtmfr, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
1.213     brouard  3363:        }
                   3364:          fprintf(ficresp, "**********\n#");
1.214     brouard  3365:        fprintf(ficresphtm, "**********</h3>\n");
                   3366:        fprintf(ficresphtmfr, "**********</h3>\n");
1.143     brouard  3367:        fprintf(ficlog, "\n#********** Variable "); 
1.198     brouard  3368:        for (z1=1; z1<=cptcoveff; z1++) fprintf(ficlog, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
1.214     brouard  3369:        fprintf(ficlog, "**********\n");
1.126     brouard  3370:       }
1.214     brouard  3371:       fprintf(ficresphtm,"<table style=\"text-align:center; border: 1px solid\">");
1.213     brouard  3372:       for(i=1; i<=nlstate;i++) {
1.126     brouard  3373:        fprintf(ficresp, " Age Prev(%d) N(%d) N",i,i);
1.213     brouard  3374:        fprintf(ficresphtm, "<th>Age</th><th>Prev(%d)</th><th>N(%d)</th><th>N</th>",i,i);
                   3375:       }
1.126     brouard  3376:       fprintf(ficresp, "\n");
1.213     brouard  3377:       fprintf(ficresphtm, "\n");
1.126     brouard  3378:       
1.214     brouard  3379:       /* Header of frequency table by age */
                   3380:       fprintf(ficresphtmfr,"<table style=\"text-align:center; border: 1px solid\">");
                   3381:       fprintf(ficresphtmfr,"<th>Age</th> ");
                   3382:       for(jk=-1; jk <=nlstate+ndeath; jk++){
                   3383:        for(m=-1; m <=nlstate+ndeath; m++){
                   3384:          if(jk!=0 && m!=0)
                   3385:            fprintf(ficresphtmfr,"<th>%d%d</th> ",jk,m);
                   3386:        }
                   3387:       }
                   3388:       fprintf(ficresphtmfr, "\n");
                   3389:       
                   3390:       /* For each age */
1.126     brouard  3391:       for(i=iagemin; i <= iagemax+3; i++){
1.213     brouard  3392:        fprintf(ficresphtm,"<tr>");
1.214     brouard  3393:        if(i==iagemax+1){
                   3394:          fprintf(ficlog,"1");
                   3395:          fprintf(ficresphtmfr,"<tr><th>0</th> ");
                   3396:        }else if(i==iagemax+2){
                   3397:          fprintf(ficlog,"0");
                   3398:          fprintf(ficresphtmfr,"<tr><th>Unknown</th> ");
                   3399:        }else if(i==iagemax+3){
1.126     brouard  3400:          fprintf(ficlog,"Total");
1.214     brouard  3401:          fprintf(ficresphtmfr,"<tr><th>Total</th> ");
1.126     brouard  3402:        }else{
                   3403:          if(first==1){
                   3404:            first=0;
                   3405:            printf("See log file for details...\n");
                   3406:          }
1.214     brouard  3407:          fprintf(ficresphtmfr,"<tr><th>%d</th> ",i);
1.126     brouard  3408:          fprintf(ficlog,"Age %d", i);
                   3409:        }
                   3410:        for(jk=1; jk <=nlstate ; jk++){
                   3411:          for(m=-1, pp[jk]=0; m <=nlstate+ndeath ; m++)
                   3412:            pp[jk] += freq[jk][m][i]; 
                   3413:        }
                   3414:        for(jk=1; jk <=nlstate ; jk++){
                   3415:          for(m=-1, pos=0; m <=0 ; m++)
                   3416:            pos += freq[jk][m][i];
                   3417:          if(pp[jk]>=1.e-10){
                   3418:            if(first==1){
1.132     brouard  3419:              printf(" %d.=%.0f loss[%d]=%.1f%%",jk,pp[jk],jk,100*pos/pp[jk]);
1.126     brouard  3420:            }
                   3421:            fprintf(ficlog," %d.=%.0f loss[%d]=%.1f%%",jk,pp[jk],jk,100*pos/pp[jk]);
                   3422:          }else{
                   3423:            if(first==1)
                   3424:              printf(" %d.=%.0f loss[%d]=NaNQ%%",jk,pp[jk],jk);
                   3425:            fprintf(ficlog," %d.=%.0f loss[%d]=NaNQ%%",jk,pp[jk],jk);
                   3426:          }
                   3427:        }
                   3428: 
                   3429:        for(jk=1; jk <=nlstate ; jk++){
                   3430:          for(m=0, pp[jk]=0; m <=nlstate+ndeath; m++)
                   3431:            pp[jk] += freq[jk][m][i];
                   3432:        }       
                   3433:        for(jk=1,pos=0,posprop=0; jk <=nlstate ; jk++){
                   3434:          pos += pp[jk];
                   3435:          posprop += prop[jk][i];
                   3436:        }
                   3437:        for(jk=1; jk <=nlstate ; jk++){
                   3438:          if(pos>=1.e-5){
                   3439:            if(first==1)
                   3440:              printf(" %d.=%.0f prev[%d]=%.1f%%",jk,pp[jk],jk,100*pp[jk]/pos);
                   3441:            fprintf(ficlog," %d.=%.0f prev[%d]=%.1f%%",jk,pp[jk],jk,100*pp[jk]/pos);
                   3442:          }else{
                   3443:            if(first==1)
                   3444:              printf(" %d.=%.0f prev[%d]=NaNQ%%",jk,pp[jk],jk);
                   3445:            fprintf(ficlog," %d.=%.0f prev[%d]=NaNQ%%",jk,pp[jk],jk);
                   3446:          }
                   3447:          if( i <= iagemax){
                   3448:            if(pos>=1.e-5){
                   3449:              fprintf(ficresp," %d %.5f %.0f %.0f",i,prop[jk][i]/posprop, prop[jk][i],posprop);
1.213     brouard  3450:              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  3451:              /*probs[i][jk][j1]= pp[jk]/pos;*/
                   3452:              /*printf("\ni=%d jk=%d j1=%d %.5f %.0f %.0f %f",i,jk,j1,pp[jk]/pos, pp[jk],pos,probs[i][jk][j1]);*/
                   3453:            }
1.213     brouard  3454:            else{
1.126     brouard  3455:              fprintf(ficresp," %d NaNq %.0f %.0f",i,prop[jk][i],posprop);
1.213     brouard  3456:              fprintf(ficresphtm,"<th>%d</th><td>NaNq</td><td>%.0f</td><td>%.0f</td>",i, prop[jk][i],posprop);
                   3457:            }
1.126     brouard  3458:          }
                   3459:        }
                   3460:        
1.214     brouard  3461:        for(jk=-1; jk <=nlstate+ndeath; jk++){
                   3462:          for(m=-1; m <=nlstate+ndeath; m++){
                   3463:            if(freq[jk][m][i] !=0 ) { /* minimizing output */
                   3464:              if(first==1){
                   3465:                printf(" %d%d=%.0f",jk,m,freq[jk][m][i]);
                   3466:              }
1.126     brouard  3467:              fprintf(ficlog," %d%d=%.0f",jk,m,freq[jk][m][i]);
                   3468:            }
1.214     brouard  3469:            if(jk!=0 && m!=0)
                   3470:              fprintf(ficresphtmfr,"<td>%.0f</td> ",freq[jk][m][i]);
                   3471:          }
                   3472:        }
                   3473:        fprintf(ficresphtmfr,"</tr>\n ");
1.213     brouard  3474:        if(i <= iagemax){
1.126     brouard  3475:          fprintf(ficresp,"\n");
1.213     brouard  3476:          fprintf(ficresphtm,"</tr>\n");
                   3477:        }
1.126     brouard  3478:        if(first==1)
                   3479:          printf("Others in log...\n");
                   3480:        fprintf(ficlog,"\n");
1.210     brouard  3481:       } /* end loop i */
1.213     brouard  3482:       fprintf(ficresphtm,"</table>\n");
1.214     brouard  3483:       fprintf(ficresphtmfr,"</table>\n");
1.145     brouard  3484:       /*}*/
1.210     brouard  3485:   } /* end j1 */
1.126     brouard  3486:   dateintmean=dateintsum/k2cpt; 
                   3487:  
                   3488:   fclose(ficresp);
1.213     brouard  3489:   fclose(ficresphtm);
1.214     brouard  3490:   fclose(ficresphtmfr);
1.126     brouard  3491:   free_ma3x(freq,-5,nlstate+ndeath,-5,nlstate+ndeath, iagemin, iagemax+3);
                   3492:   free_vector(pp,1,nlstate);
                   3493:   free_matrix(prop,1,nlstate,iagemin, iagemax+3);
                   3494:   /* End of Freq */
                   3495: }
                   3496: 
                   3497: /************ Prevalence ********************/
                   3498: 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)
                   3499: {  
                   3500:   /* Compute observed prevalence between dateprev1 and dateprev2 by counting the number of people
                   3501:      in each health status at the date of interview (if between dateprev1 and dateprev2).
                   3502:      We still use firstpass and lastpass as another selection.
                   3503:   */
                   3504:  
1.164     brouard  3505:   int i, m, jk, j1, bool, z1,j;
1.214     brouard  3506:   int mi; /* Effective wave */
                   3507:   int iage;
                   3508:   double agebegin, ageend;
1.164     brouard  3509: 
                   3510:   double **prop;
                   3511:   double posprop; 
1.126     brouard  3512:   double  y2; /* in fractional years */
                   3513:   int iagemin, iagemax;
1.145     brouard  3514:   int first; /** to stop verbosity which is redirected to log file */
1.126     brouard  3515: 
                   3516:   iagemin= (int) agemin;
                   3517:   iagemax= (int) agemax;
                   3518:   /*pp=vector(1,nlstate);*/
                   3519:   prop=matrix(1,nlstate,iagemin,iagemax+3); 
                   3520:   /*  freq=ma3x(-1,nlstate+ndeath,-1,nlstate+ndeath,iagemin,iagemax+3);*/
                   3521:   j1=0;
                   3522:   
1.145     brouard  3523:   /*j=cptcoveff;*/
1.126     brouard  3524:   if (cptcovn<1) {j=1;ncodemax[1]=1;}
                   3525:   
1.145     brouard  3526:   first=1;
                   3527:   for(j1=1; j1<= (int) pow(2,cptcoveff);j1++){
1.214     brouard  3528:     for (i=1; i<=nlstate; i++)  
                   3529:       for(iage=iagemin; iage <= iagemax+3; iage++)
                   3530:        prop[i][iage]=0.0;
                   3531:     
                   3532:     for (i=1; i<=imx; i++) { /* Each individual */
                   3533:       bool=1;
                   3534:       if  (cptcovn>0) {  /* Filter is here: Must be looked at for model=V1+V2+V3+V4 */
                   3535:        for (z1=1; z1<=cptcoveff; z1++) 
                   3536:          if (covar[Tvaraff[z1]][i]!= nbcode[Tvaraff[z1]][codtabm(j1,z1)]) 
                   3537:            bool=0;
                   3538:       } 
                   3539:       if (bool==1) { 
                   3540:        /* for(m=firstpass; m<=lastpass; m++){/\* Other selection (we can limit to certain interviews*\/ */
                   3541:        for(mi=1; mi<wav[i];mi++){
                   3542:          m=mw[mi][i];
                   3543:          agebegin=agev[m][i]; /* Age at beginning of wave before transition*/
                   3544:          /* ageend=agev[m][i]+(dh[m][i])*stepm/YEARM; /\* Age at end of wave and transition *\/ */
                   3545:          if(m >=firstpass && m <=lastpass){
1.126     brouard  3546:            y2=anint[m][i]+(mint[m][i]/12.); /* Fractional date in year */
                   3547:            if ((y2>=dateprev1) && (y2<=dateprev2)) { /* Here is the main selection (fractional years) */
                   3548:              if(agev[m][i]==0) agev[m][i]=iagemax+1;
                   3549:              if(agev[m][i]==1) agev[m][i]=iagemax+2;
                   3550:              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  3551:              if (s[m][i]>0 && s[m][i]<=nlstate) { 
1.126     brouard  3552:                /*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  3553:                prop[s[m][i]][(int)agev[m][i]] += weight[i];/* At age of beginning of transition, where status is known */
                   3554:                prop[s[m][i]][iagemax+3] += weight[i]; 
                   3555:              } /* end valid statuses */ 
                   3556:            } /* end selection of dates */
1.126     brouard  3557:          } /* end selection of waves */
1.214     brouard  3558:        } /* end effective waves */
                   3559:       } /* end bool */
                   3560:     }
                   3561:     for(i=iagemin; i <= iagemax+3; i++){  
                   3562:       for(jk=1,posprop=0; jk <=nlstate ; jk++) { 
                   3563:        posprop += prop[jk][i]; 
                   3564:       } 
                   3565:       
                   3566:       for(jk=1; jk <=nlstate ; jk++){      
                   3567:        if( i <=  iagemax){ 
                   3568:          if(posprop>=1.e-5){ 
                   3569:            probs[i][jk][j1]= prop[jk][i]/posprop;
                   3570:          } else{
                   3571:            if(first==1){
                   3572:              first=0;
                   3573:              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  3574:            }
1.214     brouard  3575:          }
                   3576:        } 
                   3577:       }/* end jk */ 
                   3578:     }/* end i */ 
1.145     brouard  3579:     /*} *//* end i1 */
                   3580:   } /* end j1 */
1.126     brouard  3581:   
                   3582:   /*  free_ma3x(freq,-1,nlstate+ndeath,-1,nlstate+ndeath, iagemin, iagemax+3);*/
                   3583:   /*free_vector(pp,1,nlstate);*/
                   3584:   free_matrix(prop,1,nlstate, iagemin,iagemax+3);
                   3585: }  /* End of prevalence */
                   3586: 
                   3587: /************* Waves Concatenation ***************/
                   3588: 
                   3589: 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)
                   3590: {
                   3591:   /* Concatenates waves: wav[i] is the number of effective (useful waves) of individual i.
                   3592:      Death is a valid wave (if date is known).
                   3593:      mw[mi][i] is the mi (mi=1 to wav[i])  effective wave of individual i
                   3594:      dh[m][i] or dh[mw[mi][i]][i] is the delay between two effective waves m=mw[mi][i]
                   3595:      and mw[mi+1][i]. dh depends on stepm.
                   3596:      */
                   3597: 
                   3598:   int i, mi, m;
                   3599:   /* int j, k=0,jk, ju, jl,jmin=1e+5, jmax=-1;
                   3600:      double sum=0., jmean=0.;*/
1.214     brouard  3601:   int first, firstwo;
1.126     brouard  3602:   int j, k=0,jk, ju, jl;
                   3603:   double sum=0.;
                   3604:   first=0;
1.214     brouard  3605:   firstwo=0;
1.164     brouard  3606:   jmin=100000;
1.126     brouard  3607:   jmax=-1;
                   3608:   jmean=0.;
1.214     brouard  3609:   for(i=1; i<=imx; i++){  /* For simple cases and if state is death */
1.126     brouard  3610:     mi=0;
                   3611:     m=firstpass;
1.214     brouard  3612:     while(s[m][i] <= nlstate){  /* a live state */
1.126     brouard  3613:       if(s[m][i]>=1 || s[m][i]==-2 || s[m][i]==-4 || s[m][i]==-5)
                   3614:        mw[++mi][i]=m;
                   3615:       if(m >=lastpass)
                   3616:        break;
                   3617:       else
                   3618:        m++;
                   3619:     }/* end while */
1.214     brouard  3620:     if (s[m][i] > nlstate){  /* In a death state */
1.126     brouard  3621:       mi++;    /* Death is another wave */
                   3622:       /* if(mi==0)  never been interviewed correctly before death */
                   3623:         /* Only death is a correct wave */
                   3624:       mw[mi][i]=m;
1.214     brouard  3625:     }else if (andc[i] != 9999) { /* A death occured after lastpass */
                   3626:       m++;
                   3627:       mi++;
                   3628:       s[m][i]=nlstate+1;  /* We are setting the status to the last of non live state */
                   3629:       mw[mi][i]=m;
                   3630:       nbwarn++;
                   3631:       if(firstwo==0){
                   3632:        printf("Warning! Death for individual %ld line=%d  occurred after last wave %d. Since 0.98r4 we considered a status %d at wave %d\nOthers in log file only\n",num[i],i,lastpass,nlstate+1, m);
                   3633:        fprintf(ficlog,"Warning! Death for individual %ld line=%d  occurred after last wave %d. Since 0.98r4 we considered a status %d at wave %d\n",num[i],i,lastpass,nlstate+1, m);
                   3634:        firstwo=1;
                   3635:       }
                   3636:       if(firstwo==1){
                   3637:        fprintf(ficlog,"Warning! Death for individual %ld line=%d  occurred after last wave %d. Since 0.98r4 we considered a status %d at wave %d\n",num[i],i,lastpass,nlstate+1, m);
                   3638:       }
1.126     brouard  3639:     }
                   3640:     wav[i]=mi;
                   3641:     if(mi==0){
                   3642:       nbwarn++;
                   3643:       if(first==0){
                   3644:        printf("Warning! No valid information for individual %ld line=%d (skipped) and may be others, see log file\n",num[i],i);
                   3645:        first=1;
                   3646:       }
                   3647:       if(first==1){
                   3648:        fprintf(ficlog,"Warning! No valid information for individual %ld line=%d (skipped)\n",num[i],i);
                   3649:       }
                   3650:     } /* end mi==0 */
                   3651:   } /* End individuals */
1.214     brouard  3652:   /* wav and mw are no more changed */
1.126     brouard  3653: 
1.214     brouard  3654:   
1.126     brouard  3655:   for(i=1; i<=imx; i++){
                   3656:     for(mi=1; mi<wav[i];mi++){
                   3657:       if (stepm <=0)
                   3658:        dh[mi][i]=1;
                   3659:       else{
                   3660:        if (s[mw[mi+1][i]][i] > nlstate) { /* A death */
                   3661:          if (agedc[i] < 2*AGESUP) {
                   3662:            j= rint(agedc[i]*12-agev[mw[mi][i]][i]*12); 
                   3663:            if(j==0) j=1;  /* Survives at least one month after exam */
                   3664:            else if(j<0){
                   3665:              nberr++;
                   3666:              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]);
                   3667:              j=1; /* Temporary Dangerous patch */
                   3668:              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);
                   3669:              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]);
                   3670:              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);
                   3671:            }
                   3672:            k=k+1;
                   3673:            if (j >= jmax){
                   3674:              jmax=j;
                   3675:              ijmax=i;
                   3676:            }
                   3677:            if (j <= jmin){
                   3678:              jmin=j;
                   3679:              ijmin=i;
                   3680:            }
                   3681:            sum=sum+j;
                   3682:            /*if (j<0) printf("j=%d num=%d \n",j,i);*/
                   3683:            /*    printf("%d %d %d %d\n", s[mw[mi][i]][i] ,s[mw[mi+1][i]][i],j,i);*/
                   3684:          }
                   3685:        }
                   3686:        else{
                   3687:          j= rint( (agev[mw[mi+1][i]][i]*12 - agev[mw[mi][i]][i]*12));
                   3688: /*       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]); */
                   3689: 
                   3690:          k=k+1;
                   3691:          if (j >= jmax) {
                   3692:            jmax=j;
                   3693:            ijmax=i;
                   3694:          }
                   3695:          else if (j <= jmin){
                   3696:            jmin=j;
                   3697:            ijmin=i;
                   3698:          }
                   3699:          /*        if (j<10) printf("j=%d jmin=%d num=%d ",j,jmin,i); */
                   3700:          /*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]);*/
                   3701:          if(j<0){
                   3702:            nberr++;
                   3703:            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]);
                   3704:            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]);
                   3705:          }
                   3706:          sum=sum+j;
                   3707:        }
                   3708:        jk= j/stepm;
                   3709:        jl= j -jk*stepm;
                   3710:        ju= j -(jk+1)*stepm;
                   3711:        if(mle <=1){ /* only if we use a the linear-interpoloation pseudo-likelihood */
                   3712:          if(jl==0){
                   3713:            dh[mi][i]=jk;
                   3714:            bh[mi][i]=0;
                   3715:          }else{ /* We want a negative bias in order to only have interpolation ie
1.136     brouard  3716:                  * to avoid the price of an extra matrix product in likelihood */
1.126     brouard  3717:            dh[mi][i]=jk+1;
                   3718:            bh[mi][i]=ju;
                   3719:          }
                   3720:        }else{
                   3721:          if(jl <= -ju){
                   3722:            dh[mi][i]=jk;
                   3723:            bh[mi][i]=jl;       /* bias is positive if real duration
                   3724:                                 * is higher than the multiple of stepm and negative otherwise.
                   3725:                                 */
                   3726:          }
                   3727:          else{
                   3728:            dh[mi][i]=jk+1;
                   3729:            bh[mi][i]=ju;
                   3730:          }
                   3731:          if(dh[mi][i]==0){
                   3732:            dh[mi][i]=1; /* At least one step */
                   3733:            bh[mi][i]=ju; /* At least one step */
                   3734:            /*  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);*/
                   3735:          }
                   3736:        } /* end if mle */
                   3737:       }
                   3738:     } /* end wave */
                   3739:   }
                   3740:   jmean=sum/k;
                   3741:   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  3742:   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  3743:  }
                   3744: 
                   3745: /*********** Tricode ****************************/
1.145     brouard  3746: void tricode(int *Tvar, int **nbcode, int imx, int *Ndum)
1.126     brouard  3747: {
1.144     brouard  3748:   /**< Uses cptcovn+2*cptcovprod as the number of covariates */
                   3749:   /*     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  3750:    * Boring subroutine which should only output nbcode[Tvar[j]][k]
1.145     brouard  3751:    * Tvar[5] in V2+V1+V3*age+V2*V4 is 2 (V2)
1.169     brouard  3752:    * nbcode[Tvar[j]][1]= 
1.144     brouard  3753:   */
1.130     brouard  3754: 
1.145     brouard  3755:   int ij=1, k=0, j=0, i=0, maxncov=NCOVMAX;
1.136     brouard  3756:   int modmaxcovj=0; /* Modality max of covariates j */
1.145     brouard  3757:   int cptcode=0; /* Modality max of covariates j */
                   3758:   int modmincovj=0; /* Modality min of covariates j */
                   3759: 
                   3760: 
1.126     brouard  3761:   cptcoveff=0; 
                   3762:  
1.144     brouard  3763:   for (k=1; k <= maxncov; k++) ncodemax[k]=0; /* Horrible constant again replaced by NCOVMAX */
1.126     brouard  3764: 
1.145     brouard  3765:   /* Loop on covariates without age and products */
1.186     brouard  3766:   for (j=1; j<=(cptcovs); j++) { /* From model V1 + V2*age+ V3 + V3*V4 keeps V1 + V3 = 2 only */
1.192     brouard  3767:     for (k=-1; k < maxncov; k++) Ndum[k]=0;
1.186     brouard  3768:     for (i=1; i<=imx; i++) { /* Loop on individuals: reads the data file to get the maximum value of the 
1.136     brouard  3769:                               modality of this covariate Vj*/ 
1.145     brouard  3770:       ij=(int)(covar[Tvar[j]][i]); /* ij=0 or 1 or -1. Value of the covariate Tvar[j] for individual i
                   3771:                                    * If product of Vn*Vm, still boolean *:
                   3772:                                    * If it was coded 1, 2, 3, 4 should be splitted into 3 boolean variables
                   3773:                                    * 1 => 0 0 0, 2 => 0 0 1, 3 => 0 1 1, 4=1 0 0   */
                   3774:       /* Finds for covariate j, n=Tvar[j] of Vn . ij is the
1.136     brouard  3775:                                      modality of the nth covariate of individual i. */
1.145     brouard  3776:       if (ij > modmaxcovj)
                   3777:         modmaxcovj=ij; 
                   3778:       else if (ij < modmincovj) 
                   3779:        modmincovj=ij; 
                   3780:       if ((ij < -1) && (ij > NCOVMAX)){
                   3781:        printf( "Error: minimal is less than -1 or maximal is bigger than %d. Exiting. \n", NCOVMAX );
                   3782:        exit(1);
                   3783:       }else
1.136     brouard  3784:       Ndum[ij]++; /*counts and stores the occurence of this modality 0, 1, -1*/
1.145     brouard  3785:       /*  If coded 1, 2, 3 , counts the number of 1 Ndum[1], number of 2, Ndum[2], etc */
1.126     brouard  3786:       /*printf("i=%d ij=%d Ndum[ij]=%d imx=%d",i,ij,Ndum[ij],imx);*/
1.136     brouard  3787:       /* getting the maximum value of the modality of the covariate
                   3788:         (should be 0 or 1 now) Tvar[j]. If V=sex and male is coded 0 and
                   3789:         female is 1, then modmaxcovj=1.*/
1.192     brouard  3790:     } /* end for loop on individuals i */
1.145     brouard  3791:     printf(" Minimal and maximal values of %d th covariate V%d: min=%d max=%d \n", j, Tvar[j], modmincovj, modmaxcovj);
1.192     brouard  3792:     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  3793:     cptcode=modmaxcovj;
1.137     brouard  3794:     /* Ndum[0] = frequency of 0 for model-covariate j, Ndum[1] frequency of 1 etc. */
1.145     brouard  3795:    /*for (i=0; i<=cptcode; i++) {*/
1.192     brouard  3796:     for (k=modmincovj;  k<=modmaxcovj; k++) { /* k=-1 ? 0 and 1*//* For each value k of the modality of model-cov j */
                   3797:       printf("Frequencies of covariates %d ie V%d with value %d: %d\n", j, Tvar[j], k, Ndum[k]);
                   3798:       fprintf(ficlog, "Frequencies of covariates %d ie V%d with value %d: %d\n", j, Tvar[j], k, Ndum[k]);
                   3799:       if( Ndum[k] != 0 ){ /* Counts if nobody answered modality k ie empty modality, we skip it and reorder */
                   3800:        if( k != -1){
                   3801:          ncodemax[j]++;  /* ncodemax[j]= Number of modalities of the j th
                   3802:                             covariate for which somebody answered excluding 
                   3803:                             undefined. Usually 2: 0 and 1. */
                   3804:        }
                   3805:        ncodemaxwundef[j]++; /* ncodemax[j]= Number of modalities of the j th
                   3806:                             covariate for which somebody answered including 
                   3807:                             undefined. Usually 3: -1, 0 and 1. */
1.145     brouard  3808:       }
                   3809:       /* In fact  ncodemax[j]=2 (dichotom. variables only) but it could be more for
                   3810:         historical reasons: 3 if coded 1, 2, 3 and 4 and Ndum[2]=0 */
1.131     brouard  3811:     } /* Ndum[-1] number of undefined modalities */
1.126     brouard  3812: 
1.136     brouard  3813:     /* j is a covariate, n=Tvar[j] of Vn; Fills nbcode */
1.186     brouard  3814:     /* For covariate j, modalities could be 1, 2, 3, 4, 5, 6, 7. 
                   3815:        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  3816:        modmincovj=3; modmaxcovj = 7;
1.186     brouard  3817:        There are only 3 modalities non empty 3, 6, 7 (or 2 if 27 is too few) : ncodemax[j]=3;
                   3818:        which will be coded 0, 1, 2 which in binary on 2=3-1 digits are 0=00 1=01, 2=10;
                   3819:        defining two dummy variables: variables V1_1 and V1_2.
1.145     brouard  3820:        nbcode[Tvar[j]][ij]=k;
                   3821:        nbcode[Tvar[j]][1]=0;
                   3822:        nbcode[Tvar[j]][2]=1;
                   3823:        nbcode[Tvar[j]][3]=2;
1.197     brouard  3824:        To be continued (not working yet).
1.145     brouard  3825:     */
1.197     brouard  3826:     ij=0; /* ij is similar to i but can jump over null modalities */
                   3827:     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*/
                   3828:        if (Ndum[i] == 0) { /* If nobody responded to this modality k */
1.192     brouard  3829:          break;
                   3830:        }
                   3831:        ij++;
1.197     brouard  3832:        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  3833:        cptcode = ij; /* New max modality for covar j */
                   3834:     } /* end of loop on modality i=-1 to 1 or more */
                   3835:       
                   3836:     /*   for (k=0; k<= cptcode; k++) { /\* k=-1 ? k=0 to 1 *\//\* Could be 1 to 4 *\//\* cptcode=modmaxcovj *\/ */
                   3837:     /*         /\*recode from 0 *\/ */
                   3838:     /*                                      k is a modality. If we have model=V1+V1*sex  */
                   3839:     /*                                      then: nbcode[1][1]=0 ; nbcode[1][2]=1; nbcode[2][1]=0 ; nbcode[2][2]=1; */
                   3840:     /*                                   But if some modality were not used, it is recoded from 0 to a newer modmaxcovj=cptcode *\/ */
                   3841:     /*         } */
                   3842:     /*         /\* cptcode = ij; *\/ /\* New max modality for covar j *\/ */
                   3843:     /*         if (ij > ncodemax[j]) { */
                   3844:     /*           printf( " Error ij=%d > ncodemax[%d]=%d\n", ij, j, ncodemax[j]);  */
                   3845:     /*           fprintf(ficlog, " Error ij=%d > ncodemax[%d]=%d\n", ij, j, ncodemax[j]); */
                   3846:     /*           break; */
                   3847:     /*         } */
                   3848:     /*   }  /\* end of loop on modality k *\/ */
1.137     brouard  3849:   } /* end of loop on model-covariate j. nbcode[Tvarj][1]=0 and nbcode[Tvarj][2]=1 sets the value of covariate j*/  
                   3850:   
1.145     brouard  3851:  for (k=-1; k< maxncov; k++) Ndum[k]=0; 
1.137     brouard  3852:   
1.187     brouard  3853:   for (i=1; i<=ncovmodel-2-nagesqr; i++) { /* -2, cste and age and eventually age*age */ 
1.145     brouard  3854:    /* Listing of all covariables in statement model to see if some covariates appear twice. For example, V1 appears twice in V1+V1*V2.*/ 
                   3855:    ij=Tvar[i]; /* Tvar might be -1 if status was unknown */ 
1.187     brouard  3856:    Ndum[ij]++; /* Might be supersed V1 + V1*age */
1.145     brouard  3857:  } 
1.126     brouard  3858: 
1.192     brouard  3859:  ij=0;
1.145     brouard  3860:  for (i=0; i<=  maxncov-1; i++) { /* modmaxcovj is unknown here. Only Ndum[2(V2),3(age*V3), 5(V3*V2) 6(V1*V4) */
                   3861:    /*printf("Ndum[%d]=%d\n",i, Ndum[i]);*/
1.126     brouard  3862:    if((Ndum[i]!=0) && (i<=ncovcol)){
1.192     brouard  3863:      ij++;
1.145     brouard  3864:      /*printf("diff Ndum[%d]=%d\n",i, Ndum[i]);*/
                   3865:      Tvaraff[ij]=i; /*For printing (unclear) */
1.192     brouard  3866:    }else{
                   3867:        /* Tvaraff[ij]=0; */
                   3868:    }
1.126     brouard  3869:  }
1.192     brouard  3870:  /* ij--; */
1.144     brouard  3871:  cptcoveff=ij; /*Number of total covariates*/
1.145     brouard  3872: 
1.126     brouard  3873: }
                   3874: 
1.145     brouard  3875: 
1.126     brouard  3876: /*********** Health Expectancies ****************/
                   3877: 
1.127     brouard  3878: 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  3879: 
                   3880: {
                   3881:   /* Health expectancies, no variances */
1.164     brouard  3882:   int i, j, nhstepm, hstepm, h, nstepm;
1.126     brouard  3883:   int nhstepma, nstepma; /* Decreasing with age */
                   3884:   double age, agelim, hf;
                   3885:   double ***p3mat;
                   3886:   double eip;
                   3887: 
                   3888:   pstamp(ficreseij);
                   3889:   fprintf(ficreseij,"# (a) Life expectancies by health status at initial age and (b) health expectancies by health status at initial age\n");
                   3890:   fprintf(ficreseij,"# Age");
                   3891:   for(i=1; i<=nlstate;i++){
                   3892:     for(j=1; j<=nlstate;j++){
                   3893:       fprintf(ficreseij," e%1d%1d ",i,j);
                   3894:     }
                   3895:     fprintf(ficreseij," e%1d. ",i);
                   3896:   }
                   3897:   fprintf(ficreseij,"\n");
                   3898: 
                   3899:   
                   3900:   if(estepm < stepm){
                   3901:     printf ("Problem %d lower than %d\n",estepm, stepm);
                   3902:   }
                   3903:   else  hstepm=estepm;   
                   3904:   /* We compute the life expectancy from trapezoids spaced every estepm months
                   3905:    * This is mainly to measure the difference between two models: for example
                   3906:    * if stepm=24 months pijx are given only every 2 years and by summing them
                   3907:    * we are calculating an estimate of the Life Expectancy assuming a linear 
                   3908:    * progression in between and thus overestimating or underestimating according
                   3909:    * to the curvature of the survival function. If, for the same date, we 
                   3910:    * estimate the model with stepm=1 month, we can keep estepm to 24 months
                   3911:    * to compare the new estimate of Life expectancy with the same linear 
                   3912:    * hypothesis. A more precise result, taking into account a more precise
                   3913:    * curvature will be obtained if estepm is as small as stepm. */
                   3914: 
                   3915:   /* For example we decided to compute the life expectancy with the smallest unit */
                   3916:   /* hstepm beeing the number of stepms, if hstepm=1 the length of hstepm is stepm. 
                   3917:      nhstepm is the number of hstepm from age to agelim 
                   3918:      nstepm is the number of stepm from age to agelin. 
                   3919:      Look at hpijx to understand the reason of that which relies in memory size
                   3920:      and note for a fixed period like estepm months */
                   3921:   /* We decided (b) to get a life expectancy respecting the most precise curvature of the
                   3922:      survival function given by stepm (the optimization length). Unfortunately it
                   3923:      means that if the survival funtion is printed only each two years of age and if
                   3924:      you sum them up and add 1 year (area under the trapezoids) you won't get the same 
                   3925:      results. So we changed our mind and took the option of the best precision.
                   3926:   */
                   3927:   hstepm=hstepm/stepm; /* Typically in stepm units, if stepm=6 & estepm=24 , = 24/6 months = 4 */ 
                   3928: 
                   3929:   agelim=AGESUP;
                   3930:   /* If stepm=6 months */
                   3931:     /* Computed by stepm unit matrices, product of hstepm matrices, stored
                   3932:        in an array of nhstepm length: nhstepm=10, hstepm=4, stepm=6 months */
                   3933:     
                   3934: /* nhstepm age range expressed in number of stepm */
                   3935:   nstepm=(int) rint((agelim-bage)*YEARM/stepm); /* Biggest nstepm */
                   3936:   /* Typically if 20 years nstepm = 20*12/6=40 stepm */ 
                   3937:   /* if (stepm >= YEARM) hstepm=1;*/
                   3938:   nhstepm = nstepm/hstepm;/* Expressed in hstepm, typically nhstepm=40/4=10 */
                   3939:   p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   3940: 
                   3941:   for (age=bage; age<=fage; age ++){ 
                   3942:     nstepma=(int) rint((agelim-bage)*YEARM/stepm); /* Biggest nstepm */
                   3943:     /* Typically if 20 years nstepm = 20*12/6=40 stepm */ 
                   3944:     /* if (stepm >= YEARM) hstepm=1;*/
                   3945:     nhstepma = nstepma/hstepm;/* Expressed in hstepm, typically nhstepma=40/4=10 */
                   3946: 
                   3947:     /* If stepm=6 months */
                   3948:     /* Computed by stepm unit matrices, product of hstepma matrices, stored
                   3949:        in an array of nhstepma length: nhstepma=10, hstepm=4, stepm=6 months */
                   3950:     
                   3951:     hpxij(p3mat,nhstepma,age,hstepm,x,nlstate,stepm,oldm, savm, cij);  
                   3952:     
                   3953:     hf=hstepm*stepm/YEARM;  /* Duration of hstepm expressed in year unit. */
                   3954:     
                   3955:     printf("%d|",(int)age);fflush(stdout);
                   3956:     fprintf(ficlog,"%d|",(int)age);fflush(ficlog);
                   3957:     
                   3958:     /* Computing expectancies */
                   3959:     for(i=1; i<=nlstate;i++)
                   3960:       for(j=1; j<=nlstate;j++)
                   3961:        for (h=0, eij[i][j][(int)age]=0; h<=nhstepm-1; h++){
                   3962:          eij[i][j][(int)age] += (p3mat[i][j][h]+p3mat[i][j][h+1])/2.0*hf;
                   3963:          
                   3964:          /* 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]);*/
                   3965: 
                   3966:        }
                   3967: 
                   3968:     fprintf(ficreseij,"%3.0f",age );
                   3969:     for(i=1; i<=nlstate;i++){
                   3970:       eip=0;
                   3971:       for(j=1; j<=nlstate;j++){
                   3972:        eip +=eij[i][j][(int)age];
                   3973:        fprintf(ficreseij,"%9.4f", eij[i][j][(int)age] );
                   3974:       }
                   3975:       fprintf(ficreseij,"%9.4f", eip );
                   3976:     }
                   3977:     fprintf(ficreseij,"\n");
                   3978:     
                   3979:   }
                   3980:   free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   3981:   printf("\n");
                   3982:   fprintf(ficlog,"\n");
                   3983:   
                   3984: }
                   3985: 
1.127     brouard  3986: 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  3987: 
                   3988: {
                   3989:   /* Covariances of health expectancies eij and of total life expectancies according
                   3990:    to initial status i, ei. .
                   3991:   */
                   3992:   int i, j, nhstepm, hstepm, h, nstepm, k, cptj, cptj2, i2, j2, ij, ji;
                   3993:   int nhstepma, nstepma; /* Decreasing with age */
                   3994:   double age, agelim, hf;
                   3995:   double ***p3matp, ***p3matm, ***varhe;
                   3996:   double **dnewm,**doldm;
                   3997:   double *xp, *xm;
                   3998:   double **gp, **gm;
                   3999:   double ***gradg, ***trgradg;
                   4000:   int theta;
                   4001: 
                   4002:   double eip, vip;
                   4003: 
                   4004:   varhe=ma3x(1,nlstate*nlstate,1,nlstate*nlstate,(int) bage, (int) fage);
                   4005:   xp=vector(1,npar);
                   4006:   xm=vector(1,npar);
                   4007:   dnewm=matrix(1,nlstate*nlstate,1,npar);
                   4008:   doldm=matrix(1,nlstate*nlstate,1,nlstate*nlstate);
                   4009:   
                   4010:   pstamp(ficresstdeij);
                   4011:   fprintf(ficresstdeij,"# Health expectancies with standard errors\n");
                   4012:   fprintf(ficresstdeij,"# Age");
                   4013:   for(i=1; i<=nlstate;i++){
                   4014:     for(j=1; j<=nlstate;j++)
                   4015:       fprintf(ficresstdeij," e%1d%1d (SE)",i,j);
                   4016:     fprintf(ficresstdeij," e%1d. ",i);
                   4017:   }
                   4018:   fprintf(ficresstdeij,"\n");
                   4019: 
                   4020:   pstamp(ficrescveij);
                   4021:   fprintf(ficrescveij,"# Subdiagonal matrix of covariances of health expectancies by age: cov(eij,ekl)\n");
                   4022:   fprintf(ficrescveij,"# Age");
                   4023:   for(i=1; i<=nlstate;i++)
                   4024:     for(j=1; j<=nlstate;j++){
                   4025:       cptj= (j-1)*nlstate+i;
                   4026:       for(i2=1; i2<=nlstate;i2++)
                   4027:        for(j2=1; j2<=nlstate;j2++){
                   4028:          cptj2= (j2-1)*nlstate+i2;
                   4029:          if(cptj2 <= cptj)
                   4030:            fprintf(ficrescveij,"  %1d%1d,%1d%1d",i,j,i2,j2);
                   4031:        }
                   4032:     }
                   4033:   fprintf(ficrescveij,"\n");
                   4034:   
                   4035:   if(estepm < stepm){
                   4036:     printf ("Problem %d lower than %d\n",estepm, stepm);
                   4037:   }
                   4038:   else  hstepm=estepm;   
                   4039:   /* We compute the life expectancy from trapezoids spaced every estepm months
                   4040:    * This is mainly to measure the difference between two models: for example
                   4041:    * if stepm=24 months pijx are given only every 2 years and by summing them
                   4042:    * we are calculating an estimate of the Life Expectancy assuming a linear 
                   4043:    * progression in between and thus overestimating or underestimating according
                   4044:    * to the curvature of the survival function. If, for the same date, we 
                   4045:    * estimate the model with stepm=1 month, we can keep estepm to 24 months
                   4046:    * to compare the new estimate of Life expectancy with the same linear 
                   4047:    * hypothesis. A more precise result, taking into account a more precise
                   4048:    * curvature will be obtained if estepm is as small as stepm. */
                   4049: 
                   4050:   /* For example we decided to compute the life expectancy with the smallest unit */
                   4051:   /* hstepm beeing the number of stepms, if hstepm=1 the length of hstepm is stepm. 
                   4052:      nhstepm is the number of hstepm from age to agelim 
                   4053:      nstepm is the number of stepm from age to agelin. 
                   4054:      Look at hpijx to understand the reason of that which relies in memory size
                   4055:      and note for a fixed period like estepm months */
                   4056:   /* We decided (b) to get a life expectancy respecting the most precise curvature of the
                   4057:      survival function given by stepm (the optimization length). Unfortunately it
                   4058:      means that if the survival funtion is printed only each two years of age and if
                   4059:      you sum them up and add 1 year (area under the trapezoids) you won't get the same 
                   4060:      results. So we changed our mind and took the option of the best precision.
                   4061:   */
                   4062:   hstepm=hstepm/stepm; /* Typically in stepm units, if stepm=6 & estepm=24 , = 24/6 months = 4 */ 
                   4063: 
                   4064:   /* If stepm=6 months */
                   4065:   /* nhstepm age range expressed in number of stepm */
                   4066:   agelim=AGESUP;
                   4067:   nstepm=(int) rint((agelim-bage)*YEARM/stepm); 
                   4068:   /* Typically if 20 years nstepm = 20*12/6=40 stepm */ 
                   4069:   /* if (stepm >= YEARM) hstepm=1;*/
                   4070:   nhstepm = nstepm/hstepm;/* Expressed in hstepm, typically nhstepm=40/4=10 */
                   4071:   
                   4072:   p3matp=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   4073:   p3matm=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   4074:   gradg=ma3x(0,nhstepm,1,npar,1,nlstate*nlstate);
                   4075:   trgradg =ma3x(0,nhstepm,1,nlstate*nlstate,1,npar);
                   4076:   gp=matrix(0,nhstepm,1,nlstate*nlstate);
                   4077:   gm=matrix(0,nhstepm,1,nlstate*nlstate);
                   4078: 
                   4079:   for (age=bage; age<=fage; age ++){ 
                   4080:     nstepma=(int) rint((agelim-bage)*YEARM/stepm); /* Biggest nstepm */
                   4081:     /* Typically if 20 years nstepm = 20*12/6=40 stepm */ 
                   4082:     /* if (stepm >= YEARM) hstepm=1;*/
                   4083:     nhstepma = nstepma/hstepm;/* Expressed in hstepm, typically nhstepma=40/4=10 */
                   4084: 
                   4085:     /* If stepm=6 months */
                   4086:     /* Computed by stepm unit matrices, product of hstepma matrices, stored
                   4087:        in an array of nhstepma length: nhstepma=10, hstepm=4, stepm=6 months */
                   4088:     
                   4089:     hf=hstepm*stepm/YEARM;  /* Duration of hstepm expressed in year unit. */
                   4090: 
                   4091:     /* Computing  Variances of health expectancies */
                   4092:     /* Gradient is computed with plus gp and minus gm. Code is duplicated in order to
                   4093:        decrease memory allocation */
                   4094:     for(theta=1; theta <=npar; theta++){
                   4095:       for(i=1; i<=npar; i++){ 
                   4096:        xp[i] = x[i] + (i==theta ?delti[theta]:0);
                   4097:        xm[i] = x[i] - (i==theta ?delti[theta]:0);
                   4098:       }
                   4099:       hpxij(p3matp,nhstepm,age,hstepm,xp,nlstate,stepm,oldm,savm, cij);  
                   4100:       hpxij(p3matm,nhstepm,age,hstepm,xm,nlstate,stepm,oldm,savm, cij);  
                   4101:   
                   4102:       for(j=1; j<= nlstate; j++){
                   4103:        for(i=1; i<=nlstate; i++){
                   4104:          for(h=0; h<=nhstepm-1; h++){
                   4105:            gp[h][(j-1)*nlstate + i] = (p3matp[i][j][h]+p3matp[i][j][h+1])/2.;
                   4106:            gm[h][(j-1)*nlstate + i] = (p3matm[i][j][h]+p3matm[i][j][h+1])/2.;
                   4107:          }
                   4108:        }
                   4109:       }
                   4110:      
                   4111:       for(ij=1; ij<= nlstate*nlstate; ij++)
                   4112:        for(h=0; h<=nhstepm-1; h++){
                   4113:          gradg[h][theta][ij]= (gp[h][ij]-gm[h][ij])/2./delti[theta];
                   4114:        }
                   4115:     }/* End theta */
                   4116:     
                   4117:     
                   4118:     for(h=0; h<=nhstepm-1; h++)
                   4119:       for(j=1; j<=nlstate*nlstate;j++)
                   4120:        for(theta=1; theta <=npar; theta++)
                   4121:          trgradg[h][j][theta]=gradg[h][theta][j];
                   4122:     
                   4123: 
                   4124:      for(ij=1;ij<=nlstate*nlstate;ij++)
                   4125:       for(ji=1;ji<=nlstate*nlstate;ji++)
                   4126:        varhe[ij][ji][(int)age] =0.;
                   4127: 
                   4128:      printf("%d|",(int)age);fflush(stdout);
                   4129:      fprintf(ficlog,"%d|",(int)age);fflush(ficlog);
                   4130:      for(h=0;h<=nhstepm-1;h++){
                   4131:       for(k=0;k<=nhstepm-1;k++){
                   4132:        matprod2(dnewm,trgradg[h],1,nlstate*nlstate,1,npar,1,npar,matcov);
                   4133:        matprod2(doldm,dnewm,1,nlstate*nlstate,1,npar,1,nlstate*nlstate,gradg[k]);
                   4134:        for(ij=1;ij<=nlstate*nlstate;ij++)
                   4135:          for(ji=1;ji<=nlstate*nlstate;ji++)
                   4136:            varhe[ij][ji][(int)age] += doldm[ij][ji]*hf*hf;
                   4137:       }
                   4138:     }
                   4139: 
                   4140:     /* Computing expectancies */
                   4141:     hpxij(p3matm,nhstepm,age,hstepm,x,nlstate,stepm,oldm, savm, cij);  
                   4142:     for(i=1; i<=nlstate;i++)
                   4143:       for(j=1; j<=nlstate;j++)
                   4144:        for (h=0, eij[i][j][(int)age]=0; h<=nhstepm-1; h++){
                   4145:          eij[i][j][(int)age] += (p3matm[i][j][h]+p3matm[i][j][h+1])/2.0*hf;
                   4146:          
                   4147:          /* 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]);*/
                   4148: 
                   4149:        }
                   4150: 
                   4151:     fprintf(ficresstdeij,"%3.0f",age );
                   4152:     for(i=1; i<=nlstate;i++){
                   4153:       eip=0.;
                   4154:       vip=0.;
                   4155:       for(j=1; j<=nlstate;j++){
                   4156:        eip += eij[i][j][(int)age];
                   4157:        for(k=1; k<=nlstate;k++) /* Sum on j and k of cov(eij,eik) */
                   4158:          vip += varhe[(j-1)*nlstate+i][(k-1)*nlstate+i][(int)age];
                   4159:        fprintf(ficresstdeij," %9.4f (%.4f)", eij[i][j][(int)age], sqrt(varhe[(j-1)*nlstate+i][(j-1)*nlstate+i][(int)age]) );
                   4160:       }
                   4161:       fprintf(ficresstdeij," %9.4f (%.4f)", eip, sqrt(vip));
                   4162:     }
                   4163:     fprintf(ficresstdeij,"\n");
                   4164: 
                   4165:     fprintf(ficrescveij,"%3.0f",age );
                   4166:     for(i=1; i<=nlstate;i++)
                   4167:       for(j=1; j<=nlstate;j++){
                   4168:        cptj= (j-1)*nlstate+i;
                   4169:        for(i2=1; i2<=nlstate;i2++)
                   4170:          for(j2=1; j2<=nlstate;j2++){
                   4171:            cptj2= (j2-1)*nlstate+i2;
                   4172:            if(cptj2 <= cptj)
                   4173:              fprintf(ficrescveij," %.4f", varhe[cptj][cptj2][(int)age]);
                   4174:          }
                   4175:       }
                   4176:     fprintf(ficrescveij,"\n");
                   4177:    
                   4178:   }
                   4179:   free_matrix(gm,0,nhstepm,1,nlstate*nlstate);
                   4180:   free_matrix(gp,0,nhstepm,1,nlstate*nlstate);
                   4181:   free_ma3x(gradg,0,nhstepm,1,npar,1,nlstate*nlstate);
                   4182:   free_ma3x(trgradg,0,nhstepm,1,nlstate*nlstate,1,npar);
                   4183:   free_ma3x(p3matm,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   4184:   free_ma3x(p3matp,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   4185:   printf("\n");
                   4186:   fprintf(ficlog,"\n");
                   4187: 
                   4188:   free_vector(xm,1,npar);
                   4189:   free_vector(xp,1,npar);
                   4190:   free_matrix(dnewm,1,nlstate*nlstate,1,npar);
                   4191:   free_matrix(doldm,1,nlstate*nlstate,1,nlstate*nlstate);
                   4192:   free_ma3x(varhe,1,nlstate*nlstate,1,nlstate*nlstate,(int) bage, (int)fage);
                   4193: }
                   4194: 
                   4195: /************ Variance ******************/
1.209     brouard  4196:  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  4197: {
                   4198:   /* Variance of health expectancies */
                   4199:   /*  double **prevalim(double **prlim, int nlstate, double *xp, double age, double **oldm, double ** savm,double ftolpl);*/
                   4200:   /* double **newm;*/
1.169     brouard  4201:   /* int movingaverage(double ***probs, double bage,double fage, double ***mobaverage, int mobilav)*/
                   4202:   
                   4203:   int movingaverage();
1.126     brouard  4204:   double **dnewm,**doldm;
                   4205:   double **dnewmp,**doldmp;
                   4206:   int i, j, nhstepm, hstepm, h, nstepm ;
1.164     brouard  4207:   int k;
1.126     brouard  4208:   double *xp;
                   4209:   double **gp, **gm;  /* for var eij */
                   4210:   double ***gradg, ***trgradg; /*for var eij */
                   4211:   double **gradgp, **trgradgp; /* for var p point j */
                   4212:   double *gpp, *gmp; /* for var p point j */
                   4213:   double **varppt; /* for var p point j nlstate to nlstate+ndeath */
                   4214:   double ***p3mat;
                   4215:   double age,agelim, hf;
                   4216:   double ***mobaverage;
                   4217:   int theta;
                   4218:   char digit[4];
                   4219:   char digitp[25];
                   4220: 
                   4221:   char fileresprobmorprev[FILENAMELENGTH];
                   4222: 
                   4223:   if(popbased==1){
                   4224:     if(mobilav!=0)
1.201     brouard  4225:       strcpy(digitp,"-POPULBASED-MOBILAV_");
                   4226:     else strcpy(digitp,"-POPULBASED-NOMOBIL_");
1.126     brouard  4227:   }
                   4228:   else 
1.201     brouard  4229:     strcpy(digitp,"-STABLBASED_");
1.126     brouard  4230: 
                   4231:   if (mobilav!=0) {
                   4232:     mobaverage= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
                   4233:     if (movingaverage(probs, bage, fage, mobaverage,mobilav)!=0){
                   4234:       fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav);
                   4235:       printf(" Error in movingaverage mobilav=%d\n",mobilav);
                   4236:     }
                   4237:   }
                   4238: 
1.201     brouard  4239:   strcpy(fileresprobmorprev,"PRMORPREV-"); 
1.126     brouard  4240:   sprintf(digit,"%-d",ij);
                   4241:   /*printf("DIGIT=%s, ij=%d ijr=%-d|\n",digit, ij,ij);*/
                   4242:   strcat(fileresprobmorprev,digit); /* Tvar to be done */
                   4243:   strcat(fileresprobmorprev,digitp); /* Popbased or not, mobilav or not */
1.202     brouard  4244:   strcat(fileresprobmorprev,fileresu);
1.126     brouard  4245:   if((ficresprobmorprev=fopen(fileresprobmorprev,"w"))==NULL) {
                   4246:     printf("Problem with resultfile: %s\n", fileresprobmorprev);
                   4247:     fprintf(ficlog,"Problem with resultfile: %s\n", fileresprobmorprev);
                   4248:   }
                   4249:   printf("Computing total mortality p.j=w1*p1j+w2*p2j+..: result on file '%s' \n",fileresprobmorprev);
                   4250:   fprintf(ficlog,"Computing total mortality p.j=w1*p1j+w2*p2j+..: result on file '%s' \n",fileresprobmorprev);
                   4251:   pstamp(ficresprobmorprev);
                   4252:   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);
                   4253:   fprintf(ficresprobmorprev,"# Age cov=%-d",ij);
                   4254:   for(j=nlstate+1; j<=(nlstate+ndeath);j++){
                   4255:     fprintf(ficresprobmorprev," p.%-d SE",j);
                   4256:     for(i=1; i<=nlstate;i++)
                   4257:       fprintf(ficresprobmorprev," w%1d p%-d%-d",i,i,j);
                   4258:   }  
                   4259:   fprintf(ficresprobmorprev,"\n");
1.208     brouard  4260:   
1.126     brouard  4261:   fprintf(ficgp,"\n# Routine varevsij");
1.200     brouard  4262:   fprintf(ficgp,"\nunset title \n");
                   4263: /* fprintf(fichtm, "#Local time at start: %s", strstart);*/
1.126     brouard  4264:   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");
                   4265:   fprintf(fichtm,"\n<br>%s  <br>\n",digitp);
                   4266: /*   } */
                   4267:   varppt = matrix(nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);
                   4268:   pstamp(ficresvij);
                   4269:   fprintf(ficresvij,"# Variance and covariance of health expectancies e.j \n#  (weighted average of eij where weights are ");
                   4270:   if(popbased==1)
1.128     brouard  4271:     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  4272:   else
                   4273:     fprintf(ficresvij,"the age specific period (stable) prevalences in each health state \n");
                   4274:   fprintf(ficresvij,"# Age");
                   4275:   for(i=1; i<=nlstate;i++)
                   4276:     for(j=1; j<=nlstate;j++)
                   4277:       fprintf(ficresvij," Cov(e.%1d, e.%1d)",i,j);
                   4278:   fprintf(ficresvij,"\n");
                   4279: 
                   4280:   xp=vector(1,npar);
                   4281:   dnewm=matrix(1,nlstate,1,npar);
                   4282:   doldm=matrix(1,nlstate,1,nlstate);
                   4283:   dnewmp= matrix(nlstate+1,nlstate+ndeath,1,npar);
                   4284:   doldmp= matrix(nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);
                   4285: 
                   4286:   gradgp=matrix(1,npar,nlstate+1,nlstate+ndeath);
                   4287:   gpp=vector(nlstate+1,nlstate+ndeath);
                   4288:   gmp=vector(nlstate+1,nlstate+ndeath);
                   4289:   trgradgp =matrix(nlstate+1,nlstate+ndeath,1,npar); /* mu or p point j*/
                   4290:   
                   4291:   if(estepm < stepm){
                   4292:     printf ("Problem %d lower than %d\n",estepm, stepm);
                   4293:   }
                   4294:   else  hstepm=estepm;   
                   4295:   /* For example we decided to compute the life expectancy with the smallest unit */
                   4296:   /* hstepm beeing the number of stepms, if hstepm=1 the length of hstepm is stepm. 
                   4297:      nhstepm is the number of hstepm from age to agelim 
1.208     brouard  4298:      nstepm is the number of stepm from age to agelim. 
1.209     brouard  4299:      Look at function hpijx to understand why because of memory size limitations, 
1.208     brouard  4300:      we decided (b) to get a life expectancy respecting the most precise curvature of the
1.126     brouard  4301:      survival function given by stepm (the optimization length). Unfortunately it
                   4302:      means that if the survival funtion is printed every two years of age and if
                   4303:      you sum them up and add 1 year (area under the trapezoids) you won't get the same 
                   4304:      results. So we changed our mind and took the option of the best precision.
                   4305:   */
                   4306:   hstepm=hstepm/stepm; /* Typically in stepm units, if stepm=6 & estepm=24 , = 24/6 months = 4 */ 
                   4307:   agelim = AGESUP;
                   4308:   for (age=bage; age<=fage; age ++){ /* If stepm=6 months */
                   4309:     nstepm=(int) rint((agelim-age)*YEARM/stepm); /* Typically 20 years = 20*12/6=40 */ 
                   4310:     nhstepm = nstepm/hstepm;/* Expressed in hstepm, typically nhstepm=40/4=10 */
                   4311:     p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   4312:     gradg=ma3x(0,nhstepm,1,npar,1,nlstate);
                   4313:     gp=matrix(0,nhstepm,1,nlstate);
                   4314:     gm=matrix(0,nhstepm,1,nlstate);
                   4315: 
                   4316: 
                   4317:     for(theta=1; theta <=npar; theta++){
                   4318:       for(i=1; i<=npar; i++){ /* Computes gradient x + delta*/
                   4319:        xp[i] = x[i] + (i==theta ?delti[theta]:0);
                   4320:       }
1.209     brouard  4321: 
                   4322:       prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ncvyearp,ij);
1.126     brouard  4323: 
                   4324:       if (popbased==1) {
                   4325:        if(mobilav ==0){
                   4326:          for(i=1; i<=nlstate;i++)
                   4327:            prlim[i][i]=probs[(int)age][i][ij];
                   4328:        }else{ /* mobilav */ 
                   4329:          for(i=1; i<=nlstate;i++)
                   4330:            prlim[i][i]=mobaverage[(int)age][i][ij];
                   4331:        }
                   4332:       }
                   4333:   
1.209     brouard  4334:       hpxij(p3mat,nhstepm,age,hstepm,xp,nlstate,stepm,oldm,savm, ij);  /* Returns p3mat[i][j][h] for h=1 to nhstepm */
1.126     brouard  4335:       for(j=1; j<= nlstate; j++){
                   4336:        for(h=0; h<=nhstepm; h++){
                   4337:          for(i=1, gp[h][j]=0.;i<=nlstate;i++)
                   4338:            gp[h][j] += prlim[i][i]*p3mat[i][j][h];
                   4339:        }
                   4340:       }
1.209     brouard  4341:       /* Next for computing probability of death (h=1 means
1.126     brouard  4342:          computed over hstepm matrices product = hstepm*stepm months) 
                   4343:          as a weighted average of prlim.
                   4344:       */
                   4345:       for(j=nlstate+1;j<=nlstate+ndeath;j++){
                   4346:        for(i=1,gpp[j]=0.; i<= nlstate; i++)
                   4347:          gpp[j] += prlim[i][i]*p3mat[i][j][1];
                   4348:       }    
                   4349:       /* end probability of death */
                   4350: 
                   4351:       for(i=1; i<=npar; i++) /* Computes gradient x - delta */
                   4352:        xp[i] = x[i] - (i==theta ?delti[theta]:0);
1.209     brouard  4353: 
                   4354:       prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ncvyearp, ij);
1.126     brouard  4355:  
                   4356:       if (popbased==1) {
                   4357:        if(mobilav ==0){
                   4358:          for(i=1; i<=nlstate;i++)
                   4359:            prlim[i][i]=probs[(int)age][i][ij];
                   4360:        }else{ /* mobilav */ 
                   4361:          for(i=1; i<=nlstate;i++)
                   4362:            prlim[i][i]=mobaverage[(int)age][i][ij];
                   4363:        }
                   4364:       }
                   4365: 
1.209     brouard  4366:       hpxij(p3mat,nhstepm,age,hstepm,xp,nlstate,stepm,oldm,savm, ij);  
                   4367: 
1.128     brouard  4368:       for(j=1; j<= nlstate; j++){  /* Sum of wi * eij = e.j */
1.126     brouard  4369:        for(h=0; h<=nhstepm; h++){
                   4370:          for(i=1, gm[h][j]=0.;i<=nlstate;i++)
                   4371:            gm[h][j] += prlim[i][i]*p3mat[i][j][h];
                   4372:        }
                   4373:       }
                   4374:       /* This for computing probability of death (h=1 means
                   4375:          computed over hstepm matrices product = hstepm*stepm months) 
                   4376:          as a weighted average of prlim.
                   4377:       */
                   4378:       for(j=nlstate+1;j<=nlstate+ndeath;j++){
                   4379:        for(i=1,gmp[j]=0.; i<= nlstate; i++)
                   4380:          gmp[j] += prlim[i][i]*p3mat[i][j][1];
                   4381:       }    
                   4382:       /* end probability of death */
                   4383: 
                   4384:       for(j=1; j<= nlstate; j++) /* vareij */
                   4385:        for(h=0; h<=nhstepm; h++){
                   4386:          gradg[h][theta][j]= (gp[h][j]-gm[h][j])/2./delti[theta];
                   4387:        }
                   4388: 
                   4389:       for(j=nlstate+1; j<= nlstate+ndeath; j++){ /* var mu */
                   4390:        gradgp[theta][j]= (gpp[j]-gmp[j])/2./delti[theta];
                   4391:       }
                   4392: 
                   4393:     } /* End theta */
                   4394: 
                   4395:     trgradg =ma3x(0,nhstepm,1,nlstate,1,npar); /* veij */
                   4396: 
                   4397:     for(h=0; h<=nhstepm; h++) /* veij */
                   4398:       for(j=1; j<=nlstate;j++)
                   4399:        for(theta=1; theta <=npar; theta++)
                   4400:          trgradg[h][j][theta]=gradg[h][theta][j];
                   4401: 
                   4402:     for(j=nlstate+1; j<=nlstate+ndeath;j++) /* mu */
                   4403:       for(theta=1; theta <=npar; theta++)
                   4404:        trgradgp[j][theta]=gradgp[theta][j];
                   4405:   
                   4406: 
                   4407:     hf=hstepm*stepm/YEARM;  /* Duration of hstepm expressed in year unit. */
                   4408:     for(i=1;i<=nlstate;i++)
                   4409:       for(j=1;j<=nlstate;j++)
                   4410:        vareij[i][j][(int)age] =0.;
                   4411: 
                   4412:     for(h=0;h<=nhstepm;h++){
                   4413:       for(k=0;k<=nhstepm;k++){
                   4414:        matprod2(dnewm,trgradg[h],1,nlstate,1,npar,1,npar,matcov);
                   4415:        matprod2(doldm,dnewm,1,nlstate,1,npar,1,nlstate,gradg[k]);
                   4416:        for(i=1;i<=nlstate;i++)
                   4417:          for(j=1;j<=nlstate;j++)
                   4418:            vareij[i][j][(int)age] += doldm[i][j]*hf*hf;
                   4419:       }
                   4420:     }
                   4421:   
                   4422:     /* pptj */
                   4423:     matprod2(dnewmp,trgradgp,nlstate+1,nlstate+ndeath,1,npar,1,npar,matcov);
                   4424:     matprod2(doldmp,dnewmp,nlstate+1,nlstate+ndeath,1,npar,nlstate+1,nlstate+ndeath,gradgp);
                   4425:     for(j=nlstate+1;j<=nlstate+ndeath;j++)
                   4426:       for(i=nlstate+1;i<=nlstate+ndeath;i++)
                   4427:        varppt[j][i]=doldmp[j][i];
                   4428:     /* end ppptj */
                   4429:     /*  x centered again */
1.209     brouard  4430: 
                   4431:     prevalim(prlim,nlstate,x,age,oldm,savm,ftolpl,ncvyearp,ij);
1.126     brouard  4432:  
                   4433:     if (popbased==1) {
                   4434:       if(mobilav ==0){
                   4435:        for(i=1; i<=nlstate;i++)
                   4436:          prlim[i][i]=probs[(int)age][i][ij];
                   4437:       }else{ /* mobilav */ 
                   4438:        for(i=1; i<=nlstate;i++)
                   4439:          prlim[i][i]=mobaverage[(int)age][i][ij];
                   4440:       }
                   4441:     }
                   4442:              
                   4443:     /* This for computing probability of death (h=1 means
                   4444:        computed over hstepm (estepm) matrices product = hstepm*stepm months) 
                   4445:        as a weighted average of prlim.
                   4446:     */
1.209     brouard  4447:     hpxij(p3mat,nhstepm,age,hstepm,x,nlstate,stepm,oldm,savm, ij);  
1.126     brouard  4448:     for(j=nlstate+1;j<=nlstate+ndeath;j++){
                   4449:       for(i=1,gmp[j]=0.;i<= nlstate; i++) 
                   4450:        gmp[j] += prlim[i][i]*p3mat[i][j][1]; 
                   4451:     }    
                   4452:     /* end probability of death */
                   4453: 
                   4454:     fprintf(ficresprobmorprev,"%3d %d ",(int) age, ij);
                   4455:     for(j=nlstate+1; j<=(nlstate+ndeath);j++){
                   4456:       fprintf(ficresprobmorprev," %11.3e %11.3e",gmp[j], sqrt(varppt[j][j]));
                   4457:       for(i=1; i<=nlstate;i++){
                   4458:        fprintf(ficresprobmorprev," %11.3e %11.3e ",prlim[i][i],p3mat[i][j][1]);
                   4459:       }
                   4460:     } 
                   4461:     fprintf(ficresprobmorprev,"\n");
                   4462: 
                   4463:     fprintf(ficresvij,"%.0f ",age );
                   4464:     for(i=1; i<=nlstate;i++)
                   4465:       for(j=1; j<=nlstate;j++){
                   4466:        fprintf(ficresvij," %.4f", vareij[i][j][(int)age]);
                   4467:       }
                   4468:     fprintf(ficresvij,"\n");
                   4469:     free_matrix(gp,0,nhstepm,1,nlstate);
                   4470:     free_matrix(gm,0,nhstepm,1,nlstate);
                   4471:     free_ma3x(gradg,0,nhstepm,1,npar,1,nlstate);
                   4472:     free_ma3x(trgradg,0,nhstepm,1,nlstate,1,npar);
                   4473:     free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   4474:   } /* End age */
                   4475:   free_vector(gpp,nlstate+1,nlstate+ndeath);
                   4476:   free_vector(gmp,nlstate+1,nlstate+ndeath);
                   4477:   free_matrix(gradgp,1,npar,nlstate+1,nlstate+ndeath);
                   4478:   free_matrix(trgradgp,nlstate+1,nlstate+ndeath,1,npar); /* mu or p point j*/
1.199     brouard  4479:   /* fprintf(ficgp,"\nunset parametric;unset label; set ter png small size 320, 240"); */
                   4480:   fprintf(ficgp,"\nunset parametric;unset label; set ter svg size 640, 480");
1.126     brouard  4481:   /* for(j=nlstate+1; j<= nlstate+ndeath; j++){ *//* Only the first actually */
1.131     brouard  4482:   fprintf(ficgp,"\n set log y; unset log x;set xlabel \"Age\"; set ylabel \"Force of mortality (year-1)\";");
1.201     brouard  4483:   fprintf(ficgp,"\nset out \"%s%s.svg\";",subdirf3(optionfilefiname,"VARMUPTJGR-",digitp),digit);
1.126     brouard  4484: /*   fprintf(ficgp,"\n plot \"%s\"  u 1:($3*%6.3f) not w l 1 ",fileresprobmorprev,YEARM/estepm); */
                   4485: /*   fprintf(ficgp,"\n replot \"%s\"  u 1:(($3+1.96*$4)*%6.3f) t \"95\%% interval\" w l 2 ",fileresprobmorprev,YEARM/estepm); */
                   4486: /*   fprintf(ficgp,"\n replot \"%s\"  u 1:(($3-1.96*$4)*%6.3f) not w l 2 ",fileresprobmorprev,YEARM/estepm); */
1.145     brouard  4487:   fprintf(ficgp,"\n plot \"%s\"  u 1:($3) not w l lt 1 ",subdirf(fileresprobmorprev));
1.170     brouard  4488:   fprintf(ficgp,"\n replot \"%s\"  u 1:(($3+1.96*$4)) t \"95%% interval\" w l lt 2 ",subdirf(fileresprobmorprev));
1.145     brouard  4489:   fprintf(ficgp,"\n replot \"%s\"  u 1:(($3-1.96*$4)) not w l lt 2 ",subdirf(fileresprobmorprev));
1.126     brouard  4490:   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  4491:   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  4492:   /*  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  4493: */
1.199     brouard  4494: /*   fprintf(ficgp,"\nset out \"varmuptjgr%s%s%s.svg\";replot;",digitp,optionfilefiname,digit); */
1.201     brouard  4495:   fprintf(ficgp,"\nset out;\nset out \"%s%s.svg\";replot;set out;\n",subdirf3(optionfilefiname,"VARMUPTJGR-",digitp),digit);
1.126     brouard  4496: 
                   4497:   free_vector(xp,1,npar);
                   4498:   free_matrix(doldm,1,nlstate,1,nlstate);
                   4499:   free_matrix(dnewm,1,nlstate,1,npar);
                   4500:   free_matrix(doldmp,nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);
                   4501:   free_matrix(dnewmp,nlstate+1,nlstate+ndeath,1,npar);
                   4502:   free_matrix(varppt,nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);
                   4503:   if (mobilav!=0) free_ma3x(mobaverage,1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
                   4504:   fclose(ficresprobmorprev);
                   4505:   fflush(ficgp);
                   4506:   fflush(fichtm); 
                   4507: }  /* end varevsij */
                   4508: 
                   4509: /************ Variance of prevlim ******************/
1.209     brouard  4510:  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  4511: {
1.205     brouard  4512:   /* Variance of prevalence limit  for each state ij using current parameters x[] and estimates of neighbourhood give by delti*/
1.126     brouard  4513:   /*  double **prevalim(double **prlim, int nlstate, double *xp, double age, double **oldm, double **savm,double ftolpl);*/
1.164     brouard  4514: 
1.126     brouard  4515:   double **dnewm,**doldm;
                   4516:   int i, j, nhstepm, hstepm;
                   4517:   double *xp;
                   4518:   double *gp, *gm;
                   4519:   double **gradg, **trgradg;
1.208     brouard  4520:   double **mgm, **mgp;
1.126     brouard  4521:   double age,agelim;
                   4522:   int theta;
                   4523:   
                   4524:   pstamp(ficresvpl);
                   4525:   fprintf(ficresvpl,"# Standard deviation of period (stable) prevalences \n");
                   4526:   fprintf(ficresvpl,"# Age");
                   4527:   for(i=1; i<=nlstate;i++)
                   4528:       fprintf(ficresvpl," %1d-%1d",i,i);
                   4529:   fprintf(ficresvpl,"\n");
                   4530: 
                   4531:   xp=vector(1,npar);
                   4532:   dnewm=matrix(1,nlstate,1,npar);
                   4533:   doldm=matrix(1,nlstate,1,nlstate);
                   4534:   
                   4535:   hstepm=1*YEARM; /* Every year of age */
                   4536:   hstepm=hstepm/stepm; /* Typically in stepm units, if j= 2 years, = 2/6 months = 4 */ 
                   4537:   agelim = AGESUP;
                   4538:   for (age=bage; age<=fage; age ++){ /* If stepm=6 months */
                   4539:     nhstepm=(int) rint((agelim-age)*YEARM/stepm); /* Typically 20 years = 20*12/6=40 */ 
                   4540:     if (stepm >= YEARM) hstepm=1;
                   4541:     nhstepm = nhstepm/hstepm; /* Typically 40/4=10 */
                   4542:     gradg=matrix(1,npar,1,nlstate);
1.208     brouard  4543:     mgp=matrix(1,npar,1,nlstate);
                   4544:     mgm=matrix(1,npar,1,nlstate);
1.126     brouard  4545:     gp=vector(1,nlstate);
                   4546:     gm=vector(1,nlstate);
                   4547: 
                   4548:     for(theta=1; theta <=npar; theta++){
                   4549:       for(i=1; i<=npar; i++){ /* Computes gradient */
                   4550:        xp[i] = x[i] + (i==theta ?delti[theta]:0);
                   4551:       }
1.209     brouard  4552:       if((int)age==79 ||(int)age== 80 ||(int)age== 81 )
                   4553:        prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ncvyearp,ij);
                   4554:       else
                   4555:        prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ncvyearp,ij);
1.208     brouard  4556:       for(i=1;i<=nlstate;i++){
1.126     brouard  4557:        gp[i] = prlim[i][i];
1.208     brouard  4558:        mgp[theta][i] = prlim[i][i];
                   4559:       }
1.126     brouard  4560:       for(i=1; i<=npar; i++) /* Computes gradient */
                   4561:        xp[i] = x[i] - (i==theta ?delti[theta]:0);
1.209     brouard  4562:       if((int)age==79 ||(int)age== 80 ||(int)age== 81 )
                   4563:        prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ncvyearp,ij);
                   4564:       else
                   4565:        prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ncvyearp,ij);
1.208     brouard  4566:       for(i=1;i<=nlstate;i++){
1.126     brouard  4567:        gm[i] = prlim[i][i];
1.208     brouard  4568:        mgm[theta][i] = prlim[i][i];
                   4569:       }
1.126     brouard  4570:       for(i=1;i<=nlstate;i++)
                   4571:        gradg[theta][i]= (gp[i]-gm[i])/2./delti[theta];
1.209     brouard  4572:       /* gradg[theta][2]= -gradg[theta][1]; */ /* For testing if nlstate=2 */
1.126     brouard  4573:     } /* End theta */
                   4574: 
                   4575:     trgradg =matrix(1,nlstate,1,npar);
                   4576: 
                   4577:     for(j=1; j<=nlstate;j++)
                   4578:       for(theta=1; theta <=npar; theta++)
                   4579:        trgradg[j][theta]=gradg[theta][j];
1.209     brouard  4580:     /* if((int)age==79 ||(int)age== 80 ||(int)age== 81 ){ */
                   4581:     /*   printf("\nmgm mgp %d ",(int)age); */
                   4582:     /*   for(j=1; j<=nlstate;j++){ */
                   4583:     /*         printf(" %d ",j); */
                   4584:     /*         for(theta=1; theta <=npar; theta++) */
                   4585:     /*           printf(" %d %lf %lf",theta,mgm[theta][j],mgp[theta][j]); */
                   4586:     /*         printf("\n "); */
                   4587:     /*   } */
                   4588:     /* } */
                   4589:     /* if((int)age==79 ||(int)age== 80 ||(int)age== 81 ){ */
                   4590:     /*   printf("\n gradg %d ",(int)age); */
                   4591:     /*   for(j=1; j<=nlstate;j++){ */
                   4592:     /*         printf("%d ",j); */
                   4593:     /*         for(theta=1; theta <=npar; theta++) */
                   4594:     /*           printf("%d %lf ",theta,gradg[theta][j]); */
                   4595:     /*         printf("\n "); */
                   4596:     /*   } */
                   4597:     /* } */
1.126     brouard  4598: 
                   4599:     for(i=1;i<=nlstate;i++)
                   4600:       varpl[i][(int)age] =0.;
1.209     brouard  4601:     if((int)age==79 ||(int)age== 80  ||(int)age== 81){
1.205     brouard  4602:     matprod2(dnewm,trgradg,1,nlstate,1,npar,1,npar,matcov);
                   4603:     matprod2(doldm,dnewm,1,nlstate,1,npar,1,nlstate,gradg);
                   4604:     }else{
1.126     brouard  4605:     matprod2(dnewm,trgradg,1,nlstate,1,npar,1,npar,matcov);
                   4606:     matprod2(doldm,dnewm,1,nlstate,1,npar,1,nlstate,gradg);
1.205     brouard  4607:     }
1.126     brouard  4608:     for(i=1;i<=nlstate;i++)
                   4609:       varpl[i][(int)age] = doldm[i][i]; /* Covariances are useless */
                   4610: 
                   4611:     fprintf(ficresvpl,"%.0f ",age );
                   4612:     for(i=1; i<=nlstate;i++)
                   4613:       fprintf(ficresvpl," %.5f (%.5f)",prlim[i][i],sqrt(varpl[i][(int)age]));
                   4614:     fprintf(ficresvpl,"\n");
                   4615:     free_vector(gp,1,nlstate);
                   4616:     free_vector(gm,1,nlstate);
1.208     brouard  4617:     free_matrix(mgm,1,npar,1,nlstate);
                   4618:     free_matrix(mgp,1,npar,1,nlstate);
1.126     brouard  4619:     free_matrix(gradg,1,npar,1,nlstate);
                   4620:     free_matrix(trgradg,1,nlstate,1,npar);
                   4621:   } /* End age */
                   4622: 
                   4623:   free_vector(xp,1,npar);
                   4624:   free_matrix(doldm,1,nlstate,1,npar);
                   4625:   free_matrix(dnewm,1,nlstate,1,nlstate);
                   4626: 
                   4627: }
                   4628: 
                   4629: /************ Variance of one-step probabilities  ******************/
                   4630: 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[])
                   4631: {
1.164     brouard  4632:   int i, j=0,  k1, l1, tj;
1.126     brouard  4633:   int k2, l2, j1,  z1;
1.164     brouard  4634:   int k=0, l;
1.145     brouard  4635:   int first=1, first1, first2;
1.126     brouard  4636:   double cv12, mu1, mu2, lc1, lc2, v12, v21, v11, v22,v1,v2, c12, tnalp;
                   4637:   double **dnewm,**doldm;
                   4638:   double *xp;
                   4639:   double *gp, *gm;
                   4640:   double **gradg, **trgradg;
                   4641:   double **mu;
1.164     brouard  4642:   double age, cov[NCOVMAX+1];
1.126     brouard  4643:   double std=2.0; /* Number of standard deviation wide of confidence ellipsoids */
                   4644:   int theta;
                   4645:   char fileresprob[FILENAMELENGTH];
                   4646:   char fileresprobcov[FILENAMELENGTH];
                   4647:   char fileresprobcor[FILENAMELENGTH];
                   4648:   double ***varpij;
                   4649: 
1.201     brouard  4650:   strcpy(fileresprob,"PROB_"); 
1.126     brouard  4651:   strcat(fileresprob,fileres);
                   4652:   if((ficresprob=fopen(fileresprob,"w"))==NULL) {
                   4653:     printf("Problem with resultfile: %s\n", fileresprob);
                   4654:     fprintf(ficlog,"Problem with resultfile: %s\n", fileresprob);
                   4655:   }
1.201     brouard  4656:   strcpy(fileresprobcov,"PROBCOV_"); 
1.202     brouard  4657:   strcat(fileresprobcov,fileresu);
1.126     brouard  4658:   if((ficresprobcov=fopen(fileresprobcov,"w"))==NULL) {
                   4659:     printf("Problem with resultfile: %s\n", fileresprobcov);
                   4660:     fprintf(ficlog,"Problem with resultfile: %s\n", fileresprobcov);
                   4661:   }
1.201     brouard  4662:   strcpy(fileresprobcor,"PROBCOR_"); 
1.202     brouard  4663:   strcat(fileresprobcor,fileresu);
1.126     brouard  4664:   if((ficresprobcor=fopen(fileresprobcor,"w"))==NULL) {
                   4665:     printf("Problem with resultfile: %s\n", fileresprobcor);
                   4666:     fprintf(ficlog,"Problem with resultfile: %s\n", fileresprobcor);
                   4667:   }
                   4668:   printf("Computing standard deviation of one-step probabilities: result on file '%s' \n",fileresprob);
                   4669:   fprintf(ficlog,"Computing standard deviation of one-step probabilities: result on file '%s' \n",fileresprob);
                   4670:   printf("Computing matrix of variance covariance of one-step probabilities: result on file '%s' \n",fileresprobcov);
                   4671:   fprintf(ficlog,"Computing matrix of variance covariance of one-step probabilities: result on file '%s' \n",fileresprobcov);
                   4672:   printf("and correlation matrix of one-step probabilities: result on file '%s' \n",fileresprobcor);
                   4673:   fprintf(ficlog,"and correlation matrix of one-step probabilities: result on file '%s' \n",fileresprobcor);
                   4674:   pstamp(ficresprob);
                   4675:   fprintf(ficresprob,"#One-step probabilities and stand. devi in ()\n");
                   4676:   fprintf(ficresprob,"# Age");
                   4677:   pstamp(ficresprobcov);
                   4678:   fprintf(ficresprobcov,"#One-step probabilities and covariance matrix\n");
                   4679:   fprintf(ficresprobcov,"# Age");
                   4680:   pstamp(ficresprobcor);
                   4681:   fprintf(ficresprobcor,"#One-step probabilities and correlation matrix\n");
                   4682:   fprintf(ficresprobcor,"# Age");
                   4683: 
                   4684: 
                   4685:   for(i=1; i<=nlstate;i++)
                   4686:     for(j=1; j<=(nlstate+ndeath);j++){
                   4687:       fprintf(ficresprob," p%1d-%1d (SE)",i,j);
                   4688:       fprintf(ficresprobcov," p%1d-%1d ",i,j);
                   4689:       fprintf(ficresprobcor," p%1d-%1d ",i,j);
                   4690:     }  
                   4691:  /* fprintf(ficresprob,"\n");
                   4692:   fprintf(ficresprobcov,"\n");
                   4693:   fprintf(ficresprobcor,"\n");
                   4694:  */
1.131     brouard  4695:   xp=vector(1,npar);
1.126     brouard  4696:   dnewm=matrix(1,(nlstate)*(nlstate+ndeath),1,npar);
                   4697:   doldm=matrix(1,(nlstate)*(nlstate+ndeath),1,(nlstate)*(nlstate+ndeath));
                   4698:   mu=matrix(1,(nlstate)*(nlstate+ndeath), (int) bage, (int)fage);
                   4699:   varpij=ma3x(1,nlstate*(nlstate+ndeath),1,nlstate*(nlstate+ndeath),(int) bage, (int) fage);
                   4700:   first=1;
                   4701:   fprintf(ficgp,"\n# Routine varprob");
                   4702:   fprintf(fichtm,"\n<li><h4> Computing and drawing one step probabilities with their confidence intervals</h4></li>\n");
                   4703:   fprintf(fichtm,"\n");
                   4704: 
1.200     brouard  4705:   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  4706:   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);
                   4707:   fprintf(fichtmcov,"\nEllipsoids of confidence centered on point (p<inf>ij</inf>, p<inf>kl</inf>) are estimated \
1.126     brouard  4708: and drawn. It helps understanding how is the covariance between two incidences.\
                   4709:  They are expressed in year<sup>-1</sup> in order to be less dependent of stepm.<br>\n");
                   4710:   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. \
                   4711: It can be understood this way: if pij and pkl where uncorrelated the (2x2) matrix of covariance \
                   4712: would have been (1/(var pij), 0 , 0, 1/(var pkl)), and the confidence interval would be 2 \
                   4713: standard deviations wide on each axis. <br>\
                   4714:  Now, if both incidences are correlated (usual case) we diagonalised the inverse of the covariance matrix\
                   4715:  and made the appropriate rotation to look at the uncorrelated principal directions.<br>\
                   4716: To be simple, these graphs help to understand the significativity of each parameter in relation to a second other one.<br> \n");
                   4717: 
                   4718:   cov[1]=1;
1.145     brouard  4719:   /* tj=cptcoveff; */
                   4720:   tj = (int) pow(2,cptcoveff);
1.126     brouard  4721:   if (cptcovn<1) {tj=1;ncodemax[1]=1;}
                   4722:   j1=0;
1.145     brouard  4723:   for(j1=1; j1<=tj;j1++){
                   4724:     /*for(i1=1; i1<=ncodemax[t];i1++){ */
                   4725:     /*j1++;*/
1.126     brouard  4726:       if  (cptcovn>0) {
                   4727:        fprintf(ficresprob, "\n#********** Variable "); 
1.198     brouard  4728:        for (z1=1; z1<=cptcoveff; z1++) fprintf(ficresprob, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
1.126     brouard  4729:        fprintf(ficresprob, "**********\n#\n");
                   4730:        fprintf(ficresprobcov, "\n#********** Variable "); 
1.198     brouard  4731:        for (z1=1; z1<=cptcoveff; z1++) fprintf(ficresprobcov, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
1.126     brouard  4732:        fprintf(ficresprobcov, "**********\n#\n");
                   4733:        
                   4734:        fprintf(ficgp, "\n#********** Variable "); 
1.198     brouard  4735:        for (z1=1; z1<=cptcoveff; z1++) fprintf(ficgp, " V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
1.126     brouard  4736:        fprintf(ficgp, "**********\n#\n");
                   4737:        
                   4738:        
                   4739:        fprintf(fichtmcov, "\n<hr  size=\"2\" color=\"#EC5E5E\">********** Variable "); 
1.198     brouard  4740:        for (z1=1; z1<=cptcoveff; z1++) fprintf(fichtm, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
1.126     brouard  4741:        fprintf(fichtmcov, "**********\n<hr size=\"2\" color=\"#EC5E5E\">");
                   4742:        
                   4743:        fprintf(ficresprobcor, "\n#********** Variable ");    
1.198     brouard  4744:        for (z1=1; z1<=cptcoveff; z1++) fprintf(ficresprobcor, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
1.126     brouard  4745:        fprintf(ficresprobcor, "**********\n#");    
                   4746:       }
                   4747:       
1.145     brouard  4748:       gradg=matrix(1,npar,1,(nlstate)*(nlstate+ndeath));
                   4749:       trgradg=matrix(1,(nlstate)*(nlstate+ndeath),1,npar);
                   4750:       gp=vector(1,(nlstate)*(nlstate+ndeath));
                   4751:       gm=vector(1,(nlstate)*(nlstate+ndeath));
1.126     brouard  4752:       for (age=bage; age<=fage; age ++){ 
                   4753:        cov[2]=age;
1.187     brouard  4754:        if(nagesqr==1)
                   4755:          cov[3]= age*age;
1.126     brouard  4756:        for (k=1; k<=cptcovn;k++) {
1.200     brouard  4757:          cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(j1,k)];
                   4758:          /*cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(j1,Tvar[k])];*//* j1 1 2 3 4
1.145     brouard  4759:                                                         * 1  1 1 1 1
                   4760:                                                         * 2  2 1 1 1
                   4761:                                                         * 3  1 2 1 1
                   4762:                                                         */
                   4763:          /* nbcode[1][1]=0 nbcode[1][2]=1;*/
1.126     brouard  4764:        }
1.186     brouard  4765:        /* for (k=1; k<=cptcovage;k++) cov[2+Tage[k]]=cov[2+Tage[k]]*cov[2]; */
1.200     brouard  4766:        for (k=1; k<=cptcovage;k++) cov[2+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(ij,k)]*cov[2];
1.126     brouard  4767:        for (k=1; k<=cptcovprod;k++)
1.200     brouard  4768:          cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,k)]*nbcode[Tvard[k][2]][codtabm(ij,k)];
1.126     brouard  4769:        
                   4770:     
                   4771:        for(theta=1; theta <=npar; theta++){
                   4772:          for(i=1; i<=npar; i++)
                   4773:            xp[i] = x[i] + (i==theta ?delti[theta]:(double)0);
                   4774:          
                   4775:          pmij(pmmij,cov,ncovmodel,xp,nlstate);
                   4776:          
                   4777:          k=0;
                   4778:          for(i=1; i<= (nlstate); i++){
                   4779:            for(j=1; j<=(nlstate+ndeath);j++){
                   4780:              k=k+1;
                   4781:              gp[k]=pmmij[i][j];
                   4782:            }
                   4783:          }
                   4784:          
                   4785:          for(i=1; i<=npar; i++)
                   4786:            xp[i] = x[i] - (i==theta ?delti[theta]:(double)0);
                   4787:     
                   4788:          pmij(pmmij,cov,ncovmodel,xp,nlstate);
                   4789:          k=0;
                   4790:          for(i=1; i<=(nlstate); i++){
                   4791:            for(j=1; j<=(nlstate+ndeath);j++){
                   4792:              k=k+1;
                   4793:              gm[k]=pmmij[i][j];
                   4794:            }
                   4795:          }
                   4796:      
                   4797:          for(i=1; i<= (nlstate)*(nlstate+ndeath); i++) 
                   4798:            gradg[theta][i]=(gp[i]-gm[i])/(double)2./delti[theta];  
                   4799:        }
                   4800: 
                   4801:        for(j=1; j<=(nlstate)*(nlstate+ndeath);j++)
                   4802:          for(theta=1; theta <=npar; theta++)
                   4803:            trgradg[j][theta]=gradg[theta][j];
                   4804:        
                   4805:        matprod2(dnewm,trgradg,1,(nlstate)*(nlstate+ndeath),1,npar,1,npar,matcov); 
                   4806:        matprod2(doldm,dnewm,1,(nlstate)*(nlstate+ndeath),1,npar,1,(nlstate)*(nlstate+ndeath),gradg);
                   4807: 
                   4808:        pmij(pmmij,cov,ncovmodel,x,nlstate);
                   4809:        
                   4810:        k=0;
                   4811:        for(i=1; i<=(nlstate); i++){
                   4812:          for(j=1; j<=(nlstate+ndeath);j++){
                   4813:            k=k+1;
                   4814:            mu[k][(int) age]=pmmij[i][j];
                   4815:          }
                   4816:        }
                   4817:        for(i=1;i<=(nlstate)*(nlstate+ndeath);i++)
                   4818:          for(j=1;j<=(nlstate)*(nlstate+ndeath);j++)
                   4819:            varpij[i][j][(int)age] = doldm[i][j];
                   4820: 
                   4821:        /*printf("\n%d ",(int)age);
                   4822:          for (i=1; i<=(nlstate)*(nlstate+ndeath);i++){
                   4823:          printf("%e [%e ;%e] ",gm[i],gm[i]-2*sqrt(doldm[i][i]),gm[i]+2*sqrt(doldm[i][i]));
                   4824:          fprintf(ficlog,"%e [%e ;%e] ",gm[i],gm[i]-2*sqrt(doldm[i][i]),gm[i]+2*sqrt(doldm[i][i]));
                   4825:          }*/
                   4826: 
                   4827:        fprintf(ficresprob,"\n%d ",(int)age);
                   4828:        fprintf(ficresprobcov,"\n%d ",(int)age);
                   4829:        fprintf(ficresprobcor,"\n%d ",(int)age);
                   4830: 
                   4831:        for (i=1; i<=(nlstate)*(nlstate+ndeath);i++)
                   4832:          fprintf(ficresprob,"%11.3e (%11.3e) ",mu[i][(int) age],sqrt(varpij[i][i][(int)age]));
                   4833:        for (i=1; i<=(nlstate)*(nlstate+ndeath);i++){
                   4834:          fprintf(ficresprobcov,"%11.3e ",mu[i][(int) age]);
                   4835:          fprintf(ficresprobcor,"%11.3e ",mu[i][(int) age]);
                   4836:        }
                   4837:        i=0;
                   4838:        for (k=1; k<=(nlstate);k++){
                   4839:          for (l=1; l<=(nlstate+ndeath);l++){ 
1.145     brouard  4840:            i++;
1.126     brouard  4841:            fprintf(ficresprobcov,"\n%d %d-%d",(int)age,k,l);
                   4842:            fprintf(ficresprobcor,"\n%d %d-%d",(int)age,k,l);
                   4843:            for (j=1; j<=i;j++){
1.145     brouard  4844:              /* printf(" k=%d l=%d i=%d j=%d\n",k,l,i,j);fflush(stdout); */
1.126     brouard  4845:              fprintf(ficresprobcov," %11.3e",varpij[i][j][(int)age]);
                   4846:              fprintf(ficresprobcor," %11.3e",varpij[i][j][(int) age]/sqrt(varpij[i][i][(int) age])/sqrt(varpij[j][j][(int)age]));
                   4847:            }
                   4848:          }
                   4849:        }/* end of loop for state */
                   4850:       } /* end of loop for age */
1.145     brouard  4851:       free_vector(gp,1,(nlstate+ndeath)*(nlstate+ndeath));
                   4852:       free_vector(gm,1,(nlstate+ndeath)*(nlstate+ndeath));
                   4853:       free_matrix(trgradg,1,(nlstate+ndeath)*(nlstate+ndeath),1,npar);
                   4854:       free_matrix(gradg,1,(nlstate+ndeath)*(nlstate+ndeath),1,npar);
                   4855:       
1.126     brouard  4856:       /* Confidence intervalle of pij  */
                   4857:       /*
1.131     brouard  4858:        fprintf(ficgp,"\nunset parametric;unset label");
1.126     brouard  4859:        fprintf(ficgp,"\nset log y;unset log x; set xlabel \"Age\";set ylabel \"probability (year-1)\"");
                   4860:        fprintf(ficgp,"\nset ter png small\nset size 0.65,0.65");
                   4861:        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);
                   4862:        fprintf(fichtm,"\n<br><img src=\"pijgr%s.png\"> ",optionfilefiname);
                   4863:        fprintf(ficgp,"\nset out \"pijgr%s.png\"",optionfilefiname);
                   4864:        fprintf(ficgp,"\nplot \"%s\" every :::%d::%d u 1:2 \"\%%lf",k1,k2,xfilevarprob);
                   4865:       */
                   4866: 
                   4867:       /* Drawing ellipsoids of confidence of two variables p(k1-l1,k2-l2)*/
1.145     brouard  4868:       first1=1;first2=2;
1.126     brouard  4869:       for (k2=1; k2<=(nlstate);k2++){
                   4870:        for (l2=1; l2<=(nlstate+ndeath);l2++){ 
                   4871:          if(l2==k2) continue;
                   4872:          j=(k2-1)*(nlstate+ndeath)+l2;
                   4873:          for (k1=1; k1<=(nlstate);k1++){
                   4874:            for (l1=1; l1<=(nlstate+ndeath);l1++){ 
                   4875:              if(l1==k1) continue;
                   4876:              i=(k1-1)*(nlstate+ndeath)+l1;
                   4877:              if(i<=j) continue;
                   4878:              for (age=bage; age<=fage; age ++){ 
                   4879:                if ((int)age %5==0){
                   4880:                  v1=varpij[i][i][(int)age]/stepm*YEARM/stepm*YEARM;
                   4881:                  v2=varpij[j][j][(int)age]/stepm*YEARM/stepm*YEARM;
                   4882:                  cv12=varpij[i][j][(int)age]/stepm*YEARM/stepm*YEARM;
                   4883:                  mu1=mu[i][(int) age]/stepm*YEARM ;
                   4884:                  mu2=mu[j][(int) age]/stepm*YEARM;
                   4885:                  c12=cv12/sqrt(v1*v2);
                   4886:                  /* Computing eigen value of matrix of covariance */
                   4887:                  lc1=((v1+v2)+sqrt((v1+v2)*(v1+v2) - 4*(v1*v2-cv12*cv12)))/2.;
                   4888:                  lc2=((v1+v2)-sqrt((v1+v2)*(v1+v2) - 4*(v1*v2-cv12*cv12)))/2.;
1.135     brouard  4889:                  if ((lc2 <0) || (lc1 <0) ){
1.145     brouard  4890:                    if(first2==1){
                   4891:                      first1=0;
                   4892:                    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);
                   4893:                    }
                   4894:                    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);
                   4895:                    /* lc1=fabs(lc1); */ /* If we want to have them positive */
                   4896:                    /* lc2=fabs(lc2); */
1.135     brouard  4897:                  }
                   4898: 
1.126     brouard  4899:                  /* Eigen vectors */
                   4900:                  v11=(1./sqrt(1+(v1-lc1)*(v1-lc1)/cv12/cv12));
                   4901:                  /*v21=sqrt(1.-v11*v11); *//* error */
                   4902:                  v21=(lc1-v1)/cv12*v11;
                   4903:                  v12=-v21;
                   4904:                  v22=v11;
                   4905:                  tnalp=v21/v11;
                   4906:                  if(first1==1){
                   4907:                    first1=0;
                   4908:                    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);
                   4909:                  }
                   4910:                  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);
                   4911:                  /*printf(fignu*/
                   4912:                  /* mu1+ v11*lc1*cost + v12*lc2*sin(t) */
                   4913:                  /* mu2+ v21*lc1*cost + v22*lc2*sin(t) */
                   4914:                  if(first==1){
                   4915:                    first=0;
1.200     brouard  4916:                    fprintf(ficgp,"\n# Ellipsoids of confidence\n#\n");
1.126     brouard  4917:                    fprintf(ficgp,"\nset parametric;unset label");
                   4918:                    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  4919:                    fprintf(ficgp,"\nset ter svg size 640, 480");
1.126     brouard  4920:                    fprintf(fichtmcov,"\n<br>Ellipsoids of confidence cov(p%1d%1d,p%1d%1d) expressed in year<sup>-1</sup>\
1.201     brouard  4921:  :<a href=\"%s_%d%1d%1d-%1d%1d.svg\">\
                   4922: %s_%d%1d%1d-%1d%1d.svg</A>, ",k1,l1,k2,l2,\
                   4923:                            subdirf2(optionfilefiname,"VARPIJGR_"), j1,k1,l1,k2,l2,\
                   4924:                            subdirf2(optionfilefiname,"VARPIJGR_"), j1,k1,l1,k2,l2);
                   4925:                    fprintf(fichtmcov,"\n<br><img src=\"%s_%d%1d%1d-%1d%1d.svg\"> ",subdirf2(optionfilefiname,"VARPIJGR_"), j1,k1,l1,k2,l2);
1.126     brouard  4926:                    fprintf(fichtmcov,"\n<br> Correlation at age %d (%.3f),",(int) age, c12);
1.201     brouard  4927:                    fprintf(ficgp,"\nset out \"%s_%d%1d%1d-%1d%1d.svg\"",subdirf2(optionfilefiname,"VARPIJGR_"), j1,k1,l1,k2,l2);
1.126     brouard  4928:                    fprintf(ficgp,"\nset label \"%d\" at %11.3e,%11.3e center",(int) age, mu1,mu2);
                   4929:                    fprintf(ficgp,"\n# Age %d, p%1d%1d - p%1d%1d",(int) age, k1,l1,k2,l2);
                   4930:                    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",\
                   4931:                            mu1,std,v11,sqrt(lc1),v12,sqrt(lc2),\
                   4932:                            mu2,std,v21,sqrt(lc1),v22,sqrt(lc2));
                   4933:                  }else{
                   4934:                    first=0;
                   4935:                    fprintf(fichtmcov," %d (%.3f),",(int) age, c12);
                   4936:                    fprintf(ficgp,"\n# Age %d, p%1d%1d - p%1d%1d",(int) age, k1,l1,k2,l2);
                   4937:                    fprintf(ficgp,"\nset label \"%d\" at %11.3e,%11.3e center",(int) age, mu1,mu2);
                   4938:                    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",\
                   4939:                            mu1,std,v11,sqrt(lc1),v12,sqrt(lc2),\
                   4940:                            mu2,std,v21,sqrt(lc1),v22,sqrt(lc2));
                   4941:                  }/* if first */
                   4942:                } /* age mod 5 */
                   4943:              } /* end loop age */
1.201     brouard  4944:              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  4945:              first=1;
                   4946:            } /*l12 */
                   4947:          } /* k12 */
                   4948:        } /*l1 */
                   4949:       }/* k1 */
1.169     brouard  4950:       /* } */ /* loop covariates */
1.126     brouard  4951:   }
                   4952:   free_ma3x(varpij,1,nlstate,1,nlstate+ndeath,(int) bage, (int)fage);
                   4953:   free_matrix(mu,1,(nlstate+ndeath)*(nlstate+ndeath),(int) bage, (int)fage);
                   4954:   free_matrix(doldm,1,(nlstate)*(nlstate+ndeath),1,(nlstate)*(nlstate+ndeath));
                   4955:   free_matrix(dnewm,1,(nlstate)*(nlstate+ndeath),1,npar);
                   4956:   free_vector(xp,1,npar);
                   4957:   fclose(ficresprob);
                   4958:   fclose(ficresprobcov);
                   4959:   fclose(ficresprobcor);
                   4960:   fflush(ficgp);
                   4961:   fflush(fichtmcov);
                   4962: }
                   4963: 
                   4964: 
                   4965: /******************* Printing html file ***********/
1.201     brouard  4966: void printinghtml(char fileresu[], char title[], char datafile[], int firstpass, \
1.126     brouard  4967:                  int lastpass, int stepm, int weightopt, char model[],\
                   4968:                  int imx,int jmin, int jmax, double jmeanint,char rfileres[],\
1.211     brouard  4969:                  int popforecast, int prevfcast, int estepm ,          \
1.213     brouard  4970:                  double jprev1, double mprev1,double anprev1, double dateprev1, \
                   4971:                  double jprev2, double mprev2,double anprev2, double dateprev2){
1.126     brouard  4972:   int jj1, k1, i1, cpt;
                   4973: 
                   4974:    fprintf(fichtm,"<ul><li><a href='#firstorder'>Result files (first order: no variance)</a>\n \
                   4975:    <li><a href='#secondorder'>Result files (second order (variance)</a>\n \
                   4976: </ul>");
1.214     brouard  4977:    fprintf(fichtm,"<ul><li><h4><a name='firstorder'>Result files (first order: no variance)</a></h4>\n");
                   4978:    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",
                   4979:           jprev1, mprev1,anprev1,jprev2, mprev2,anprev2,subdirfext3(optionfilefiname,"PHTMFR_",".htm"),subdirfext3(optionfilefiname,"PHTMFR_",".htm"));
                   4980:    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  4981:           jprev1, mprev1,anprev1,jprev2, mprev2,anprev2,subdirfext3(optionfilefiname,"PHTM_",".htm"),subdirfext3(optionfilefiname,"PHTM_",".htm"));
                   4982:    fprintf(fichtm,",  <a href=\"%s\">%s</a> (text file) <br>\n",subdirf2(fileresu,"P_"),subdirf2(fileresu,"P_"));
1.126     brouard  4983:    fprintf(fichtm,"\
                   4984:  - Estimated transition probabilities over %d (stepm) months: <a href=\"%s\">%s</a><br>\n ",
1.201     brouard  4985:           stepm,subdirf2(fileresu,"PIJ_"),subdirf2(fileresu,"PIJ_"));
1.126     brouard  4986:    fprintf(fichtm,"\
                   4987:  - Period (stable) prevalence in each health state: <a href=\"%s\">%s</a> <br>\n",
1.201     brouard  4988:           subdirf2(fileresu,"PL_"),subdirf2(fileresu,"PL_"));
1.126     brouard  4989:    fprintf(fichtm,"\
1.211     brouard  4990:  - (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  4991:    <a href=\"%s\">%s</a> <br>\n",
1.201     brouard  4992:           estepm,subdirf2(fileresu,"E_"),subdirf2(fileresu,"E_"));
1.211     brouard  4993:    if(prevfcast==1){
                   4994:      fprintf(fichtm,"\
                   4995:  - Prevalence projections by age and states:                           \
1.201     brouard  4996:    <a href=\"%s\">%s</a> <br>\n</li>", subdirf2(fileresu,"F_"),subdirf2(fileresu,"F_"));
1.211     brouard  4997:    }
1.126     brouard  4998: 
                   4999: fprintf(fichtm," \n<ul><li><b>Graphs</b></li><p>");
                   5000: 
1.145     brouard  5001:  m=pow(2,cptcoveff);
1.126     brouard  5002:  if (cptcovn < 1) {m=1;ncodemax[1]=1;}
                   5003: 
                   5004:  jj1=0;
                   5005:  for(k1=1; k1<=m;k1++){
1.192     brouard  5006:    /* for(i1=1; i1<=ncodemax[k1];i1++){ */
1.126     brouard  5007:      jj1++;
                   5008:      if (cptcovn > 0) {
                   5009:        fprintf(fichtm,"<hr  size=\"2\" color=\"#EC5E5E\">************ Results for covariates");
1.192     brouard  5010:        for (cpt=1; cpt<=cptcoveff;cpt++){ 
1.198     brouard  5011:         fprintf(fichtm," V%d=%d ",Tvaraff[cpt],nbcode[Tvaraff[cpt]][codtabm(jj1,cpt)]);
                   5012:         printf(" V%d=%d ",Tvaraff[cpt],nbcode[Tvaraff[cpt]][codtabm(jj1,cpt)]);fflush(stdout);
1.192     brouard  5013:        }
1.126     brouard  5014:        fprintf(fichtm," ************\n<hr size=\"2\" color=\"#EC5E5E\">");
                   5015:      }
1.201     brouard  5016:      /* aij, bij */
1.211     brouard  5017:      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> \
                   5018: <img src=\"%s_%d-1.svg\">",model,subdirf2(optionfilefiname,"PE_"),jj1,subdirf2(optionfilefiname,"PE_"),jj1,subdirf2(optionfilefiname,"PE_"),jj1);
1.126     brouard  5019:      /* Pij */
1.211     brouard  5020:      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  5021: <img src=\"%s_%d-2.svg\">",stepm,subdirf2(optionfilefiname,"PE_"),jj1,subdirf2(optionfilefiname,"PE_"),jj1,subdirf2(optionfilefiname,"PE_"),jj1);     
1.126     brouard  5022:      /* Quasi-incidences */
1.211     brouard  5023:      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  5024:  before but expressed in per year i.e. quasi incidences if stepm is small and probabilities too,\
1.211     brouard  5025:  incidence (rates) are the limit when h tends to zero of the ratio of the probability  <sub>h</sub>P<sub>ij</sub> \
                   5026: 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  5027: <img src=\"%s_%d-3.svg\">",stepm,subdirf2(optionfilefiname,"PE_"),jj1,subdirf2(optionfilefiname,"PE_"),jj1,subdirf2(optionfilefiname,"PE_"),jj1); 
                   5028:      /* Survival functions (period) in state j */
                   5029:      for(cpt=1; cpt<=nlstate;cpt++){
                   5030:        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> \
                   5031: <img src=\"%s_%d-%d.svg\">", cpt, cpt, nlstate, subdirf2(optionfilefiname,"LIJ_"),cpt,jj1,subdirf2(optionfilefiname,"LIJ_"),cpt,jj1,subdirf2(optionfilefiname,"LIJ_"),cpt,jj1);
                   5032:      }
                   5033:      /* State specific survival functions (period) */
                   5034:      for(cpt=1; cpt<=nlstate;cpt++){
1.208     brouard  5035:        fprintf(fichtm,"<br>\n- Survival functions from state %d in each live state and total.\
1.201     brouard  5036:  Or probability to survive in various states (1 to %d) being in state %d at different ages.\
                   5037:  <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);
                   5038:      }
                   5039:      /* Period (stable) prevalence in each health state */
                   5040:      for(cpt=1; cpt<=nlstate;cpt++){
                   5041:        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> \
                   5042: <img src=\"%s_%d-%d.svg\">", cpt, cpt, nlstate, subdirf2(optionfilefiname,"P_"),cpt,jj1,subdirf2(optionfilefiname,"P_"),cpt,jj1,subdirf2(optionfilefiname,"P_"),cpt,jj1);
                   5043:      }
1.211     brouard  5044:     if(prevfcast==1){
                   5045:       /* Projection of prevalence up to period (stable) prevalence in each health state */
                   5046:       for(cpt=1; cpt<=nlstate;cpt++){
1.214     brouard  5047:        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  5048: <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  5049:       }
                   5050:     }
                   5051: 
1.126     brouard  5052:      for(cpt=1; cpt<=nlstate;cpt++) {
1.205     brouard  5053:        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  5054: <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  5055:      }
1.192     brouard  5056:    /* } /\* end i1 *\/ */
1.126     brouard  5057:  }/* End k1 */
                   5058:  fprintf(fichtm,"</ul>");
                   5059: 
                   5060:  fprintf(fichtm,"\
                   5061: \n<br><li><h4> <a name='secondorder'>Result files (second order: variances)</a></h4>\n\
1.193     brouard  5062:  - Parameter file with estimated parameters and covariance matrix: <a href=\"%s\">%s</a> <br> \
1.203     brouard  5063:  - 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  5064: But because parameters are usually highly correlated (a higher incidence of disability \
                   5065: and a higher incidence of recovery can give very close observed transition) it might \
                   5066: be very useful to look not only at linear confidence intervals estimated from the \
                   5067: variances but at the covariance matrix. And instead of looking at the estimated coefficients \
                   5068: (parameters) of the logistic regression, it might be more meaningful to visualize the \
                   5069: covariance matrix of the one-step probabilities. \
                   5070: See page 'Matrix of variance-covariance of one-step probabilities' below. \n", rfileres,rfileres);
1.126     brouard  5071: 
1.193     brouard  5072:  fprintf(fichtm," - Standard deviation of one-step probabilities: <a href=\"%s\">%s</a> <br>\n",
1.201     brouard  5073:         subdirf2(fileresu,"PROB_"),subdirf2(fileresu,"PROB_"));
1.126     brouard  5074:  fprintf(fichtm,"\
                   5075:  - Variance-covariance of one-step probabilities: <a href=\"%s\">%s</a> <br>\n",
1.201     brouard  5076:         subdirf2(fileresu,"PROBCOV_"),subdirf2(fileresu,"PROBCOV_"));
1.126     brouard  5077: 
                   5078:  fprintf(fichtm,"\
                   5079:  - Correlation matrix of one-step probabilities: <a href=\"%s\">%s</a> <br>\n",
1.201     brouard  5080:         subdirf2(fileresu,"PROBCOR_"),subdirf2(fileresu,"PROBCOR_"));
1.126     brouard  5081:  fprintf(fichtm,"\
                   5082:  - 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): \
                   5083:    <a href=\"%s\">%s</a> <br>\n</li>",
1.201     brouard  5084:           estepm,subdirf2(fileresu,"CVE_"),subdirf2(fileresu,"CVE_"));
1.126     brouard  5085:  fprintf(fichtm,"\
                   5086:  - (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): \
                   5087:    <a href=\"%s\">%s</a> <br>\n</li>",
1.201     brouard  5088:           estepm,subdirf2(fileresu,"STDE_"),subdirf2(fileresu,"STDE_"));
1.126     brouard  5089:  fprintf(fichtm,"\
1.128     brouard  5090:  - 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  5091:         estepm, subdirf2(fileresu,"V_"),subdirf2(fileresu,"V_"));
1.126     brouard  5092:  fprintf(fichtm,"\
1.128     brouard  5093:  - 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  5094:         estepm, subdirf2(fileresu,"T_"),subdirf2(fileresu,"T_"));
1.126     brouard  5095:  fprintf(fichtm,"\
                   5096:  - Standard deviation of period (stable) prevalences: <a href=\"%s\">%s</a> <br>\n",\
1.201     brouard  5097:         subdirf2(fileresu,"VPL_"),subdirf2(fileresu,"VPL_"));
1.126     brouard  5098: 
                   5099: /*  if(popforecast==1) fprintf(fichtm,"\n */
                   5100: /*  - Prevalences forecasting: <a href=\"f%s\">f%s</a> <br>\n */
                   5101: /*  - Population forecasting (if popforecast=1): <a href=\"pop%s\">pop%s</a> <br>\n */
                   5102: /*     <br>",fileres,fileres,fileres,fileres); */
                   5103: /*  else  */
                   5104: /*    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); */
                   5105:  fflush(fichtm);
                   5106:  fprintf(fichtm," <ul><li><b>Graphs</b></li><p>");
                   5107: 
1.145     brouard  5108:  m=pow(2,cptcoveff);
1.126     brouard  5109:  if (cptcovn < 1) {m=1;ncodemax[1]=1;}
                   5110: 
                   5111:  jj1=0;
                   5112:  for(k1=1; k1<=m;k1++){
1.192     brouard  5113:    /* for(i1=1; i1<=ncodemax[k1];i1++){ */
1.126     brouard  5114:      jj1++;
                   5115:      if (cptcovn > 0) {
                   5116:        fprintf(fichtm,"<hr  size=\"2\" color=\"#EC5E5E\">************ Results for covariates");
                   5117:        for (cpt=1; cpt<=cptcoveff;cpt++) 
1.198     brouard  5118:         fprintf(fichtm," V%d=%d ",Tvaraff[cpt],nbcode[Tvaraff[cpt]][codtabm(jj1,cpt)]);
1.126     brouard  5119:        fprintf(fichtm," ************\n<hr size=\"2\" color=\"#EC5E5E\">");
                   5120:      }
                   5121:      for(cpt=1; cpt<=nlstate;cpt++) {
                   5122:        fprintf(fichtm,"<br>- Observed (cross-sectional) and period (incidence based) \
1.205     brouard  5123: prevalence (with 95%% confidence interval) in state (%d): <a href=\"%s_%d%d.svg\"> %s_%d-%d.svg <br>\
                   5124: <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  5125:      }
                   5126:      fprintf(fichtm,"\n<br>- Total life expectancy by age and \
1.128     brouard  5127: health expectancies in states (1) and (2). If popbased=1 the smooth (due to the model) \
                   5128: true period expectancies (those weighted with period prevalences are also\
                   5129:  drawn in addition to the population based expectancies computed using\
1.205     brouard  5130:  observed and cahotic prevalences:  <a href=\"%s_%d.svg\">%s_%d.svg<br>\
                   5131: <img src=\"%s_%d.svg\">",subdirf2(optionfilefiname,"E_"),jj1,subdirf2(optionfilefiname,"E_"),jj1,subdirf2(optionfilefiname,"E_"),jj1);
1.192     brouard  5132:    /* } /\* end i1 *\/ */
1.126     brouard  5133:  }/* End k1 */
                   5134:  fprintf(fichtm,"</ul>");
                   5135:  fflush(fichtm);
                   5136: }
                   5137: 
                   5138: /******************* Gnuplot file **************/
1.211     brouard  5139:     void printinggnuplot(char fileresu[], char optionfilefiname[], double ageminpar, double agemaxpar, double fage , int prevfcast, char pathc[], double p[]){
1.126     brouard  5140: 
                   5141:   char dirfileres[132],optfileres[132];
1.164     brouard  5142:   int cpt=0,k1=0,i=0,k=0,j=0,jk=0,k2=0,k3=0,ij=0,l=0;
1.211     brouard  5143:   int lv=0, vlv=0, kl=0;
1.130     brouard  5144:   int ng=0;
1.201     brouard  5145:   int vpopbased;
1.126     brouard  5146: /*   if((ficgp=fopen(optionfilegnuplot,"a"))==NULL) { */
                   5147: /*     printf("Problem with file %s",optionfilegnuplot); */
                   5148: /*     fprintf(ficlog,"Problem with file %s",optionfilegnuplot); */
                   5149: /*   } */
                   5150: 
                   5151:   /*#ifdef windows */
                   5152:   fprintf(ficgp,"cd \"%s\" \n",pathc);
                   5153:     /*#endif */
                   5154:   m=pow(2,cptcoveff);
                   5155: 
1.202     brouard  5156:   /* Contribution to likelihood */
                   5157:   /* Plot the probability implied in the likelihood */
                   5158:     fprintf(ficgp,"\n# Contributions to the Likelihood, mle >=1. For mle=4 no interpolation, pure matrix products.\n#\n");
                   5159:     fprintf(ficgp,"\n set log y; unset log x;set xlabel \"Age\"; set ylabel \"Likelihood (-2Log(L))\";");
                   5160:     /* fprintf(ficgp,"\nset ter svg size 640, 480"); */ /* Too big for svg */
1.205     brouard  5161:     fprintf(ficgp,"\nset ter pngcairo size 640, 480");
1.204     brouard  5162: /* nice for mle=4 plot by number of matrix products.
1.202     brouard  5163:    replot  "rrtest1/toto.txt" u 2:($4 == 1 && $5==2 ? $9 : 1/0):5 t "p12" with point lc 1 */
                   5164: /* replot exp(p1+p2*x)/(1+exp(p1+p2*x)+exp(p3+p4*x)+exp(p5+p6*x)) t "p12(x)"  */
                   5165:     /* fprintf(ficgp,"\nset out \"%s.svg\";",subdirf2(optionfilefiname,"ILK_")); */
1.204     brouard  5166:     fprintf(ficgp,"\nset out \"%s-dest.png\";",subdirf2(optionfilefiname,"ILK_"));
1.214     brouard  5167:     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  5168:     fprintf(ficgp,"\nset out \"%s-ori.png\";",subdirf2(optionfilefiname,"ILK_"));
1.214     brouard  5169:     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  5170:     for (i=1; i<= nlstate ; i ++) {
                   5171:       fprintf(ficgp,"\nset out \"%s-p%dj.png\";set ylabel \"Probability for each individual/wave\";",subdirf2(optionfilefiname,"ILK_"),i);
1.205     brouard  5172:       fprintf(ficgp,"unset log;\n# plot weighted, mean weight should have point size of 0.5\n plot  \"%s\"",subdirf(fileresilk));
1.214     brouard  5173:       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  5174:       for (j=2; j<= nlstate+ndeath ; j ++) {
1.214     brouard  5175:        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  5176:       }
                   5177:       fprintf(ficgp,";\nset out; unset ylabel;\n"); 
                   5178:     }
                   5179:     /* 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 */             
                   5180:     /* fprintf(ficgp,"\nset log y;plot  \"%s\" u 2:(-$11):3 t \"All sample, all transitions\" with dots lc variable",subdirf(fileresilk)); */
                   5181:     /* 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  5182:     fprintf(ficgp,"\nset out;unset log\n");
1.202     brouard  5183:     /* fprintf(ficgp,"\nset out \"%s.svg\"; replot; set out; # bug gnuplot",subdirf2(optionfilefiname,"ILK_")); */
                   5184: 
1.126     brouard  5185:   strcpy(dirfileres,optionfilefiname);
                   5186:   strcpy(optfileres,"vpl");
                   5187:  /* 1eme*/
1.211     brouard  5188:   for (cpt=1; cpt<= nlstate ; cpt ++) { /* For each live state */
                   5189:     for (k1=1; k1<= m ; k1 ++) { /* For each combination of covariate */
                   5190:       /* plot [100000000000000000000:-100000000000000000000] "mysbiaspar/vplrmysbiaspar.txt to check */
                   5191:       fprintf(ficgp,"\n# 1st: Period (stable) prevalence with CI: 'VPL_' files ");
                   5192:       for (k=1; k<=cptcoveff; k++){    /* For each covariate and each value */
                   5193:        lv= decodtabm(k1,k,cptcoveff); /* Should be the covariate number corresponding to k1 combination */
                   5194:        /* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
                   5195:        /* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
                   5196:        /* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
                   5197:        vlv= nbcode[Tvaraff[lv]][lv];
                   5198:        fprintf(ficgp," V%d=%d ",k,vlv);
                   5199:       }
                   5200:       fprintf(ficgp,"\n#\n");
                   5201: 
1.201     brouard  5202:      fprintf(ficgp,"\nset out \"%s_%d-%d.svg\" \n",subdirf2(optionfilefiname,"V_"),cpt,k1);
                   5203:      fprintf(ficgp,"\n#set out \"V_%s_%d-%d.svg\" \n",optionfilefiname,cpt,k1);
1.126     brouard  5204:      fprintf(ficgp,"set xlabel \"Age\" \n\
                   5205: set ylabel \"Probability\" \n\
1.199     brouard  5206: set ter svg size 640, 480\n\
1.201     brouard  5207: plot [%.f:%.f] \"%s\" every :::%d::%d u 1:2 \"%%lf",ageminpar,fage,subdirf2(fileresu,"VPL_"),k1-1,k1-1);
1.126     brouard  5208: 
                   5209:      for (i=1; i<= nlstate ; i ++) {
1.170     brouard  5210:        if (i==cpt) fprintf(ficgp," %%lf (%%lf)");
                   5211:        else        fprintf(ficgp," %%*lf (%%*lf)");
1.126     brouard  5212:      }
1.201     brouard  5213:      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  5214:      for (i=1; i<= nlstate ; i ++) {
1.170     brouard  5215:        if (i==cpt) fprintf(ficgp," %%lf (%%lf)");
                   5216:        else fprintf(ficgp," %%*lf (%%*lf)");
1.126     brouard  5217:      } 
1.201     brouard  5218:      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  5219:      for (i=1; i<= nlstate ; i ++) {
1.170     brouard  5220:        if (i==cpt) fprintf(ficgp," %%lf (%%lf)");
                   5221:        else fprintf(ficgp," %%*lf (%%*lf)");
1.126     brouard  5222:      }  
1.201     brouard  5223:      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));
                   5224:      fprintf(ficgp,"\nset out \n");
                   5225:     } /* k1 */
                   5226:   } /* cpt */
1.126     brouard  5227:   /*2 eme*/
                   5228:   for (k1=1; k1<= m ; k1 ++) { 
1.211     brouard  5229:       fprintf(ficgp,"\n# 2nd: Total life expectancy with CI: 't' files ");
                   5230:       for (k=1; k<=cptcoveff; k++){    /* For each covariate and each value */
                   5231:        lv= decodtabm(k1,k,cptcoveff); /* Should be the covariate number corresponding to k1 combination */
                   5232:        /* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
                   5233:        /* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
                   5234:        /* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
                   5235:        vlv= nbcode[Tvaraff[lv]][lv];
                   5236:        fprintf(ficgp," V%d=%d ",k,vlv);
                   5237:       }
                   5238:       fprintf(ficgp,"\n#\n");
                   5239: 
1.201     brouard  5240:     fprintf(ficgp,"\nset out \"%s_%d.svg\" \n",subdirf2(optionfilefiname,"E_"),k1);
                   5241:     for(vpopbased=0; vpopbased <= popbased; vpopbased++){ /* Done for vpopbased=0 and vpopbased=1 if popbased==1*/
                   5242:       if(vpopbased==0)
                   5243:        fprintf(ficgp,"set ylabel \"Years\" \nset ter svg size 640, 480\nplot [%.f:%.f] ",ageminpar,fage);
                   5244:       else
                   5245:        fprintf(ficgp,"\nreplot ");
                   5246:       for (i=1; i<= nlstate+1 ; i ++) {
                   5247:        k=2*i;
                   5248:        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);
                   5249:        for (j=1; j<= nlstate+1 ; j ++) {
                   5250:          if (j==i) fprintf(ficgp," %%lf (%%lf)");
                   5251:          else fprintf(ficgp," %%*lf (%%*lf)");
                   5252:        }   
                   5253:        if (i== 1) fprintf(ficgp,"\" t\"TLE\" w l lt %d, \\\n",i);
                   5254:        else fprintf(ficgp,"\" t\"LE in state (%d)\" w l lt %d, \\\n",i-1,i+1);
                   5255:        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);
                   5256:        for (j=1; j<= nlstate+1 ; j ++) {
                   5257:          if (j==i) fprintf(ficgp," %%lf (%%lf)");
                   5258:          else fprintf(ficgp," %%*lf (%%*lf)");
                   5259:        }   
                   5260:        fprintf(ficgp,"\" t\"\" w l lt 0,");
                   5261:        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);
                   5262:        for (j=1; j<= nlstate+1 ; j ++) {
                   5263:          if (j==i) fprintf(ficgp," %%lf (%%lf)");
                   5264:          else fprintf(ficgp," %%*lf (%%*lf)");
                   5265:        }   
                   5266:        if (i== (nlstate+1)) fprintf(ficgp,"\" t\"\" w l lt 0");
                   5267:        else fprintf(ficgp,"\" t\"\" w l lt 0,\\\n");
                   5268:       } /* state */
                   5269:     } /* vpopbased */
                   5270:     fprintf(ficgp,"\nset out;set out \"%s_%d.svg\"; replot; set out; \n",subdirf2(optionfilefiname,"E_"),k1); /* Buggy gnuplot */
                   5271:   } /* k1 */
1.211     brouard  5272: 
                   5273: 
1.126     brouard  5274:   /*3eme*/
                   5275:   for (k1=1; k1<= m ; k1 ++) { 
                   5276:     for (cpt=1; cpt<= nlstate ; cpt ++) {
1.211     brouard  5277:       fprintf(ficgp,"\n# 3d: Life expectancy with EXP_ files:  cov=%d state=%d",k1, cpt);
                   5278:       for (k=1; k<=cptcoveff; k++){    /* For each covariate and each value */
                   5279:        lv= decodtabm(k1,k,cptcoveff); /* Should be the covariate number corresponding to k1 combination */
                   5280:        /* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
                   5281:        /* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
                   5282:        /* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
                   5283:        vlv= nbcode[Tvaraff[lv]][lv];
                   5284:        fprintf(ficgp," V%d=%d ",k,vlv);
                   5285:       }
                   5286:       fprintf(ficgp,"\n#\n");
                   5287: 
1.126     brouard  5288:       /*       k=2+nlstate*(2*cpt-2); */
                   5289:       k=2+(nlstate+1)*(cpt-1);
1.201     brouard  5290:       fprintf(ficgp,"\nset out \"%s_%d%d.svg\" \n",subdirf2(optionfilefiname,"EXP_"),cpt,k1);
1.199     brouard  5291:       fprintf(ficgp,"set ter svg size 640, 480\n\
1.201     brouard  5292: 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  5293:       /*fprintf(ficgp,",\"e%s\" every :::%d::%d u 1:($%d-2*$%d) \"\%%lf ",fileres,k1-1,k1-1,k,k+1);
                   5294:        for (i=1; i<= nlstate*2 ; i ++) fprintf(ficgp,"\%%lf (\%%lf) ");
                   5295:        fprintf(ficgp,"\" t \"e%d1\" w l",cpt);
                   5296:        fprintf(ficgp,",\"e%s\" every :::%d::%d u 1:($%d+2*$%d) \"\%%lf ",fileres,k1-1,k1-1,k,k+1);
                   5297:        for (i=1; i<= nlstate*2 ; i ++) fprintf(ficgp,"\%%lf (\%%lf) ");
                   5298:        fprintf(ficgp,"\" t \"e%d1\" w l",cpt);
                   5299:        
                   5300:       */
                   5301:       for (i=1; i< nlstate ; i ++) {
1.201     brouard  5302:        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  5303:        /*      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);*/
                   5304:        
                   5305:       } 
1.201     brouard  5306:       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  5307:     }
                   5308:   }
                   5309:   
1.201     brouard  5310:   /* Survival functions (period) from state i in state j by initial state i */
                   5311:   for (k1=1; k1<= m ; k1 ++) { /* For each multivariate if any */
                   5312:     for (cpt=1; cpt<=nlstate ; cpt ++) { /* For each life state */
1.211     brouard  5313:       fprintf(ficgp,"\n#\n#\n# Survival functions in state j : 'LIJ_' files, cov=%d state=%d",k1, cpt);
                   5314:       for (k=1; k<=cptcoveff; k++){    /* For each covariate and each value */
                   5315:        lv= decodtabm(k1,k,cptcoveff); /* Should be the covariate number corresponding to k1 combination */
                   5316:        /* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
                   5317:        /* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
                   5318:        /* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
                   5319:        vlv= nbcode[Tvaraff[lv]][lv];
                   5320:        fprintf(ficgp," V%d=%d ",k,vlv);
                   5321:       }
                   5322:       fprintf(ficgp,"\n#\n");
                   5323: 
1.201     brouard  5324:       fprintf(ficgp,"\nset out \"%s_%d-%d.svg\" \n",subdirf2(optionfilefiname,"LIJ_"),cpt,k1);
                   5325:       fprintf(ficgp,"set xlabel \"Age\" \nset ylabel \"Probability to be alive\" \n\
                   5326: set ter svg size 640, 480\n\
                   5327: unset log y\n\
                   5328: plot [%.f:%.f]  ", ageminpar, agemaxpar);
1.211     brouard  5329:       k=3;
1.201     brouard  5330:       for (i=1; i<= nlstate ; i ++){
                   5331:        if(i==1)
                   5332:          fprintf(ficgp,"\"%s\"",subdirf2(fileresu,"PIJ_"));
                   5333:        else
                   5334:          fprintf(ficgp,", '' ");
                   5335:        l=(nlstate+ndeath)*(i-1)+1;
                   5336:        fprintf(ficgp," u ($1==%d ? ($3):1/0):($%d/($%d",k1,k+l+(cpt-1),k+l);
                   5337:        for (j=2; j<= nlstate+ndeath ; j ++)
                   5338:          fprintf(ficgp,"+$%d",k+l+j-1);
                   5339:        fprintf(ficgp,")) t \"l(%d,%d)\" w l",i,cpt);
                   5340:       } /* nlstate */
                   5341:       fprintf(ficgp,"\nset out\n");
                   5342:     } /* end cpt state*/ 
                   5343:   } /* end covariate */  
                   5344: 
                   5345:   /* Survival functions (period) from state i in state j by final state j */
1.202     brouard  5346:   for (k1=1; k1<= m ; k1 ++) { /* For each covariate if any */
1.201     brouard  5347:     for (cpt=1; cpt<=nlstate ; cpt ++) { /* For each inital state  */
                   5348:       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  5349:       for (k=1; k<=cptcoveff; k++){    /* For each covariate and each value */
                   5350:        lv= decodtabm(k1,k,cptcoveff); /* Should be the covariate number corresponding to k1 combination */
                   5351:        /* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
                   5352:        /* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
                   5353:        /* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
                   5354:        vlv= nbcode[Tvaraff[lv]][lv];
                   5355:        fprintf(ficgp," V%d=%d ",k,vlv);
                   5356:       }
                   5357:       fprintf(ficgp,"\n#\n");
                   5358: 
1.201     brouard  5359:       fprintf(ficgp,"\nset out \"%s_%d-%d.svg\" \n",subdirf2(optionfilefiname,"LIJT_"),cpt,k1);
                   5360:       fprintf(ficgp,"set xlabel \"Age\" \nset ylabel \"Probability to be alive\" \n\
                   5361: set ter svg size 640, 480\n\
                   5362: unset log y\n\
                   5363: plot [%.f:%.f]  ", ageminpar, agemaxpar);
1.211     brouard  5364:       k=3;
1.201     brouard  5365:       for (j=1; j<= nlstate ; j ++){ /* Lived in state j */
                   5366:        if(j==1)
                   5367:          fprintf(ficgp,"\"%s\"",subdirf2(fileresu,"PIJ_"));
                   5368:        else
                   5369:          fprintf(ficgp,", '' ");
                   5370:        l=(nlstate+ndeath)*(cpt-1) +j;
                   5371:        fprintf(ficgp," u (($1==%d && (floor($2)%%5 == 0)) ? ($3):1/0):($%d",k1,k+l);
                   5372:        /* for (i=2; i<= nlstate+ndeath ; i ++) */
                   5373:        /*   fprintf(ficgp,"+$%d",k+l+i-1); */
                   5374:        fprintf(ficgp,") t \"l(%d,%d)\" w l",cpt,j);
                   5375:       } /* nlstate */
                   5376:       fprintf(ficgp,", '' ");
                   5377:       fprintf(ficgp," u (($1==%d && (floor($2)%%5 == 0)) ? ($3):1/0):(",k1);
                   5378:       for (j=1; j<= nlstate ; j ++){ /* Lived in state j */
                   5379:        l=(nlstate+ndeath)*(cpt-1) +j;
                   5380:        if(j < nlstate)
                   5381:          fprintf(ficgp,"$%d +",k+l);
                   5382:        else
                   5383:          fprintf(ficgp,"$%d) t\"l(%d,.)\" w l",k+l,cpt);
                   5384:       }
                   5385:       fprintf(ficgp,"\nset out\n");
                   5386:     } /* end cpt state*/ 
                   5387:   } /* end covariate */  
                   5388: 
1.202     brouard  5389:   /* CV preval stable (period) for each covariate */
1.211     brouard  5390:   for (k1=1; k1<= m ; k1 ++) { /* For each covariate combination (1 to m=2**k), if any covariate is present */
1.153     brouard  5391:     for (cpt=1; cpt<=nlstate ; cpt ++) { /* For each life state */
1.211     brouard  5392:       fprintf(ficgp,"\n#\n#\n#CV preval stable (period): 'pij' files, covariatecombination#=%d state=%d",k1, cpt);
                   5393:       for (k=1; k<=cptcoveff; k++){    /* For each covariate and each value */
                   5394:        lv= decodtabm(k1,k,cptcoveff); /* Should be the covariate number corresponding to k1 combination */
                   5395:        /* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
                   5396:        /* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
                   5397:        /* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
                   5398:        vlv= nbcode[Tvaraff[lv]][lv];
                   5399:        fprintf(ficgp," V%d=%d ",k,vlv);
                   5400:       }
                   5401:       fprintf(ficgp,"\n#\n");
                   5402: 
1.201     brouard  5403:       fprintf(ficgp,"\nset out \"%s_%d-%d.svg\" \n",subdirf2(optionfilefiname,"P_"),cpt,k1);
1.126     brouard  5404:       fprintf(ficgp,"set xlabel \"Age\" \nset ylabel \"Probability\" \n\
1.199     brouard  5405: set ter svg size 640, 480\n\
1.126     brouard  5406: unset log y\n\
1.153     brouard  5407: plot [%.f:%.f]  ", ageminpar, agemaxpar);
1.211     brouard  5408:       k=3; /* Offset */
1.153     brouard  5409:       for (i=1; i<= nlstate ; i ++){
                   5410:        if(i==1)
1.201     brouard  5411:          fprintf(ficgp,"\"%s\"",subdirf2(fileresu,"PIJ_"));
1.153     brouard  5412:        else
                   5413:          fprintf(ficgp,", '' ");
1.154     brouard  5414:        l=(nlstate+ndeath)*(i-1)+1;
                   5415:        fprintf(ficgp," u ($1==%d ? ($3):1/0):($%d/($%d",k1,k+l+(cpt-1),k+l);
1.201     brouard  5416:        for (j=2; j<= nlstate ; j ++)
                   5417:          fprintf(ficgp,"+$%d",k+l+j-1);
1.153     brouard  5418:        fprintf(ficgp,")) t \"prev(%d,%d)\" w l",i,cpt);
                   5419:       } /* nlstate */
1.201     brouard  5420:       fprintf(ficgp,"\nset out\n");
1.153     brouard  5421:     } /* end cpt state*/ 
                   5422:   } /* end covariate */  
1.201     brouard  5423: 
1.211     brouard  5424:   if(prevfcast==1){
                   5425:   /* Projection from cross-sectional to stable (period) for each covariate */
                   5426: 
                   5427:     for (k1=1; k1<= m ; k1 ++) { /* For each covariate combination (1 to m=2**k), if any covariate is present */
                   5428:       for (cpt=1; cpt<=nlstate ; cpt ++) { /* For each life state */
                   5429:        fprintf(ficgp,"\n#\n#\n#Projection of prevalence to stable (period): 'PROJ_' files, covariatecombination#=%d state=%d",k1, cpt);
                   5430:        for (k=1; k<=cptcoveff; k++){    /* For each correspondig covariate value  */
                   5431:          lv= decodtabm(k1,k,cptcoveff); /* Should be the covariate value corresponding to k1 combination and kth covariate */
                   5432:          /* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
                   5433:          /* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
                   5434:          /* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
                   5435:          vlv= nbcode[Tvaraff[lv]][lv];
                   5436:          fprintf(ficgp," V%d=%d ",k,vlv);
                   5437:        }
                   5438:        fprintf(ficgp,"\n#\n");
                   5439:        
                   5440:        fprintf(ficgp,"# hpijx=probability over h years, hp.jx is weighted by observed prev\n ");
                   5441:        fprintf(ficgp,"\nset out \"%s_%d-%d.svg\" \n",subdirf2(optionfilefiname,"PROJ_"),cpt,k1);
                   5442:        fprintf(ficgp,"set xlabel \"Age\" \nset ylabel \"Prevalence\" \n\
                   5443: set ter svg size 640, 480\n\
                   5444: unset log y\n\
                   5445: plot [%.f:%.f]  ", ageminpar, agemaxpar);
                   5446:        for (i=1; i<= nlstate+1 ; i ++){  /* nlstate +1 p11 p21 p.1 */
                   5447:          /*#  V1  = 1  V2 =  0 yearproj age p11 p21 p.1 p12 p22 p.2 p13 p23 p.3*/
                   5448:          /*#   1    2   3    4    5      6  7   8   9   10   11 12  13   14  15 */   
                   5449:          /*# yearproj age p11 p21 p.1 p12 p22 p.2 p13 p23 p.3*/
                   5450:          /*#   1       2   3    4    5      6  7   8   9   10   11 12  13   14  15 */   
                   5451:          if(i==1){
                   5452:            fprintf(ficgp,"\"%s\"",subdirf2(fileresu,"F_"));
                   5453:          }else{
                   5454:            fprintf(ficgp,",\\\n '' ");
                   5455:          }
                   5456:          if(cptcoveff ==0){ /* No covariate */
                   5457:            fprintf(ficgp," u 2:("); /* Age is in 2 */
                   5458:            /*# yearproj age p11 p21 p31 p.1 p12 p22 p32 p.2 p13 p23 p33 p.3 p14 p24 p34 p.4*/
                   5459:            /*#   1       2   3   4   5  6    7  8   9   10  11  12  13  14  15  16  17  18 */
                   5460:            if(i==nlstate+1)
                   5461:              fprintf(ficgp," $%d/(1.-$%d)) t 'p.%d' with line ", \
                   5462:                        2+(cpt-1)*(nlstate+1)+1+(i-1),  2+1+(i-1)+(nlstate+1)*nlstate,cpt );
                   5463:            else
                   5464:              fprintf(ficgp," $%d/(1.-$%d)) t 'p%d%d' with line ", \
                   5465:                      2+(cpt-1)*(nlstate+1)+1+(i-1),  2+1+(i-1)+(nlstate+1)*nlstate,i,cpt );
                   5466:          }else{
                   5467:            fprintf(ficgp,"u 6:(("); /* Age is in 6 */
                   5468:            /*#  V1  = 1  V2 =  0 yearproj age p11 p21 p.1 p12 p22 p.2 p13 p23 p.3*/
                   5469:            /*#   1    2   3    4    5      6  7   8   9   10   11 12  13   14  15 */   
                   5470:            kl=0;
                   5471:            for (k=1; k<=cptcoveff; k++){    /* For each covariate  */
                   5472:              lv= decodtabm(k1,k,cptcoveff); /* Should be the covariate value corresponding to k1 combination and kth covariate */
                   5473:              /* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
                   5474:              /* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
                   5475:              /* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
                   5476:              vlv= nbcode[Tvaraff[lv]][lv];
                   5477:              kl++;
                   5478:              /* 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 *\/ */
                   5479:              /*6+(cpt-1)*(nlstate+1)+1+(i-1)+(nlstate+1)*nlstate; 6+(1-1)*(2+1)+1+(1-1) +(2+1)*2=13 */ 
                   5480:              /*6+1+(i-1)+(nlstate+1)*nlstate; 6+1+(1-1) +(2+1)*2=13 */ 
                   5481:              /* ''  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*/
                   5482:              if(k==cptcoveff)
                   5483:                if(i==nlstate+1)
                   5484:                  fprintf(ficgp,"$%d==%d && $%d==%d)? $%d/(1.-$%d) : 1/0) t 'p.%d' with line ",kl, k,kl+1,nbcode[Tvaraff[lv]][lv], \
                   5485:                          6+(cpt-1)*(nlstate+1)+1+(i-1),  6+1+(i-1)+(nlstate+1)*nlstate,cpt );
                   5486:                else
                   5487:                  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], \
                   5488:                          6+(cpt-1)*(nlstate+1)+1+(i-1),  6+1+(i-1)+(nlstate+1)*nlstate,i,cpt );
                   5489:              else{
                   5490:                fprintf(ficgp,"$%d==%d && $%d==%d && ",kl, k,kl+1,nbcode[Tvaraff[lv]][lv]);
                   5491:                kl++;
                   5492:              }
                   5493:            } /* end covariate */
                   5494:          } /* end if covariate */
                   5495:        } /* nlstate */
                   5496:        fprintf(ficgp,"\nset out\n");
                   5497:       } /* end cpt state*/
                   5498:     } /* end covariate */
                   5499:   } /* End if prevfcast */
                   5500: 
                   5501: 
1.126     brouard  5502:   /* proba elementaires */
1.187     brouard  5503:   fprintf(ficgp,"\n##############\n#MLE estimated parameters\n#############\n");
1.126     brouard  5504:   for(i=1,jk=1; i <=nlstate; i++){
1.187     brouard  5505:     fprintf(ficgp,"# initial state %d\n",i);
1.126     brouard  5506:     for(k=1; k <=(nlstate+ndeath); k++){
                   5507:       if (k != i) {
1.187     brouard  5508:        fprintf(ficgp,"#   current state %d\n",k);
1.126     brouard  5509:        for(j=1; j <=ncovmodel; j++){
1.187     brouard  5510:          fprintf(ficgp,"p%d=%f; ",jk,p[jk]);
1.126     brouard  5511:          jk++; 
                   5512:        }
1.187     brouard  5513:        fprintf(ficgp,"\n");
1.126     brouard  5514:       }
                   5515:     }
                   5516:    }
1.187     brouard  5517:   fprintf(ficgp,"##############\n#\n");
                   5518: 
1.145     brouard  5519:   /*goto avoid;*/
1.200     brouard  5520:   fprintf(ficgp,"\n##############\n#Graphics of probabilities or incidences\n#############\n");
1.187     brouard  5521:   fprintf(ficgp,"# logi(p12/p11)=a12+b12*age+c12age*age+d12*V1+e12*V1*age\n");
                   5522:   fprintf(ficgp,"# logi(p12/p11)=p1 +p2*age +p3*age*age+ p4*V1+ p5*V1*age\n");
                   5523:   fprintf(ficgp,"# logi(p13/p11)=a13+b13*age+c13age*age+d13*V1+e13*V1*age\n");
                   5524:   fprintf(ficgp,"# logi(p13/p11)=p6 +p7*age +p8*age*age+ p9*V1+ p10*V1*age\n");
                   5525:   fprintf(ficgp,"# p12+p13+p14+p11=1=p11(1+exp(a12+b12*age+c12age*age+d12*V1+e12*V1*age)\n");
                   5526:   fprintf(ficgp,"#                      +exp(a13+b13*age+c13age*age+d13*V1+e13*V1*age)+...)\n");
                   5527:   fprintf(ficgp,"# p11=1/(1+exp(a12+b12*age+c12age*age+d12*V1+e12*V1*age)\n");
                   5528:   fprintf(ficgp,"#                      +exp(a13+b13*age+c13age*age+d13*V1+e13*V1*age)+...)\n");
                   5529:   fprintf(ficgp,"# p12=exp(a12+b12*age+c12age*age+d12*V1+e12*V1*age)/\n");
                   5530:   fprintf(ficgp,"#     (1+exp(a12+b12*age+c12age*age+d12*V1+e12*V1*age)\n");
                   5531:   fprintf(ficgp,"#       +exp(a13+b13*age+c13age*age+d13*V1+e13*V1*age))\n");
                   5532:   fprintf(ficgp,"#       +exp(a14+b14*age+c14age*age+d14*V1+e14*V1*age)+...)\n");
                   5533:   fprintf(ficgp,"#\n");
1.201     brouard  5534:    for(ng=1; ng<=3;ng++){ /* Number of graphics: first is logit, 2nd is probabilities, third is incidences per year*/
1.187     brouard  5535:      fprintf(ficgp,"# ng=%d\n",ng);
                   5536:      fprintf(ficgp,"#   jk=1 to 2^%d=%d\n",cptcoveff,m);
1.126     brouard  5537:      for(jk=1; jk <=m; jk++) {
1.187     brouard  5538:        fprintf(ficgp,"#    jk=%d\n",jk);
1.201     brouard  5539:        fprintf(ficgp,"\nset out \"%s_%d-%d.svg\" ",subdirf2(optionfilefiname,"PE_"),jk,ng);
                   5540:        fprintf(ficgp,"\nset ter svg size 640, 480 ");
                   5541:        if (ng==1){
                   5542:         fprintf(ficgp,"\nset ylabel \"Value of the logit of the model\"\n"); /* exp(a12+b12*x) could be nice */
                   5543:         fprintf(ficgp,"\nunset log y");
                   5544:        }else if (ng==2){
                   5545:         fprintf(ficgp,"\nset ylabel \"Probability\"\n");
                   5546:         fprintf(ficgp,"\nset log y");
                   5547:        }else if (ng==3){
1.126     brouard  5548:         fprintf(ficgp,"\nset ylabel \"Quasi-incidence per year\"\n");
1.201     brouard  5549:         fprintf(ficgp,"\nset log y");
                   5550:        }else
                   5551:         fprintf(ficgp,"\nunset title ");
                   5552:        fprintf(ficgp,"\nplot  [%.f:%.f] ",ageminpar,agemaxpar);
1.126     brouard  5553:        i=1;
                   5554:        for(k2=1; k2<=nlstate; k2++) {
                   5555:         k3=i;
                   5556:         for(k=1; k<=(nlstate+ndeath); k++) {
                   5557:           if (k != k2){
1.201     brouard  5558:             switch( ng) {
                   5559:             case 1:
1.187     brouard  5560:               if(nagesqr==0)
1.201     brouard  5561:                 fprintf(ficgp," p%d+p%d*x",i,i+1);
1.187     brouard  5562:               else /* nagesqr =1 */
1.201     brouard  5563:                 fprintf(ficgp," p%d+p%d*x+p%d*x*x",i,i+1,i+1+nagesqr);
                   5564:               break;
                   5565:             case 2: /* ng=2 */
1.187     brouard  5566:               if(nagesqr==0)
                   5567:                 fprintf(ficgp," exp(p%d+p%d*x",i,i+1);
                   5568:               else /* nagesqr =1 */
1.201     brouard  5569:                   fprintf(ficgp," exp(p%d+p%d*x+p%d*x*x",i,i+1,i+1+nagesqr);
                   5570:               break;
                   5571:             case 3:
                   5572:               if(nagesqr==0)
                   5573:                 fprintf(ficgp," %f*exp(p%d+p%d*x",YEARM/stepm,i,i+1);
                   5574:               else /* nagesqr =1 */
                   5575:                 fprintf(ficgp," %f*exp(p%d+p%d*x+p%d*x*x",YEARM/stepm,i,i+1,i+1+nagesqr);
                   5576:               break;
                   5577:             }
1.141     brouard  5578:             ij=1;/* To be checked else nbcode[0][0] wrong */
1.187     brouard  5579:             for(j=3; j <=ncovmodel-nagesqr; j++) {
1.197     brouard  5580:               /* printf("Tage[%d]=%d, j=%d\n", ij, Tage[ij], j); */
                   5581:               if(ij <=cptcovage) { /* Bug valgrind */
                   5582:                 if((j-2)==Tage[ij]) { /* Bug valgrind */
1.200     brouard  5583:                   fprintf(ficgp,"+p%d*%d*x",i+j+nagesqr-1,nbcode[Tvar[j-2]][codtabm(jk,j-2)]);
                   5584:                   /* fprintf(ficgp,"+p%d*%d*x",i+j+nagesqr-1,nbcode[Tvar[j-2]][codtabm(jk,Tvar[j-2])]); */
1.197     brouard  5585:                   ij++;
                   5586:                 }
1.186     brouard  5587:               }
                   5588:               else
1.198     brouard  5589:                 fprintf(ficgp,"+p%d*%d",i+j+nagesqr-1,nbcode[Tvar[j-2]][codtabm(jk,j-2)]);
1.126     brouard  5590:             }
1.201     brouard  5591:             if(ng != 1){
                   5592:               fprintf(ficgp,")/(1");
1.126     brouard  5593:             
1.201     brouard  5594:               for(k1=1; k1 <=nlstate; k1++){ 
                   5595:                 if(nagesqr==0)
                   5596:                   fprintf(ficgp,"+exp(p%d+p%d*x",k3+(k1-1)*ncovmodel,k3+(k1-1)*ncovmodel+1);
                   5597:                 else /* nagesqr =1 */
                   5598:                   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);
                   5599:                 
                   5600:                 ij=1;
                   5601:                 for(j=3; j <=ncovmodel-nagesqr; j++){
                   5602:                   if(ij <=cptcovage) { /* Bug valgrind */
                   5603:                     if((j-2)==Tage[ij]) { /* Bug valgrind */
                   5604:                       fprintf(ficgp,"+p%d*%d*x",k3+(k1-1)*ncovmodel+1+j-2+nagesqr,nbcode[Tvar[j-2]][codtabm(jk,j-2)]);
                   5605:                       /* fprintf(ficgp,"+p%d*%d*x",k3+(k1-1)*ncovmodel+1+j-2+nagesqr,nbcode[Tvar[j-2]][codtabm(jk,Tvar[j-2])]); */
                   5606:                       ij++;
                   5607:                     }
1.197     brouard  5608:                   }
1.201     brouard  5609:                   else
                   5610:                     fprintf(ficgp,"+p%d*%d",k3+(k1-1)*ncovmodel+1+j-2+nagesqr,nbcode[Tvar[j-2]][codtabm(jk,j-2)]);
1.186     brouard  5611:                 }
1.201     brouard  5612:                 fprintf(ficgp,")");
1.126     brouard  5613:               }
                   5614:               fprintf(ficgp,")");
1.201     brouard  5615:               if(ng ==2)
                   5616:                 fprintf(ficgp," t \"p%d%d\" ", k2,k);
                   5617:               else /* ng= 3 */
                   5618:                 fprintf(ficgp," t \"i%d%d\" ", k2,k);
                   5619:             }else{ /* end ng <> 1 */
                   5620:               fprintf(ficgp," t \"logit(p%d%d)\" ", k2,k);
1.126     brouard  5621:             }
                   5622:             if ((k+k2)!= (nlstate*2+ndeath)) fprintf(ficgp,",");
                   5623:             i=i+ncovmodel;
                   5624:           }
                   5625:         } /* end k */
                   5626:        } /* end k2 */
1.201     brouard  5627:        fprintf(ficgp,"\n set out\n");
1.126     brouard  5628:      } /* end jk */
                   5629:    } /* end ng */
1.164     brouard  5630:  /* avoid: */
1.126     brouard  5631:    fflush(ficgp); 
                   5632: }  /* end gnuplot */
                   5633: 
                   5634: 
                   5635: /*************** Moving average **************/
                   5636: int movingaverage(double ***probs, double bage,double fage, double ***mobaverage, int mobilav){
                   5637: 
                   5638:   int i, cpt, cptcod;
                   5639:   int modcovmax =1;
                   5640:   int mobilavrange, mob;
                   5641:   double age;
                   5642: 
                   5643:   modcovmax=2*cptcoveff;/* Max number of modalities. We suppose 
                   5644:                           a covariate has 2 modalities */
                   5645:   if (cptcovn<1) modcovmax=1; /* At least 1 pass */
                   5646: 
                   5647:   if(mobilav==1||mobilav ==3 ||mobilav==5 ||mobilav== 7){
                   5648:     if(mobilav==1) mobilavrange=5; /* default */
                   5649:     else mobilavrange=mobilav;
                   5650:     for (age=bage; age<=fage; age++)
                   5651:       for (i=1; i<=nlstate;i++)
                   5652:        for (cptcod=1;cptcod<=modcovmax;cptcod++)
                   5653:          mobaverage[(int)age][i][cptcod]=probs[(int)age][i][cptcod];
                   5654:     /* We keep the original values on the extreme ages bage, fage and for 
                   5655:        fage+1 and bage-1 we use a 3 terms moving average; for fage+2 bage+2
                   5656:        we use a 5 terms etc. until the borders are no more concerned. 
                   5657:     */ 
                   5658:     for (mob=3;mob <=mobilavrange;mob=mob+2){
                   5659:       for (age=bage+(mob-1)/2; age<=fage-(mob-1)/2; age++){
                   5660:        for (i=1; i<=nlstate;i++){
                   5661:          for (cptcod=1;cptcod<=modcovmax;cptcod++){
                   5662:            mobaverage[(int)age][i][cptcod] =probs[(int)age][i][cptcod];
                   5663:              for (cpt=1;cpt<=(mob-1)/2;cpt++){
                   5664:                mobaverage[(int)age][i][cptcod] +=probs[(int)age-cpt][i][cptcod];
                   5665:                mobaverage[(int)age][i][cptcod] +=probs[(int)age+cpt][i][cptcod];
                   5666:              }
                   5667:            mobaverage[(int)age][i][cptcod]=mobaverage[(int)age][i][cptcod]/mob;
                   5668:          }
                   5669:        }
                   5670:       }/* end age */
                   5671:     }/* end mob */
                   5672:   }else return -1;
                   5673:   return 0;
                   5674: }/* End movingaverage */
                   5675: 
                   5676: 
                   5677: /************** Forecasting ******************/
1.169     brouard  5678: 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  5679:   /* proj1, year, month, day of starting projection 
                   5680:      agemin, agemax range of age
                   5681:      dateprev1 dateprev2 range of dates during which prevalence is computed
                   5682:      anproj2 year of en of projection (same day and month as proj1).
                   5683:   */
1.164     brouard  5684:   int yearp, stepsize, hstepm, nhstepm, j, k, cptcod, i, h, i1;
1.126     brouard  5685:   double agec; /* generic age */
                   5686:   double agelim, ppij, yp,yp1,yp2,jprojmean,mprojmean,anprojmean;
                   5687:   double *popeffectif,*popcount;
                   5688:   double ***p3mat;
                   5689:   double ***mobaverage;
                   5690:   char fileresf[FILENAMELENGTH];
                   5691: 
                   5692:   agelim=AGESUP;
1.211     brouard  5693:   /* Compute observed prevalence between dateprev1 and dateprev2 by counting the number of people
                   5694:      in each health status at the date of interview (if between dateprev1 and dateprev2).
                   5695:      We still use firstpass and lastpass as another selection.
                   5696:   */
1.214     brouard  5697:   /* freqsummary(fileres, agemin, agemax, s, agev, nlstate, imx,Tvaraff,nbcode, ncodemax,mint,anint,strstart,\ */
                   5698:   /*         firstpass, lastpass,  stepm,  weightopt, model); */
1.126     brouard  5699:   prevalence(probs, ageminpar, agemax, s, agev, nlstate, imx, Tvar, nbcode, ncodemax, mint, anint, dateprev1, dateprev2, firstpass, lastpass);
                   5700:  
1.201     brouard  5701:   strcpy(fileresf,"F_"); 
                   5702:   strcat(fileresf,fileresu);
1.126     brouard  5703:   if((ficresf=fopen(fileresf,"w"))==NULL) {
                   5704:     printf("Problem with forecast resultfile: %s\n", fileresf);
                   5705:     fprintf(ficlog,"Problem with forecast resultfile: %s\n", fileresf);
                   5706:   }
1.215   ! brouard  5707:   printf("Computing forecasting: result on file '%s', please wait... \n", fileresf);
        !          5708:   fprintf(ficlog,"Computing forecasting: result on file '%s', please wait... \n", fileresf);
1.126     brouard  5709: 
                   5710:   if (cptcoveff==0) ncodemax[cptcoveff]=1;
                   5711: 
                   5712:   if (mobilav!=0) {
                   5713:     mobaverage= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
                   5714:     if (movingaverage(probs, ageminpar, fage, mobaverage,mobilav)!=0){
                   5715:       fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav);
                   5716:       printf(" Error in movingaverage mobilav=%d\n",mobilav);
                   5717:     }
                   5718:   }
                   5719: 
                   5720:   stepsize=(int) (stepm+YEARM-1)/YEARM;
                   5721:   if (stepm<=12) stepsize=1;
                   5722:   if(estepm < stepm){
                   5723:     printf ("Problem %d lower than %d\n",estepm, stepm);
                   5724:   }
                   5725:   else  hstepm=estepm;   
                   5726: 
                   5727:   hstepm=hstepm/stepm; 
                   5728:   yp1=modf(dateintmean,&yp);/* extracts integral of datemean in yp  and
                   5729:                                fractional in yp1 */
                   5730:   anprojmean=yp;
                   5731:   yp2=modf((yp1*12),&yp);
                   5732:   mprojmean=yp;
                   5733:   yp1=modf((yp2*30.5),&yp);
                   5734:   jprojmean=yp;
                   5735:   if(jprojmean==0) jprojmean=1;
                   5736:   if(mprojmean==0) jprojmean=1;
                   5737: 
                   5738:   i1=cptcoveff;
                   5739:   if (cptcovn < 1){i1=1;}
                   5740:   
                   5741:   fprintf(ficresf,"# Mean day of interviews %.lf/%.lf/%.lf (%.2f) between %.2f and %.2f \n",jprojmean,mprojmean,anprojmean,dateintmean,dateprev1,dateprev2); 
                   5742:   
                   5743:   fprintf(ficresf,"#****** Routine prevforecast **\n");
                   5744: 
                   5745: /*           if (h==(int)(YEARM*yearp)){ */
                   5746:   for(cptcov=1, k=0;cptcov<=i1;cptcov++){
                   5747:     for(cptcod=1;cptcod<=ncodemax[cptcoveff];cptcod++){
                   5748:       k=k+1;
1.211     brouard  5749:       fprintf(ficresf,"\n#****** hpijx=probability over h years, hp.jx is weighted by observed prev \n#");
1.126     brouard  5750:       for(j=1;j<=cptcoveff;j++) {
1.211     brouard  5751:        fprintf(ficresf," V%d (=) %d",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
1.126     brouard  5752:       }
1.211     brouard  5753:       fprintf(ficresf," yearproj age");
1.126     brouard  5754:       for(j=1; j<=nlstate+ndeath;j++){ 
                   5755:        for(i=1; i<=nlstate;i++)              
                   5756:           fprintf(ficresf," p%d%d",i,j);
                   5757:        fprintf(ficresf," p.%d",j);
                   5758:       }
                   5759:       for (yearp=0; yearp<=(anproj2-anproj1);yearp +=stepsize) { 
                   5760:        fprintf(ficresf,"\n");
                   5761:        fprintf(ficresf,"\n# Forecasting at date %.lf/%.lf/%.lf ",jproj1,mproj1,anproj1+yearp);   
                   5762: 
                   5763:        for (agec=fage; agec>=(ageminpar-1); agec--){ 
                   5764:          nhstepm=(int) rint((agelim-agec)*YEARM/stepm); 
                   5765:          nhstepm = nhstepm/hstepm; 
                   5766:          p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   5767:          oldm=oldms;savm=savms;
                   5768:          hpxij(p3mat,nhstepm,agec,hstepm,p,nlstate,stepm,oldm,savm, k);  
                   5769:        
                   5770:          for (h=0; h<=nhstepm; h++){
                   5771:            if (h*hstepm/YEARM*stepm ==yearp) {
                   5772:               fprintf(ficresf,"\n");
                   5773:               for(j=1;j<=cptcoveff;j++) 
1.198     brouard  5774:                 fprintf(ficresf,"%d %d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
1.126     brouard  5775:              fprintf(ficresf,"%.f %.f ",anproj1+yearp,agec+h*hstepm/YEARM*stepm);
                   5776:            } 
                   5777:            for(j=1; j<=nlstate+ndeath;j++) {
                   5778:              ppij=0.;
                   5779:              for(i=1; i<=nlstate;i++) {
                   5780:                if (mobilav==1) 
                   5781:                  ppij=ppij+p3mat[i][j][h]*mobaverage[(int)agec][i][cptcod];
                   5782:                else {
                   5783:                  ppij=ppij+p3mat[i][j][h]*probs[(int)(agec)][i][cptcod];
                   5784:                }
                   5785:                if (h*hstepm/YEARM*stepm== yearp) {
                   5786:                  fprintf(ficresf," %.3f", p3mat[i][j][h]);
                   5787:                }
                   5788:              } /* end i */
                   5789:              if (h*hstepm/YEARM*stepm==yearp) {
                   5790:                fprintf(ficresf," %.3f", ppij);
                   5791:              }
                   5792:            }/* end j */
                   5793:          } /* end h */
                   5794:          free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   5795:        } /* end agec */
                   5796:       } /* end yearp */
                   5797:     } /* end cptcod */
                   5798:   } /* end  cptcov */
                   5799:        
                   5800:   if (mobilav!=0) free_ma3x(mobaverage,1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
                   5801: 
                   5802:   fclose(ficresf);
1.215   ! brouard  5803:   printf("End of Computing forecasting \n");
        !          5804:   fprintf(ficlog,"End of Computing forecasting\n");
        !          5805: 
1.126     brouard  5806: }
                   5807: 
                   5808: /************** Forecasting *****not tested NB*************/
1.169     brouard  5809: 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  5810:   
                   5811:   int cpt, stepsize, hstepm, nhstepm, j,k,c, cptcod, i,h;
                   5812:   int *popage;
                   5813:   double calagedatem, agelim, kk1, kk2;
                   5814:   double *popeffectif,*popcount;
                   5815:   double ***p3mat,***tabpop,***tabpopprev;
                   5816:   double ***mobaverage;
                   5817:   char filerespop[FILENAMELENGTH];
                   5818: 
                   5819:   tabpop= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
                   5820:   tabpopprev= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
                   5821:   agelim=AGESUP;
                   5822:   calagedatem=(anpyram+mpyram/12.+jpyram/365.-dateintmean)*YEARM;
                   5823:   
                   5824:   prevalence(probs, ageminpar, agemax, s, agev, nlstate, imx, Tvar, nbcode, ncodemax, mint, anint, dateprev1, dateprev2, firstpass, lastpass);
                   5825:   
                   5826:   
1.201     brouard  5827:   strcpy(filerespop,"POP_"); 
                   5828:   strcat(filerespop,fileresu);
1.126     brouard  5829:   if((ficrespop=fopen(filerespop,"w"))==NULL) {
                   5830:     printf("Problem with forecast resultfile: %s\n", filerespop);
                   5831:     fprintf(ficlog,"Problem with forecast resultfile: %s\n", filerespop);
                   5832:   }
                   5833:   printf("Computing forecasting: result on file '%s' \n", filerespop);
                   5834:   fprintf(ficlog,"Computing forecasting: result on file '%s' \n", filerespop);
                   5835: 
                   5836:   if (cptcoveff==0) ncodemax[cptcoveff]=1;
                   5837: 
                   5838:   if (mobilav!=0) {
                   5839:     mobaverage= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
                   5840:     if (movingaverage(probs, ageminpar, fage, mobaverage,mobilav)!=0){
                   5841:       fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav);
                   5842:       printf(" Error in movingaverage mobilav=%d\n",mobilav);
                   5843:     }
                   5844:   }
                   5845: 
                   5846:   stepsize=(int) (stepm+YEARM-1)/YEARM;
                   5847:   if (stepm<=12) stepsize=1;
                   5848:   
                   5849:   agelim=AGESUP;
                   5850:   
                   5851:   hstepm=1;
                   5852:   hstepm=hstepm/stepm; 
                   5853:   
                   5854:   if (popforecast==1) {
                   5855:     if((ficpop=fopen(popfile,"r"))==NULL) {
                   5856:       printf("Problem with population file : %s\n",popfile);exit(0);
                   5857:       fprintf(ficlog,"Problem with population file : %s\n",popfile);exit(0);
                   5858:     } 
                   5859:     popage=ivector(0,AGESUP);
                   5860:     popeffectif=vector(0,AGESUP);
                   5861:     popcount=vector(0,AGESUP);
                   5862:     
                   5863:     i=1;   
                   5864:     while ((c=fscanf(ficpop,"%d %lf\n",&popage[i],&popcount[i])) != EOF) i=i+1;
                   5865:    
                   5866:     imx=i;
                   5867:     for (i=1; i<imx;i++) popeffectif[popage[i]]=popcount[i];
                   5868:   }
                   5869: 
                   5870:   for(cptcov=1,k=0;cptcov<=i2;cptcov++){
                   5871:    for(cptcod=1;cptcod<=ncodemax[cptcoveff];cptcod++){
                   5872:       k=k+1;
                   5873:       fprintf(ficrespop,"\n#******");
                   5874:       for(j=1;j<=cptcoveff;j++) {
1.198     brouard  5875:        fprintf(ficrespop," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
1.126     brouard  5876:       }
                   5877:       fprintf(ficrespop,"******\n");
                   5878:       fprintf(ficrespop,"# Age");
                   5879:       for(j=1; j<=nlstate+ndeath;j++) fprintf(ficrespop," P.%d",j);
                   5880:       if (popforecast==1)  fprintf(ficrespop," [Population]");
                   5881:       
                   5882:       for (cpt=0; cpt<=0;cpt++) { 
                   5883:        fprintf(ficrespop,"\n\n# Forecasting at date %.lf/%.lf/%.lf ",jpyram,mpyram,anpyram+cpt);   
                   5884:        
                   5885:        for (agedeb=(fage-((int)calagedatem %12/12.)); agedeb>=(ageminpar-((int)calagedatem %12)/12.); agedeb--){ 
                   5886:          nhstepm=(int) rint((agelim-agedeb)*YEARM/stepm); 
                   5887:          nhstepm = nhstepm/hstepm; 
                   5888:          
                   5889:          p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   5890:          oldm=oldms;savm=savms;
                   5891:          hpxij(p3mat,nhstepm,agedeb,hstepm,p,nlstate,stepm,oldm,savm, k);  
                   5892:        
                   5893:          for (h=0; h<=nhstepm; h++){
                   5894:            if (h==(int) (calagedatem+YEARM*cpt)) {
                   5895:              fprintf(ficrespop,"\n %3.f ",agedeb+h*hstepm/YEARM*stepm);
                   5896:            } 
                   5897:            for(j=1; j<=nlstate+ndeath;j++) {
                   5898:              kk1=0.;kk2=0;
                   5899:              for(i=1; i<=nlstate;i++) {              
                   5900:                if (mobilav==1) 
                   5901:                  kk1=kk1+p3mat[i][j][h]*mobaverage[(int)agedeb+1][i][cptcod];
                   5902:                else {
                   5903:                  kk1=kk1+p3mat[i][j][h]*probs[(int)(agedeb+1)][i][cptcod];
                   5904:                }
                   5905:              }
                   5906:              if (h==(int)(calagedatem+12*cpt)){
                   5907:                tabpop[(int)(agedeb)][j][cptcod]=kk1;
                   5908:                  /*fprintf(ficrespop," %.3f", kk1);
                   5909:                    if (popforecast==1) fprintf(ficrespop," [%.f]", kk1*popeffectif[(int)agedeb+1]);*/
                   5910:              }
                   5911:            }
                   5912:            for(i=1; i<=nlstate;i++){
                   5913:              kk1=0.;
                   5914:                for(j=1; j<=nlstate;j++){
                   5915:                  kk1= kk1+tabpop[(int)(agedeb)][j][cptcod]; 
                   5916:                }
                   5917:                  tabpopprev[(int)(agedeb)][i][cptcod]=tabpop[(int)(agedeb)][i][cptcod]/kk1*popeffectif[(int)(agedeb+(calagedatem+12*cpt)*hstepm/YEARM*stepm-1)];
                   5918:            }
                   5919: 
                   5920:            if (h==(int)(calagedatem+12*cpt)) for(j=1; j<=nlstate;j++) 
                   5921:              fprintf(ficrespop," %15.2f",tabpopprev[(int)(agedeb+1)][j][cptcod]);
                   5922:          }
                   5923:          free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   5924:        }
                   5925:       }
                   5926:  
                   5927:   /******/
                   5928: 
                   5929:       for (cpt=1; cpt<=(anpyram1-anpyram);cpt++) { 
                   5930:        fprintf(ficrespop,"\n\n# Forecasting at date %.lf/%.lf/%.lf ",jpyram,mpyram,anpyram+cpt);   
                   5931:        for (agedeb=(fage-((int)calagedatem %12/12.)); agedeb>=(ageminpar-((int)calagedatem %12)/12.); agedeb--){ 
                   5932:          nhstepm=(int) rint((agelim-agedeb)*YEARM/stepm); 
                   5933:          nhstepm = nhstepm/hstepm; 
                   5934:          
                   5935:          p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   5936:          oldm=oldms;savm=savms;
                   5937:          hpxij(p3mat,nhstepm,agedeb,hstepm,p,nlstate,stepm,oldm,savm, k);  
                   5938:          for (h=0; h<=nhstepm; h++){
                   5939:            if (h==(int) (calagedatem+YEARM*cpt)) {
                   5940:              fprintf(ficresf,"\n %3.f ",agedeb+h*hstepm/YEARM*stepm);
                   5941:            } 
                   5942:            for(j=1; j<=nlstate+ndeath;j++) {
                   5943:              kk1=0.;kk2=0;
                   5944:              for(i=1; i<=nlstate;i++) {              
                   5945:                kk1=kk1+p3mat[i][j][h]*tabpopprev[(int)agedeb+1][i][cptcod];    
                   5946:              }
                   5947:              if (h==(int)(calagedatem+12*cpt)) fprintf(ficresf," %15.2f", kk1);        
                   5948:            }
                   5949:          }
                   5950:          free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   5951:        }
                   5952:       }
                   5953:    } 
                   5954:   }
                   5955:  
                   5956:   if (mobilav!=0) free_ma3x(mobaverage,1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
                   5957: 
                   5958:   if (popforecast==1) {
                   5959:     free_ivector(popage,0,AGESUP);
                   5960:     free_vector(popeffectif,0,AGESUP);
                   5961:     free_vector(popcount,0,AGESUP);
                   5962:   }
                   5963:   free_ma3x(tabpop,1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
                   5964:   free_ma3x(tabpopprev,1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
                   5965:   fclose(ficrespop);
                   5966: } /* End of popforecast */
                   5967: 
                   5968: int fileappend(FILE *fichier, char *optionfich)
                   5969: {
                   5970:   if((fichier=fopen(optionfich,"a"))==NULL) {
                   5971:     printf("Problem with file: %s\n", optionfich);
                   5972:     fprintf(ficlog,"Problem with file: %s\n", optionfich);
                   5973:     return (0);
                   5974:   }
                   5975:   fflush(fichier);
                   5976:   return (1);
                   5977: }
                   5978: 
                   5979: 
                   5980: /**************** function prwizard **********************/
                   5981: void prwizard(int ncovmodel, int nlstate, int ndeath,  char model[], FILE *ficparo)
                   5982: {
                   5983: 
                   5984:   /* Wizard to print covariance matrix template */
                   5985: 
1.164     brouard  5986:   char ca[32], cb[32];
                   5987:   int i,j, k, li, lj, lk, ll, jj, npar, itimes;
1.126     brouard  5988:   int numlinepar;
                   5989: 
                   5990:   printf("# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
                   5991:   fprintf(ficparo,"# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
                   5992:   for(i=1; i <=nlstate; i++){
                   5993:     jj=0;
                   5994:     for(j=1; j <=nlstate+ndeath; j++){
                   5995:       if(j==i) continue;
                   5996:       jj++;
                   5997:       /*ca[0]= k+'a'-1;ca[1]='\0';*/
                   5998:       printf("%1d%1d",i,j);
                   5999:       fprintf(ficparo,"%1d%1d",i,j);
                   6000:       for(k=1; k<=ncovmodel;k++){
                   6001:        /*        printf(" %lf",param[i][j][k]); */
                   6002:        /*        fprintf(ficparo," %lf",param[i][j][k]); */
                   6003:        printf(" 0.");
                   6004:        fprintf(ficparo," 0.");
                   6005:       }
                   6006:       printf("\n");
                   6007:       fprintf(ficparo,"\n");
                   6008:     }
                   6009:   }
                   6010:   printf("# Scales (for hessian or gradient estimation)\n");
                   6011:   fprintf(ficparo,"# Scales (for hessian or gradient estimation)\n");
                   6012:   npar= (nlstate+ndeath-1)*nlstate*ncovmodel; /* Number of parameters*/ 
                   6013:   for(i=1; i <=nlstate; i++){
                   6014:     jj=0;
                   6015:     for(j=1; j <=nlstate+ndeath; j++){
                   6016:       if(j==i) continue;
                   6017:       jj++;
                   6018:       fprintf(ficparo,"%1d%1d",i,j);
                   6019:       printf("%1d%1d",i,j);
                   6020:       fflush(stdout);
                   6021:       for(k=1; k<=ncovmodel;k++){
                   6022:        /*      printf(" %le",delti3[i][j][k]); */
                   6023:        /*      fprintf(ficparo," %le",delti3[i][j][k]); */
                   6024:        printf(" 0.");
                   6025:        fprintf(ficparo," 0.");
                   6026:       }
                   6027:       numlinepar++;
                   6028:       printf("\n");
                   6029:       fprintf(ficparo,"\n");
                   6030:     }
                   6031:   }
                   6032:   printf("# Covariance matrix\n");
                   6033: /* # 121 Var(a12)\n\ */
                   6034: /* # 122 Cov(b12,a12) Var(b12)\n\ */
                   6035: /* # 131 Cov(a13,a12) Cov(a13,b12, Var(a13)\n\ */
                   6036: /* # 132 Cov(b13,a12) Cov(b13,b12, Cov(b13,a13) Var(b13)\n\ */
                   6037: /* # 212 Cov(a21,a12) Cov(a21,b12, Cov(a21,a13) Cov(a21,b13) Var(a21)\n\ */
                   6038: /* # 212 Cov(b21,a12) Cov(b21,b12, Cov(b21,a13) Cov(b21,b13) Cov(b21,a21) Var(b21)\n\ */
                   6039: /* # 232 Cov(a23,a12) Cov(a23,b12, Cov(a23,a13) Cov(a23,b13) Cov(a23,a21) Cov(a23,b21) Var(a23)\n\ */
                   6040: /* # 232 Cov(b23,a12) Cov(b23,b12) ... Var (b23)\n" */
                   6041:   fflush(stdout);
                   6042:   fprintf(ficparo,"# Covariance matrix\n");
                   6043:   /* # 121 Var(a12)\n\ */
                   6044:   /* # 122 Cov(b12,a12) Var(b12)\n\ */
                   6045:   /* #   ...\n\ */
                   6046:   /* # 232 Cov(b23,a12)  Cov(b23,b12) ... Var (b23)\n" */
                   6047:   
                   6048:   for(itimes=1;itimes<=2;itimes++){
                   6049:     jj=0;
                   6050:     for(i=1; i <=nlstate; i++){
                   6051:       for(j=1; j <=nlstate+ndeath; j++){
                   6052:        if(j==i) continue;
                   6053:        for(k=1; k<=ncovmodel;k++){
                   6054:          jj++;
                   6055:          ca[0]= k+'a'-1;ca[1]='\0';
                   6056:          if(itimes==1){
                   6057:            printf("#%1d%1d%d",i,j,k);
                   6058:            fprintf(ficparo,"#%1d%1d%d",i,j,k);
                   6059:          }else{
                   6060:            printf("%1d%1d%d",i,j,k);
                   6061:            fprintf(ficparo,"%1d%1d%d",i,j,k);
                   6062:            /*  printf(" %.5le",matcov[i][j]); */
                   6063:          }
                   6064:          ll=0;
                   6065:          for(li=1;li <=nlstate; li++){
                   6066:            for(lj=1;lj <=nlstate+ndeath; lj++){
                   6067:              if(lj==li) continue;
                   6068:              for(lk=1;lk<=ncovmodel;lk++){
                   6069:                ll++;
                   6070:                if(ll<=jj){
                   6071:                  cb[0]= lk +'a'-1;cb[1]='\0';
                   6072:                  if(ll<jj){
                   6073:                    if(itimes==1){
                   6074:                      printf(" Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
                   6075:                      fprintf(ficparo," Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
                   6076:                    }else{
                   6077:                      printf(" 0.");
                   6078:                      fprintf(ficparo," 0.");
                   6079:                    }
                   6080:                  }else{
                   6081:                    if(itimes==1){
                   6082:                      printf(" Var(%s%1d%1d)",ca,i,j);
                   6083:                      fprintf(ficparo," Var(%s%1d%1d)",ca,i,j);
                   6084:                    }else{
                   6085:                      printf(" 0.");
                   6086:                      fprintf(ficparo," 0.");
                   6087:                    }
                   6088:                  }
                   6089:                }
                   6090:              } /* end lk */
                   6091:            } /* end lj */
                   6092:          } /* end li */
                   6093:          printf("\n");
                   6094:          fprintf(ficparo,"\n");
                   6095:          numlinepar++;
                   6096:        } /* end k*/
                   6097:       } /*end j */
                   6098:     } /* end i */
                   6099:   } /* end itimes */
                   6100: 
                   6101: } /* end of prwizard */
                   6102: /******************* Gompertz Likelihood ******************************/
                   6103: double gompertz(double x[])
                   6104: { 
                   6105:   double A,B,L=0.0,sump=0.,num=0.;
                   6106:   int i,n=0; /* n is the size of the sample */
                   6107: 
                   6108:   for (i=0;i<=imx-1 ; i++) {
                   6109:     sump=sump+weight[i];
                   6110:     /*    sump=sump+1;*/
                   6111:     num=num+1;
                   6112:   }
                   6113:  
                   6114:  
                   6115:   /* for (i=0; i<=imx; i++) 
                   6116:      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]);*/
                   6117: 
                   6118:   for (i=1;i<=imx ; i++)
                   6119:     {
                   6120:       if (cens[i] == 1 && wav[i]>1)
                   6121:        A=-x[1]/(x[2])*(exp(x[2]*(agecens[i]-agegomp))-exp(x[2]*(ageexmed[i]-agegomp)));
                   6122:       
                   6123:       if (cens[i] == 0 && wav[i]>1)
                   6124:        A=-x[1]/(x[2])*(exp(x[2]*(agedc[i]-agegomp))-exp(x[2]*(ageexmed[i]-agegomp)))
                   6125:             +log(x[1]/YEARM)+x[2]*(agedc[i]-agegomp)+log(YEARM);  
                   6126:       
                   6127:       /*if (wav[i] > 1 && agecens[i] > 15) {*/ /* ??? */
                   6128:       if (wav[i] > 1 ) { /* ??? */
                   6129:        L=L+A*weight[i];
                   6130:        /*      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]);*/
                   6131:       }
                   6132:     }
                   6133: 
                   6134:  /*printf("x1=%2.9f x2=%2.9f x3=%2.9f L=%f\n",x[1],x[2],x[3],L);*/
                   6135:  
                   6136:   return -2*L*num/sump;
                   6137: }
                   6138: 
1.136     brouard  6139: #ifdef GSL
                   6140: /******************* Gompertz_f Likelihood ******************************/
                   6141: double gompertz_f(const gsl_vector *v, void *params)
                   6142: { 
                   6143:   double A,B,LL=0.0,sump=0.,num=0.;
                   6144:   double *x= (double *) v->data;
                   6145:   int i,n=0; /* n is the size of the sample */
                   6146: 
                   6147:   for (i=0;i<=imx-1 ; i++) {
                   6148:     sump=sump+weight[i];
                   6149:     /*    sump=sump+1;*/
                   6150:     num=num+1;
                   6151:   }
                   6152:  
                   6153:  
                   6154:   /* for (i=0; i<=imx; i++) 
                   6155:      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]);*/
                   6156:   printf("x[0]=%lf x[1]=%lf\n",x[0],x[1]);
                   6157:   for (i=1;i<=imx ; i++)
                   6158:     {
                   6159:       if (cens[i] == 1 && wav[i]>1)
                   6160:        A=-x[0]/(x[1])*(exp(x[1]*(agecens[i]-agegomp))-exp(x[1]*(ageexmed[i]-agegomp)));
                   6161:       
                   6162:       if (cens[i] == 0 && wav[i]>1)
                   6163:        A=-x[0]/(x[1])*(exp(x[1]*(agedc[i]-agegomp))-exp(x[1]*(ageexmed[i]-agegomp)))
                   6164:             +log(x[0]/YEARM)+x[1]*(agedc[i]-agegomp)+log(YEARM);  
                   6165:       
                   6166:       /*if (wav[i] > 1 && agecens[i] > 15) {*/ /* ??? */
                   6167:       if (wav[i] > 1 ) { /* ??? */
                   6168:        LL=LL+A*weight[i];
                   6169:        /*      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]);*/
                   6170:       }
                   6171:     }
                   6172: 
                   6173:  /*printf("x1=%2.9f x2=%2.9f x3=%2.9f L=%f\n",x[1],x[2],x[3],L);*/
                   6174:   printf("x[0]=%lf x[1]=%lf -2*LL*num/sump=%lf\n",x[0],x[1],-2*LL*num/sump);
                   6175:  
                   6176:   return -2*LL*num/sump;
                   6177: }
                   6178: #endif
                   6179: 
1.126     brouard  6180: /******************* Printing html file ***********/
1.201     brouard  6181: void printinghtmlmort(char fileresu[], char title[], char datafile[], int firstpass, \
1.126     brouard  6182:                  int lastpass, int stepm, int weightopt, char model[],\
                   6183:                  int imx,  double p[],double **matcov,double agemortsup){
                   6184:   int i,k;
                   6185: 
                   6186:   fprintf(fichtm,"<ul><li><h4>Result files </h4>\n Force of mortality. Parameters of the Gompertz fit (with confidence interval in brackets):<br>");
                   6187:   fprintf(fichtm,"  mu(age) =%lf*exp(%lf*(age-%d)) per year<br><br>",p[1],p[2],agegomp);
                   6188:   for (i=1;i<=2;i++) 
                   6189:     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  6190:   fprintf(fichtm,"<br><br><img src=\"graphmort.svg\">");
1.126     brouard  6191:   fprintf(fichtm,"</ul>");
                   6192: 
                   6193: fprintf(fichtm,"<ul><li><h4>Life table</h4>\n <br>");
                   6194: 
                   6195:  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>");
                   6196: 
                   6197:  for (k=agegomp;k<(agemortsup-2);k++) 
                   6198:    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]);
                   6199: 
                   6200:  
                   6201:   fflush(fichtm);
                   6202: }
                   6203: 
                   6204: /******************* Gnuplot file **************/
1.201     brouard  6205: void printinggnuplotmort(char fileresu[], char optionfilefiname[], double ageminpar, double agemaxpar, double fage , char pathc[], double p[]){
1.126     brouard  6206: 
                   6207:   char dirfileres[132],optfileres[132];
1.164     brouard  6208: 
1.126     brouard  6209:   int ng;
                   6210: 
                   6211: 
                   6212:   /*#ifdef windows */
                   6213:   fprintf(ficgp,"cd \"%s\" \n",pathc);
                   6214:     /*#endif */
                   6215: 
                   6216: 
                   6217:   strcpy(dirfileres,optionfilefiname);
                   6218:   strcpy(optfileres,"vpl");
1.199     brouard  6219:   fprintf(ficgp,"set out \"graphmort.svg\"\n "); 
1.126     brouard  6220:   fprintf(ficgp,"set xlabel \"Age\"\n set ylabel \"Force of mortality (per year)\" \n "); 
1.199     brouard  6221:   fprintf(ficgp, "set ter svg size 640, 480\n set log y\n"); 
1.145     brouard  6222:   /* fprintf(ficgp, "set size 0.65,0.65\n"); */
1.126     brouard  6223:   fprintf(ficgp,"plot [%d:100] %lf*exp(%lf*(x-%d))",agegomp,p[1],p[2],agegomp);
                   6224: 
                   6225: } 
                   6226: 
1.136     brouard  6227: int readdata(char datafile[], int firstobs, int lastobs, int *imax)
                   6228: {
1.126     brouard  6229: 
1.136     brouard  6230:   /*-------- data file ----------*/
                   6231:   FILE *fic;
                   6232:   char dummy[]="                         ";
1.164     brouard  6233:   int i=0, j=0, n=0;
1.136     brouard  6234:   int linei, month, year,iout;
                   6235:   char line[MAXLINE], linetmp[MAXLINE];
1.164     brouard  6236:   char stra[MAXLINE], strb[MAXLINE];
1.136     brouard  6237:   char *stratrunc;
                   6238:   int lstra;
1.126     brouard  6239: 
                   6240: 
1.136     brouard  6241:   if((fic=fopen(datafile,"r"))==NULL)    {
1.195     brouard  6242:     printf("Problem while opening datafile: %s\n", datafile);fflush(stdout);
                   6243:     fprintf(ficlog,"Problem while opening datafile: %s\n", datafile);fflush(ficlog);return 1;
1.136     brouard  6244:   }
1.126     brouard  6245: 
1.136     brouard  6246:   i=1;
                   6247:   linei=0;
                   6248:   while ((fgets(line, MAXLINE, fic) != NULL) &&((i >= firstobs) && (i <=lastobs))) {
                   6249:     linei=linei+1;
                   6250:     for(j=strlen(line); j>=0;j--){  /* Untabifies line */
                   6251:       if(line[j] == '\t')
                   6252:        line[j] = ' ';
                   6253:     }
                   6254:     for(j=strlen(line)-1; (line[j]==' ')||(line[j]==10)||(line[j]==13);j--){
                   6255:       ;
                   6256:     };
                   6257:     line[j+1]=0;  /* Trims blanks at end of line */
                   6258:     if(line[0]=='#'){
                   6259:       fprintf(ficlog,"Comment line\n%s\n",line);
                   6260:       printf("Comment line\n%s\n",line);
                   6261:       continue;
                   6262:     }
                   6263:     trimbb(linetmp,line); /* Trims multiple blanks in line */
1.164     brouard  6264:     strcpy(line, linetmp);
1.136     brouard  6265:   
1.126     brouard  6266: 
1.136     brouard  6267:     for (j=maxwav;j>=1;j--){
1.137     brouard  6268:       cutv(stra, strb, line, ' '); 
1.136     brouard  6269:       if(strb[0]=='.') { /* Missing status */
                   6270:        lval=-1;
                   6271:       }else{
                   6272:        errno=0;
                   6273:        lval=strtol(strb,&endptr,10); 
                   6274:       /*       if (errno == ERANGE && (lval == LONG_MAX || lval == LONG_MIN))*/
                   6275:        if( strb[0]=='\0' || (*endptr != '\0')){
1.141     brouard  6276:          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);
                   6277:          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  6278:          return 1;
                   6279:        }
                   6280:       }
                   6281:       s[j][i]=lval;
                   6282:       
                   6283:       strcpy(line,stra);
                   6284:       cutv(stra, strb,line,' ');
1.169     brouard  6285:       if( (iout=sscanf(strb,"%d/%d",&month, &year)) != 0){
1.136     brouard  6286:       }
1.169     brouard  6287:       else  if( (iout=sscanf(strb,"%s.",dummy)) != 0){
1.136     brouard  6288:        month=99;
                   6289:        year=9999;
                   6290:       }else{
1.141     brouard  6291:        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);
                   6292:        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  6293:        return 1;
                   6294:       }
                   6295:       anint[j][i]= (double) year; 
                   6296:       mint[j][i]= (double)month; 
                   6297:       strcpy(line,stra);
                   6298:     } /* ENd Waves */
                   6299:     
                   6300:     cutv(stra, strb,line,' '); 
1.169     brouard  6301:     if( (iout=sscanf(strb,"%d/%d",&month, &year)) != 0){
1.136     brouard  6302:     }
1.169     brouard  6303:     else  if( (iout=sscanf(strb,"%s.",dummy)) != 0){
1.136     brouard  6304:       month=99;
                   6305:       year=9999;
                   6306:     }else{
1.141     brouard  6307:       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);
                   6308:        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  6309:        return 1;
                   6310:     }
                   6311:     andc[i]=(double) year; 
                   6312:     moisdc[i]=(double) month; 
                   6313:     strcpy(line,stra);
                   6314:     
                   6315:     cutv(stra, strb,line,' '); 
1.169     brouard  6316:     if( (iout=sscanf(strb,"%d/%d",&month, &year)) != 0){
1.136     brouard  6317:     }
1.169     brouard  6318:     else  if( (iout=sscanf(strb,"%s.", dummy)) != 0){
1.136     brouard  6319:       month=99;
                   6320:       year=9999;
                   6321:     }else{
1.141     brouard  6322:       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);
                   6323:       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  6324:        return 1;
                   6325:     }
                   6326:     if (year==9999) {
1.141     brouard  6327:       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);
                   6328:       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  6329:        return 1;
1.126     brouard  6330: 
1.136     brouard  6331:     }
                   6332:     annais[i]=(double)(year);
                   6333:     moisnais[i]=(double)(month); 
                   6334:     strcpy(line,stra);
                   6335:     
                   6336:     cutv(stra, strb,line,' '); 
                   6337:     errno=0;
                   6338:     dval=strtod(strb,&endptr); 
                   6339:     if( strb[0]=='\0' || (*endptr != '\0')){
1.141     brouard  6340:       printf("Error reading data around '%f' at line number %d, \"%s\" for individual %d\nShould be a weight.  Exiting.\n",dval, i,line,linei);
                   6341:       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  6342:       fflush(ficlog);
                   6343:       return 1;
                   6344:     }
                   6345:     weight[i]=dval; 
                   6346:     strcpy(line,stra);
                   6347:     
                   6348:     for (j=ncovcol;j>=1;j--){
                   6349:       cutv(stra, strb,line,' '); 
                   6350:       if(strb[0]=='.') { /* Missing status */
                   6351:        lval=-1;
                   6352:       }else{
                   6353:        errno=0;
                   6354:        lval=strtol(strb,&endptr,10); 
                   6355:        if( strb[0]=='\0' || (*endptr != '\0')){
1.141     brouard  6356:          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);
                   6357:          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  6358:          return 1;
                   6359:        }
                   6360:       }
                   6361:       if(lval <-1 || lval >1){
1.141     brouard  6362:        printf("Error reading data around '%ld' at line number %d for individual %d, '%s'\n \
1.136     brouard  6363:  Should be a value of %d(nth) covariate (0 should be the value for the reference and 1\n \
                   6364:  for the alternative. IMaCh does not build design variables automatically, do it yourself.\n \
                   6365:  For example, for multinomial values like 1, 2 and 3,\n \
                   6366:  build V1=0 V2=0 for the reference value (1),\n \
                   6367:         V1=1 V2=0 for (2) \n \
                   6368:  and V1=0 V2=1 for (3). V1=1 V2=1 should not exist and the corresponding\n \
                   6369:  output of IMaCh is often meaningless.\n \
                   6370:  Exiting.\n",lval,linei, i,line,j);
1.141     brouard  6371:        fprintf(ficlog,"Error reading data around '%ld' at line number %d for individual %d, '%s'\n \
1.136     brouard  6372:  Should be a value of %d(nth) covariate (0 should be the value for the reference and 1\n \
                   6373:  for the alternative. IMaCh does not build design variables automatically, do it yourself.\n \
                   6374:  For example, for multinomial values like 1, 2 and 3,\n \
                   6375:  build V1=0 V2=0 for the reference value (1),\n \
                   6376:         V1=1 V2=0 for (2) \n \
                   6377:  and V1=0 V2=1 for (3). V1=1 V2=1 should not exist and the corresponding\n \
                   6378:  output of IMaCh is often meaningless.\n \
                   6379:  Exiting.\n",lval,linei, i,line,j);fflush(ficlog);
                   6380:        return 1;
                   6381:       }
                   6382:       covar[j][i]=(double)(lval);
                   6383:       strcpy(line,stra);
                   6384:     }  
                   6385:     lstra=strlen(stra);
                   6386:      
                   6387:     if(lstra > 9){ /* More than 2**32 or max of what printf can write with %ld */
                   6388:       stratrunc = &(stra[lstra-9]);
                   6389:       num[i]=atol(stratrunc);
                   6390:     }
                   6391:     else
                   6392:       num[i]=atol(stra);
                   6393:     /*if((s[2][i]==2) && (s[3][i]==-1)&&(s[4][i]==9)){
                   6394:       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;}*/
                   6395:     
                   6396:     i=i+1;
                   6397:   } /* End loop reading  data */
1.126     brouard  6398: 
1.136     brouard  6399:   *imax=i-1; /* Number of individuals */
                   6400:   fclose(fic);
                   6401:  
                   6402:   return (0);
1.164     brouard  6403:   /* endread: */
1.136     brouard  6404:     printf("Exiting readdata: ");
                   6405:     fclose(fic);
                   6406:     return (1);
1.126     brouard  6407: 
                   6408: 
                   6409: 
1.136     brouard  6410: }
1.145     brouard  6411: void removespace(char *str) {
                   6412:   char *p1 = str, *p2 = str;
                   6413:   do
                   6414:     while (*p2 == ' ')
                   6415:       p2++;
1.169     brouard  6416:   while (*p1++ == *p2++);
1.145     brouard  6417: }
                   6418: 
                   6419: int decodemodel ( char model[], int lastobs) /**< This routine decode the model and returns:
1.187     brouard  6420:    * Model  V1+V2+V3+V8+V7*V8+V5*V6+V8*age+V3*age+age*age
                   6421:    * - nagesqr = 1 if age*age in the model, otherwise 0.
                   6422:    * - cptcovt total number of covariates of the model nbocc(+)+1 = 8 excepting constant and age and age*age
                   6423:    * - cptcovn or number of covariates k of the models excluding age*products =6 and age*age
1.145     brouard  6424:    * - cptcovage number of covariates with age*products =2
                   6425:    * - cptcovs number of simple covariates
                   6426:    * - 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
                   6427:    *     which is a new column after the 9 (ncovcol) variables. 
                   6428:    * - if k is a product Vn*Vm covar[k][i] is filled with correct values for each individual
                   6429:    * - Tprod[l] gives the kth covariates of the product Vn*Vm l=1 to cptcovprod-cptcovage
                   6430:    *    Tprod[1]@2 {5, 6}: position of first product V7*V8 is 5, and second V5*V6 is 6.
                   6431:    * - Tvard[k]  p Tvard[1][1]@4 {7, 8, 5, 6} for V7*V8 and V5*V6 .
                   6432:  */
1.136     brouard  6433: {
1.145     brouard  6434:   int i, j, k, ks;
1.164     brouard  6435:   int  j1, k1, k2;
1.136     brouard  6436:   char modelsav[80];
1.145     brouard  6437:   char stra[80], strb[80], strc[80], strd[80],stre[80];
1.187     brouard  6438:   char *strpt;
1.136     brouard  6439: 
1.145     brouard  6440:   /*removespace(model);*/
1.136     brouard  6441:   if (strlen(model) >1){ /* If there is at least 1 covariate */
1.145     brouard  6442:     j=0, j1=0, k1=0, k2=-1, ks=0, cptcovn=0;
1.137     brouard  6443:     if (strstr(model,"AGE") !=0){
1.192     brouard  6444:       printf("Error. AGE must be in lower case 'age' model=1+age+%s. ",model);
                   6445:       fprintf(ficlog,"Error. AGE must be in lower case model=1+age+%s. ",model);fflush(ficlog);
1.136     brouard  6446:       return 1;
                   6447:     }
1.141     brouard  6448:     if (strstr(model,"v") !=0){
                   6449:       printf("Error. 'v' must be in upper case 'V' model=%s ",model);
                   6450:       fprintf(ficlog,"Error. 'v' must be in upper case model=%s ",model);fflush(ficlog);
                   6451:       return 1;
                   6452:     }
1.187     brouard  6453:     strcpy(modelsav,model); 
                   6454:     if ((strpt=strstr(model,"age*age")) !=0){
                   6455:       printf(" strpt=%s, model=%s\n",strpt, model);
                   6456:       if(strpt != model){
                   6457:       printf("Error in model: 'model=%s'; 'age*age' should in first place before other covariates\n \
1.192     brouard  6458:  'model=1+age+age*age+V1.' or 'model=1+age+age*age+V1+V1*age.', please swap as well as \n \
1.187     brouard  6459:  corresponding column of parameters.\n",model);
                   6460:       fprintf(ficlog,"Error in model: 'model=%s'; 'age*age' should in first place before other covariates\n \
1.192     brouard  6461:  'model=1+age+age*age+V1.' or 'model=1+age+age*age+V1+V1*age.', please swap as well as \n \
1.187     brouard  6462:  corresponding column of parameters.\n",model); fflush(ficlog);
                   6463:       return 1;
                   6464:     }
                   6465: 
                   6466:       nagesqr=1;
                   6467:       if (strstr(model,"+age*age") !=0)
                   6468:        substrchaine(modelsav, model, "+age*age");
                   6469:       else if (strstr(model,"age*age+") !=0)
                   6470:        substrchaine(modelsav, model, "age*age+");
                   6471:       else 
                   6472:        substrchaine(modelsav, model, "age*age");
                   6473:     }else
                   6474:       nagesqr=0;
                   6475:     if (strlen(modelsav) >1){
                   6476:       j=nbocc(modelsav,'+'); /**< j=Number of '+' */
                   6477:       j1=nbocc(modelsav,'*'); /**< j1=Number of '*' */
                   6478:       cptcovs=j+1-j1; /**<  Number of simple covariates V1+V1*age+V3 +V3*V4+age*age=> V1 + V3 =2  */
                   6479:       cptcovt= j+1; /* Number of total covariates in the model, not including
                   6480:                   * cst, age and age*age 
                   6481:                   * V1+V1*age+ V3 + V3*V4+age*age=> 4*/
                   6482:                   /* including age products which are counted in cptcovage.
                   6483:                  * but the covariates which are products must be treated 
                   6484:                  * separately: ncovn=4- 2=2 (V1+V3). */
                   6485:       cptcovprod=j1; /**< Number of products  V1*V2 +v3*age = 2 */
                   6486:       cptcovprodnoage=0; /**< Number of covariate products without age: V3*V4 =1  */
                   6487: 
                   6488:     
                   6489:       /*   Design
                   6490:        *  V1   V2   V3   V4  V5  V6  V7  V8  V9 Weight
                   6491:        *  <          ncovcol=8                >
                   6492:        * Model V2 + V1 + V3*age + V3 + V5*V6 + V7*V8 + V8*age + V8
                   6493:        *   k=  1    2      3       4     5       6      7        8
                   6494:        *  cptcovn number of covariates (not including constant and age ) = # of + plus 1 = 7+1=8
                   6495:        *  covar[k,i], value of kth covariate if not including age for individual i:
                   6496:        *       covar[1][i]= (V2), covar[4][i]=(V3), covar[8][i]=(V8)
                   6497:        *  Tvar[k] # of the kth covariate:  Tvar[1]=2  Tvar[4]=3 Tvar[8]=8
                   6498:        *       if multiplied by age: V3*age Tvar[3=V3*age]=3 (V3) Tvar[7]=8 and 
                   6499:        *  Tage[++cptcovage]=k
                   6500:        *       if products, new covar are created after ncovcol with k1
                   6501:        *  Tvar[k]=ncovcol+k1; # of the kth covariate product:  Tvar[5]=ncovcol+1=10  Tvar[6]=ncovcol+1=11
                   6502:        *  Tprod[k1]=k; Tprod[1]=5 Tprod[2]= 6; gives the position of the k1th product
                   6503:        *  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
                   6504:        *  Tvar[cptcovn+k2]=Tvard[k1][1];Tvar[cptcovn+k2+1]=Tvard[k1][2];
                   6505:        *  Tvar[8+1]=5;Tvar[8+2]=6;Tvar[8+3]=7;Tvar[8+4]=8 inverted
                   6506:        *  V1   V2   V3   V4  V5  V6  V7  V8  V9  V10  V11
                   6507:        *  <          ncovcol=8                >
                   6508:        *       Model V2 + V1 + V3*age + V3 + V5*V6 + V7*V8 + V8*age + V8    d1   d1   d2  d2
                   6509:        *          k=  1    2      3       4     5       6      7        8    9   10   11  12
                   6510:        *     Tvar[k]= 2    1      3       3    10      11      8        8    5    6    7   8
                   6511:        * p Tvar[1]@12={2,   1,     3,      3,   11,     10,     8,       8,   7,   8,   5,  6}
                   6512:        * p Tprod[1]@2={                         6, 5}
                   6513:        *p Tvard[1][1]@4= {7, 8, 5, 6}
                   6514:        * covar[k][i]= V2   V1      ?      V3    V5*V6?   V7*V8?  ?       V8   
                   6515:        *  cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*cov[2];
                   6516:        *How to reorganize?
                   6517:        * Model V1 + V2 + V3 + V8 + V5*V6 + V7*V8 + V3*age + V8*age
                   6518:        * Tvars {2,   1,     3,      3,   11,     10,     8,       8,   7,   8,   5,  6}
                   6519:        *       {2,   1,     4,      8,    5,      6,     3,       7}
                   6520:        * Struct []
                   6521:        */
1.145     brouard  6522: 
1.187     brouard  6523:       /* This loop fills the array Tvar from the string 'model'.*/
                   6524:       /* j is the number of + signs in the model V1+V2+V3 j=2 i=3 to 1 */
                   6525:       /*   modelsav=V2+V1+V4+age*V3 strb=age*V3 stra=V2+V1+V4  */
                   6526:       /*       k=4 (age*V3) Tvar[k=4]= 3 (from V3) Tage[cptcovage=1]=4 */
                   6527:       /*       k=3 V4 Tvar[k=3]= 4 (from V4) */
                   6528:       /*       k=2 V1 Tvar[k=2]= 1 (from V1) */
                   6529:       /*       k=1 Tvar[1]=2 (from V2) */
                   6530:       /*       k=5 Tvar[5] */
                   6531:       /* for (k=1; k<=cptcovn;k++) { */
1.198     brouard  6532:       /*       cov[2+k]=nbcode[Tvar[k]][codtabm(ij,Tvar[k])]; */
1.187     brouard  6533:       /*       } */
1.198     brouard  6534:       /* for (k=1; k<=cptcovage;k++) cov[2+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(ij,Tvar[Tage[k])]]*cov[2]; */
1.187     brouard  6535:       /*
                   6536:        * Treating invertedly V2+V1+V3*age+V2*V4 is as if written V2*V4 +V3*age + V1 + V2 */
                   6537:       for(k=cptcovt; k>=1;k--) /**< Number of covariates */
1.145     brouard  6538:         Tvar[k]=0;
1.187     brouard  6539:       cptcovage=0;
                   6540:       for(k=1; k<=cptcovt;k++){ /* Loop on total covariates of the model */
                   6541:        cutl(stra,strb,modelsav,'+'); /* keeps in strb after the first '+' 
                   6542:                                         modelsav==V2+V1+V4+V3*age strb=V3*age stra=V2+V1+V4 */ 
                   6543:        if (nbocc(modelsav,'+')==0) strcpy(strb,modelsav); /* and analyzes it */
                   6544:        /*      printf("i=%d a=%s b=%s sav=%s\n",i, stra,strb,modelsav);*/
                   6545:        /*scanf("%d",i);*/
                   6546:        if (strchr(strb,'*')) {  /**< Model includes a product V2+V1+V4+V3*age strb=V3*age */
                   6547:          cutl(strc,strd,strb,'*'); /**< strd*strc  Vm*Vn: strb=V3*age(input) strc=age strd=V3 ; V3*V2 strc=V2, strd=V3 */
                   6548:          if (strcmp(strc,"age")==0) { /**< Model includes age: Vn*age */
                   6549:            /* covar is not filled and then is empty */
                   6550:            cptcovprod--;
                   6551:            cutl(stre,strb,strd,'V'); /* strd=V3(input): stre="3" */
                   6552:            Tvar[k]=atoi(stre);  /* V2+V1+V4+V3*age Tvar[4]=3 ; V1+V2*age Tvar[2]=2; V1+V1*age Tvar[2]=1 */
                   6553:            cptcovage++; /* Sums the number of covariates which include age as a product */
                   6554:            Tage[cptcovage]=k;  /* Tvar[4]=3, Tage[1] = 4 or V1+V1*age Tvar[2]=1, Tage[1]=2 */
                   6555:            /*printf("stre=%s ", stre);*/
                   6556:          } else if (strcmp(strd,"age")==0) { /* or age*Vn */
                   6557:            cptcovprod--;
                   6558:            cutl(stre,strb,strc,'V');
                   6559:            Tvar[k]=atoi(stre);
                   6560:            cptcovage++;
                   6561:            Tage[cptcovage]=k;
                   6562:          } else {  /* Age is not in the model product V2+V1+V1*V4+V3*age+V3*V2  strb=V3*V2*/
                   6563:            /* loops on k1=1 (V3*V2) and k1=2 V4*V3 */
                   6564:            cptcovn++;
                   6565:            cptcovprodnoage++;k1++;
                   6566:            cutl(stre,strb,strc,'V'); /* strc= Vn, stre is n; strb=V3*V2 stre=3 strc=*/
                   6567:            Tvar[k]=ncovcol+k1; /* For model-covariate k tells which data-covariate to use but
                   6568:                                   because this model-covariate is a construction we invent a new column
                   6569:                                   ncovcol + k1
                   6570:                                   If already ncovcol=4 and model=V2+V1+V1*V4+age*V3+V3*V2
                   6571:                                   Tvar[3=V1*V4]=4+1 Tvar[5=V3*V2]=4 + 2= 6, etc */
                   6572:            cutl(strc,strb,strd,'V'); /* strd was Vm, strc is m */
                   6573:            Tprod[k1]=k;  /* Tprod[1]=3(=V1*V4) for V2+V1+V1*V4+age*V3+V3*V2  */
                   6574:            Tvard[k1][1] =atoi(strc); /* m 1 for V1*/
                   6575:            Tvard[k1][2] =atoi(stre); /* n 4 for V4*/
                   6576:            k2=k2+2;
                   6577:            Tvar[cptcovt+k2]=Tvard[k1][1]; /* Tvar[(cptcovt=4+k2=1)=5]= 1 (V1) */
                   6578:            Tvar[cptcovt+k2+1]=Tvard[k1][2];  /* Tvar[(cptcovt=4+(k2=1)+1)=6]= 4 (V4) */
                   6579:            for (i=1; i<=lastobs;i++){
                   6580:              /* Computes the new covariate which is a product of
                   6581:                 covar[n][i]* covar[m][i] and stores it at ncovol+k1 May not be defined */
                   6582:              covar[ncovcol+k1][i]=covar[atoi(stre)][i]*covar[atoi(strc)][i];
                   6583:            }
                   6584:          } /* End age is not in the model */
                   6585:        } /* End if model includes a product */
                   6586:        else { /* no more sum */
                   6587:          /*printf("d=%s c=%s b=%s\n", strd,strc,strb);*/
                   6588:          /*  scanf("%d",i);*/
                   6589:          cutl(strd,strc,strb,'V');
                   6590:          ks++; /**< Number of simple covariates */
1.145     brouard  6591:          cptcovn++;
1.187     brouard  6592:          Tvar[k]=atoi(strd);
                   6593:        }
                   6594:        strcpy(modelsav,stra);  /* modelsav=V2+V1+V4 stra=V2+V1+V4 */ 
                   6595:        /*printf("a=%s b=%s sav=%s\n", stra,strb,modelsav);
                   6596:          scanf("%d",i);*/
                   6597:       } /* end of loop + on total covariates */
                   6598:     } /* end if strlen(modelsave == 0) age*age might exist */
                   6599:   } /* end if strlen(model == 0) */
1.136     brouard  6600:   
                   6601:   /*The number n of Vn is stored in Tvar. cptcovage =number of age covariate. Tage gives the position of age. cptcovprod= number of products.
                   6602:     If model=V1+V1*age then Tvar[1]=1 Tvar[2]=1 cptcovage=1 Tage[1]=2 cptcovprod=0*/
                   6603: 
                   6604:   /* printf("tvar1=%d tvar2=%d tvar3=%d cptcovage=%d Tage=%d",Tvar[1],Tvar[2],Tvar[3],cptcovage,Tage[1]);
                   6605:   printf("cptcovprod=%d ", cptcovprod);
                   6606:   fprintf(ficlog,"cptcovprod=%d ", cptcovprod);
                   6607: 
                   6608:   scanf("%d ",i);*/
                   6609: 
                   6610: 
1.137     brouard  6611:   return (0); /* with covar[new additional covariate if product] and Tage if age */ 
1.164     brouard  6612:   /*endread:*/
1.136     brouard  6613:     printf("Exiting decodemodel: ");
                   6614:     return (1);
                   6615: }
                   6616: 
1.169     brouard  6617: int calandcheckages(int imx, int maxwav, double *agemin, double *agemax, int *nberr, int *nbwarn )
1.136     brouard  6618: {
                   6619:   int i, m;
                   6620: 
                   6621:   for (i=1; i<=imx; i++) {
                   6622:     for(m=2; (m<= maxwav); m++) {
                   6623:       if (((int)mint[m][i]== 99) && (s[m][i] <= nlstate)){
                   6624:        anint[m][i]=9999;
                   6625:        s[m][i]=-1;
                   6626:       }
                   6627:       if((int)moisdc[i]==99 && (int)andc[i]==9999 && s[m][i]>nlstate){
1.169     brouard  6628:        *nberr = *nberr + 1;
                   6629:        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);
                   6630:        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  6631:        s[m][i]=-1;
                   6632:       }
                   6633:       if((int)moisdc[i]==99 && (int)andc[i]!=9999 && s[m][i]>nlstate){
1.169     brouard  6634:        (*nberr)++;
1.136     brouard  6635:        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]); 
                   6636:        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]); 
                   6637:        s[m][i]=-1; /* We prefer to skip it (and to skip it in version 0.8a1 too */
                   6638:       }
                   6639:     }
                   6640:   }
                   6641: 
                   6642:   for (i=1; i<=imx; i++)  {
                   6643:     agedc[i]=(moisdc[i]/12.+andc[i])-(moisnais[i]/12.+annais[i]);
                   6644:     for(m=firstpass; (m<= lastpass); m++){
1.214     brouard  6645:       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  6646:        if (s[m][i] >= nlstate+1) {
1.169     brouard  6647:          if(agedc[i]>0){
                   6648:            if((int)moisdc[i]!=99 && (int)andc[i]!=9999){
1.136     brouard  6649:              agev[m][i]=agedc[i];
1.214     brouard  6650:              /*if(moisdc[i]==99 && andc[i]==9999) s[m][i]=-1;*/
1.169     brouard  6651:            }else {
1.136     brouard  6652:              if ((int)andc[i]!=9999){
                   6653:                nbwarn++;
                   6654:                printf("Warning negative age at death: %ld line:%d\n",num[i],i);
                   6655:                fprintf(ficlog,"Warning negative age at death: %ld line:%d\n",num[i],i);
                   6656:                agev[m][i]=-1;
                   6657:              }
                   6658:            }
1.169     brouard  6659:          } /* agedc > 0 */
1.214     brouard  6660:        } /* end if */
1.136     brouard  6661:        else if(s[m][i] !=9){ /* Standard case, age in fractional
                   6662:                                 years but with the precision of a month */
                   6663:          agev[m][i]=(mint[m][i]/12.+1./24.+anint[m][i])-(moisnais[i]/12.+1./24.+annais[i]);
                   6664:          if((int)mint[m][i]==99 || (int)anint[m][i]==9999)
                   6665:            agev[m][i]=1;
                   6666:          else if(agev[m][i] < *agemin){ 
                   6667:            *agemin=agev[m][i];
                   6668:            printf(" Min anint[%d][%d]=%.2f annais[%d]=%.2f, agemin=%.2f\n",m,i,anint[m][i], i,annais[i], *agemin);
                   6669:          }
                   6670:          else if(agev[m][i] >*agemax){
                   6671:            *agemax=agev[m][i];
1.156     brouard  6672:            /* printf(" Max anint[%d][%d]=%.0f annais[%d]=%.0f, agemax=%.2f\n",m,i,anint[m][i], i,annais[i], *agemax);*/
1.136     brouard  6673:          }
                   6674:          /*agev[m][i]=anint[m][i]-annais[i];*/
                   6675:          /*     agev[m][i] = age[i]+2*m;*/
1.214     brouard  6676:        } /* en if 9*/
1.136     brouard  6677:        else { /* =9 */
1.214     brouard  6678:          /* printf("Debug num[%d]=%ld s[%d][%d]=%d\n",i,num[i], m,i, s[m][i]); */
1.136     brouard  6679:          agev[m][i]=1;
                   6680:          s[m][i]=-1;
                   6681:        }
                   6682:       }
1.214     brouard  6683:       else if(s[m][i]==0) /*= 0 Unknown */
1.136     brouard  6684:        agev[m][i]=1;
1.214     brouard  6685:       else{
                   6686:        printf("Warning, num[%d]=%ld, s[%d][%d]=%d\n", i, num[i], m, i,s[m][i]); 
                   6687:        fprintf(ficlog, "Warning, num[%d]=%ld, s[%d][%d]=%d\n", i, num[i], m, i,s[m][i]); 
                   6688:        agev[m][i]=0;
                   6689:       }
                   6690:     } /* End for lastpass */
                   6691:   }
1.136     brouard  6692:     
                   6693:   for (i=1; i<=imx; i++)  {
                   6694:     for(m=firstpass; (m<=lastpass); m++){
                   6695:       if (s[m][i] > (nlstate+ndeath)) {
1.169     brouard  6696:        (*nberr)++;
1.136     brouard  6697:        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);     
                   6698:        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);     
                   6699:        return 1;
                   6700:       }
                   6701:     }
                   6702:   }
                   6703: 
                   6704:   /*for (i=1; i<=imx; i++){
                   6705:   for (m=firstpass; (m<lastpass); m++){
                   6706:      printf("%ld %d %.lf %d %d\n", num[i],(covar[1][i]),agev[m][i],s[m][i],s[m+1][i]);
                   6707: }
                   6708: 
                   6709: }*/
                   6710: 
                   6711: 
1.139     brouard  6712:   printf("Total number of individuals= %d, Agemin = %.2f, Agemax= %.2f\n\n", imx, *agemin, *agemax);
                   6713:   fprintf(ficlog,"Total number of individuals= %d, Agemin = %.2f, Agemax= %.2f\n\n", imx, *agemin, *agemax); 
1.136     brouard  6714: 
                   6715:   return (0);
1.164     brouard  6716:  /* endread:*/
1.136     brouard  6717:     printf("Exiting calandcheckages: ");
                   6718:     return (1);
                   6719: }
                   6720: 
1.172     brouard  6721: #if defined(_MSC_VER)
                   6722: /*printf("Visual C++ compiler: %s \n;", _MSC_FULL_VER);*/
                   6723: /*fprintf(ficlog, "Visual C++ compiler: %s \n;", _MSC_FULL_VER);*/
                   6724: //#include "stdafx.h"
                   6725: //#include <stdio.h>
                   6726: //#include <tchar.h>
                   6727: //#include <windows.h>
                   6728: //#include <iostream>
                   6729: typedef BOOL(WINAPI *LPFN_ISWOW64PROCESS) (HANDLE, PBOOL);
                   6730: 
                   6731: LPFN_ISWOW64PROCESS fnIsWow64Process;
                   6732: 
                   6733: BOOL IsWow64()
                   6734: {
                   6735:        BOOL bIsWow64 = FALSE;
                   6736: 
                   6737:        //typedef BOOL (APIENTRY *LPFN_ISWOW64PROCESS)
                   6738:        //  (HANDLE, PBOOL);
                   6739: 
                   6740:        //LPFN_ISWOW64PROCESS fnIsWow64Process;
                   6741: 
                   6742:        HMODULE module = GetModuleHandle(_T("kernel32"));
                   6743:        const char funcName[] = "IsWow64Process";
                   6744:        fnIsWow64Process = (LPFN_ISWOW64PROCESS)
                   6745:                GetProcAddress(module, funcName);
                   6746: 
                   6747:        if (NULL != fnIsWow64Process)
                   6748:        {
                   6749:                if (!fnIsWow64Process(GetCurrentProcess(),
                   6750:                        &bIsWow64))
                   6751:                        //throw std::exception("Unknown error");
                   6752:                        printf("Unknown error\n");
                   6753:        }
                   6754:        return bIsWow64 != FALSE;
                   6755: }
                   6756: #endif
1.177     brouard  6757: 
1.191     brouard  6758: void syscompilerinfo(int logged)
1.167     brouard  6759:  {
                   6760:    /* #include "syscompilerinfo.h"*/
1.185     brouard  6761:    /* command line Intel compiler 32bit windows, XP compatible:*/
                   6762:    /* /GS /W3 /Gy
                   6763:       /Zc:wchar_t /Zi /O2 /Fd"Release\vc120.pdb" /D "WIN32" /D "NDEBUG" /D
                   6764:       "_CONSOLE" /D "_LIB" /D "_USING_V110_SDK71_" /D "_UNICODE" /D
                   6765:       "UNICODE" /Qipo /Zc:forScope /Gd /Oi /MT /Fa"Release\" /EHsc /nologo
1.186     brouard  6766:       /Fo"Release\" /Qprof-dir "Release\" /Fp"Release\IMaCh.pch"
                   6767:    */ 
                   6768:    /* 64 bits */
1.185     brouard  6769:    /*
                   6770:      /GS /W3 /Gy
                   6771:      /Zc:wchar_t /Zi /O2 /Fd"x64\Release\vc120.pdb" /D "WIN32" /D "NDEBUG"
                   6772:      /D "_CONSOLE" /D "_LIB" /D "_UNICODE" /D "UNICODE" /Qipo /Zc:forScope
                   6773:      /Oi /MD /Fa"x64\Release\" /EHsc /nologo /Fo"x64\Release\" /Qprof-dir
                   6774:      "x64\Release\" /Fp"x64\Release\IMaCh.pch" */
                   6775:    /* Optimization are useless and O3 is slower than O2 */
                   6776:    /*
                   6777:      /GS /W3 /Gy /Zc:wchar_t /Zi /O3 /Fd"x64\Release\vc120.pdb" /D "WIN32" 
                   6778:      /D "NDEBUG" /D "_CONSOLE" /D "_LIB" /D "_UNICODE" /D "UNICODE" /Qipo 
                   6779:      /Zc:forScope /Oi /MD /Fa"x64\Release\" /EHsc /nologo /Qparallel 
                   6780:      /Fo"x64\Release\" /Qprof-dir "x64\Release\" /Fp"x64\Release\IMaCh.pch" 
                   6781:    */
1.186     brouard  6782:    /* Link is */ /* /OUT:"visual studio
1.185     brouard  6783:       2013\Projects\IMaCh\Release\IMaCh.exe" /MANIFEST /NXCOMPAT
                   6784:       /PDB:"visual studio
                   6785:       2013\Projects\IMaCh\Release\IMaCh.pdb" /DYNAMICBASE
                   6786:       "kernel32.lib" "user32.lib" "gdi32.lib" "winspool.lib"
                   6787:       "comdlg32.lib" "advapi32.lib" "shell32.lib" "ole32.lib"
                   6788:       "oleaut32.lib" "uuid.lib" "odbc32.lib" "odbccp32.lib"
                   6789:       /MACHINE:X86 /OPT:REF /SAFESEH /INCREMENTAL:NO
                   6790:       /SUBSYSTEM:CONSOLE",5.01" /MANIFESTUAC:"level='asInvoker'
                   6791:       uiAccess='false'"
                   6792:       /ManifestFile:"Release\IMaCh.exe.intermediate.manifest" /OPT:ICF
                   6793:       /NOLOGO /TLBID:1
                   6794:    */
1.177     brouard  6795: #if defined __INTEL_COMPILER
1.178     brouard  6796: #if defined(__GNUC__)
                   6797:        struct utsname sysInfo;  /* For Intel on Linux and OS/X */
                   6798: #endif
1.177     brouard  6799: #elif defined(__GNUC__) 
1.179     brouard  6800: #ifndef  __APPLE__
1.174     brouard  6801: #include <gnu/libc-version.h>  /* Only on gnu */
1.179     brouard  6802: #endif
1.177     brouard  6803:    struct utsname sysInfo;
1.178     brouard  6804:    int cross = CROSS;
                   6805:    if (cross){
                   6806:           printf("Cross-");
1.191     brouard  6807:           if(logged) fprintf(ficlog, "Cross-");
1.178     brouard  6808:    }
1.174     brouard  6809: #endif
                   6810: 
1.171     brouard  6811: #include <stdint.h>
1.178     brouard  6812: 
1.191     brouard  6813:    printf("Compiled with:");if(logged)fprintf(ficlog,"Compiled with:");
1.169     brouard  6814: #if defined(__clang__)
1.191     brouard  6815:    printf(" Clang/LLVM");if(logged)fprintf(ficlog," Clang/LLVM");      /* Clang/LLVM. ---------------------------------------------- */
1.169     brouard  6816: #endif
                   6817: #if defined(__ICC) || defined(__INTEL_COMPILER)
1.191     brouard  6818:    printf(" Intel ICC/ICPC");if(logged)fprintf(ficlog," Intel ICC/ICPC");/* Intel ICC/ICPC. ------------------------------------------ */
1.169     brouard  6819: #endif
                   6820: #if defined(__GNUC__) || defined(__GNUG__)
1.191     brouard  6821:    printf(" GNU GCC/G++");if(logged)fprintf(ficlog," GNU GCC/G++");/* GNU GCC/G++. --------------------------------------------- */
1.169     brouard  6822: #endif
                   6823: #if defined(__HP_cc) || defined(__HP_aCC)
1.191     brouard  6824:    printf(" Hewlett-Packard C/aC++");if(logged)fprintf(fcilog," Hewlett-Packard C/aC++"); /* Hewlett-Packard C/aC++. ---------------------------------- */
1.169     brouard  6825: #endif
                   6826: #if defined(__IBMC__) || defined(__IBMCPP__)
1.191     brouard  6827:    printf(" IBM XL C/C++"); if(logged) fprintf(ficlog," IBM XL C/C++");/* IBM XL C/C++. -------------------------------------------- */
1.169     brouard  6828: #endif
                   6829: #if defined(_MSC_VER)
1.191     brouard  6830:    printf(" Microsoft Visual Studio");if(logged)fprintf(ficlog," Microsoft Visual Studio");/* Microsoft Visual Studio. --------------------------------- */
1.169     brouard  6831: #endif
                   6832: #if defined(__PGI)
1.191     brouard  6833:    printf(" Portland Group PGCC/PGCPP");if(logged) fprintf(ficlog," Portland Group PGCC/PGCPP");/* Portland Group PGCC/PGCPP. ------------------------------- */
1.169     brouard  6834: #endif
                   6835: #if defined(__SUNPRO_C) || defined(__SUNPRO_CC)
1.191     brouard  6836:    printf(" Oracle Solaris Studio");if(logged)fprintf(ficlog," Oracle Solaris Studio\n");/* Oracle Solaris Studio. ----------------------------------- */
1.167     brouard  6837: #endif
1.191     brouard  6838:    printf(" for "); if (logged) fprintf(ficlog, " for ");
1.169     brouard  6839:    
1.167     brouard  6840: // http://stackoverflow.com/questions/4605842/how-to-identify-platform-compiler-from-preprocessor-macros
                   6841: #ifdef _WIN32 // note the underscore: without it, it's not msdn official!
                   6842:     // Windows (x64 and x86)
1.191     brouard  6843:    printf("Windows (x64 and x86) ");if(logged) fprintf(ficlog,"Windows (x64 and x86) ");
1.167     brouard  6844: #elif __unix__ // all unices, not all compilers
                   6845:     // Unix
1.191     brouard  6846:    printf("Unix ");if(logged) fprintf(ficlog,"Unix ");
1.167     brouard  6847: #elif __linux__
                   6848:     // linux
1.191     brouard  6849:    printf("linux ");if(logged) fprintf(ficlog,"linux ");
1.167     brouard  6850: #elif __APPLE__
1.174     brouard  6851:     // Mac OS, not sure if this is covered by __posix__ and/or __unix__ though..
1.191     brouard  6852:    printf("Mac OS ");if(logged) fprintf(ficlog,"Mac OS ");
1.167     brouard  6853: #endif
                   6854: 
                   6855: /*  __MINGW32__          */
                   6856: /*  __CYGWIN__  */
                   6857: /* __MINGW64__  */
                   6858: // http://msdn.microsoft.com/en-us/library/b0084kay.aspx
                   6859: /* _MSC_VER  //the Visual C++ compiler is 17.00.51106.1, the _MSC_VER macro evaluates to 1700. Type cl /?  */
                   6860: /* _MSC_FULL_VER //the Visual C++ compiler is 15.00.20706.01, the _MSC_FULL_VER macro evaluates to 150020706 */
                   6861: /* _WIN64  // Defined for applications for Win64. */
                   6862: /* _M_X64 // Defined for compilations that target x64 processors. */
                   6863: /* _DEBUG // Defined when you compile with /LDd, /MDd, and /MTd. */
1.171     brouard  6864: 
1.167     brouard  6865: #if UINTPTR_MAX == 0xffffffff
1.191     brouard  6866:    printf(" 32-bit"); if(logged) fprintf(ficlog," 32-bit");/* 32-bit */
1.167     brouard  6867: #elif UINTPTR_MAX == 0xffffffffffffffff
1.191     brouard  6868:    printf(" 64-bit"); if(logged) fprintf(ficlog," 64-bit");/* 64-bit */
1.167     brouard  6869: #else
1.191     brouard  6870:    printf(" wtf-bit"); if(logged) fprintf(ficlog," wtf-bit");/* wtf */
1.167     brouard  6871: #endif
                   6872: 
1.169     brouard  6873: #if defined(__GNUC__)
                   6874: # if defined(__GNUC_PATCHLEVEL__)
                   6875: #  define __GNUC_VERSION__ (__GNUC__ * 10000 \
                   6876:                             + __GNUC_MINOR__ * 100 \
                   6877:                             + __GNUC_PATCHLEVEL__)
                   6878: # else
                   6879: #  define __GNUC_VERSION__ (__GNUC__ * 10000 \
                   6880:                             + __GNUC_MINOR__ * 100)
                   6881: # endif
1.174     brouard  6882:    printf(" using GNU C version %d.\n", __GNUC_VERSION__);
1.191     brouard  6883:    if(logged) fprintf(ficlog, " using GNU C version %d.\n", __GNUC_VERSION__);
1.176     brouard  6884: 
                   6885:    if (uname(&sysInfo) != -1) {
                   6886:      printf("Running on: %s %s %s %s %s\n",sysInfo.sysname, sysInfo.nodename, sysInfo.release, sysInfo.version, sysInfo.machine);
1.191     brouard  6887:         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  6888:    }
                   6889:    else
                   6890:       perror("uname() error");
1.179     brouard  6891:    //#ifndef __INTEL_COMPILER 
                   6892: #if !defined (__INTEL_COMPILER) && !defined(__APPLE__)
1.174     brouard  6893:    printf("GNU libc version: %s\n", gnu_get_libc_version()); 
1.191     brouard  6894:    if(logged) fprintf(ficlog,"GNU libc version: %s\n", gnu_get_libc_version());
1.177     brouard  6895: #endif
1.169     brouard  6896: #endif
1.172     brouard  6897: 
                   6898:    //   void main()
                   6899:    //   {
1.169     brouard  6900: #if defined(_MSC_VER)
1.174     brouard  6901:    if (IsWow64()){
1.191     brouard  6902:           printf("\nThe program (probably compiled for 32bit) is running under WOW64 (64bit) emulation.\n");
                   6903:           if (logged) fprintf(ficlog, "\nThe program (probably compiled for 32bit) is running under WOW64 (64bit) emulation.\n");
1.174     brouard  6904:    }
                   6905:    else{
1.191     brouard  6906:           printf("\nThe program is not running under WOW64 (i.e probably on a 64bit Windows).\n");
                   6907:           if (logged) fprintf(ficlog, "\nThe programm is not running under WOW64 (i.e probably on a 64bit Windows).\n");
1.174     brouard  6908:    }
1.172     brouard  6909:    //     printf("\nPress Enter to continue...");
                   6910:    //     getchar();
                   6911:    //   }
                   6912: 
1.169     brouard  6913: #endif
                   6914:    
1.167     brouard  6915: 
                   6916:  }
1.136     brouard  6917: 
1.209     brouard  6918:  int prevalence_limit(double *p, double **prlim, double ageminpar, double agemaxpar, double ftolpl, int *ncvyearp){
1.180     brouard  6919:   /*--------------- Prevalence limit  (period or stable prevalence) --------------*/
                   6920:   int i, j, k, i1 ;
1.202     brouard  6921:   /* double ftolpl = 1.e-10; */
1.180     brouard  6922:   double age, agebase, agelim;
1.203     brouard  6923:   double tot;
1.180     brouard  6924: 
1.202     brouard  6925:   strcpy(filerespl,"PL_");
                   6926:   strcat(filerespl,fileresu);
                   6927:   if((ficrespl=fopen(filerespl,"w"))==NULL) {
                   6928:     printf("Problem with period (stable) prevalence resultfile: %s\n", filerespl);return 1;
                   6929:     fprintf(ficlog,"Problem with period (stable) prevalence resultfile: %s\n", filerespl);return 1;
                   6930:   }
                   6931:   printf("Computing period (stable) prevalence: result on file '%s' \n", filerespl);
                   6932:   fprintf(ficlog,"Computing period (stable) prevalence: result on file '%s' \n", filerespl);
                   6933:   pstamp(ficrespl);
1.203     brouard  6934:   fprintf(ficrespl,"# Period (stable) prevalence. Precision given by ftolpl=%g \n", ftolpl);
1.202     brouard  6935:   fprintf(ficrespl,"#Age ");
                   6936:   for(i=1; i<=nlstate;i++) fprintf(ficrespl,"%d-%d ",i,i);
                   6937:   fprintf(ficrespl,"\n");
1.180     brouard  6938:   
                   6939:     /* prlim=matrix(1,nlstate,1,nlstate);*/ /* back in main */
                   6940: 
                   6941:     agebase=ageminpar;
                   6942:     agelim=agemaxpar;
                   6943: 
                   6944:     i1=pow(2,cptcoveff);
                   6945:     if (cptcovn < 1){i1=1;}
                   6946: 
                   6947:     for(cptcov=1,k=0;cptcov<=i1;cptcov++){
                   6948:     /* for(cptcov=1,k=0;cptcov<=1;cptcov++){ */
                   6949:       //for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){
                   6950:        k=k+1;
                   6951:        /* to clean */
1.198     brouard  6952:        //printf("cptcov=%d cptcod=%d codtab=%d\n",cptcov, cptcod,codtabm(cptcod,cptcov));
1.200     brouard  6953:        fprintf(ficrespl,"#******");
                   6954:        printf("#******");
                   6955:        fprintf(ficlog,"#******");
1.180     brouard  6956:        for(j=1;j<=cptcoveff;j++) {
1.198     brouard  6957:          fprintf(ficrespl," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
                   6958:          printf(" V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
                   6959:          fprintf(ficlog," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
1.180     brouard  6960:        }
                   6961:        fprintf(ficrespl,"******\n");
                   6962:        printf("******\n");
                   6963:        fprintf(ficlog,"******\n");
                   6964: 
                   6965:        fprintf(ficrespl,"#Age ");
                   6966:        for(j=1;j<=cptcoveff;j++) {
1.200     brouard  6967:          fprintf(ficrespl,"V%d %d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
1.180     brouard  6968:        }
1.203     brouard  6969:        for(i=1; i<=nlstate;i++) fprintf(ficrespl,"  %d-%d   ",i,i);
                   6970:        fprintf(ficrespl,"Total Years_to_converge\n");
1.180     brouard  6971:        
                   6972:        for (age=agebase; age<=agelim; age++){
                   6973:        /* for (age=agebase; age<=agebase; age++){ */
1.209     brouard  6974:          prevalim(prlim, nlstate, p, age, oldm, savm, ftolpl, ncvyearp, k);
1.180     brouard  6975:          fprintf(ficrespl,"%.0f ",age );
                   6976:          for(j=1;j<=cptcoveff;j++)
1.198     brouard  6977:            fprintf(ficrespl,"%d %d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
1.203     brouard  6978:          tot=0.;
                   6979:          for(i=1; i<=nlstate;i++){
                   6980:            tot +=  prlim[i][i];
1.180     brouard  6981:            fprintf(ficrespl," %.5f", prlim[i][i]);
1.203     brouard  6982:          }
1.209     brouard  6983:          fprintf(ficrespl," %.3f %d\n", tot, *ncvyearp);
1.180     brouard  6984:        } /* Age */
                   6985:        /* was end of cptcod */
                   6986:     } /* cptcov */
1.184     brouard  6987:        return 0;
1.180     brouard  6988: }
                   6989: 
                   6990: int hPijx(double *p, int bage, int fage){
                   6991:     /*------------- h Pij x at various ages ------------*/
                   6992: 
                   6993:   int stepsize;
                   6994:   int agelim;
                   6995:   int hstepm;
                   6996:   int nhstepm;
                   6997:   int h, i, i1, j, k;
                   6998: 
                   6999:   double agedeb;
                   7000:   double ***p3mat;
                   7001: 
1.201     brouard  7002:     strcpy(filerespij,"PIJ_");  strcat(filerespij,fileresu);
1.180     brouard  7003:     if((ficrespij=fopen(filerespij,"w"))==NULL) {
                   7004:       printf("Problem with Pij resultfile: %s\n", filerespij); return 1;
                   7005:       fprintf(ficlog,"Problem with Pij resultfile: %s\n", filerespij); return 1;
                   7006:     }
                   7007:     printf("Computing pij: result on file '%s' \n", filerespij);
                   7008:     fprintf(ficlog,"Computing pij: result on file '%s' \n", filerespij);
                   7009:   
                   7010:     stepsize=(int) (stepm+YEARM-1)/YEARM;
                   7011:     /*if (stepm<=24) stepsize=2;*/
                   7012: 
                   7013:     agelim=AGESUP;
                   7014:     hstepm=stepsize*YEARM; /* Every year of age */
                   7015:     hstepm=hstepm/stepm; /* Typically 2 years, = 2/6 months = 4 */ 
                   7016: 
                   7017:     /* hstepm=1;   aff par mois*/
                   7018:     pstamp(ficrespij);
                   7019:     fprintf(ficrespij,"#****** h Pij x Probability to be in state j at age x+h being in i at x ");
                   7020:     i1= pow(2,cptcoveff);
1.183     brouard  7021:    /* for(cptcov=1,k=0;cptcov<=i1;cptcov++){ */
                   7022:    /*    /\*for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){*\/ */
                   7023:    /*          k=k+1;  */
                   7024:     for (k=1; k <= (int) pow(2,cptcoveff); k++){
                   7025:       fprintf(ficrespij,"\n#****** ");
                   7026:       for(j=1;j<=cptcoveff;j++) 
1.198     brouard  7027:        fprintf(ficrespij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
1.183     brouard  7028:       fprintf(ficrespij,"******\n");
                   7029:       
                   7030:       for (agedeb=fage; agedeb>=bage; agedeb--){ /* If stepm=6 months */
                   7031:        nhstepm=(int) rint((agelim-agedeb)*YEARM/stepm); /* Typically 20 years = 20*12/6=40 */ 
                   7032:        nhstepm = nhstepm/hstepm; /* Typically 40/4=10 */
                   7033:        
                   7034:        /*        nhstepm=nhstepm*YEARM; aff par mois*/
1.180     brouard  7035:        
1.183     brouard  7036:        p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   7037:        oldm=oldms;savm=savms;
                   7038:        hpxij(p3mat,nhstepm,agedeb,hstepm,p,nlstate,stepm,oldm,savm, k);  
                   7039:        fprintf(ficrespij,"# Cov Agex agex+h hpijx with i,j=");
                   7040:        for(i=1; i<=nlstate;i++)
                   7041:          for(j=1; j<=nlstate+ndeath;j++)
                   7042:            fprintf(ficrespij," %1d-%1d",i,j);
                   7043:        fprintf(ficrespij,"\n");
                   7044:        for (h=0; h<=nhstepm; h++){
                   7045:          /*agedebphstep = agedeb + h*hstepm/YEARM*stepm;*/
                   7046:          fprintf(ficrespij,"%d %3.f %3.f",k, agedeb, agedeb + h*hstepm/YEARM*stepm );
1.180     brouard  7047:          for(i=1; i<=nlstate;i++)
                   7048:            for(j=1; j<=nlstate+ndeath;j++)
1.183     brouard  7049:              fprintf(ficrespij," %.5f", p3mat[i][j][h]);
1.180     brouard  7050:          fprintf(ficrespij,"\n");
                   7051:        }
1.183     brouard  7052:        free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   7053:        fprintf(ficrespij,"\n");
                   7054:       }
1.180     brouard  7055:       /*}*/
                   7056:     }
1.184     brouard  7057:        return 0;
1.180     brouard  7058: }
                   7059: 
                   7060: 
1.136     brouard  7061: /***********************************************/
                   7062: /**************** Main Program *****************/
                   7063: /***********************************************/
                   7064: 
                   7065: int main(int argc, char *argv[])
                   7066: {
                   7067: #ifdef GSL
                   7068:   const gsl_multimin_fminimizer_type *T;
                   7069:   size_t iteri = 0, it;
                   7070:   int rval = GSL_CONTINUE;
                   7071:   int status = GSL_SUCCESS;
                   7072:   double ssval;
                   7073: #endif
                   7074:   int movingaverage(double ***probs, double bage,double fage, double ***mobaverage, int mobilav);
1.164     brouard  7075:   int i,j, k, n=MAXN,iter=0,m,size=100, cptcod;
1.209     brouard  7076:   int ncvyear=0; /* Number of years needed for the period prevalence to converge */
1.164     brouard  7077:   int jj, ll, li, lj, lk;
1.136     brouard  7078:   int numlinepar=0; /* Current linenumber of parameter file */
1.197     brouard  7079:   int num_filled;
1.136     brouard  7080:   int itimes;
                   7081:   int NDIM=2;
                   7082:   int vpopbased=0;
                   7083: 
1.164     brouard  7084:   char ca[32], cb[32];
1.136     brouard  7085:   /*  FILE *fichtm; *//* Html File */
                   7086:   /* FILE *ficgp;*/ /*Gnuplot File */
                   7087:   struct stat info;
1.191     brouard  7088:   double agedeb=0.;
1.194     brouard  7089: 
                   7090:   double ageminpar=AGEOVERFLOW,agemin=AGEOVERFLOW, agemaxpar=-AGEOVERFLOW, agemax=-AGEOVERFLOW;
1.136     brouard  7091: 
1.165     brouard  7092:   double fret;
1.191     brouard  7093:   double dum=0.; /* Dummy variable */
1.136     brouard  7094:   double ***p3mat;
                   7095:   double ***mobaverage;
1.164     brouard  7096: 
                   7097:   char line[MAXLINE];
1.197     brouard  7098:   char path[MAXLINE],pathc[MAXLINE],pathcd[MAXLINE],pathtot[MAXLINE];
                   7099: 
                   7100:   char model[MAXLINE], modeltemp[MAXLINE];
1.136     brouard  7101:   char pathr[MAXLINE], pathimach[MAXLINE]; 
1.164     brouard  7102:   char *tok, *val; /* pathtot */
1.136     brouard  7103:   int firstobs=1, lastobs=10;
1.195     brouard  7104:   int c,  h , cpt, c2;
1.191     brouard  7105:   int jl=0;
                   7106:   int i1, j1, jk, stepsize=0;
1.194     brouard  7107:   int count=0;
                   7108: 
1.164     brouard  7109:   int *tab; 
1.136     brouard  7110:   int mobilavproj=0 , prevfcast=0 ; /* moving average of prev, If prevfcast=1 prevalence projection */
                   7111:   int mobilav=0,popforecast=0;
1.191     brouard  7112:   int hstepm=0, nhstepm=0;
1.136     brouard  7113:   int agemortsup;
                   7114:   float  sumlpop=0.;
                   7115:   double jprev1=1, mprev1=1,anprev1=2000,jprev2=1, mprev2=1,anprev2=2000;
                   7116:   double jpyram=1, mpyram=1,anpyram=2000,jpyram1=1, mpyram1=1,anpyram1=2000;
                   7117: 
1.191     brouard  7118:   double bage=0, fage=110., age, agelim=0., agebase=0.;
1.136     brouard  7119:   double ftolpl=FTOL;
                   7120:   double **prlim;
                   7121:   double ***param; /* Matrix of parameters */
                   7122:   double  *p;
                   7123:   double **matcov; /* Matrix of covariance */
1.203     brouard  7124:   double **hess; /* Hessian matrix */
1.136     brouard  7125:   double ***delti3; /* Scale */
                   7126:   double *delti; /* Scale */
                   7127:   double ***eij, ***vareij;
                   7128:   double **varpl; /* Variances of prevalence limits by age */
                   7129:   double *epj, vepp;
1.164     brouard  7130: 
1.136     brouard  7131:   double dateprev1, dateprev2,jproj1=1,mproj1=1,anproj1=2000,jproj2=1,mproj2=1,anproj2=2000;
                   7132:   double **ximort;
1.145     brouard  7133:   char *alph[]={"a","a","b","c","d","e"}, str[4]="1234";
1.136     brouard  7134:   int *dcwave;
                   7135: 
1.164     brouard  7136:   char z[1]="c";
1.136     brouard  7137: 
                   7138:   /*char  *strt;*/
                   7139:   char strtend[80];
1.126     brouard  7140: 
1.164     brouard  7141: 
1.126     brouard  7142: /*   setlocale (LC_ALL, ""); */
                   7143: /*   bindtextdomain (PACKAGE, LOCALEDIR); */
                   7144: /*   textdomain (PACKAGE); */
                   7145: /*   setlocale (LC_CTYPE, ""); */
                   7146: /*   setlocale (LC_MESSAGES, ""); */
                   7147: 
                   7148:   /*   gettimeofday(&start_time, (struct timezone*)0); */ /* at first time */
1.157     brouard  7149:   rstart_time = time(NULL);  
                   7150:   /*  (void) gettimeofday(&start_time,&tzp);*/
                   7151:   start_time = *localtime(&rstart_time);
1.126     brouard  7152:   curr_time=start_time;
1.157     brouard  7153:   /*tml = *localtime(&start_time.tm_sec);*/
                   7154:   /* strcpy(strstart,asctime(&tml)); */
                   7155:   strcpy(strstart,asctime(&start_time));
1.126     brouard  7156: 
                   7157: /*  printf("Localtime (at start)=%s",strstart); */
1.157     brouard  7158: /*  tp.tm_sec = tp.tm_sec +86400; */
                   7159: /*  tm = *localtime(&start_time.tm_sec); */
1.126     brouard  7160: /*   tmg.tm_year=tmg.tm_year +dsign*dyear; */
                   7161: /*   tmg.tm_mon=tmg.tm_mon +dsign*dmonth; */
                   7162: /*   tmg.tm_hour=tmg.tm_hour + 1; */
1.157     brouard  7163: /*   tp.tm_sec = mktime(&tmg); */
1.126     brouard  7164: /*   strt=asctime(&tmg); */
                   7165: /*   printf("Time(after) =%s",strstart);  */
                   7166: /*  (void) time (&time_value);
                   7167: *  printf("time=%d,t-=%d\n",time_value,time_value-86400);
                   7168: *  tm = *localtime(&time_value);
                   7169: *  strstart=asctime(&tm);
                   7170: *  printf("tim_value=%d,asctime=%s\n",time_value,strstart); 
                   7171: */
                   7172: 
                   7173:   nberr=0; /* Number of errors and warnings */
                   7174:   nbwarn=0;
1.184     brouard  7175: #ifdef WIN32
                   7176:   _getcwd(pathcd, size);
                   7177: #else
1.126     brouard  7178:   getcwd(pathcd, size);
1.184     brouard  7179: #endif
1.191     brouard  7180:   syscompilerinfo(0);
1.196     brouard  7181:   printf("\nIMaCh version %s, %s\n%s",version, copyright, fullversion);
1.126     brouard  7182:   if(argc <=1){
                   7183:     printf("\nEnter the parameter file name: ");
1.205     brouard  7184:     if(!fgets(pathr,FILENAMELENGTH,stdin)){
                   7185:       printf("ERROR Empty parameter file name\n");
                   7186:       goto end;
                   7187:     }
1.126     brouard  7188:     i=strlen(pathr);
                   7189:     if(pathr[i-1]=='\n')
                   7190:       pathr[i-1]='\0';
1.156     brouard  7191:     i=strlen(pathr);
1.205     brouard  7192:     if(i >= 1 && pathr[i-1]==' ') {/* This may happen when dragging on oS/X! */
1.156     brouard  7193:       pathr[i-1]='\0';
1.205     brouard  7194:     }
                   7195:     i=strlen(pathr);
                   7196:     if( i==0 ){
                   7197:       printf("ERROR Empty parameter file name\n");
                   7198:       goto end;
                   7199:     }
                   7200:     for (tok = pathr; tok != NULL; ){
1.126     brouard  7201:       printf("Pathr |%s|\n",pathr);
                   7202:       while ((val = strsep(&tok, "\"" )) != NULL && *val == '\0');
                   7203:       printf("val= |%s| pathr=%s\n",val,pathr);
                   7204:       strcpy (pathtot, val);
                   7205:       if(pathr[0] == '\0') break; /* Dirty */
                   7206:     }
                   7207:   }
                   7208:   else{
                   7209:     strcpy(pathtot,argv[1]);
                   7210:   }
                   7211:   /*if(getcwd(pathcd, MAXLINE)!= NULL)printf ("Error pathcd\n");*/
                   7212:   /*cygwin_split_path(pathtot,path,optionfile);
                   7213:     printf("pathtot=%s, path=%s, optionfile=%s\n",pathtot,path,optionfile);*/
                   7214:   /* cutv(path,optionfile,pathtot,'\\');*/
                   7215: 
                   7216:   /* Split argv[0], imach program to get pathimach */
                   7217:   printf("\nargv[0]=%s argv[1]=%s, \n",argv[0],argv[1]);
                   7218:   split(argv[0],pathimach,optionfile,optionfilext,optionfilefiname);
                   7219:   printf("\nargv[0]=%s pathimach=%s, \noptionfile=%s \noptionfilext=%s \noptionfilefiname=%s\n",argv[0],pathimach,optionfile,optionfilext,optionfilefiname);
                   7220:  /*   strcpy(pathimach,argv[0]); */
                   7221:   /* Split argv[1]=pathtot, parameter file name to get path, optionfile, extension and name */
                   7222:   split(pathtot,path,optionfile,optionfilext,optionfilefiname);
                   7223:   printf("\npathtot=%s,\npath=%s,\noptionfile=%s \noptionfilext=%s \noptionfilefiname=%s\n",pathtot,path,optionfile,optionfilext,optionfilefiname);
1.184     brouard  7224: #ifdef WIN32
                   7225:   _chdir(path); /* Can be a relative path */
                   7226:   if(_getcwd(pathcd,MAXLINE) > 0) /* So pathcd is the full path */
                   7227: #else
1.126     brouard  7228:   chdir(path); /* Can be a relative path */
1.184     brouard  7229:   if (getcwd(pathcd, MAXLINE) > 0) /* So pathcd is the full path */
                   7230: #endif
                   7231:   printf("Current directory %s!\n",pathcd);
1.126     brouard  7232:   strcpy(command,"mkdir ");
                   7233:   strcat(command,optionfilefiname);
                   7234:   if((outcmd=system(command)) != 0){
1.169     brouard  7235:     printf("Directory already exists (or can't create it) %s%s, err=%d\n",path,optionfilefiname,outcmd);
1.126     brouard  7236:     /* fprintf(ficlog,"Problem creating directory %s%s\n",path,optionfilefiname); */
                   7237:     /* fclose(ficlog); */
                   7238: /*     exit(1); */
                   7239:   }
                   7240: /*   if((imk=mkdir(optionfilefiname))<0){ */
                   7241: /*     perror("mkdir"); */
                   7242: /*   } */
                   7243: 
                   7244:   /*-------- arguments in the command line --------*/
                   7245: 
1.186     brouard  7246:   /* Main Log file */
1.126     brouard  7247:   strcat(filelog, optionfilefiname);
                   7248:   strcat(filelog,".log");    /* */
                   7249:   if((ficlog=fopen(filelog,"w"))==NULL)    {
                   7250:     printf("Problem with logfile %s\n",filelog);
                   7251:     goto end;
                   7252:   }
                   7253:   fprintf(ficlog,"Log filename:%s\n",filelog);
1.197     brouard  7254:   fprintf(ficlog,"Version %s %s",version,fullversion);
1.126     brouard  7255:   fprintf(ficlog,"\nEnter the parameter file name: \n");
                   7256:   fprintf(ficlog,"pathimach=%s\npathtot=%s\n\
                   7257:  path=%s \n\
                   7258:  optionfile=%s\n\
                   7259:  optionfilext=%s\n\
1.156     brouard  7260:  optionfilefiname='%s'\n",pathimach,pathtot,path,optionfile,optionfilext,optionfilefiname);
1.126     brouard  7261: 
1.197     brouard  7262:   syscompilerinfo(1);
1.167     brouard  7263: 
1.126     brouard  7264:   printf("Local time (at start):%s",strstart);
                   7265:   fprintf(ficlog,"Local time (at start): %s",strstart);
                   7266:   fflush(ficlog);
                   7267: /*   (void) gettimeofday(&curr_time,&tzp); */
1.157     brouard  7268: /*   printf("Elapsed time %d\n", asc_diff_time(curr_time.tm_sec-start_time.tm_sec,tmpout)); */
1.126     brouard  7269: 
                   7270:   /* */
                   7271:   strcpy(fileres,"r");
                   7272:   strcat(fileres, optionfilefiname);
1.201     brouard  7273:   strcat(fileresu, optionfilefiname); /* Without r in front */
1.126     brouard  7274:   strcat(fileres,".txt");    /* Other files have txt extension */
1.201     brouard  7275:   strcat(fileresu,".txt");    /* Other files have txt extension */
1.126     brouard  7276: 
1.186     brouard  7277:   /* Main ---------arguments file --------*/
1.126     brouard  7278: 
                   7279:   if((ficpar=fopen(optionfile,"r"))==NULL)    {
1.155     brouard  7280:     printf("Problem with optionfile '%s' with errno='%s'\n",optionfile,strerror(errno));
                   7281:     fprintf(ficlog,"Problem with optionfile '%s' with errno='%s'\n",optionfile,strerror(errno));
1.126     brouard  7282:     fflush(ficlog);
1.149     brouard  7283:     /* goto end; */
                   7284:     exit(70); 
1.126     brouard  7285:   }
                   7286: 
                   7287: 
                   7288: 
                   7289:   strcpy(filereso,"o");
1.201     brouard  7290:   strcat(filereso,fileresu);
1.126     brouard  7291:   if((ficparo=fopen(filereso,"w"))==NULL) { /* opened on subdirectory */
                   7292:     printf("Problem with Output resultfile: %s\n", filereso);
                   7293:     fprintf(ficlog,"Problem with Output resultfile: %s\n", filereso);
                   7294:     fflush(ficlog);
                   7295:     goto end;
                   7296:   }
                   7297: 
                   7298:   /* Reads comments: lines beginning with '#' */
                   7299:   numlinepar=0;
1.197     brouard  7300: 
                   7301:     /* First parameter line */
                   7302:   while(fgets(line, MAXLINE, ficpar)) {
                   7303:     /* If line starts with a # it is a comment */
                   7304:     if (line[0] == '#') {
                   7305:       numlinepar++;
                   7306:       fputs(line,stdout);
                   7307:       fputs(line,ficparo);
                   7308:       fputs(line,ficlog);
                   7309:       continue;
                   7310:     }else
                   7311:       break;
                   7312:   }
                   7313:   if((num_filled=sscanf(line,"title=%s datafile=%s lastobs=%d firstpass=%d lastpass=%d\n", \
                   7314:                        title, datafile, &lastobs, &firstpass,&lastpass)) !=EOF){
                   7315:     if (num_filled != 5) {
                   7316:       printf("Should be 5 parameters\n");
                   7317:     }
1.126     brouard  7318:     numlinepar++;
1.197     brouard  7319:     printf("title=%s datafile=%s lastobs=%d firstpass=%d lastpass=%d\n", title, datafile, lastobs, firstpass,lastpass);
                   7320:   }
                   7321:   /* Second parameter line */
                   7322:   while(fgets(line, MAXLINE, ficpar)) {
                   7323:     /* If line starts with a # it is a comment */
                   7324:     if (line[0] == '#') {
                   7325:       numlinepar++;
                   7326:       fputs(line,stdout);
                   7327:       fputs(line,ficparo);
                   7328:       fputs(line,ficlog);
                   7329:       continue;
                   7330:     }else
                   7331:       break;
                   7332:   }
                   7333:   if((num_filled=sscanf(line,"ftol=%lf stepm=%d ncovcol=%d nlstate=%d ndeath=%d maxwav=%d mle=%d weight=%d\n", \
                   7334:                        &ftol, &stepm, &ncovcol, &nlstate, &ndeath, &maxwav, &mle, &weightopt)) !=EOF){
                   7335:     if (num_filled != 8) {
1.209     brouard  7336:       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");
                   7337:       printf("but line=%s\n",line);
1.197     brouard  7338:     }
                   7339:     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  7340:   }
1.203     brouard  7341:   /* ftolpl=6*ftol*1.e5; /\* 6.e-3 make convergences in less than 80 loops for the prevalence limit *\/ */
1.209     brouard  7342:   /*ftolpl=6.e-4; *//* 6.e-3 make convergences in less than 80 loops for the prevalence limit */
1.197     brouard  7343:   /* Third parameter line */
                   7344:   while(fgets(line, MAXLINE, ficpar)) {
                   7345:     /* If line starts with a # it is a comment */
                   7346:     if (line[0] == '#') {
                   7347:       numlinepar++;
                   7348:       fputs(line,stdout);
                   7349:       fputs(line,ficparo);
                   7350:       fputs(line,ficlog);
                   7351:       continue;
                   7352:     }else
                   7353:       break;
                   7354:   }
1.201     brouard  7355:   if((num_filled=sscanf(line,"model=1+age%[^.\n]", model)) !=EOF){
                   7356:     if (num_filled == 0)
                   7357:             model[0]='\0';
                   7358:     else if (num_filled != 1){
1.197     brouard  7359:       printf("ERROR %d: Model should be at minimum 'model=1+age.' %s\n",num_filled, line);
                   7360:       fprintf(ficlog,"ERROR %d: Model should be at minimum 'model=1+age.' %s\n",num_filled, line);
                   7361:       model[0]='\0';
                   7362:       goto end;
                   7363:     }
                   7364:     else{
                   7365:       if (model[0]=='+'){
                   7366:        for(i=1; i<=strlen(model);i++)
                   7367:          modeltemp[i-1]=model[i];
1.201     brouard  7368:        strcpy(model,modeltemp); 
1.197     brouard  7369:       }
                   7370:     }
1.199     brouard  7371:     /* printf(" model=1+age%s modeltemp= %s, model=%s\n",model, modeltemp, model);fflush(stdout); */
1.203     brouard  7372:     printf("model=1+age+%s\n",model);fflush(stdout);
1.197     brouard  7373:   }
                   7374:   /* 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); */
                   7375:   /* numlinepar=numlinepar+3; /\* In general *\/ */
                   7376:   /* 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  7377:   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);
                   7378:   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  7379:   fflush(ficlog);
1.190     brouard  7380:   /* if(model[0]=='#'|| model[0]== '\0'){ */
                   7381:   if(model[0]=='#'){
1.187     brouard  7382:     printf("Error in 'model' line: model should start with 'model=1+age+' and end with '.' \n \
                   7383:  'model=1+age+.' or 'model=1+age+V1.' or 'model=1+age+age*age+V1+V1*age.' or \n \
                   7384:  'model=1+age+V1+V2.' or 'model=1+age+V1+V2+V1*V2.' etc. \n");         \
                   7385:     if(mle != -1){
                   7386:       printf("Fix the model line and run imach with mle=-1 to get a correct template of the parameter file.\n");
                   7387:       exit(1);
                   7388:     }
                   7389:   }
1.126     brouard  7390:   while((c=getc(ficpar))=='#' && c!= EOF){
                   7391:     ungetc(c,ficpar);
                   7392:     fgets(line, MAXLINE, ficpar);
                   7393:     numlinepar++;
1.195     brouard  7394:     if(line[1]=='q'){ /* This #q will quit imach (the answer is q) */
                   7395:       z[0]=line[1];
                   7396:     }
                   7397:     /* printf("****line [1] = %c \n",line[1]); */
1.141     brouard  7398:     fputs(line, stdout);
                   7399:     //puts(line);
1.126     brouard  7400:     fputs(line,ficparo);
                   7401:     fputs(line,ficlog);
                   7402:   }
                   7403:   ungetc(c,ficpar);
                   7404: 
                   7405:    
1.145     brouard  7406:   covar=matrix(0,NCOVMAX,1,n);  /**< used in readdata */
1.136     brouard  7407:   cptcovn=0; /*Number of covariates, i.e. number of '+' in model statement plus one, indepently of n in Vn*/
                   7408:   /* v1+v2+v3+v2*v4+v5*age makes cptcovn = 5
                   7409:      v1+v2*age+v2*v3 makes cptcovn = 3
                   7410:   */
                   7411:   if (strlen(model)>1) 
1.187     brouard  7412:     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  7413:   else
1.187     brouard  7414:     ncovmodel=2; /* Constant and age */
1.133     brouard  7415:   nforce= (nlstate+ndeath-1)*nlstate; /* Number of forces ij from state i to j */
                   7416:   npar= nforce*ncovmodel; /* Number of parameters like aij*/
1.131     brouard  7417:   if(npar >MAXPARM || nlstate >NLSTATEMAX || ndeath >NDEATHMAX || ncovmodel>NCOVMAX){
                   7418:     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);
                   7419:     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);
                   7420:     fflush(stdout);
                   7421:     fclose (ficlog);
                   7422:     goto end;
                   7423:   }
1.126     brouard  7424:   delti3= ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel);
                   7425:   delti=delti3[1][1];
                   7426:   /*delti=vector(1,npar); *//* Scale of each paramater (output from hesscov)*/
                   7427:   if(mle==-1){ /* Print a wizard for help writing covariance matrix */
                   7428:     prwizard(ncovmodel, nlstate, ndeath, model, ficparo);
1.191     brouard  7429:     printf(" You chose mle=-1, look at file %s for a template of covariance matrix \n",filereso);
                   7430:     fprintf(ficlog," You chose mle=-1, look at file %s for a template of covariance matrix \n",filereso);
1.126     brouard  7431:     free_ma3x(delti3,1,nlstate,1, nlstate+ndeath-1,1,ncovmodel); 
                   7432:     fclose (ficparo);
                   7433:     fclose (ficlog);
                   7434:     goto end;
                   7435:     exit(0);
                   7436:   }
1.186     brouard  7437:   else if(mle==-3) { /* Main Wizard */
1.126     brouard  7438:     prwizard(ncovmodel, nlstate, ndeath, model, ficparo);
1.192     brouard  7439:     printf(" You chose mle=-3, look at file %s for a template of covariance matrix \n",filereso);
                   7440:     fprintf(ficlog," You chose mle=-3, look at file %s for a template of covariance matrix \n",filereso);
1.126     brouard  7441:     param= ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel);
                   7442:     matcov=matrix(1,npar,1,npar);
1.203     brouard  7443:     hess=matrix(1,npar,1,npar);
1.126     brouard  7444:   }
                   7445:   else{
1.145     brouard  7446:     /* Read guessed parameters */
1.126     brouard  7447:     /* Reads comments: lines beginning with '#' */
                   7448:     while((c=getc(ficpar))=='#' && c!= EOF){
                   7449:       ungetc(c,ficpar);
                   7450:       fgets(line, MAXLINE, ficpar);
                   7451:       numlinepar++;
1.141     brouard  7452:       fputs(line,stdout);
1.126     brouard  7453:       fputs(line,ficparo);
                   7454:       fputs(line,ficlog);
                   7455:     }
                   7456:     ungetc(c,ficpar);
                   7457:     
                   7458:     param= ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel);
                   7459:     for(i=1; i <=nlstate; i++){
                   7460:       j=0;
                   7461:       for(jj=1; jj <=nlstate+ndeath; jj++){
                   7462:        if(jj==i) continue;
                   7463:        j++;
                   7464:        fscanf(ficpar,"%1d%1d",&i1,&j1);
1.193     brouard  7465:        if ((i1 != i) || (j1 != jj)){
1.126     brouard  7466:          printf("Error in line parameters number %d, %1d%1d instead of %1d%1d \n \
                   7467: It might be a problem of design; if ncovcol and the model are correct\n \
                   7468: run imach with mle=-1 to get a correct template of the parameter file.\n",numlinepar, i,j, i1, j1);
                   7469:          exit(1);
                   7470:        }
                   7471:        fprintf(ficparo,"%1d%1d",i1,j1);
                   7472:        if(mle==1)
1.193     brouard  7473:          printf("%1d%1d",i,jj);
                   7474:        fprintf(ficlog,"%1d%1d",i,jj);
1.126     brouard  7475:        for(k=1; k<=ncovmodel;k++){
                   7476:          fscanf(ficpar," %lf",&param[i][j][k]);
                   7477:          if(mle==1){
                   7478:            printf(" %lf",param[i][j][k]);
                   7479:            fprintf(ficlog," %lf",param[i][j][k]);
                   7480:          }
                   7481:          else
                   7482:            fprintf(ficlog," %lf",param[i][j][k]);
                   7483:          fprintf(ficparo," %lf",param[i][j][k]);
                   7484:        }
                   7485:        fscanf(ficpar,"\n");
                   7486:        numlinepar++;
                   7487:        if(mle==1)
                   7488:          printf("\n");
                   7489:        fprintf(ficlog,"\n");
                   7490:        fprintf(ficparo,"\n");
                   7491:       }
                   7492:     }  
                   7493:     fflush(ficlog);
                   7494: 
1.145     brouard  7495:     /* Reads scales values */
1.126     brouard  7496:     p=param[1][1];
                   7497:     
                   7498:     /* Reads comments: lines beginning with '#' */
                   7499:     while((c=getc(ficpar))=='#' && c!= EOF){
                   7500:       ungetc(c,ficpar);
                   7501:       fgets(line, MAXLINE, ficpar);
                   7502:       numlinepar++;
1.141     brouard  7503:       fputs(line,stdout);
1.126     brouard  7504:       fputs(line,ficparo);
                   7505:       fputs(line,ficlog);
                   7506:     }
                   7507:     ungetc(c,ficpar);
                   7508: 
                   7509:     for(i=1; i <=nlstate; i++){
                   7510:       for(j=1; j <=nlstate+ndeath-1; j++){
                   7511:        fscanf(ficpar,"%1d%1d",&i1,&j1);
1.164     brouard  7512:        if ( (i1-i) * (j1-j) != 0){
1.126     brouard  7513:          printf("Error in line parameters number %d, %1d%1d instead of %1d%1d \n",numlinepar, i,j, i1, j1);
                   7514:          exit(1);
                   7515:        }
                   7516:        printf("%1d%1d",i,j);
                   7517:        fprintf(ficparo,"%1d%1d",i1,j1);
                   7518:        fprintf(ficlog,"%1d%1d",i1,j1);
                   7519:        for(k=1; k<=ncovmodel;k++){
                   7520:          fscanf(ficpar,"%le",&delti3[i][j][k]);
                   7521:          printf(" %le",delti3[i][j][k]);
                   7522:          fprintf(ficparo," %le",delti3[i][j][k]);
                   7523:          fprintf(ficlog," %le",delti3[i][j][k]);
                   7524:        }
                   7525:        fscanf(ficpar,"\n");
                   7526:        numlinepar++;
                   7527:        printf("\n");
                   7528:        fprintf(ficparo,"\n");
                   7529:        fprintf(ficlog,"\n");
                   7530:       }
                   7531:     }
                   7532:     fflush(ficlog);
                   7533: 
1.145     brouard  7534:     /* Reads covariance matrix */
1.126     brouard  7535:     delti=delti3[1][1];
                   7536: 
                   7537: 
                   7538:     /* free_ma3x(delti3,1,nlstate,1,nlstate+ndeath-1,1,ncovmodel); */ /* Hasn't to to freed here otherwise delti is no more allocated */
                   7539:   
                   7540:     /* Reads comments: lines beginning with '#' */
                   7541:     while((c=getc(ficpar))=='#' && c!= EOF){
                   7542:       ungetc(c,ficpar);
                   7543:       fgets(line, MAXLINE, ficpar);
                   7544:       numlinepar++;
1.141     brouard  7545:       fputs(line,stdout);
1.126     brouard  7546:       fputs(line,ficparo);
                   7547:       fputs(line,ficlog);
                   7548:     }
                   7549:     ungetc(c,ficpar);
                   7550:   
                   7551:     matcov=matrix(1,npar,1,npar);
1.203     brouard  7552:     hess=matrix(1,npar,1,npar);
1.131     brouard  7553:     for(i=1; i <=npar; i++)
                   7554:       for(j=1; j <=npar; j++) matcov[i][j]=0.;
                   7555:       
1.194     brouard  7556:     /* Scans npar lines */
1.126     brouard  7557:     for(i=1; i <=npar; i++){
1.194     brouard  7558:       count=fscanf(ficpar,"%1d%1d%1d",&i1,&j1,&jk);
                   7559:       if(count != 3){
                   7560:        printf("Error! Error in parameter file %s at line %d after line starting with %1d%1d%1d\n\
                   7561: This is probably because your covariance matrix doesn't \n  contain exactly %d lines corresponding to your model line '1+age+%s'.\n\
                   7562: Please run with mle=-1 to get a correct covariance matrix.\n",optionfile,numlinepar, i1,j1,jk, npar, model);
                   7563:        fprintf(ficlog,"Error! Error in parameter file %s at line %d after line starting with %1d%1d%1d\n\
                   7564: This is probably because your covariance matrix doesn't \n  contain exactly %d lines corresponding to your model line '1+age+%s'.\n\
                   7565: Please run with mle=-1 to get a correct covariance matrix.\n",optionfile,numlinepar, i1,j1,jk, npar, model);
                   7566:        exit(1);
                   7567:       }else
1.126     brouard  7568:       if(mle==1)
1.194     brouard  7569:        printf("%1d%1d%1d",i1,j1,jk);
                   7570:       fprintf(ficlog,"%1d%1d%1d",i1,j1,jk);
                   7571:       fprintf(ficparo,"%1d%1d%1d",i1,j1,jk);
1.126     brouard  7572:       for(j=1; j <=i; j++){
                   7573:        fscanf(ficpar," %le",&matcov[i][j]);
                   7574:        if(mle==1){
                   7575:          printf(" %.5le",matcov[i][j]);
                   7576:        }
                   7577:        fprintf(ficlog," %.5le",matcov[i][j]);
                   7578:        fprintf(ficparo," %.5le",matcov[i][j]);
                   7579:       }
                   7580:       fscanf(ficpar,"\n");
                   7581:       numlinepar++;
                   7582:       if(mle==1)
                   7583:        printf("\n");
                   7584:       fprintf(ficlog,"\n");
                   7585:       fprintf(ficparo,"\n");
                   7586:     }
1.194     brouard  7587:     /* End of read covariance matrix npar lines */
1.126     brouard  7588:     for(i=1; i <=npar; i++)
                   7589:       for(j=i+1;j<=npar;j++)
                   7590:        matcov[i][j]=matcov[j][i];
                   7591:     
                   7592:     if(mle==1)
                   7593:       printf("\n");
                   7594:     fprintf(ficlog,"\n");
                   7595:     
                   7596:     fflush(ficlog);
                   7597:     
                   7598:     /*-------- Rewriting parameter file ----------*/
                   7599:     strcpy(rfileres,"r");    /* "Rparameterfile */
                   7600:     strcat(rfileres,optionfilefiname);    /* Parameter file first name*/
                   7601:     strcat(rfileres,".");    /* */
                   7602:     strcat(rfileres,optionfilext);    /* Other files have txt extension */
                   7603:     if((ficres =fopen(rfileres,"w"))==NULL) {
1.201     brouard  7604:       printf("Problem writing new parameter file: %s\n", rfileres);goto end;
                   7605:       fprintf(ficlog,"Problem writing new parameter file: %s\n", rfileres);goto end;
1.126     brouard  7606:     }
                   7607:     fprintf(ficres,"#%s\n",version);
                   7608:   }    /* End of mle != -3 */
                   7609: 
1.186     brouard  7610:   /*  Main data
                   7611:    */
1.126     brouard  7612:   n= lastobs;
                   7613:   num=lvector(1,n);
                   7614:   moisnais=vector(1,n);
                   7615:   annais=vector(1,n);
                   7616:   moisdc=vector(1,n);
                   7617:   andc=vector(1,n);
                   7618:   agedc=vector(1,n);
                   7619:   cod=ivector(1,n);
                   7620:   weight=vector(1,n);
                   7621:   for(i=1;i<=n;i++) weight[i]=1.0; /* Equal weights, 1 by default */
                   7622:   mint=matrix(1,maxwav,1,n);
                   7623:   anint=matrix(1,maxwav,1,n);
1.131     brouard  7624:   s=imatrix(1,maxwav+1,1,n); /* s[i][j] health state for wave i and individual j */ 
1.126     brouard  7625:   tab=ivector(1,NCOVMAX);
1.144     brouard  7626:   ncodemax=ivector(1,NCOVMAX); /* Number of code per covariate; if O and 1 only, 2**ncov; V1+V2+V3+V4=>16 */
1.192     brouard  7627:   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  7628: 
1.136     brouard  7629:   /* Reads data from file datafile */
                   7630:   if (readdata(datafile, firstobs, lastobs, &imx)==1)
                   7631:     goto end;
                   7632: 
                   7633:   /* Calculation of the number of parameters from char model */
1.137     brouard  7634:     /*    modelsav=V2+V1+V4+age*V3 strb=age*V3 stra=V2+V1+V4 
                   7635:        k=4 (age*V3) Tvar[k=4]= 3 (from V3) Tag[cptcovage=1]=4
                   7636:        k=3 V4 Tvar[k=3]= 4 (from V4)
                   7637:        k=2 V1 Tvar[k=2]= 1 (from V1)
                   7638:        k=1 Tvar[1]=2 (from V2)
                   7639:     */
                   7640:   Tvar=ivector(1,NCOVMAX); /* Was 15 changed to NCOVMAX. */
                   7641:   /*  V2+V1+V4+age*V3 is a model with 4 covariates (3 plus signs). 
                   7642:       For each model-covariate stores the data-covariate id. Tvar[1]=2, Tvar[2]=1, Tvar[3]=4, 
                   7643:       Tvar[4=age*V3] is 3 and 'age' is recorded in Tage.
                   7644:   */
                   7645:   /* For model-covariate k tells which data-covariate to use but
                   7646:     because this model-covariate is a construction we invent a new column
                   7647:     ncovcol + k1
                   7648:     If already ncovcol=4 and model=V2+V1+V1*V4+age*V3
                   7649:     Tvar[3=V1*V4]=4+1 etc */
1.145     brouard  7650:   Tprod=ivector(1,NCOVMAX); /* Gives the position of a product */
1.137     brouard  7651:   /* Tprod[k1=1]=3(=V1*V4) for V2+V1+V1*V4+age*V3
                   7652:      if  V2+V1+V1*V4+age*V3+V3*V2   TProd[k1=2]=5 (V3*V2)
                   7653:   */
1.145     brouard  7654:   Tvaraff=ivector(1,NCOVMAX); /* Unclear */
                   7655:   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  7656:                            * For V3*V2 (in V2+V1+V1*V4+age*V3+V3*V2), V3*V2 position is 2nd. 
                   7657:                            * Tvard[k1=2][1]=3 (V3) Tvard[k1=2][2]=2(V2) */
1.145     brouard  7658:   Tage=ivector(1,NCOVMAX); /* Gives the covariate id of covariates associated with age: V2 + V1 + age*V4 + V3*age
1.137     brouard  7659:                         4 covariates (3 plus signs)
                   7660:                         Tage[1=V3*age]= 4; Tage[2=age*V4] = 3
                   7661:                      */  
1.136     brouard  7662: 
1.186     brouard  7663: /* Main decodemodel */
                   7664: 
1.187     brouard  7665: 
1.136     brouard  7666:   if(decodemodel(model, lastobs) == 1)
                   7667:     goto end;
                   7668: 
1.137     brouard  7669:   if((double)(lastobs-imx)/(double)imx > 1.10){
                   7670:     nbwarn++;
                   7671:     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); 
                   7672:     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); 
                   7673:   }
1.136     brouard  7674:     /*  if(mle==1){*/
1.137     brouard  7675:   if (weightopt != 1) { /* Maximisation without weights. We can have weights different from 1 but want no weight*/
                   7676:     for(i=1;i<=imx;i++) weight[i]=1.0; /* changed to imx */
1.136     brouard  7677:   }
                   7678: 
                   7679:     /*-calculation of age at interview from date of interview and age at death -*/
                   7680:   agev=matrix(1,maxwav,1,imx);
                   7681: 
                   7682:   if(calandcheckages(imx, maxwav, &agemin, &agemax, &nberr, &nbwarn) == 1)
                   7683:     goto end;
                   7684: 
1.126     brouard  7685: 
1.136     brouard  7686:   agegomp=(int)agemin;
                   7687:   free_vector(moisnais,1,n);
                   7688:   free_vector(annais,1,n);
1.126     brouard  7689:   /* free_matrix(mint,1,maxwav,1,n);
                   7690:      free_matrix(anint,1,maxwav,1,n);*/
1.215   ! brouard  7691:   /* free_vector(moisdc,1,n); */
        !          7692:   /* free_vector(andc,1,n); */
1.145     brouard  7693:   /* */
                   7694:   
1.126     brouard  7695:   wav=ivector(1,imx);
1.214     brouard  7696:   /* dh=imatrix(1,lastpass-firstpass+1,1,imx); */
                   7697:   /* bh=imatrix(1,lastpass-firstpass+1,1,imx); */
                   7698:   /* mw=imatrix(1,lastpass-firstpass+1,1,imx); */
                   7699:   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.*/
                   7700:   bh=imatrix(1,lastpass-firstpass+2,1,imx);
                   7701:   mw=imatrix(1,lastpass-firstpass+2,1,imx);
1.126     brouard  7702:    
                   7703:   /* Concatenates waves */
1.214     brouard  7704:   /* Concatenates waves: wav[i] is the number of effective (useful waves) of individual i.
                   7705:      Death is a valid wave (if date is known).
                   7706:      mw[mi][i] is the number of (mi=1 to wav[i]) effective wave out of mi of individual i
                   7707:      dh[m][i] or dh[mw[mi][i]][i] is the delay between two effective waves m=mw[mi][i]
                   7708:      and mw[mi+1][i]. dh depends on stepm.
                   7709:   */
                   7710: 
1.126     brouard  7711:   concatwav(wav, dh, bh, mw, s, agedc, agev,  firstpass, lastpass, imx, nlstate, stepm);
1.145     brouard  7712:   /* */
                   7713:  
1.215   ! brouard  7714:   free_vector(moisdc,1,n);
        !          7715:   free_vector(andc,1,n);
        !          7716: 
1.126     brouard  7717:   /* Routine tricode is to calculate cptcoveff (real number of unique covariates) and to associate covariable number and modality */
                   7718: 
                   7719:   nbcode=imatrix(0,NCOVMAX,0,NCOVMAX); 
                   7720:   ncodemax[1]=1;
1.145     brouard  7721:   Ndum =ivector(-1,NCOVMAX);  
1.187     brouard  7722:   if (ncovmodel-nagesqr > 2 ) /* That is if covariate other than cst, age and age*age */
1.145     brouard  7723:     tricode(Tvar,nbcode,imx, Ndum); /**< Fills nbcode[Tvar[j]][l]; */
1.211     brouard  7724:   /* Nbcode gives the value of the lth modality (currently 1 to 2) of jth covariate, in
1.186     brouard  7725:      V2+V1*age, there are 3 covariates Tvar[2]=1 (V1).*/
1.211     brouard  7726:   /* 1 to ncodemax[j] which is the maximum value of this jth covariate */
1.145     brouard  7727: 
1.200     brouard  7728:   /*  codtab=imatrix(1,100,1,10);*/ /* codtab[h,k]=( (h-1) - mod(k-1,2**(k-1) )/2**(k-1) */
1.198     brouard  7729:   /*printf(" codtab[1,1],codtab[100,10]=%d,%d\n", codtab[1][1],codtabm(100,10));*/
1.186     brouard  7730:   /* codtab gives the value 1 or 2 of the hth combination of k covariates (1 or 2).*/
1.211     brouard  7731:   /* nbcode[Tvaraff[j]][codtabm(h,j)]) : if there are only 2 modalities for a covariate j, 
                   7732:    * codtabm(h,j) gives its value classified at position h and nbcode gives how it is coded 
                   7733:    * (currently 0 or 1) in the data.
                   7734:    * In a loop on h=1 to 2**k, and a loop on j (=1 to k), we get the value of 
                   7735:    * corresponding modality (h,j).
                   7736:    */
                   7737: 
1.145     brouard  7738:   h=0;
                   7739: 
                   7740: 
                   7741:   /*if (cptcovn > 0) */
1.126     brouard  7742:       
1.145     brouard  7743:  
1.126     brouard  7744:   m=pow(2,cptcoveff);
                   7745:  
1.144     brouard  7746:          /**< codtab(h,k)  k   = codtab[h,k]=( (h-1) - mod(k-1,2**(k-1) )/2**(k-1) + 1
1.211     brouard  7747:           * For k=4 covariates, h goes from 1 to m=2**k
                   7748:           * codtabm(h,k)=  (1 & (h-1) >> (k-1)) + 1;
                   7749:            * #define codtabm(h,k)  (1 & (h-1) >> (k-1))+1
1.186     brouard  7750:           *     h\k   1     2     3     4
1.143     brouard  7751:           *______________________________  
                   7752:           *     1 i=1 1 i=1 1 i=1 1 i=1 1
                   7753:           *     2     2     1     1     1
                   7754:           *     3 i=2 1     2     1     1
                   7755:           *     4     2     2     1     1
                   7756:           *     5 i=3 1 i=2 1     2     1
                   7757:           *     6     2     1     2     1
                   7758:           *     7 i=4 1     2     2     1
                   7759:           *     8     2     2     2     1
1.197     brouard  7760:           *     9 i=5 1 i=3 1 i=2 1     2
                   7761:           *    10     2     1     1     2
                   7762:           *    11 i=6 1     2     1     2
                   7763:           *    12     2     2     1     2
                   7764:           *    13 i=7 1 i=4 1     2     2    
                   7765:           *    14     2     1     2     2
                   7766:           *    15 i=8 1     2     2     2
                   7767:           *    16     2     2     2     2
1.143     brouard  7768:           */
1.212     brouard  7769:   /* How to do the opposite? From combination h (=1 to 2**k) how to get the value on the covariates? */
1.211     brouard  7770:      /* from h=5 and m, we get then number of covariates k=log(m)/log(2)=4
                   7771:      * and the value of each covariate?
                   7772:      * V1=1, V2=1, V3=2, V4=1 ?
                   7773:      * h-1=4 and 4 is 0100 or reverse 0010, and +1 is 1121 ok.
                   7774:      * h=6, 6-1=5, 5 is 0101, 1010, 2121, V1=2nd, V2=1st, V3=2nd, V4=1st.
                   7775:      * In order to get the real value in the data, we use nbcode
                   7776:      * nbcode[Tvar[3][2nd]]=1 and nbcode[Tvar[4][1]]=0
                   7777:      * We are keeping this crazy system in order to be able (in the future?) 
                   7778:      * to have more than 2 values (0 or 1) for a covariate.
                   7779:      * #define codtabm(h,k)  (1 & (h-1) >> (k-1))+1
                   7780:      * h=6, k=2? h-1=5=0101, reverse 1010, +1=2121, k=2nd position: value is 1: codtabm(6,2)=1
                   7781:      *              bbbbbbbb
                   7782:      *              76543210     
                   7783:      *   h-1        00000101 (6-1=5)
                   7784:      *(h-1)>>(k-1)= 00000001 >> (2-1) = 1 right shift
                   7785:      *           &
                   7786:      *     1        00000001 (1)
                   7787:      *              00000001        = 1 & ((h-1) >> (k-1))
                   7788:      *          +1= 00000010 =2 
                   7789:      *
                   7790:      * h=14, k=3 => h'=h-1=13, k'=k-1=2
                   7791:      *          h'      1101 =2^3+2^2+0x2^1+2^0
                   7792:      *    >>k'            11
                   7793:      *          &   00000001
                   7794:      *            = 00000001
                   7795:      *      +1    = 00000010=2    =  codtabm(14,3)   
                   7796:      * Reverse h=6 and m=16?
                   7797:      * cptcoveff=log(16)/log(2)=4 covariate: 6-1=5=0101 reversed=1010 +1=2121 =>V1=2, V2=1, V3=2, V4=1.
                   7798:      * for (j=1 to cptcoveff) Vj=decodtabm(j,h,cptcoveff)
                   7799:      * decodtabm(h,j,cptcoveff)= (((h-1) >> (j-1)) & 1) +1 
                   7800:      * decodtabm(h,j,cptcoveff)= (h <= (1<<cptcoveff)?(((h-1) >> (j-1)) & 1) +1 : -1)
                   7801:      * V3=decodtabm(14,3,2**4)=2
                   7802:      *          h'=13   1101 =2^3+2^2+0x2^1+2^0
                   7803:      *(h-1) >> (j-1)    0011 =13 >> 2
                   7804:      *          &1 000000001
                   7805:      *           = 000000001
                   7806:      *         +1= 000000010 =2
                   7807:      *                  2211
                   7808:      *                  V1=1+1, V2=0+1, V3=1+1, V4=1+1
                   7809:      *                  V3=2
                   7810:      */
                   7811: 
1.202     brouard  7812:   /* /\* for(h=1; h <=100 ;h++){  *\/ */
                   7813:   /*   /\* printf("h=%2d ", h); *\/ */
                   7814:   /*    /\* for(k=1; k <=10; k++){ *\/ */
                   7815:   /*      /\* printf("k=%d %d ",k,codtabm(h,k)); *\/ */
                   7816:   /*    /\*   codtab[h][k]=codtabm(h,k); *\/ */
                   7817:   /*    /\* } *\/ */
                   7818:   /*    /\* printf("\n"); *\/ */
                   7819:   /* } */
1.197     brouard  7820:   /* for(k=1;k<=cptcoveff; k++){ /\* scans any effective covariate *\/ */
                   7821:   /*   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 *\/  */
                   7822:   /*     for(j=1; j <= ncodemax[k]; j++){ /\* For each modality of this covariate ncodemax=2*\/ */
                   7823:   /*   for(cpt=1; cpt <=pow(2,k-1); cpt++){  /\* cpt=1 to 8/2**(3+1-1 or 3+1-3) =1 or 4 *\/  */
                   7824:   /*     h++; */
                   7825:   /*     if (h>m)  */
                   7826:   /*       h=1; */
                   7827:   /*     codtab[h][k]=j; */
                   7828:   /*     /\* codtab[12][3]=1; *\/ */
                   7829:   /*     /\*codtab[h][Tvar[k]]=j;*\/ */
                   7830:   /*     /\* 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]]); *\/ */
                   7831:   /*   }  */
                   7832:   /*     } */
                   7833:   /*   } */
                   7834:   /* }  */
1.126     brouard  7835:   /* printf("codtab[1][2]=%d codtab[2][2]=%d",codtab[1][2],codtab[2][2]); 
                   7836:      codtab[1][2]=1;codtab[2][2]=2; */
1.197     brouard  7837:   /* for(i=1; i <=m ;i++){  */
                   7838:   /*    for(k=1; k <=cptcovn; k++){ */
                   7839:   /*      printf("i=%d k=%d %d %d ",i,k,codtab[i][k], cptcoveff); */
                   7840:   /*    } */
                   7841:   /*    printf("\n"); */
                   7842:   /* } */
                   7843:   /*   scanf("%d",i);*/
1.145     brouard  7844: 
                   7845:  free_ivector(Ndum,-1,NCOVMAX);
                   7846: 
                   7847: 
1.126     brouard  7848:     
1.186     brouard  7849:   /* Initialisation of ----------- gnuplot -------------*/
1.126     brouard  7850:   strcpy(optionfilegnuplot,optionfilefiname);
                   7851:   if(mle==-3)
1.201     brouard  7852:     strcat(optionfilegnuplot,"-MORT_");
1.126     brouard  7853:   strcat(optionfilegnuplot,".gp");
                   7854: 
                   7855:   if((ficgp=fopen(optionfilegnuplot,"w"))==NULL) {
                   7856:     printf("Problem with file %s",optionfilegnuplot);
                   7857:   }
                   7858:   else{
1.204     brouard  7859:     fprintf(ficgp,"\n# IMaCh-%s\n", version); 
1.126     brouard  7860:     fprintf(ficgp,"# %s\n", optionfilegnuplot); 
1.141     brouard  7861:     //fprintf(ficgp,"set missing 'NaNq'\n");
                   7862:     fprintf(ficgp,"set datafile missing 'NaNq'\n");
1.126     brouard  7863:   }
                   7864:   /*  fclose(ficgp);*/
1.186     brouard  7865: 
                   7866: 
                   7867:   /* Initialisation of --------- index.htm --------*/
1.126     brouard  7868: 
                   7869:   strcpy(optionfilehtm,optionfilefiname); /* Main html file */
                   7870:   if(mle==-3)
1.201     brouard  7871:     strcat(optionfilehtm,"-MORT_");
1.126     brouard  7872:   strcat(optionfilehtm,".htm");
                   7873:   if((fichtm=fopen(optionfilehtm,"w"))==NULL)    {
1.131     brouard  7874:     printf("Problem with %s \n",optionfilehtm);
                   7875:     exit(0);
1.126     brouard  7876:   }
                   7877: 
                   7878:   strcpy(optionfilehtmcov,optionfilefiname); /* Only for matrix of covariance */
                   7879:   strcat(optionfilehtmcov,"-cov.htm");
                   7880:   if((fichtmcov=fopen(optionfilehtmcov,"w"))==NULL)    {
                   7881:     printf("Problem with %s \n",optionfilehtmcov), exit(0);
                   7882:   }
                   7883:   else{
                   7884:   fprintf(fichtmcov,"<html><head>\n<title>IMaCh Cov %s</title></head>\n <body><font size=\"2\">%s <br> %s</font> \
                   7885: <hr size=\"2\" color=\"#EC5E5E\"> \n\
1.204     brouard  7886: Title=%s <br>Datafile=%s Firstpass=%d Lastpass=%d Stepm=%d Weight=%d Model=1+age+%s<br>\n",\
1.126     brouard  7887:          optionfilehtmcov,version,fullversion,title,datafile,firstpass,lastpass,stepm, weightopt, model);
                   7888:   }
                   7889: 
1.213     brouard  7890:   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  7891: <hr size=\"2\" color=\"#EC5E5E\"> \n\
                   7892: <font size=\"2\">IMaCh-%s <br> %s</font> \
1.126     brouard  7893: <hr size=\"2\" color=\"#EC5E5E\"> \n\
1.204     brouard  7894: Title=%s <br>Datafile=%s Firstpass=%d Lastpass=%d Stepm=%d Weight=%d Model=1+age+%s<br>\n\
1.126     brouard  7895: \n\
                   7896: <hr  size=\"2\" color=\"#EC5E5E\">\
                   7897:  <ul><li><h4>Parameter files</h4>\n\
                   7898:  - Parameter file: <a href=\"%s.%s\">%s.%s</a><br>\n\
                   7899:  - Copy of the parameter file: <a href=\"o%s\">o%s</a><br>\n\
                   7900:  - Log file of the run: <a href=\"%s\">%s</a><br>\n\
                   7901:  - Gnuplot file name: <a href=\"%s\">%s</a><br>\n\
                   7902:  - Date and time at start: %s</ul>\n",\
                   7903:          optionfilehtm,version,fullversion,title,datafile,firstpass,lastpass,stepm, weightopt, model,\
                   7904:          optionfilefiname,optionfilext,optionfilefiname,optionfilext,\
                   7905:          fileres,fileres,\
                   7906:          filelog,filelog,optionfilegnuplot,optionfilegnuplot,strstart);
                   7907:   fflush(fichtm);
                   7908: 
                   7909:   strcpy(pathr,path);
                   7910:   strcat(pathr,optionfilefiname);
1.184     brouard  7911: #ifdef WIN32
                   7912:   _chdir(optionfilefiname); /* Move to directory named optionfile */
                   7913: #else
1.126     brouard  7914:   chdir(optionfilefiname); /* Move to directory named optionfile */
1.184     brouard  7915: #endif
                   7916:          
1.126     brouard  7917:   
                   7918:   /* Calculates basic frequencies. Computes observed prevalence at single age
                   7919:      and prints on file fileres'p'. */
1.214     brouard  7920:   freqsummary(fileres, agemin, agemax, s, agev, nlstate, imx,Tvaraff,nbcode, ncodemax,mint,anint,strstart,\
                   7921:              firstpass, lastpass,  stepm,  weightopt, model);
1.126     brouard  7922: 
                   7923:   fprintf(fichtm,"\n");
                   7924:   fprintf(fichtm,"<br>Total number of observations=%d <br>\n\
                   7925: Youngest age at first (selected) pass %.2f, oldest age %.2f<br>\n\
                   7926: Interval (in months) between two waves: Min=%d Max=%d Mean=%.2lf<br>\n",\
                   7927:          imx,agemin,agemax,jmin,jmax,jmean);
                   7928:   pmmij= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
                   7929:     oldms= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
                   7930:     newms= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
                   7931:     savms= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
                   7932:     oldm=oldms; newm=newms; savm=savms; /* Keeps fixed addresses to free */
                   7933:     
                   7934:    
                   7935:   /* For Powell, parameters are in a vector p[] starting at p[1]
                   7936:      so we point p on param[1][1] so that p[1] maps on param[1][1][1] */
                   7937:   p=param[1][1]; /* *(*(*(param +1)+1)+0) */
                   7938: 
                   7939:   globpr=0; /* To get the number ipmx of contributions and the sum of weights*/
1.186     brouard  7940:   /* For mortality only */
1.126     brouard  7941:   if (mle==-3){
1.136     brouard  7942:     ximort=matrix(1,NDIM,1,NDIM); 
1.186     brouard  7943:     /*     ximort=gsl_matrix_alloc(1,NDIM,1,NDIM); */
1.126     brouard  7944:     cens=ivector(1,n);
                   7945:     ageexmed=vector(1,n);
                   7946:     agecens=vector(1,n);
                   7947:     dcwave=ivector(1,n);
                   7948:  
                   7949:     for (i=1; i<=imx; i++){
                   7950:       dcwave[i]=-1;
                   7951:       for (m=firstpass; m<=lastpass; m++)
                   7952:        if (s[m][i]>nlstate) {
                   7953:          dcwave[i]=m;
                   7954:          /*    printf("i=%d j=%d s=%d dcwave=%d\n",i,j, s[j][i],dcwave[i]);*/
                   7955:          break;
                   7956:        }
                   7957:     }
                   7958: 
                   7959:     for (i=1; i<=imx; i++) {
                   7960:       if (wav[i]>0){
                   7961:        ageexmed[i]=agev[mw[1][i]][i];
                   7962:        j=wav[i];
                   7963:        agecens[i]=1.; 
                   7964: 
                   7965:        if (ageexmed[i]> 1 && wav[i] > 0){
                   7966:          agecens[i]=agev[mw[j][i]][i];
                   7967:          cens[i]= 1;
                   7968:        }else if (ageexmed[i]< 1) 
                   7969:          cens[i]= -1;
                   7970:        if (agedc[i]< AGESUP && agedc[i]>1 && dcwave[i]>firstpass && dcwave[i]<=lastpass)
                   7971:          cens[i]=0 ;
                   7972:       }
                   7973:       else cens[i]=-1;
                   7974:     }
                   7975:     
                   7976:     for (i=1;i<=NDIM;i++) {
                   7977:       for (j=1;j<=NDIM;j++)
                   7978:        ximort[i][j]=(i == j ? 1.0 : 0.0);
                   7979:     }
                   7980:     
1.145     brouard  7981:     /*p[1]=0.0268; p[NDIM]=0.083;*/
1.126     brouard  7982:     /*printf("%lf %lf", p[1], p[2]);*/
                   7983:     
                   7984:     
1.136     brouard  7985: #ifdef GSL
                   7986:     printf("GSL optimization\n");  fprintf(ficlog,"Powell\n");
1.162     brouard  7987: #else
1.126     brouard  7988:     printf("Powell\n");  fprintf(ficlog,"Powell\n");
1.136     brouard  7989: #endif
1.201     brouard  7990:     strcpy(filerespow,"POW-MORT_"); 
                   7991:     strcat(filerespow,fileresu);
1.126     brouard  7992:     if((ficrespow=fopen(filerespow,"w"))==NULL) {
                   7993:       printf("Problem with resultfile: %s\n", filerespow);
                   7994:       fprintf(ficlog,"Problem with resultfile: %s\n", filerespow);
                   7995:     }
1.136     brouard  7996: #ifdef GSL
                   7997:     fprintf(ficrespow,"# GSL optimization\n# iter -2*LL");
1.162     brouard  7998: #else
1.126     brouard  7999:     fprintf(ficrespow,"# Powell\n# iter -2*LL");
1.136     brouard  8000: #endif
1.126     brouard  8001:     /*  for (i=1;i<=nlstate;i++)
                   8002:        for(j=1;j<=nlstate+ndeath;j++)
                   8003:        if(j!=i)fprintf(ficrespow," p%1d%1d",i,j);
                   8004:     */
                   8005:     fprintf(ficrespow,"\n");
1.136     brouard  8006: #ifdef GSL
                   8007:     /* gsl starts here */ 
                   8008:     T = gsl_multimin_fminimizer_nmsimplex;
                   8009:     gsl_multimin_fminimizer *sfm = NULL;
                   8010:     gsl_vector *ss, *x;
                   8011:     gsl_multimin_function minex_func;
                   8012: 
                   8013:     /* Initial vertex size vector */
                   8014:     ss = gsl_vector_alloc (NDIM);
                   8015:     
                   8016:     if (ss == NULL){
                   8017:       GSL_ERROR_VAL ("failed to allocate space for ss", GSL_ENOMEM, 0);
                   8018:     }
                   8019:     /* Set all step sizes to 1 */
                   8020:     gsl_vector_set_all (ss, 0.001);
                   8021: 
                   8022:     /* Starting point */
1.126     brouard  8023:     
1.136     brouard  8024:     x = gsl_vector_alloc (NDIM);
                   8025:     
                   8026:     if (x == NULL){
                   8027:       gsl_vector_free(ss);
                   8028:       GSL_ERROR_VAL ("failed to allocate space for x", GSL_ENOMEM, 0);
                   8029:     }
                   8030:   
                   8031:     /* Initialize method and iterate */
                   8032:     /*     p[1]=0.0268; p[NDIM]=0.083; */
1.186     brouard  8033:     /*     gsl_vector_set(x, 0, 0.0268); */
                   8034:     /*     gsl_vector_set(x, 1, 0.083); */
1.136     brouard  8035:     gsl_vector_set(x, 0, p[1]);
                   8036:     gsl_vector_set(x, 1, p[2]);
                   8037: 
                   8038:     minex_func.f = &gompertz_f;
                   8039:     minex_func.n = NDIM;
                   8040:     minex_func.params = (void *)&p; /* ??? */
                   8041:     
                   8042:     sfm = gsl_multimin_fminimizer_alloc (T, NDIM);
                   8043:     gsl_multimin_fminimizer_set (sfm, &minex_func, x, ss);
                   8044:     
                   8045:     printf("Iterations beginning .....\n\n");
                   8046:     printf("Iter. #    Intercept       Slope     -Log Likelihood     Simplex size\n");
                   8047: 
                   8048:     iteri=0;
                   8049:     while (rval == GSL_CONTINUE){
                   8050:       iteri++;
                   8051:       status = gsl_multimin_fminimizer_iterate(sfm);
                   8052:       
                   8053:       if (status) printf("error: %s\n", gsl_strerror (status));
                   8054:       fflush(0);
                   8055:       
                   8056:       if (status) 
                   8057:         break;
                   8058:       
                   8059:       rval = gsl_multimin_test_size (gsl_multimin_fminimizer_size (sfm), 1e-6);
                   8060:       ssval = gsl_multimin_fminimizer_size (sfm);
                   8061:       
                   8062:       if (rval == GSL_SUCCESS)
                   8063:         printf ("converged to a local maximum at\n");
                   8064:       
                   8065:       printf("%5d ", iteri);
                   8066:       for (it = 0; it < NDIM; it++){
                   8067:        printf ("%10.5f ", gsl_vector_get (sfm->x, it));
                   8068:       }
                   8069:       printf("f() = %-10.5f ssize = %.7f\n", sfm->fval, ssval);
                   8070:     }
                   8071:     
                   8072:     printf("\n\n Please note: Program should be run many times with varying starting points to detemine global maximum\n\n");
                   8073:     
                   8074:     gsl_vector_free(x); /* initial values */
                   8075:     gsl_vector_free(ss); /* inital step size */
                   8076:     for (it=0; it<NDIM; it++){
                   8077:       p[it+1]=gsl_vector_get(sfm->x,it);
                   8078:       fprintf(ficrespow," %.12lf", p[it]);
                   8079:     }
                   8080:     gsl_multimin_fminimizer_free (sfm); /* p *(sfm.x.data) et p *(sfm.x.data+1)  */
                   8081: #endif
                   8082: #ifdef POWELL
                   8083:      powell(p,ximort,NDIM,ftol,&iter,&fret,gompertz);
                   8084: #endif  
1.126     brouard  8085:     fclose(ficrespow);
                   8086:     
1.203     brouard  8087:     hesscov(matcov, hess, p, NDIM, delti, 1e-4, gompertz); 
1.126     brouard  8088: 
                   8089:     for(i=1; i <=NDIM; i++)
                   8090:       for(j=i+1;j<=NDIM;j++)
                   8091:        matcov[i][j]=matcov[j][i];
                   8092:     
                   8093:     printf("\nCovariance matrix\n ");
1.203     brouard  8094:     fprintf(ficlog,"\nCovariance matrix\n ");
1.126     brouard  8095:     for(i=1; i <=NDIM; i++) {
                   8096:       for(j=1;j<=NDIM;j++){ 
                   8097:        printf("%f ",matcov[i][j]);
1.203     brouard  8098:        fprintf(ficlog,"%f ",matcov[i][j]);
1.126     brouard  8099:       }
1.203     brouard  8100:       printf("\n ");  fprintf(ficlog,"\n ");
1.126     brouard  8101:     }
                   8102:     
                   8103:     printf("iter=%d MLE=%f Eq=%lf*exp(%lf*(age-%d))\n",iter,-gompertz(p),p[1],p[2],agegomp);
1.193     brouard  8104:     for (i=1;i<=NDIM;i++) {
1.126     brouard  8105:       printf("%f [%f ; %f]\n",p[i],p[i]-2*sqrt(matcov[i][i]),p[i]+2*sqrt(matcov[i][i]));
1.193     brouard  8106:       fprintf(ficlog,"%f [%f ; %f]\n",p[i],p[i]-2*sqrt(matcov[i][i]),p[i]+2*sqrt(matcov[i][i]));
                   8107:     }
1.126     brouard  8108:     lsurv=vector(1,AGESUP);
                   8109:     lpop=vector(1,AGESUP);
                   8110:     tpop=vector(1,AGESUP);
                   8111:     lsurv[agegomp]=100000;
                   8112:     
                   8113:     for (k=agegomp;k<=AGESUP;k++) {
                   8114:       agemortsup=k;
                   8115:       if (p[1]*exp(p[2]*(k-agegomp))>1) break;
                   8116:     }
                   8117:     
                   8118:     for (k=agegomp;k<agemortsup;k++)
                   8119:       lsurv[k+1]=lsurv[k]-lsurv[k]*(p[1]*exp(p[2]*(k-agegomp)));
                   8120:     
                   8121:     for (k=agegomp;k<agemortsup;k++){
                   8122:       lpop[k]=(lsurv[k]+lsurv[k+1])/2.;
                   8123:       sumlpop=sumlpop+lpop[k];
                   8124:     }
                   8125:     
                   8126:     tpop[agegomp]=sumlpop;
                   8127:     for (k=agegomp;k<(agemortsup-3);k++){
                   8128:       /*  tpop[k+1]=2;*/
                   8129:       tpop[k+1]=tpop[k]-lpop[k];
                   8130:     }
                   8131:     
                   8132:     
                   8133:     printf("\nAge   lx     qx    dx    Lx     Tx     e(x)\n");
                   8134:     for (k=agegomp;k<(agemortsup-2);k++) 
                   8135:       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]);
                   8136:     
                   8137:     
                   8138:     replace_back_to_slash(pathc,pathcd); /* Even gnuplot wants a / */
1.194     brouard  8139:     if(ageminpar == AGEOVERFLOW ||agemaxpar == AGEOVERFLOW){
                   8140:        printf("Warning! Error in gnuplot file with ageminpar %f or agemaxpar %f overflow\n\
                   8141: This is probably because your parameter file doesn't \n  contain the exact number of lines (or columns) corresponding to your model line.\n\
                   8142: Please run with mle=-1 to get a correct covariance matrix.\n",ageminpar,agemaxpar);
                   8143:        fprintf(ficlog,"Warning! Error in gnuplot file with ageminpar %f or agemaxpar %f overflow\n\
                   8144: This is probably because your parameter file doesn't \n  contain the exact number of lines (or columns) corresponding to your model line.\n\
                   8145: Please run with mle=-1 to get a correct covariance matrix.\n",ageminpar,agemaxpar);
                   8146:     }else
1.201     brouard  8147:       printinggnuplotmort(fileresu, optionfilefiname,ageminpar,agemaxpar,fage, pathc,p);
                   8148:     printinghtmlmort(fileresu,title,datafile, firstpass, lastpass, \
1.126     brouard  8149:                     stepm, weightopt,\
                   8150:                     model,imx,p,matcov,agemortsup);
                   8151:     
                   8152:     free_vector(lsurv,1,AGESUP);
                   8153:     free_vector(lpop,1,AGESUP);
                   8154:     free_vector(tpop,1,AGESUP);
1.136     brouard  8155: #ifdef GSL
                   8156:     free_ivector(cens,1,n);
                   8157:     free_vector(agecens,1,n);
                   8158:     free_ivector(dcwave,1,n);
                   8159:     free_matrix(ximort,1,NDIM,1,NDIM);
                   8160: #endif
1.186     brouard  8161:   } /* Endof if mle==-3 mortality only */
1.205     brouard  8162:   /* Standard  */
                   8163:   else{ /* For mle !=- 3, could be 0 or 1 or 4 etc. */
                   8164:     globpr=0;/* Computes sum of likelihood for globpr=1 and funcone */
                   8165:     /* Computes likelihood for initial parameters, uses funcone to compute gpimx and gsw */
1.132     brouard  8166:     likelione(ficres, p, npar, nlstate, &globpr, &ipmx, &sw, &fretone, funcone); /* Prints the contributions to the likelihood */
1.126     brouard  8167:     printf("First Likeli=%12.6f ipmx=%ld sw=%12.6f",fretone,ipmx,sw);
                   8168:     for (k=1; k<=npar;k++)
                   8169:       printf(" %d %8.5f",k,p[k]);
                   8170:     printf("\n");
1.205     brouard  8171:     if(mle>=1){ /* Could be 1 or 2, Real Maximization */
                   8172:       /* mlikeli uses func not funcone */
                   8173:       mlikeli(ficres,p, npar, ncovmodel, nlstate, ftol, func);
                   8174:     }
                   8175:     if(mle==0) {/* No optimization, will print the likelihoods for the datafile */
                   8176:       globpr=0;/* Computes sum of likelihood for globpr=1 and funcone */
                   8177:       /* Computes likelihood for initial parameters, uses funcone to compute gpimx and gsw */
                   8178:       likelione(ficres, p, npar, nlstate, &globpr, &ipmx, &sw, &fretone, funcone); /* Prints the contributions to the likelihood */
                   8179:     }
                   8180:     globpr=1; /* again, to print the individual contributions using computed gpimx and gsw */
1.126     brouard  8181:     likelione(ficres, p, npar, nlstate, &globpr, &ipmx, &sw, &fretone, funcone); /* Prints the contributions to the likelihood */
                   8182:     printf("Second Likeli=%12.6f ipmx=%ld sw=%12.6f",fretone,ipmx,sw);
                   8183:     for (k=1; k<=npar;k++)
                   8184:       printf(" %d %8.5f",k,p[k]);
                   8185:     printf("\n");
                   8186:     
                   8187:     /*--------- results files --------------*/
1.192     brouard  8188:     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  8189:     
                   8190:     
                   8191:     fprintf(ficres,"# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
                   8192:     printf("# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
                   8193:     fprintf(ficlog,"# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
                   8194:     for(i=1,jk=1; i <=nlstate; i++){
                   8195:       for(k=1; k <=(nlstate+ndeath); k++){
                   8196:        if (k != i) {
                   8197:          printf("%d%d ",i,k);
                   8198:          fprintf(ficlog,"%d%d ",i,k);
                   8199:          fprintf(ficres,"%1d%1d ",i,k);
                   8200:          for(j=1; j <=ncovmodel; j++){
1.190     brouard  8201:            printf("%12.7f ",p[jk]);
                   8202:            fprintf(ficlog,"%12.7f ",p[jk]);
                   8203:            fprintf(ficres,"%12.7f ",p[jk]);
1.126     brouard  8204:            jk++; 
                   8205:          }
                   8206:          printf("\n");
                   8207:          fprintf(ficlog,"\n");
                   8208:          fprintf(ficres,"\n");
                   8209:        }
                   8210:       }
                   8211:     }
1.203     brouard  8212:     if(mle != 0){
                   8213:       /* Computing hessian and covariance matrix only at a peak of the Likelihood, that is after optimization */
1.126     brouard  8214:       ftolhess=ftol; /* Usually correct */
1.203     brouard  8215:       hesscov(matcov, hess, p, npar, delti, ftolhess, func);
                   8216:       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");
                   8217:       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");
                   8218:       for(i=1,jk=1; i <=nlstate; i++){
                   8219:        for(k=1; k <=(nlstate+ndeath); k++){
                   8220:          if (k != i) {
                   8221:            printf("%d%d ",i,k);
                   8222:            fprintf(ficlog,"%d%d ",i,k);
                   8223:            for(j=1; j <=ncovmodel; j++){
                   8224:              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]));
                   8225:              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]));
                   8226:              jk++; 
                   8227:            }
                   8228:            printf("\n");
                   8229:            fprintf(ficlog,"\n");
1.193     brouard  8230:          }
                   8231:        }
                   8232:       }
1.203     brouard  8233:     } /* end of hesscov and Wald tests */
1.193     brouard  8234: 
1.203     brouard  8235:     /*  */
1.126     brouard  8236:     fprintf(ficres,"# Scales (for hessian or gradient estimation)\n");
                   8237:     printf("# Scales (for hessian or gradient estimation)\n");
                   8238:     fprintf(ficlog,"# Scales (for hessian or gradient estimation)\n");
                   8239:     for(i=1,jk=1; i <=nlstate; i++){
                   8240:       for(j=1; j <=nlstate+ndeath; j++){
                   8241:        if (j!=i) {
                   8242:          fprintf(ficres,"%1d%1d",i,j);
                   8243:          printf("%1d%1d",i,j);
                   8244:          fprintf(ficlog,"%1d%1d",i,j);
                   8245:          for(k=1; k<=ncovmodel;k++){
                   8246:            printf(" %.5e",delti[jk]);
                   8247:            fprintf(ficlog," %.5e",delti[jk]);
                   8248:            fprintf(ficres," %.5e",delti[jk]);
                   8249:            jk++;
                   8250:          }
                   8251:          printf("\n");
                   8252:          fprintf(ficlog,"\n");
                   8253:          fprintf(ficres,"\n");
                   8254:        }
                   8255:       }
                   8256:     }
                   8257:     
                   8258:     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  8259:     if(mle >= 1) /* To big for the screen */
1.126     brouard  8260:       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");
                   8261:     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");
                   8262:     /* # 121 Var(a12)\n\ */
                   8263:     /* # 122 Cov(b12,a12) Var(b12)\n\ */
                   8264:     /* # 131 Cov(a13,a12) Cov(a13,b12, Var(a13)\n\ */
                   8265:     /* # 132 Cov(b13,a12) Cov(b13,b12, Cov(b13,a13) Var(b13)\n\ */
                   8266:     /* # 212 Cov(a21,a12) Cov(a21,b12, Cov(a21,a13) Cov(a21,b13) Var(a21)\n\ */
                   8267:     /* # 212 Cov(b21,a12) Cov(b21,b12, Cov(b21,a13) Cov(b21,b13) Cov(b21,a21) Var(b21)\n\ */
                   8268:     /* # 232 Cov(a23,a12) Cov(a23,b12, Cov(a23,a13) Cov(a23,b13) Cov(a23,a21) Cov(a23,b21) Var(a23)\n\ */
                   8269:     /* # 232 Cov(b23,a12) Cov(b23,b12) ... Var (b23)\n" */
                   8270:     
                   8271:     
                   8272:     /* Just to have a covariance matrix which will be more understandable
                   8273:        even is we still don't want to manage dictionary of variables
                   8274:     */
                   8275:     for(itimes=1;itimes<=2;itimes++){
                   8276:       jj=0;
                   8277:       for(i=1; i <=nlstate; i++){
                   8278:        for(j=1; j <=nlstate+ndeath; j++){
                   8279:          if(j==i) continue;
                   8280:          for(k=1; k<=ncovmodel;k++){
                   8281:            jj++;
                   8282:            ca[0]= k+'a'-1;ca[1]='\0';
                   8283:            if(itimes==1){
                   8284:              if(mle>=1)
                   8285:                printf("#%1d%1d%d",i,j,k);
                   8286:              fprintf(ficlog,"#%1d%1d%d",i,j,k);
                   8287:              fprintf(ficres,"#%1d%1d%d",i,j,k);
                   8288:            }else{
                   8289:              if(mle>=1)
                   8290:                printf("%1d%1d%d",i,j,k);
                   8291:              fprintf(ficlog,"%1d%1d%d",i,j,k);
                   8292:              fprintf(ficres,"%1d%1d%d",i,j,k);
                   8293:            }
                   8294:            ll=0;
                   8295:            for(li=1;li <=nlstate; li++){
                   8296:              for(lj=1;lj <=nlstate+ndeath; lj++){
                   8297:                if(lj==li) continue;
                   8298:                for(lk=1;lk<=ncovmodel;lk++){
                   8299:                  ll++;
                   8300:                  if(ll<=jj){
                   8301:                    cb[0]= lk +'a'-1;cb[1]='\0';
                   8302:                    if(ll<jj){
                   8303:                      if(itimes==1){
                   8304:                        if(mle>=1)
                   8305:                          printf(" Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
                   8306:                        fprintf(ficlog," Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
                   8307:                        fprintf(ficres," Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
                   8308:                      }else{
                   8309:                        if(mle>=1)
                   8310:                          printf(" %.5e",matcov[jj][ll]); 
                   8311:                        fprintf(ficlog," %.5e",matcov[jj][ll]); 
                   8312:                        fprintf(ficres," %.5e",matcov[jj][ll]); 
                   8313:                      }
                   8314:                    }else{
                   8315:                      if(itimes==1){
                   8316:                        if(mle>=1)
                   8317:                          printf(" Var(%s%1d%1d)",ca,i,j);
                   8318:                        fprintf(ficlog," Var(%s%1d%1d)",ca,i,j);
                   8319:                        fprintf(ficres," Var(%s%1d%1d)",ca,i,j);
                   8320:                      }else{
                   8321:                        if(mle>=1)
1.203     brouard  8322:                          printf(" %.7e",matcov[jj][ll]); 
                   8323:                        fprintf(ficlog," %.7e",matcov[jj][ll]); 
                   8324:                        fprintf(ficres," %.7e",matcov[jj][ll]); 
1.126     brouard  8325:                      }
                   8326:                    }
                   8327:                  }
                   8328:                } /* end lk */
                   8329:              } /* end lj */
                   8330:            } /* end li */
                   8331:            if(mle>=1)
                   8332:              printf("\n");
                   8333:            fprintf(ficlog,"\n");
                   8334:            fprintf(ficres,"\n");
                   8335:            numlinepar++;
                   8336:          } /* end k*/
                   8337:        } /*end j */
                   8338:       } /* end i */
                   8339:     } /* end itimes */
                   8340:     
                   8341:     fflush(ficlog);
                   8342:     fflush(ficres);
1.209     brouard  8343:       while(fgets(line, MAXLINE, ficpar)) {
                   8344:     /* If line starts with a # it is a comment */
                   8345:     if (line[0] == '#') {
                   8346:       numlinepar++;
1.141     brouard  8347:       fputs(line,stdout);
1.126     brouard  8348:       fputs(line,ficparo);
1.209     brouard  8349:       fputs(line,ficlog);
                   8350:       continue;
                   8351:     }else
                   8352:       break;
                   8353:   }
                   8354: 
                   8355:     /* while((c=getc(ficpar))=='#' && c!= EOF){ */
                   8356:     /*   ungetc(c,ficpar); */
                   8357:     /*   fgets(line, MAXLINE, ficpar); */
                   8358:     /*   fputs(line,stdout); */
                   8359:     /*   fputs(line,ficparo); */
                   8360:     /* } */
                   8361:     /* ungetc(c,ficpar); */
1.126     brouard  8362:     
                   8363:     estepm=0;
1.209     brouard  8364:     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){
                   8365: 
                   8366:     if (num_filled != 6) {
                   8367:       printf("Not 6 parameters in line, for example:agemin=60 agemax=95 bage=55 fage=95 estepm=24 ftolpl=6e-4\n");
                   8368:       printf("but line=%s\n",line);
                   8369:       goto end;
                   8370:     }
                   8371:     printf("agemin=%lf agemax=%lf bage=%lf fage=%lf estepm=%d ftolpl=%lf\n",ageminpar,agemaxpar, bage, fage, estepm, ftolpl);
                   8372:   }
                   8373:   /* ftolpl=6*ftol*1.e5; /\* 6.e-3 make convergences in less than 80 loops for the prevalence limit *\/ */
                   8374:   /*ftolpl=6.e-4;*/ /* 6.e-3 make convergences in less than 80 loops for the prevalence limit */
                   8375: 
                   8376:     /* fscanf(ficpar,"agemin=%lf agemax=%lf bage=%lf fage=%lf estepm=%d ftolpl=%\n",&ageminpar,&agemaxpar, &bage, &fage, &estepm); */
1.126     brouard  8377:     if (estepm==0 || estepm < stepm) estepm=stepm;
                   8378:     if (fage <= 2) {
                   8379:       bage = ageminpar;
                   8380:       fage = agemaxpar;
                   8381:     }
                   8382:     
                   8383:     fprintf(ficres,"# agemin agemax for life expectancy, bage fage (if mle==0 ie no data nor Max likelihood).\n");
1.211     brouard  8384:     fprintf(ficres,"agemin=%.0f agemax=%.0f bage=%.0f fage=%.0f estepm=%d ftolpl=%e\n",ageminpar,agemaxpar,bage,fage, estepm, ftolpl);
                   8385:     fprintf(ficparo,"agemin=%.0f agemax=%.0f bage=%.0f fage=%.0f estepm=%d, ftolpl=%e\n",ageminpar,agemaxpar,bage,fage, estepm, ftolpl);
1.186     brouard  8386: 
                   8387:     /* Other stuffs, more or less useful */    
1.126     brouard  8388:     while((c=getc(ficpar))=='#' && c!= EOF){
                   8389:       ungetc(c,ficpar);
                   8390:       fgets(line, MAXLINE, ficpar);
1.141     brouard  8391:       fputs(line,stdout);
1.126     brouard  8392:       fputs(line,ficparo);
                   8393:     }
                   8394:     ungetc(c,ficpar);
                   8395:     
                   8396:     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);
                   8397:     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);
                   8398:     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);
                   8399:     printf("begin-prev-date=%.lf/%.lf/%.lf end-prev-date=%.lf/%.lf/%.lf mov_average=%d\n",jprev1, mprev1,anprev1,jprev2, mprev2,anprev2,mobilav);
                   8400:     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);
                   8401:     
                   8402:     while((c=getc(ficpar))=='#' && c!= EOF){
                   8403:       ungetc(c,ficpar);
                   8404:       fgets(line, MAXLINE, ficpar);
1.141     brouard  8405:       fputs(line,stdout);
1.126     brouard  8406:       fputs(line,ficparo);
                   8407:     }
                   8408:     ungetc(c,ficpar);
                   8409:     
                   8410:     
                   8411:     dateprev1=anprev1+(mprev1-1)/12.+(jprev1-1)/365.;
                   8412:     dateprev2=anprev2+(mprev2-1)/12.+(jprev2-1)/365.;
                   8413:     
                   8414:     fscanf(ficpar,"pop_based=%d\n",&popbased);
1.193     brouard  8415:     fprintf(ficlog,"pop_based=%d\n",popbased);
1.126     brouard  8416:     fprintf(ficparo,"pop_based=%d\n",popbased);   
                   8417:     fprintf(ficres,"pop_based=%d\n",popbased);   
                   8418:     
                   8419:     while((c=getc(ficpar))=='#' && c!= EOF){
                   8420:       ungetc(c,ficpar);
                   8421:       fgets(line, MAXLINE, ficpar);
1.141     brouard  8422:       fputs(line,stdout);
1.126     brouard  8423:       fputs(line,ficparo);
                   8424:     }
                   8425:     ungetc(c,ficpar);
                   8426:     
                   8427:     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);
                   8428:     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);
                   8429:     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);
                   8430:     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);
                   8431:     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);
                   8432:     /* day and month of proj2 are not used but only year anproj2.*/
                   8433:     
                   8434:     
                   8435:     
1.145     brouard  8436:      /* freqsummary(fileres, agemin, agemax, s, agev, nlstate, imx,Tvaraff,nbcode, ncodemax,mint,anint); */
                   8437:     /* ,dateprev1,dateprev2,jprev1, mprev1,anprev1,jprev2, mprev2,anprev2); */
1.126     brouard  8438:     
                   8439:     replace_back_to_slash(pathc,pathcd); /* Even gnuplot wants a / */
1.194     brouard  8440:     if(ageminpar == AGEOVERFLOW ||agemaxpar == -AGEOVERFLOW){
                   8441:        printf("Warning! Error in gnuplot file with ageminpar %f or agemaxpar %f overflow\n\
                   8442: This is probably because your parameter file doesn't \n  contain the exact number of lines (or columns) corresponding to your model line.\n\
                   8443: Please run with mle=-1 to get a correct covariance matrix.\n",ageminpar,agemaxpar);
                   8444:        fprintf(ficlog,"Warning! Error in gnuplot file with ageminpar %f or agemaxpar %f overflow\n\
                   8445: This is probably because your parameter file doesn't \n  contain the exact number of lines (or columns) corresponding to your model line.\n\
                   8446: Please run with mle=-1 to get a correct covariance matrix.\n",ageminpar,agemaxpar);
                   8447:     }else
1.211     brouard  8448:       printinggnuplot(fileresu, optionfilefiname,ageminpar,agemaxpar,fage, prevfcast, pathc,p);
1.126     brouard  8449:     
1.201     brouard  8450:     printinghtml(fileresu,title,datafile, firstpass, lastpass, stepm, weightopt,\
1.211     brouard  8451:                 model,imx,jmin,jmax,jmean,rfileres,popforecast,prevfcast,estepm, \
1.213     brouard  8452:                 jprev1,mprev1,anprev1,dateprev1,jprev2,mprev2,anprev2,dateprev2);
1.126     brouard  8453:       
                   8454:    /*------------ free_vector  -------------*/
                   8455:    /*  chdir(path); */
                   8456:  
1.215   ! brouard  8457:     /* free_ivector(wav,1,imx); */  /* Moved after last prevalence call */
        !          8458:     /* free_imatrix(dh,1,lastpass-firstpass+2,1,imx); */
        !          8459:     /* free_imatrix(bh,1,lastpass-firstpass+2,1,imx); */
        !          8460:     /* free_imatrix(mw,1,lastpass-firstpass+2,1,imx);    */
1.126     brouard  8461:     free_lvector(num,1,n);
                   8462:     free_vector(agedc,1,n);
                   8463:     /*free_matrix(covar,0,NCOVMAX,1,n);*/
                   8464:     /*free_matrix(covar,1,NCOVMAX,1,n);*/
                   8465:     fclose(ficparo);
                   8466:     fclose(ficres);
                   8467: 
                   8468: 
1.186     brouard  8469:     /* Other results (useful)*/
                   8470: 
                   8471: 
1.126     brouard  8472:     /*--------------- Prevalence limit  (period or stable prevalence) --------------*/
1.180     brouard  8473:     /*#include "prevlim.h"*/  /* Use ficrespl, ficlog */
                   8474:     prlim=matrix(1,nlstate,1,nlstate);
1.209     brouard  8475:     prevalence_limit(p, prlim,  ageminpar, agemaxpar, ftolpl, &ncvyear);
1.126     brouard  8476:     fclose(ficrespl);
                   8477: 
1.145     brouard  8478: #ifdef FREEEXIT2
                   8479: #include "freeexit2.h"
                   8480: #endif
                   8481: 
1.126     brouard  8482:     /*------------- h Pij x at various ages ------------*/
1.180     brouard  8483:     /*#include "hpijx.h"*/
                   8484:     hPijx(p, bage, fage);
1.145     brouard  8485:     fclose(ficrespij);
1.126     brouard  8486: 
1.145     brouard  8487:   /*-------------- Variance of one-step probabilities---*/
                   8488:     k=1;
1.126     brouard  8489:     varprob(optionfilefiname, matcov, p, delti, nlstate, bage, fage,k,Tvar,nbcode, ncodemax,strstart);
                   8490: 
                   8491: 
                   8492:     probs= ma3x(1,AGESUP,1,NCOVMAX, 1,NCOVMAX);
                   8493:     for(i=1;i<=AGESUP;i++)
                   8494:       for(j=1;j<=NCOVMAX;j++)
                   8495:        for(k=1;k<=NCOVMAX;k++)
                   8496:          probs[i][j][k]=0.;
                   8497: 
                   8498:     /*---------- Forecasting ------------------*/
                   8499:     /*if((stepm == 1) && (strcmp(model,".")==0)){*/
                   8500:     if(prevfcast==1){
                   8501:       /*    if(stepm ==1){*/
1.201     brouard  8502:       prevforecast(fileresu, anproj1, mproj1, jproj1, agemin, agemax, dateprev1, dateprev2, mobilavproj, bage, fage, firstpass, lastpass, anproj2, p, cptcoveff);
1.126     brouard  8503:       /* (popforecast==1) populforecast(fileres, anpyram,mpyram,jpyram, agemin,agemax, dateprev1, dateprev2,mobilav, agedeb, fage, popforecast, popfile, anpyram1,p, i1);*/
                   8504:       /*      }  */
                   8505:       /*      else{ */
                   8506:       /*        erreur=108; */
                   8507:       /*        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); */
                   8508:       /*        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); */
                   8509:       /*      } */
                   8510:     }
1.186     brouard  8511:  
                   8512:     /* ------ Other prevalence ratios------------ */
1.126     brouard  8513: 
1.127     brouard  8514:     /* Computes prevalence between agemin (i.e minimal age computed) and no more ageminpar */
                   8515: 
                   8516:     prevalence(probs, agemin, agemax, s, agev, nlstate, imx, Tvar, nbcode, ncodemax, mint, anint, dateprev1, dateprev2, firstpass, lastpass);
                   8517:     /*  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",\
                   8518:        ageminpar, agemax, s[lastpass][imx], agev[lastpass][imx], nlstate, imx, mint[lastpass][imx],anint[lastpass][imx], dateprev1, dateprev2, firstpass, lastpass);
                   8519:     */
1.215   ! brouard  8520:     free_ivector(wav,1,imx);
        !          8521:     free_imatrix(dh,1,lastpass-firstpass+2,1,imx);
        !          8522:     free_imatrix(bh,1,lastpass-firstpass+2,1,imx);
        !          8523:     free_imatrix(mw,1,lastpass-firstpass+2,1,imx);   
        !          8524: 
1.126     brouard  8525: 
1.127     brouard  8526:     if (mobilav!=0) {
                   8527:       mobaverage= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
                   8528:       if (movingaverage(probs, bage, fage, mobaverage,mobilav)!=0){
                   8529:        fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav);
                   8530:        printf(" Error in movingaverage mobilav=%d\n",mobilav);
                   8531:       }
1.126     brouard  8532:     }
                   8533: 
                   8534: 
1.127     brouard  8535:     /*---------- Health expectancies, no variances ------------*/
                   8536: 
1.201     brouard  8537:     strcpy(filerese,"E_");
                   8538:     strcat(filerese,fileresu);
1.126     brouard  8539:     if((ficreseij=fopen(filerese,"w"))==NULL) {
                   8540:       printf("Problem with Health Exp. resultfile: %s\n", filerese); exit(0);
                   8541:       fprintf(ficlog,"Problem with Health Exp. resultfile: %s\n", filerese); exit(0);
                   8542:     }
1.208     brouard  8543:     printf("Computing Health Expectancies: result on file '%s' ...", filerese);fflush(stdout);
                   8544:     fprintf(ficlog,"Computing Health Expectancies: result on file '%s' ...", filerese);fflush(ficlog);
1.145     brouard  8545:     /*for(cptcov=1,k=0;cptcov<=i1;cptcov++){
                   8546:       for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){*/
                   8547:           
                   8548:     for (k=1; k <= (int) pow(2,cptcoveff); k++){
1.127     brouard  8549:        fprintf(ficreseij,"\n#****** ");
                   8550:        for(j=1;j<=cptcoveff;j++) {
1.200     brouard  8551:          fprintf(ficreseij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
1.127     brouard  8552:        }
                   8553:        fprintf(ficreseij,"******\n");
                   8554: 
                   8555:        eij=ma3x(1,nlstate,1,nlstate,(int) bage, (int) fage);
                   8556:        oldm=oldms;savm=savms;
                   8557:        evsij(eij, p, nlstate, stepm, (int) bage, (int)fage, oldm, savm, k, estepm, strstart);  
                   8558:       
                   8559:        free_ma3x(eij,1,nlstate,1,nlstate,(int) bage, (int)fage);
1.145     brouard  8560:       /*}*/
1.127     brouard  8561:     }
                   8562:     fclose(ficreseij);
1.208     brouard  8563:     printf("done evsij\n");fflush(stdout);
                   8564:     fprintf(ficlog,"done evsij\n");fflush(ficlog);
1.127     brouard  8565: 
                   8566:     /*---------- Health expectancies and variances ------------*/
                   8567: 
                   8568: 
1.201     brouard  8569:     strcpy(filerest,"T_");
                   8570:     strcat(filerest,fileresu);
1.127     brouard  8571:     if((ficrest=fopen(filerest,"w"))==NULL) {
                   8572:       printf("Problem with total LE resultfile: %s\n", filerest);goto end;
                   8573:       fprintf(ficlog,"Problem with total LE resultfile: %s\n", filerest);goto end;
                   8574:     }
1.208     brouard  8575:     printf("Computing Total Life expectancies with their standard errors: file '%s' ...\n", filerest); fflush(stdout);
                   8576:     fprintf(ficlog,"Computing Total Life expectancies with their standard errors: file '%s' ...\n", filerest); fflush(ficlog);
1.127     brouard  8577: 
1.126     brouard  8578: 
1.201     brouard  8579:     strcpy(fileresstde,"STDE_");
                   8580:     strcat(fileresstde,fileresu);
1.126     brouard  8581:     if((ficresstdeij=fopen(fileresstde,"w"))==NULL) {
                   8582:       printf("Problem with Health Exp. and std errors resultfile: %s\n", fileresstde); exit(0);
                   8583:       fprintf(ficlog,"Problem with Health Exp. and std errors resultfile: %s\n", fileresstde); exit(0);
                   8584:     }
1.208     brouard  8585:     printf("  Computing Health Expectancies and standard errors: result on file '%s' \n", fileresstde);
                   8586:     fprintf(ficlog,"  Computing Health Expectancies and standard errors: result on file '%s' \n", fileresstde);
1.126     brouard  8587: 
1.201     brouard  8588:     strcpy(filerescve,"CVE_");
                   8589:     strcat(filerescve,fileresu);
1.126     brouard  8590:     if((ficrescveij=fopen(filerescve,"w"))==NULL) {
                   8591:       printf("Problem with Covar. Health Exp. resultfile: %s\n", filerescve); exit(0);
                   8592:       fprintf(ficlog,"Problem with Covar. Health Exp. resultfile: %s\n", filerescve); exit(0);
                   8593:     }
1.208     brouard  8594:     printf("    Computing Covar. of Health Expectancies: result on file '%s' \n", filerescve);
                   8595:     fprintf(ficlog,"    Computing Covar. of Health Expectancies: result on file '%s' \n", filerescve);
1.126     brouard  8596: 
1.201     brouard  8597:     strcpy(fileresv,"V_");
                   8598:     strcat(fileresv,fileresu);
1.126     brouard  8599:     if((ficresvij=fopen(fileresv,"w"))==NULL) {
                   8600:       printf("Problem with variance resultfile: %s\n", fileresv);exit(0);
                   8601:       fprintf(ficlog,"Problem with variance resultfile: %s\n", fileresv);exit(0);
                   8602:     }
1.208     brouard  8603:     printf("      Computing Variance-covariance of DFLEs: file '%s' ... ", fileresv);fflush(stdout);
                   8604:     fprintf(ficlog,"      Computing Variance-covariance of DFLEs: file '%s' ... ", fileresv);fflush(ficlog);
1.126     brouard  8605: 
1.145     brouard  8606:     /*for(cptcov=1,k=0;cptcov<=i1;cptcov++){
                   8607:       for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){*/
                   8608:           
                   8609:     for (k=1; k <= (int) pow(2,cptcoveff); k++){
1.208     brouard  8610:       fprintf(ficrest,"\n#****** ");
                   8611:       for(j=1;j<=cptcoveff;j++) 
                   8612:        fprintf(ficrest,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
                   8613:       fprintf(ficrest,"******\n");
                   8614:       
                   8615:       fprintf(ficresstdeij,"\n#****** ");
                   8616:       fprintf(ficrescveij,"\n#****** ");
                   8617:       for(j=1;j<=cptcoveff;j++) {
                   8618:        fprintf(ficresstdeij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
                   8619:        fprintf(ficrescveij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
                   8620:       }
                   8621:       fprintf(ficresstdeij,"******\n");
                   8622:       fprintf(ficrescveij,"******\n");
                   8623:       
                   8624:       fprintf(ficresvij,"\n#****** ");
                   8625:       for(j=1;j<=cptcoveff;j++) 
                   8626:        fprintf(ficresvij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
                   8627:       fprintf(ficresvij,"******\n");
                   8628:       
                   8629:       eij=ma3x(1,nlstate,1,nlstate,(int) bage, (int) fage);
                   8630:       oldm=oldms;savm=savms;
                   8631:       printf(" cvevsij %d, ",k);
                   8632:       fprintf(ficlog, " cvevsij %d, ",k);
                   8633:       cvevsij(eij, p, nlstate, stepm, (int) bage, (int)fage, oldm, savm, k, estepm, delti, matcov, strstart);
                   8634:       printf(" end cvevsij \n ");
                   8635:       fprintf(ficlog, " end cvevsij \n ");
                   8636:       
                   8637:       /*
                   8638:        */
                   8639:       /* goto endfree; */
                   8640:       
                   8641:       vareij=ma3x(1,nlstate,1,nlstate,(int) bage, (int) fage);
                   8642:       pstamp(ficrest);
                   8643:       
                   8644:       
                   8645:       for(vpopbased=0; vpopbased <= popbased; vpopbased++){ /* Done for vpopbased=0 and vpopbased=1 if popbased==1*/
                   8646:        oldm=oldms;savm=savms; /* ZZ Segmentation fault */
                   8647:        cptcod= 0; /* To be deleted */
                   8648:        printf("varevsij %d \n",vpopbased);
                   8649:        fprintf(ficlog, "varevsij %d \n",vpopbased);
1.209     brouard  8650:        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  8651:        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 ");
                   8652:        if(vpopbased==1)
                   8653:          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);
                   8654:        else
                   8655:          fprintf(ficrest,"the age specific period (stable) prevalences in each health state \n");
                   8656:        fprintf(ficrest,"# Age popbased mobilav e.. (std) ");
                   8657:        for (i=1;i<=nlstate;i++) fprintf(ficrest,"e.%d (std) ",i);
                   8658:        fprintf(ficrest,"\n");
                   8659:        /* printf("Which p?\n"); for(i=1;i<=npar;i++)printf("p[i=%d]=%lf,",i,p[i]);printf("\n"); */
                   8660:        epj=vector(1,nlstate+1);
                   8661:        printf("Computing age specific period (stable) prevalences in each health state \n");
                   8662:        fprintf(ficlog,"Computing age specific period (stable) prevalences in each health state \n");
                   8663:        for(age=bage; age <=fage ;age++){
1.209     brouard  8664:          prevalim(prlim, nlstate, p, age, oldm, savm, ftolpl, &ncvyear, k); /*ZZ Is it the correct prevalim */
1.208     brouard  8665:          if (vpopbased==1) {
                   8666:            if(mobilav ==0){
                   8667:              for(i=1; i<=nlstate;i++)
                   8668:                prlim[i][i]=probs[(int)age][i][k];
                   8669:            }else{ /* mobilav */ 
                   8670:              for(i=1; i<=nlstate;i++)
                   8671:                prlim[i][i]=mobaverage[(int)age][i][k];
1.126     brouard  8672:            }
1.208     brouard  8673:          }
                   8674:          
                   8675:          fprintf(ficrest," %4.0f %d %d",age, vpopbased, mobilav);
                   8676:          /* fprintf(ficrest," %4.0f %d %d %d %d",age, vpopbased, mobilav,Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]); */ /* to be done */
                   8677:          /* printf(" age %4.0f ",age); */
                   8678:          for(j=1, epj[nlstate+1]=0.;j <=nlstate;j++){
                   8679:            for(i=1, epj[j]=0.;i <=nlstate;i++) {
                   8680:              epj[j] += prlim[i][i]*eij[i][j][(int)age];
                   8681:              /*ZZZ  printf("%lf %lf ", prlim[i][i] ,eij[i][j][(int)age]);*/
                   8682:              /* printf("%lf %lf ", prlim[i][i] ,eij[i][j][(int)age]); */
1.126     brouard  8683:            }
1.208     brouard  8684:            epj[nlstate+1] +=epj[j];
                   8685:          }
                   8686:          /* printf(" age %4.0f \n",age); */
                   8687:          
                   8688:          for(i=1, vepp=0.;i <=nlstate;i++)
                   8689:            for(j=1;j <=nlstate;j++)
                   8690:              vepp += vareij[i][j][(int)age];
                   8691:          fprintf(ficrest," %7.3f (%7.3f)", epj[nlstate+1],sqrt(vepp));
                   8692:          for(j=1;j <=nlstate;j++){
                   8693:            fprintf(ficrest," %7.3f (%7.3f)", epj[j],sqrt(vareij[j][j][(int)age]));
1.126     brouard  8694:          }
1.208     brouard  8695:          fprintf(ficrest,"\n");
1.126     brouard  8696:        }
1.208     brouard  8697:       } /* End vpopbased */
                   8698:       free_ma3x(eij,1,nlstate,1,nlstate,(int) bage, (int)fage);
                   8699:       free_ma3x(vareij,1,nlstate,1,nlstate,(int) bage, (int)fage);
                   8700:       free_vector(epj,1,nlstate+1);
                   8701:       printf("done \n");fflush(stdout);
                   8702:       fprintf(ficlog,"done\n");fflush(ficlog);
                   8703:       
1.145     brouard  8704:       /*}*/
1.208     brouard  8705:     } /* End k */
1.126     brouard  8706:     free_vector(weight,1,n);
1.145     brouard  8707:     free_imatrix(Tvard,1,NCOVMAX,1,2);
1.126     brouard  8708:     free_imatrix(s,1,maxwav+1,1,n);
                   8709:     free_matrix(anint,1,maxwav,1,n); 
                   8710:     free_matrix(mint,1,maxwav,1,n);
                   8711:     free_ivector(cod,1,n);
                   8712:     free_ivector(tab,1,NCOVMAX);
                   8713:     fclose(ficresstdeij);
                   8714:     fclose(ficrescveij);
                   8715:     fclose(ficresvij);
                   8716:     fclose(ficrest);
1.208     brouard  8717:     printf("done Health expectancies\n");fflush(stdout);
                   8718:     fprintf(ficlog,"done Health expectancies\n");fflush(ficlog);
1.126     brouard  8719:     fclose(ficpar);
                   8720:   
                   8721:     /*------- Variance of period (stable) prevalence------*/   
                   8722: 
1.201     brouard  8723:     strcpy(fileresvpl,"VPL_");
                   8724:     strcat(fileresvpl,fileresu);
1.126     brouard  8725:     if((ficresvpl=fopen(fileresvpl,"w"))==NULL) {
                   8726:       printf("Problem with variance of period (stable) prevalence  resultfile: %s\n", fileresvpl);
                   8727:       exit(0);
                   8728:     }
1.208     brouard  8729:     printf("Computing Variance-covariance of period (stable) prevalence: file '%s' ...", fileresvpl);fflush(stdout);
                   8730:     fprintf(ficlog, "Computing Variance-covariance of period (stable) prevalence: file '%s' ...", fileresvpl);fflush(ficlog);
1.126     brouard  8731: 
1.145     brouard  8732:     /*for(cptcov=1,k=0;cptcov<=i1;cptcov++){
                   8733:       for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){*/
                   8734:           
                   8735:     for (k=1; k <= (int) pow(2,cptcoveff); k++){
                   8736:        fprintf(ficresvpl,"\n#****** ");
1.126     brouard  8737:        for(j=1;j<=cptcoveff;j++) 
1.200     brouard  8738:          fprintf(ficresvpl,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
1.126     brouard  8739:        fprintf(ficresvpl,"******\n");
                   8740:       
                   8741:        varpl=matrix(1,nlstate,(int) bage, (int) fage);
                   8742:        oldm=oldms;savm=savms;
1.209     brouard  8743:        varprevlim(fileres, varpl, matcov, p, delti, nlstate, stepm, (int) bage, (int) fage, oldm, savm, prlim, ftolpl, &ncvyear, k, strstart);
1.126     brouard  8744:        free_matrix(varpl,1,nlstate,(int) bage, (int)fage);
1.145     brouard  8745:       /*}*/
1.126     brouard  8746:     }
                   8747: 
                   8748:     fclose(ficresvpl);
1.208     brouard  8749:     printf("done variance-covariance of period prevalence\n");fflush(stdout);
                   8750:     fprintf(ficlog,"done variance-covariance of period prevalence\n");fflush(ficlog);
1.126     brouard  8751: 
                   8752:     /*---------- End : free ----------------*/
                   8753:     if (mobilav!=0) free_ma3x(mobaverage,1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
                   8754:     free_ma3x(probs,1,AGESUP,1,NCOVMAX, 1,NCOVMAX);
                   8755:   }  /* mle==-3 arrives here for freeing */
1.164     brouard  8756:  /* endfree:*/
1.141     brouard  8757:     free_matrix(prlim,1,nlstate,1,nlstate); /*here or after loop ? */
1.126     brouard  8758:     free_matrix(pmmij,1,nlstate+ndeath,1,nlstate+ndeath);
                   8759:     free_matrix(oldms, 1,nlstate+ndeath,1,nlstate+ndeath);
                   8760:     free_matrix(newms, 1,nlstate+ndeath,1,nlstate+ndeath);
                   8761:     free_matrix(savms, 1,nlstate+ndeath,1,nlstate+ndeath);
                   8762:     free_matrix(covar,0,NCOVMAX,1,n);
                   8763:     free_matrix(matcov,1,npar,1,npar);
1.203     brouard  8764:     free_matrix(hess,1,npar,1,npar);
1.126     brouard  8765:     /*free_vector(delti,1,npar);*/
                   8766:     free_ma3x(delti3,1,nlstate,1, nlstate+ndeath-1,1,ncovmodel); 
                   8767:     free_matrix(agev,1,maxwav,1,imx);
                   8768:     free_ma3x(param,1,nlstate,1, nlstate+ndeath-1,1,ncovmodel);
                   8769: 
1.145     brouard  8770:     free_ivector(ncodemax,1,NCOVMAX);
1.192     brouard  8771:     free_ivector(ncodemaxwundef,1,NCOVMAX);
1.145     brouard  8772:     free_ivector(Tvar,1,NCOVMAX);
                   8773:     free_ivector(Tprod,1,NCOVMAX);
                   8774:     free_ivector(Tvaraff,1,NCOVMAX);
                   8775:     free_ivector(Tage,1,NCOVMAX);
1.126     brouard  8776: 
                   8777:     free_imatrix(nbcode,0,NCOVMAX,0,NCOVMAX);
1.200     brouard  8778:     /* free_imatrix(codtab,1,100,1,10); */
1.126     brouard  8779:   fflush(fichtm);
                   8780:   fflush(ficgp);
                   8781:   
                   8782: 
                   8783:   if((nberr >0) || (nbwarn>0)){
                   8784:     printf("End of Imach with %d errors and/or %d warnings\n",nberr,nbwarn);
                   8785:     fprintf(ficlog,"End of Imach with %d errors and/or warnings %d\n",nberr,nbwarn);
                   8786:   }else{
                   8787:     printf("End of Imach\n");
                   8788:     fprintf(ficlog,"End of Imach\n");
                   8789:   }
                   8790:   printf("See log file on %s\n",filelog);
                   8791:   /*  gettimeofday(&end_time, (struct timezone*)0);*/  /* after time */
1.157     brouard  8792:   /*(void) gettimeofday(&end_time,&tzp);*/
                   8793:   rend_time = time(NULL);  
                   8794:   end_time = *localtime(&rend_time);
                   8795:   /* tml = *localtime(&end_time.tm_sec); */
                   8796:   strcpy(strtend,asctime(&end_time));
1.126     brouard  8797:   printf("Local time at start %s\nLocal time at end   %s",strstart, strtend); 
                   8798:   fprintf(ficlog,"Local time at start %s\nLocal time at end   %s\n",strstart, strtend); 
1.157     brouard  8799:   printf("Total time used %s\n", asc_diff_time(rend_time -rstart_time,tmpout));
1.126     brouard  8800: 
1.157     brouard  8801:   printf("Total time was %.0lf Sec.\n", difftime(rend_time,rstart_time));
                   8802:   fprintf(ficlog,"Total time used %s\n", asc_diff_time(rend_time -rstart_time,tmpout));
                   8803:   fprintf(ficlog,"Total time was %.0lf Sec.\n", difftime(rend_time,rstart_time));
1.126     brouard  8804:   /*  printf("Total time was %d uSec.\n", total_usecs);*/
                   8805: /*   if(fileappend(fichtm,optionfilehtm)){ */
                   8806:   fprintf(fichtm,"<br>Local time at start %s<br>Local time at end   %s<br>\n</body></html>",strstart, strtend);
                   8807:   fclose(fichtm);
                   8808:   fprintf(fichtmcov,"<br>Local time at start %s<br>Local time at end   %s<br>\n</body></html>",strstart, strtend);
                   8809:   fclose(fichtmcov);
                   8810:   fclose(ficgp);
                   8811:   fclose(ficlog);
                   8812:   /*------ End -----------*/
                   8813: 
                   8814: 
                   8815:    printf("Before Current directory %s!\n",pathcd);
1.184     brouard  8816: #ifdef WIN32
                   8817:    if (_chdir(pathcd) != 0)
                   8818:           printf("Can't move to directory %s!\n",path);
                   8819:    if(_getcwd(pathcd,MAXLINE) > 0)
                   8820: #else
1.126     brouard  8821:    if(chdir(pathcd) != 0)
1.184     brouard  8822:           printf("Can't move to directory %s!\n", path);
                   8823:    if (getcwd(pathcd, MAXLINE) > 0)
                   8824: #endif 
1.126     brouard  8825:     printf("Current directory %s!\n",pathcd);
                   8826:   /*strcat(plotcmd,CHARSEPARATOR);*/
                   8827:   sprintf(plotcmd,"gnuplot");
1.157     brouard  8828: #ifdef _WIN32
1.126     brouard  8829:   sprintf(plotcmd,"\"%sgnuplot.exe\"",pathimach);
                   8830: #endif
                   8831:   if(!stat(plotcmd,&info)){
1.158     brouard  8832:     printf("Error or gnuplot program not found: '%s'\n",plotcmd);fflush(stdout);
1.126     brouard  8833:     if(!stat(getenv("GNUPLOTBIN"),&info)){
1.158     brouard  8834:       printf("Error or gnuplot program not found: '%s' Environment GNUPLOTBIN not set.\n",plotcmd);fflush(stdout);
1.126     brouard  8835:     }else
                   8836:       strcpy(pplotcmd,plotcmd);
1.157     brouard  8837: #ifdef __unix
1.126     brouard  8838:     strcpy(plotcmd,GNUPLOTPROGRAM);
                   8839:     if(!stat(plotcmd,&info)){
1.158     brouard  8840:       printf("Error gnuplot program not found: '%s'\n",plotcmd);fflush(stdout);
1.126     brouard  8841:     }else
                   8842:       strcpy(pplotcmd,plotcmd);
                   8843: #endif
                   8844:   }else
                   8845:     strcpy(pplotcmd,plotcmd);
                   8846:   
                   8847:   sprintf(plotcmd,"%s %s",pplotcmd, optionfilegnuplot);
1.158     brouard  8848:   printf("Starting graphs with: '%s'\n",plotcmd);fflush(stdout);
1.126     brouard  8849: 
                   8850:   if((outcmd=system(plotcmd)) != 0){
1.158     brouard  8851:     printf("gnuplot command might not be in your path: '%s', err=%d\n", plotcmd, outcmd);
1.154     brouard  8852:     printf("\n Trying if gnuplot resides on the same directory that IMaCh\n");
1.152     brouard  8853:     sprintf(plotcmd,"%sgnuplot %s", pathimach, optionfilegnuplot);
1.150     brouard  8854:     if((outcmd=system(plotcmd)) != 0)
1.153     brouard  8855:       printf("\n Still a problem with gnuplot command %s, err=%d\n", plotcmd, outcmd);
1.126     brouard  8856:   }
1.158     brouard  8857:   printf(" Successful, please wait...");
1.126     brouard  8858:   while (z[0] != 'q') {
                   8859:     /* chdir(path); */
1.154     brouard  8860:     printf("\nType e to edit results with your browser, g to graph again and q for exit: ");
1.126     brouard  8861:     scanf("%s",z);
                   8862: /*     if (z[0] == 'c') system("./imach"); */
                   8863:     if (z[0] == 'e') {
1.158     brouard  8864: #ifdef __APPLE__
1.152     brouard  8865:       sprintf(pplotcmd, "open %s", optionfilehtm);
1.157     brouard  8866: #elif __linux
                   8867:       sprintf(pplotcmd, "xdg-open %s", optionfilehtm);
1.153     brouard  8868: #else
1.152     brouard  8869:       sprintf(pplotcmd, "%s", optionfilehtm);
1.153     brouard  8870: #endif
                   8871:       printf("Starting browser with: %s",pplotcmd);fflush(stdout);
                   8872:       system(pplotcmd);
1.126     brouard  8873:     }
                   8874:     else if (z[0] == 'g') system(plotcmd);
                   8875:     else if (z[0] == 'q') exit(0);
                   8876:   }
                   8877:   end:
                   8878:   while (z[0] != 'q') {
1.195     brouard  8879:     printf("\nType  q for exiting: "); fflush(stdout);
1.126     brouard  8880:     scanf("%s",z);
                   8881:   }
                   8882: }

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