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

1.206   ! brouard     1: /* $Id: imach.c,v 1.205 2015/10/23 15:50:53 brouard Exp $
1.126     brouard     2:   $State: Exp $
1.163     brouard     3:   $Log: imach.c,v $
1.206   ! brouard     4:   Revision 1.205  2015/10/23 15:50:53  brouard
        !             5:   Summary: 0.98r3 some clarification for graphs on likelihood contributions
        !             6: 
1.205     brouard     7:   Revision 1.204  2015/10/01 16:20:26  brouard
                      8:   Summary: Some new graphs of contribution to likelihood
                      9: 
1.204     brouard    10:   Revision 1.203  2015/09/30 17:45:14  brouard
                     11:   Summary: looking at better estimation of the hessian
                     12: 
                     13:   Also a better criteria for convergence to the period prevalence And
                     14:   therefore adding the number of years needed to converge. (The
                     15:   prevalence in any alive state shold sum to one
                     16: 
1.203     brouard    17:   Revision 1.202  2015/09/22 19:45:16  brouard
                     18:   Summary: Adding some overall graph on contribution to likelihood. Might change
                     19: 
1.202     brouard    20:   Revision 1.201  2015/09/15 17:34:58  brouard
                     21:   Summary: 0.98r0
                     22: 
                     23:   - Some new graphs like suvival functions
                     24:   - Some bugs fixed like model=1+age+V2.
                     25: 
1.201     brouard    26:   Revision 1.200  2015/09/09 16:53:55  brouard
                     27:   Summary: Big bug thanks to Flavia
                     28: 
                     29:   Even model=1+age+V2. did not work anymore
                     30: 
1.200     brouard    31:   Revision 1.199  2015/09/07 14:09:23  brouard
                     32:   Summary: 0.98q6 changing default small png format for graph to vectorized svg.
                     33: 
1.199     brouard    34:   Revision 1.198  2015/09/03 07:14:39  brouard
                     35:   Summary: 0.98q5 Flavia
                     36: 
1.198     brouard    37:   Revision 1.197  2015/09/01 18:24:39  brouard
                     38:   *** empty log message ***
                     39: 
1.197     brouard    40:   Revision 1.196  2015/08/18 23:17:52  brouard
                     41:   Summary: 0.98q5
                     42: 
1.196     brouard    43:   Revision 1.195  2015/08/18 16:28:39  brouard
                     44:   Summary: Adding a hack for testing purpose
                     45: 
                     46:   After reading the title, ftol and model lines, if the comment line has
                     47:   a q, starting with #q, the answer at the end of the run is quit. It
                     48:   permits to run test files in batch with ctest. The former workaround was
                     49:   $ echo q | imach foo.imach
                     50: 
1.195     brouard    51:   Revision 1.194  2015/08/18 13:32:00  brouard
                     52:   Summary:  Adding error when the covariance matrix doesn't contain the exact number of lines required by the model line.
                     53: 
1.194     brouard    54:   Revision 1.193  2015/08/04 07:17:42  brouard
                     55:   Summary: 0.98q4
                     56: 
1.193     brouard    57:   Revision 1.192  2015/07/16 16:49:02  brouard
                     58:   Summary: Fixing some outputs
                     59: 
1.192     brouard    60:   Revision 1.191  2015/07/14 10:00:33  brouard
                     61:   Summary: Some fixes
                     62: 
1.191     brouard    63:   Revision 1.190  2015/05/05 08:51:13  brouard
                     64:   Summary: Adding digits in output parameters (7 digits instead of 6)
                     65: 
                     66:   Fix 1+age+.
                     67: 
1.190     brouard    68:   Revision 1.189  2015/04/30 14:45:16  brouard
                     69:   Summary: 0.98q2
                     70: 
1.189     brouard    71:   Revision 1.188  2015/04/30 08:27:53  brouard
                     72:   *** empty log message ***
                     73: 
1.188     brouard    74:   Revision 1.187  2015/04/29 09:11:15  brouard
                     75:   *** empty log message ***
                     76: 
1.187     brouard    77:   Revision 1.186  2015/04/23 12:01:52  brouard
                     78:   Summary: V1*age is working now, version 0.98q1
                     79: 
                     80:   Some codes had been disabled in order to simplify and Vn*age was
                     81:   working in the optimization phase, ie, giving correct MLE parameters,
                     82:   but, as usual, outputs were not correct and program core dumped.
                     83: 
1.186     brouard    84:   Revision 1.185  2015/03/11 13:26:42  brouard
                     85:   Summary: Inclusion of compile and links command line for Intel Compiler
                     86: 
1.185     brouard    87:   Revision 1.184  2015/03/11 11:52:39  brouard
                     88:   Summary: Back from Windows 8. Intel Compiler
                     89: 
1.184     brouard    90:   Revision 1.183  2015/03/10 20:34:32  brouard
                     91:   Summary: 0.98q0, trying with directest, mnbrak fixed
                     92: 
                     93:   We use directest instead of original Powell test; probably no
                     94:   incidence on the results, but better justifications;
                     95:   We fixed Numerical Recipes mnbrak routine which was wrong and gave
                     96:   wrong results.
                     97: 
1.183     brouard    98:   Revision 1.182  2015/02/12 08:19:57  brouard
                     99:   Summary: Trying to keep directest which seems simpler and more general
                    100:   Author: Nicolas Brouard
                    101: 
1.182     brouard   102:   Revision 1.181  2015/02/11 23:22:24  brouard
                    103:   Summary: Comments on Powell added
                    104: 
                    105:   Author:
                    106: 
1.181     brouard   107:   Revision 1.180  2015/02/11 17:33:45  brouard
                    108:   Summary: Finishing move from main to function (hpijx and prevalence_limit)
                    109: 
1.180     brouard   110:   Revision 1.179  2015/01/04 09:57:06  brouard
                    111:   Summary: back to OS/X
                    112: 
1.179     brouard   113:   Revision 1.178  2015/01/04 09:35:48  brouard
                    114:   *** empty log message ***
                    115: 
1.178     brouard   116:   Revision 1.177  2015/01/03 18:40:56  brouard
                    117:   Summary: Still testing ilc32 on OSX
                    118: 
1.177     brouard   119:   Revision 1.176  2015/01/03 16:45:04  brouard
                    120:   *** empty log message ***
                    121: 
1.176     brouard   122:   Revision 1.175  2015/01/03 16:33:42  brouard
                    123:   *** empty log message ***
                    124: 
1.175     brouard   125:   Revision 1.174  2015/01/03 16:15:49  brouard
                    126:   Summary: Still in cross-compilation
                    127: 
1.174     brouard   128:   Revision 1.173  2015/01/03 12:06:26  brouard
                    129:   Summary: trying to detect cross-compilation
                    130: 
1.173     brouard   131:   Revision 1.172  2014/12/27 12:07:47  brouard
                    132:   Summary: Back from Visual Studio and Intel, options for compiling for Windows XP
                    133: 
1.172     brouard   134:   Revision 1.171  2014/12/23 13:26:59  brouard
                    135:   Summary: Back from Visual C
                    136: 
                    137:   Still problem with utsname.h on Windows
                    138: 
1.171     brouard   139:   Revision 1.170  2014/12/23 11:17:12  brouard
                    140:   Summary: Cleaning some \%% back to %%
                    141: 
                    142:   The escape was mandatory for a specific compiler (which one?), but too many warnings.
                    143: 
1.170     brouard   144:   Revision 1.169  2014/12/22 23:08:31  brouard
                    145:   Summary: 0.98p
                    146: 
                    147:   Outputs some informations on compiler used, OS etc. Testing on different platforms.
                    148: 
1.169     brouard   149:   Revision 1.168  2014/12/22 15:17:42  brouard
1.170     brouard   150:   Summary: update
1.169     brouard   151: 
1.168     brouard   152:   Revision 1.167  2014/12/22 13:50:56  brouard
                    153:   Summary: Testing uname and compiler version and if compiled 32 or 64
                    154: 
                    155:   Testing on Linux 64
                    156: 
1.167     brouard   157:   Revision 1.166  2014/12/22 11:40:47  brouard
                    158:   *** empty log message ***
                    159: 
1.166     brouard   160:   Revision 1.165  2014/12/16 11:20:36  brouard
                    161:   Summary: After compiling on Visual C
                    162: 
                    163:   * imach.c (Module): Merging 1.61 to 1.162
                    164: 
1.165     brouard   165:   Revision 1.164  2014/12/16 10:52:11  brouard
                    166:   Summary: Merging with Visual C after suppressing some warnings for unused variables. Also fixing Saito's bug 0.98Xn
                    167: 
                    168:   * imach.c (Module): Merging 1.61 to 1.162
                    169: 
1.164     brouard   170:   Revision 1.163  2014/12/16 10:30:11  brouard
                    171:   * imach.c (Module): Merging 1.61 to 1.162
                    172: 
1.163     brouard   173:   Revision 1.162  2014/09/25 11:43:39  brouard
                    174:   Summary: temporary backup 0.99!
                    175: 
1.162     brouard   176:   Revision 1.1  2014/09/16 11:06:58  brouard
                    177:   Summary: With some code (wrong) for nlopt
                    178: 
                    179:   Author:
                    180: 
                    181:   Revision 1.161  2014/09/15 20:41:41  brouard
                    182:   Summary: Problem with macro SQR on Intel compiler
                    183: 
1.161     brouard   184:   Revision 1.160  2014/09/02 09:24:05  brouard
                    185:   *** empty log message ***
                    186: 
1.160     brouard   187:   Revision 1.159  2014/09/01 10:34:10  brouard
                    188:   Summary: WIN32
                    189:   Author: Brouard
                    190: 
1.159     brouard   191:   Revision 1.158  2014/08/27 17:11:51  brouard
                    192:   *** empty log message ***
                    193: 
1.158     brouard   194:   Revision 1.157  2014/08/27 16:26:55  brouard
                    195:   Summary: Preparing windows Visual studio version
                    196:   Author: Brouard
                    197: 
                    198:   In order to compile on Visual studio, time.h is now correct and time_t
                    199:   and tm struct should be used. difftime should be used but sometimes I
                    200:   just make the differences in raw time format (time(&now).
                    201:   Trying to suppress #ifdef LINUX
                    202:   Add xdg-open for __linux in order to open default browser.
                    203: 
1.157     brouard   204:   Revision 1.156  2014/08/25 20:10:10  brouard
                    205:   *** empty log message ***
                    206: 
1.156     brouard   207:   Revision 1.155  2014/08/25 18:32:34  brouard
                    208:   Summary: New compile, minor changes
                    209:   Author: Brouard
                    210: 
1.155     brouard   211:   Revision 1.154  2014/06/20 17:32:08  brouard
                    212:   Summary: Outputs now all graphs of convergence to period prevalence
                    213: 
1.154     brouard   214:   Revision 1.153  2014/06/20 16:45:46  brouard
                    215:   Summary: If 3 live state, convergence to period prevalence on same graph
                    216:   Author: Brouard
                    217: 
1.153     brouard   218:   Revision 1.152  2014/06/18 17:54:09  brouard
                    219:   Summary: open browser, use gnuplot on same dir than imach if not found in the path
                    220: 
1.152     brouard   221:   Revision 1.151  2014/06/18 16:43:30  brouard
                    222:   *** empty log message ***
                    223: 
1.151     brouard   224:   Revision 1.150  2014/06/18 16:42:35  brouard
                    225:   Summary: If gnuplot is not in the path try on same directory than imach binary (OSX)
                    226:   Author: brouard
                    227: 
1.150     brouard   228:   Revision 1.149  2014/06/18 15:51:14  brouard
                    229:   Summary: Some fixes in parameter files errors
                    230:   Author: Nicolas Brouard
                    231: 
1.149     brouard   232:   Revision 1.148  2014/06/17 17:38:48  brouard
                    233:   Summary: Nothing new
                    234:   Author: Brouard
                    235: 
                    236:   Just a new packaging for OS/X version 0.98nS
                    237: 
1.148     brouard   238:   Revision 1.147  2014/06/16 10:33:11  brouard
                    239:   *** empty log message ***
                    240: 
1.147     brouard   241:   Revision 1.146  2014/06/16 10:20:28  brouard
                    242:   Summary: Merge
                    243:   Author: Brouard
                    244: 
                    245:   Merge, before building revised version.
                    246: 
1.146     brouard   247:   Revision 1.145  2014/06/10 21:23:15  brouard
                    248:   Summary: Debugging with valgrind
                    249:   Author: Nicolas Brouard
                    250: 
                    251:   Lot of changes in order to output the results with some covariates
                    252:   After the Edimburgh REVES conference 2014, it seems mandatory to
                    253:   improve the code.
                    254:   No more memory valgrind error but a lot has to be done in order to
                    255:   continue the work of splitting the code into subroutines.
                    256:   Also, decodemodel has been improved. Tricode is still not
                    257:   optimal. nbcode should be improved. Documentation has been added in
                    258:   the source code.
                    259: 
1.144     brouard   260:   Revision 1.143  2014/01/26 09:45:38  brouard
                    261:   Summary: Version 0.98nR (to be improved, but gives same optimization results as 0.98k. Nice, promising
                    262: 
                    263:   * imach.c (Module): Trying to merge old staffs together while being at Tokyo. Not tested...
                    264:   (Module): Version 0.98nR Running ok, but output format still only works for three covariates.
                    265: 
1.143     brouard   266:   Revision 1.142  2014/01/26 03:57:36  brouard
                    267:   Summary: gnuplot changed plot w l 1 has to be changed to plot w l lt 2
                    268: 
                    269:   * imach.c (Module): Trying to merge old staffs together while being at Tokyo. Not tested...
                    270: 
1.142     brouard   271:   Revision 1.141  2014/01/26 02:42:01  brouard
                    272:   * imach.c (Module): Trying to merge old staffs together while being at Tokyo. Not tested...
                    273: 
1.141     brouard   274:   Revision 1.140  2011/09/02 10:37:54  brouard
                    275:   Summary: times.h is ok with mingw32 now.
                    276: 
1.140     brouard   277:   Revision 1.139  2010/06/14 07:50:17  brouard
                    278:   After the theft of my laptop, I probably lost some lines of codes which were not uploaded to the CVS tree.
                    279:   I remember having already fixed agemin agemax which are pointers now but not cvs saved.
                    280: 
1.139     brouard   281:   Revision 1.138  2010/04/30 18:19:40  brouard
                    282:   *** empty log message ***
                    283: 
1.138     brouard   284:   Revision 1.137  2010/04/29 18:11:38  brouard
                    285:   (Module): Checking covariates for more complex models
                    286:   than V1+V2. A lot of change to be done. Unstable.
                    287: 
1.137     brouard   288:   Revision 1.136  2010/04/26 20:30:53  brouard
                    289:   (Module): merging some libgsl code. Fixing computation
                    290:   of likelione (using inter/intrapolation if mle = 0) in order to
                    291:   get same likelihood as if mle=1.
                    292:   Some cleaning of code and comments added.
                    293: 
1.136     brouard   294:   Revision 1.135  2009/10/29 15:33:14  brouard
                    295:   (Module): Now imach stops if date of birth, at least year of birth, is not given. Some cleaning of the code.
                    296: 
1.135     brouard   297:   Revision 1.134  2009/10/29 13:18:53  brouard
                    298:   (Module): Now imach stops if date of birth, at least year of birth, is not given. Some cleaning of the code.
                    299: 
1.134     brouard   300:   Revision 1.133  2009/07/06 10:21:25  brouard
                    301:   just nforces
                    302: 
1.133     brouard   303:   Revision 1.132  2009/07/06 08:22:05  brouard
                    304:   Many tings
                    305: 
1.132     brouard   306:   Revision 1.131  2009/06/20 16:22:47  brouard
                    307:   Some dimensions resccaled
                    308: 
1.131     brouard   309:   Revision 1.130  2009/05/26 06:44:34  brouard
                    310:   (Module): Max Covariate is now set to 20 instead of 8. A
                    311:   lot of cleaning with variables initialized to 0. Trying to make
                    312:   V2+V3*age+V1+V4 strb=V3*age+V1+V4 working better.
                    313: 
1.130     brouard   314:   Revision 1.129  2007/08/31 13:49:27  lievre
                    315:   Modification of the way of exiting when the covariate is not binary in order to see on the window the error message before exiting
                    316: 
1.129     lievre    317:   Revision 1.128  2006/06/30 13:02:05  brouard
                    318:   (Module): Clarifications on computing e.j
                    319: 
1.128     brouard   320:   Revision 1.127  2006/04/28 18:11:50  brouard
                    321:   (Module): Yes the sum of survivors was wrong since
                    322:   imach-114 because nhstepm was no more computed in the age
                    323:   loop. Now we define nhstepma in the age loop.
                    324:   (Module): In order to speed up (in case of numerous covariates) we
                    325:   compute health expectancies (without variances) in a first step
                    326:   and then all the health expectancies with variances or standard
                    327:   deviation (needs data from the Hessian matrices) which slows the
                    328:   computation.
                    329:   In the future we should be able to stop the program is only health
                    330:   expectancies and graph are needed without standard deviations.
                    331: 
1.127     brouard   332:   Revision 1.126  2006/04/28 17:23:28  brouard
                    333:   (Module): Yes the sum of survivors was wrong since
                    334:   imach-114 because nhstepm was no more computed in the age
                    335:   loop. Now we define nhstepma in the age loop.
                    336:   Version 0.98h
                    337: 
1.126     brouard   338:   Revision 1.125  2006/04/04 15:20:31  lievre
                    339:   Errors in calculation of health expectancies. Age was not initialized.
                    340:   Forecasting file added.
                    341: 
                    342:   Revision 1.124  2006/03/22 17:13:53  lievre
                    343:   Parameters are printed with %lf instead of %f (more numbers after the comma).
                    344:   The log-likelihood is printed in the log file
                    345: 
                    346:   Revision 1.123  2006/03/20 10:52:43  brouard
                    347:   * imach.c (Module): <title> changed, corresponds to .htm file
                    348:   name. <head> headers where missing.
                    349: 
                    350:   * imach.c (Module): Weights can have a decimal point as for
                    351:   English (a comma might work with a correct LC_NUMERIC environment,
                    352:   otherwise the weight is truncated).
                    353:   Modification of warning when the covariates values are not 0 or
                    354:   1.
                    355:   Version 0.98g
                    356: 
                    357:   Revision 1.122  2006/03/20 09:45:41  brouard
                    358:   (Module): Weights can have a decimal point as for
                    359:   English (a comma might work with a correct LC_NUMERIC environment,
                    360:   otherwise the weight is truncated).
                    361:   Modification of warning when the covariates values are not 0 or
                    362:   1.
                    363:   Version 0.98g
                    364: 
                    365:   Revision 1.121  2006/03/16 17:45:01  lievre
                    366:   * imach.c (Module): Comments concerning covariates added
                    367: 
                    368:   * imach.c (Module): refinements in the computation of lli if
                    369:   status=-2 in order to have more reliable computation if stepm is
                    370:   not 1 month. Version 0.98f
                    371: 
                    372:   Revision 1.120  2006/03/16 15:10:38  lievre
                    373:   (Module): refinements in the computation of lli if
                    374:   status=-2 in order to have more reliable computation if stepm is
                    375:   not 1 month. Version 0.98f
                    376: 
                    377:   Revision 1.119  2006/03/15 17:42:26  brouard
                    378:   (Module): Bug if status = -2, the loglikelihood was
                    379:   computed as likelihood omitting the logarithm. Version O.98e
                    380: 
                    381:   Revision 1.118  2006/03/14 18:20:07  brouard
                    382:   (Module): varevsij Comments added explaining the second
                    383:   table of variances if popbased=1 .
                    384:   (Module): Covariances of eij, ekl added, graphs fixed, new html link.
                    385:   (Module): Function pstamp added
                    386:   (Module): Version 0.98d
                    387: 
                    388:   Revision 1.117  2006/03/14 17:16:22  brouard
                    389:   (Module): varevsij Comments added explaining the second
                    390:   table of variances if popbased=1 .
                    391:   (Module): Covariances of eij, ekl added, graphs fixed, new html link.
                    392:   (Module): Function pstamp added
                    393:   (Module): Version 0.98d
                    394: 
                    395:   Revision 1.116  2006/03/06 10:29:27  brouard
                    396:   (Module): Variance-covariance wrong links and
                    397:   varian-covariance of ej. is needed (Saito).
                    398: 
                    399:   Revision 1.115  2006/02/27 12:17:45  brouard
                    400:   (Module): One freematrix added in mlikeli! 0.98c
                    401: 
                    402:   Revision 1.114  2006/02/26 12:57:58  brouard
                    403:   (Module): Some improvements in processing parameter
                    404:   filename with strsep.
                    405: 
                    406:   Revision 1.113  2006/02/24 14:20:24  brouard
                    407:   (Module): Memory leaks checks with valgrind and:
                    408:   datafile was not closed, some imatrix were not freed and on matrix
                    409:   allocation too.
                    410: 
                    411:   Revision 1.112  2006/01/30 09:55:26  brouard
                    412:   (Module): Back to gnuplot.exe instead of wgnuplot.exe
                    413: 
                    414:   Revision 1.111  2006/01/25 20:38:18  brouard
                    415:   (Module): Lots of cleaning and bugs added (Gompertz)
                    416:   (Module): Comments can be added in data file. Missing date values
                    417:   can be a simple dot '.'.
                    418: 
                    419:   Revision 1.110  2006/01/25 00:51:50  brouard
                    420:   (Module): Lots of cleaning and bugs added (Gompertz)
                    421: 
                    422:   Revision 1.109  2006/01/24 19:37:15  brouard
                    423:   (Module): Comments (lines starting with a #) are allowed in data.
                    424: 
                    425:   Revision 1.108  2006/01/19 18:05:42  lievre
                    426:   Gnuplot problem appeared...
                    427:   To be fixed
                    428: 
                    429:   Revision 1.107  2006/01/19 16:20:37  brouard
                    430:   Test existence of gnuplot in imach path
                    431: 
                    432:   Revision 1.106  2006/01/19 13:24:36  brouard
                    433:   Some cleaning and links added in html output
                    434: 
                    435:   Revision 1.105  2006/01/05 20:23:19  lievre
                    436:   *** empty log message ***
                    437: 
                    438:   Revision 1.104  2005/09/30 16:11:43  lievre
                    439:   (Module): sump fixed, loop imx fixed, and simplifications.
                    440:   (Module): If the status is missing at the last wave but we know
                    441:   that the person is alive, then we can code his/her status as -2
                    442:   (instead of missing=-1 in earlier versions) and his/her
                    443:   contributions to the likelihood is 1 - Prob of dying from last
                    444:   health status (= 1-p13= p11+p12 in the easiest case of somebody in
                    445:   the healthy state at last known wave). Version is 0.98
                    446: 
                    447:   Revision 1.103  2005/09/30 15:54:49  lievre
                    448:   (Module): sump fixed, loop imx fixed, and simplifications.
                    449: 
                    450:   Revision 1.102  2004/09/15 17:31:30  brouard
                    451:   Add the possibility to read data file including tab characters.
                    452: 
                    453:   Revision 1.101  2004/09/15 10:38:38  brouard
                    454:   Fix on curr_time
                    455: 
                    456:   Revision 1.100  2004/07/12 18:29:06  brouard
                    457:   Add version for Mac OS X. Just define UNIX in Makefile
                    458: 
                    459:   Revision 1.99  2004/06/05 08:57:40  brouard
                    460:   *** empty log message ***
                    461: 
                    462:   Revision 1.98  2004/05/16 15:05:56  brouard
                    463:   New version 0.97 . First attempt to estimate force of mortality
                    464:   directly from the data i.e. without the need of knowing the health
                    465:   state at each age, but using a Gompertz model: log u =a + b*age .
                    466:   This is the basic analysis of mortality and should be done before any
                    467:   other analysis, in order to test if the mortality estimated from the
                    468:   cross-longitudinal survey is different from the mortality estimated
                    469:   from other sources like vital statistic data.
                    470: 
                    471:   The same imach parameter file can be used but the option for mle should be -3.
                    472: 
1.133     brouard   473:   Agnès, who wrote this part of the code, tried to keep most of the
1.126     brouard   474:   former routines in order to include the new code within the former code.
                    475: 
                    476:   The output is very simple: only an estimate of the intercept and of
                    477:   the slope with 95% confident intervals.
                    478: 
                    479:   Current limitations:
                    480:   A) Even if you enter covariates, i.e. with the
                    481:   model= V1+V2 equation for example, the programm does only estimate a unique global model without covariates.
                    482:   B) There is no computation of Life Expectancy nor Life Table.
                    483: 
                    484:   Revision 1.97  2004/02/20 13:25:42  lievre
                    485:   Version 0.96d. Population forecasting command line is (temporarily)
                    486:   suppressed.
                    487: 
                    488:   Revision 1.96  2003/07/15 15:38:55  brouard
                    489:   * imach.c (Repository): Errors in subdirf, 2, 3 while printing tmpout is
                    490:   rewritten within the same printf. Workaround: many printfs.
                    491: 
                    492:   Revision 1.95  2003/07/08 07:54:34  brouard
                    493:   * imach.c (Repository):
                    494:   (Repository): Using imachwizard code to output a more meaningful covariance
                    495:   matrix (cov(a12,c31) instead of numbers.
                    496: 
                    497:   Revision 1.94  2003/06/27 13:00:02  brouard
                    498:   Just cleaning
                    499: 
                    500:   Revision 1.93  2003/06/25 16:33:55  brouard
                    501:   (Module): On windows (cygwin) function asctime_r doesn't
                    502:   exist so I changed back to asctime which exists.
                    503:   (Module): Version 0.96b
                    504: 
                    505:   Revision 1.92  2003/06/25 16:30:45  brouard
                    506:   (Module): On windows (cygwin) function asctime_r doesn't
                    507:   exist so I changed back to asctime which exists.
                    508: 
                    509:   Revision 1.91  2003/06/25 15:30:29  brouard
                    510:   * imach.c (Repository): Duplicated warning errors corrected.
                    511:   (Repository): Elapsed time after each iteration is now output. It
                    512:   helps to forecast when convergence will be reached. Elapsed time
                    513:   is stamped in powell.  We created a new html file for the graphs
                    514:   concerning matrix of covariance. It has extension -cov.htm.
                    515: 
                    516:   Revision 1.90  2003/06/24 12:34:15  brouard
                    517:   (Module): Some bugs corrected for windows. Also, when
                    518:   mle=-1 a template is output in file "or"mypar.txt with the design
                    519:   of the covariance matrix to be input.
                    520: 
                    521:   Revision 1.89  2003/06/24 12:30:52  brouard
                    522:   (Module): Some bugs corrected for windows. Also, when
                    523:   mle=-1 a template is output in file "or"mypar.txt with the design
                    524:   of the covariance matrix to be input.
                    525: 
                    526:   Revision 1.88  2003/06/23 17:54:56  brouard
                    527:   * 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.
                    528: 
                    529:   Revision 1.87  2003/06/18 12:26:01  brouard
                    530:   Version 0.96
                    531: 
                    532:   Revision 1.86  2003/06/17 20:04:08  brouard
                    533:   (Module): Change position of html and gnuplot routines and added
                    534:   routine fileappend.
                    535: 
                    536:   Revision 1.85  2003/06/17 13:12:43  brouard
                    537:   * imach.c (Repository): Check when date of death was earlier that
                    538:   current date of interview. It may happen when the death was just
                    539:   prior to the death. In this case, dh was negative and likelihood
                    540:   was wrong (infinity). We still send an "Error" but patch by
                    541:   assuming that the date of death was just one stepm after the
                    542:   interview.
                    543:   (Repository): Because some people have very long ID (first column)
                    544:   we changed int to long in num[] and we added a new lvector for
                    545:   memory allocation. But we also truncated to 8 characters (left
                    546:   truncation)
                    547:   (Repository): No more line truncation errors.
                    548: 
                    549:   Revision 1.84  2003/06/13 21:44:43  brouard
                    550:   * imach.c (Repository): Replace "freqsummary" at a correct
                    551:   place. It differs from routine "prevalence" which may be called
                    552:   many times. Probs is memory consuming and must be used with
                    553:   parcimony.
                    554:   Version 0.95a3 (should output exactly the same maximization than 0.8a2)
                    555: 
                    556:   Revision 1.83  2003/06/10 13:39:11  lievre
                    557:   *** empty log message ***
                    558: 
                    559:   Revision 1.82  2003/06/05 15:57:20  brouard
                    560:   Add log in  imach.c and  fullversion number is now printed.
                    561: 
                    562: */
                    563: /*
                    564:    Interpolated Markov Chain
                    565: 
                    566:   Short summary of the programme:
                    567:   
                    568:   This program computes Healthy Life Expectancies from
                    569:   cross-longitudinal data. Cross-longitudinal data consist in: -1- a
                    570:   first survey ("cross") where individuals from different ages are
                    571:   interviewed on their health status or degree of disability (in the
                    572:   case of a health survey which is our main interest) -2- at least a
                    573:   second wave of interviews ("longitudinal") which measure each change
                    574:   (if any) in individual health status.  Health expectancies are
                    575:   computed from the time spent in each health state according to a
                    576:   model. More health states you consider, more time is necessary to reach the
                    577:   Maximum Likelihood of the parameters involved in the model.  The
                    578:   simplest model is the multinomial logistic model where pij is the
                    579:   probability to be observed in state j at the second wave
                    580:   conditional to be observed in state i at the first wave. Therefore
                    581:   the model is: log(pij/pii)= aij + bij*age+ cij*sex + etc , where
                    582:   'age' is age and 'sex' is a covariate. If you want to have a more
                    583:   complex model than "constant and age", you should modify the program
                    584:   where the markup *Covariates have to be included here again* invites
                    585:   you to do it.  More covariates you add, slower the
                    586:   convergence.
                    587: 
                    588:   The advantage of this computer programme, compared to a simple
                    589:   multinomial logistic model, is clear when the delay between waves is not
                    590:   identical for each individual. Also, if a individual missed an
                    591:   intermediate interview, the information is lost, but taken into
                    592:   account using an interpolation or extrapolation.  
                    593: 
                    594:   hPijx is the probability to be observed in state i at age x+h
                    595:   conditional to the observed state i at age x. The delay 'h' can be
                    596:   split into an exact number (nh*stepm) of unobserved intermediate
                    597:   states. This elementary transition (by month, quarter,
                    598:   semester or year) is modelled as a multinomial logistic.  The hPx
                    599:   matrix is simply the matrix product of nh*stepm elementary matrices
                    600:   and the contribution of each individual to the likelihood is simply
                    601:   hPijx.
                    602: 
                    603:   Also this programme outputs the covariance matrix of the parameters but also
                    604:   of the life expectancies. It also computes the period (stable) prevalence. 
                    605:   
1.133     brouard   606:   Authors: Nicolas Brouard (brouard@ined.fr) and Agnès Lièvre (lievre@ined.fr).
                    607:            Institut national d'études démographiques, Paris.
1.126     brouard   608:   This software have been partly granted by Euro-REVES, a concerted action
                    609:   from the European Union.
                    610:   It is copyrighted identically to a GNU software product, ie programme and
                    611:   software can be distributed freely for non commercial use. Latest version
                    612:   can be accessed at http://euroreves.ined.fr/imach .
                    613: 
                    614:   Help to debug: LD_PRELOAD=/usr/local/lib/libnjamd.so ./imach foo.imach
                    615:   or better on gdb : set env LD_PRELOAD=/usr/local/lib/libnjamd.so
                    616:   
                    617:   **********************************************************************/
                    618: /*
                    619:   main
                    620:   read parameterfile
                    621:   read datafile
                    622:   concatwav
                    623:   freqsummary
                    624:   if (mle >= 1)
                    625:     mlikeli
                    626:   print results files
                    627:   if mle==1 
                    628:      computes hessian
                    629:   read end of parameter file: agemin, agemax, bage, fage, estepm
                    630:       begin-prev-date,...
                    631:   open gnuplot file
                    632:   open html file
1.145     brouard   633:   period (stable) prevalence      | pl_nom    1-1 2-2 etc by covariate
                    634:    for age prevalim()             | #****** V1=0  V2=1  V3=1  V4=0 ******
                    635:                                   | 65 1 0 2 1 3 1 4 0  0.96326 0.03674
                    636:     freexexit2 possible for memory heap.
                    637: 
                    638:   h Pij x                         | pij_nom  ficrestpij
                    639:    # Cov Agex agex+h hpijx with i,j= 1-1 1-2     1-3     2-1     2-2     2-3
                    640:        1  85   85    1.00000             0.00000 0.00000 0.00000 1.00000 0.00000
                    641:        1  85   86    0.68299             0.22291 0.09410 0.71093 0.00000 0.28907
                    642: 
                    643:        1  65   99    0.00364             0.00322 0.99314 0.00350 0.00310 0.99340
                    644:        1  65  100    0.00214             0.00204 0.99581 0.00206 0.00196 0.99597
                    645:   variance of p one-step probabilities varprob  | prob_nom   ficresprob #One-step probabilities and stand. devi in ()
                    646:    Standard deviation of one-step probabilities | probcor_nom   ficresprobcor #One-step probabilities and correlation matrix
                    647:    Matrix of variance covariance of one-step probabilities |  probcov_nom ficresprobcov #One-step probabilities and covariance matrix
                    648: 
1.126     brouard   649:   forecasting if prevfcast==1 prevforecast call prevalence()
                    650:   health expectancies
                    651:   Variance-covariance of DFLE
                    652:   prevalence()
                    653:    movingaverage()
                    654:   varevsij() 
                    655:   if popbased==1 varevsij(,popbased)
                    656:   total life expectancies
                    657:   Variance of period (stable) prevalence
                    658:  end
                    659: */
                    660: 
1.187     brouard   661: /* #define DEBUG */
                    662: /* #define DEBUGBRENT */
1.203     brouard   663: /* #define DEBUGLINMIN */
                    664: /* #define DEBUGHESS */
                    665: #define DEBUGHESSIJ
                    666: /* #define LINMINORIGINAL  /\* Don't use loop on scale in linmin (accepting nan)*\/ */
1.165     brouard   667: #define POWELL /* Instead of NLOPT */
1.192     brouard   668: #define POWELLF1F3 /* Skip test */
1.186     brouard   669: /* #define POWELLORIGINAL /\* Don't use Directest to decide new direction but original Powell test *\/ */
                    670: /* #define MNBRAKORIGINAL /\* Don't use mnbrak fix *\/ */
1.126     brouard   671: 
                    672: #include <math.h>
                    673: #include <stdio.h>
                    674: #include <stdlib.h>
                    675: #include <string.h>
1.159     brouard   676: 
                    677: #ifdef _WIN32
                    678: #include <io.h>
1.172     brouard   679: #include <windows.h>
                    680: #include <tchar.h>
1.159     brouard   681: #else
1.126     brouard   682: #include <unistd.h>
1.159     brouard   683: #endif
1.126     brouard   684: 
                    685: #include <limits.h>
                    686: #include <sys/types.h>
1.171     brouard   687: 
                    688: #if defined(__GNUC__)
                    689: #include <sys/utsname.h> /* Doesn't work on Windows */
                    690: #endif
                    691: 
1.126     brouard   692: #include <sys/stat.h>
                    693: #include <errno.h>
1.159     brouard   694: /* extern int errno; */
1.126     brouard   695: 
1.157     brouard   696: /* #ifdef LINUX */
                    697: /* #include <time.h> */
                    698: /* #include "timeval.h" */
                    699: /* #else */
                    700: /* #include <sys/time.h> */
                    701: /* #endif */
                    702: 
1.126     brouard   703: #include <time.h>
                    704: 
1.136     brouard   705: #ifdef GSL
                    706: #include <gsl/gsl_errno.h>
                    707: #include <gsl/gsl_multimin.h>
                    708: #endif
                    709: 
1.167     brouard   710: 
1.162     brouard   711: #ifdef NLOPT
                    712: #include <nlopt.h>
                    713: typedef struct {
                    714:   double (* function)(double [] );
                    715: } myfunc_data ;
                    716: #endif
                    717: 
1.126     brouard   718: /* #include <libintl.h> */
                    719: /* #define _(String) gettext (String) */
                    720: 
1.141     brouard   721: #define MAXLINE 1024 /* Was 256. Overflow with 312 with 2 states and 4 covariates. Should be ok */
1.126     brouard   722: 
                    723: #define GNUPLOTPROGRAM "gnuplot"
                    724: /*#define GNUPLOTPROGRAM "..\\gp37mgw\\wgnuplot"*/
                    725: #define FILENAMELENGTH 132
                    726: 
                    727: #define        GLOCK_ERROR_NOPATH              -1      /* empty path */
                    728: #define        GLOCK_ERROR_GETCWD              -2      /* cannot get cwd */
                    729: 
1.144     brouard   730: #define MAXPARM 128 /**< Maximum number of parameters for the optimization */
                    731: #define NPARMAX 64 /**< (nlstate+ndeath-1)*nlstate*ncovmodel */
1.126     brouard   732: 
                    733: #define NINTERVMAX 8
1.144     brouard   734: #define NLSTATEMAX 8 /**< Maximum number of live states (for func) */
                    735: #define NDEATHMAX 8 /**< Maximum number of dead states (for func) */
                    736: #define NCOVMAX 20 /**< Maximum number of covariates, including generated covariates V1*V2 */
1.197     brouard   737: #define codtabm(h,k)  (1 & (h-1) >> (k-1))+1
1.126     brouard   738: #define MAXN 20000
1.144     brouard   739: #define YEARM 12. /**< Number of months per year */
1.126     brouard   740: #define AGESUP 130
                    741: #define AGEBASE 40
1.194     brouard   742: #define AGEOVERFLOW 1.e20
1.164     brouard   743: #define AGEGOMP 10 /**< Minimal age for Gompertz adjustment */
1.157     brouard   744: #ifdef _WIN32
                    745: #define DIRSEPARATOR '\\'
                    746: #define CHARSEPARATOR "\\"
                    747: #define ODIRSEPARATOR '/'
                    748: #else
1.126     brouard   749: #define DIRSEPARATOR '/'
                    750: #define CHARSEPARATOR "/"
                    751: #define ODIRSEPARATOR '\\'
                    752: #endif
                    753: 
1.206   ! brouard   754: /* $Id: imach.c,v 1.205 2015/10/23 15:50:53 brouard Exp $ */
1.126     brouard   755: /* $State: Exp $ */
1.196     brouard   756: #include "version.h"
                    757: char version[]=__IMACH_VERSION__;
1.204     brouard   758: 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.206   ! brouard   759: char fullversion[]="$Revision: 1.205 $ $Date: 2015/10/23 15:50:53 $"; 
1.126     brouard   760: char strstart[80];
                    761: char optionfilext[10], optionfilefiname[FILENAMELENGTH];
1.130     brouard   762: int erreur=0, nberr=0, nbwarn=0; /* Error number, number of errors number of warnings  */
1.187     brouard   763: int nagesqr=0, nforce=0; /* nagesqr=1 if model is including age*age, number of forces */
1.145     brouard   764: /* Number of covariates model=V2+V1+ V3*age+V2*V4 */
                    765: int cptcovn=0; /**< cptcovn number of covariates added in the model (excepting constant and age and age*product) */
                    766: int cptcovt=0; /**< cptcovt number of covariates added in the model (excepting constant and age) */
                    767: int cptcovs=0; /**< cptcovs number of simple covariates V2+V1 =2 */
                    768: int cptcovage=0; /**< Number of covariates with age: V3*age only =1 */
                    769: int cptcovprodnoage=0; /**< Number of covariate products without age */   
                    770: int cptcoveff=0; /* Total number of covariates to vary for printing results */
                    771: int cptcov=0; /* Working variable */
1.126     brouard   772: int npar=NPARMAX;
                    773: int nlstate=2; /* Number of live states */
                    774: int ndeath=1; /* Number of dead states */
1.130     brouard   775: int ncovmodel=0, ncovcol=0;     /* Total number of covariables including constant a12*1 +b12*x ncovmodel=2 */
1.126     brouard   776: int popbased=0;
                    777: 
                    778: int *wav; /* Number of waves for this individuual 0 is possible */
1.130     brouard   779: int maxwav=0; /* Maxim number of waves */
                    780: int jmin=0, jmax=0; /* min, max spacing between 2 waves */
                    781: int ijmin=0, ijmax=0; /* Individuals having jmin and jmax */ 
                    782: int gipmx=0, gsw=0; /* Global variables on the number of contributions 
1.126     brouard   783:                   to the likelihood and the sum of weights (done by funcone)*/
1.130     brouard   784: int mle=1, weightopt=0;
1.126     brouard   785: int **mw; /* mw[mi][i] is number of the mi wave for this individual */
                    786: int **dh; /* dh[mi][i] is number of steps between mi,mi+1 for this individual */
                    787: int **bh; /* bh[mi][i] is the bias (+ or -) for this individual if the delay between
                    788:           * wave mi and wave mi+1 is not an exact multiple of stepm. */
1.162     brouard   789: int countcallfunc=0;  /* Count the number of calls to func */
1.130     brouard   790: double jmean=1; /* Mean space between 2 waves */
1.145     brouard   791: double **matprod2(); /* test */
1.126     brouard   792: double **oldm, **newm, **savm; /* Working pointers to matrices */
                    793: double **oldms, **newms, **savms; /* Fixed working pointers to matrices */
1.136     brouard   794: /*FILE *fic ; */ /* Used in readdata only */
                    795: FILE *ficpar, *ficparo,*ficres, *ficresp, *ficrespl, *ficrespij, *ficrest,*ficresf,*ficrespop;
1.126     brouard   796: FILE *ficlog, *ficrespow;
1.130     brouard   797: int globpr=0; /* Global variable for printing or not */
1.126     brouard   798: double fretone; /* Only one call to likelihood */
1.130     brouard   799: long ipmx=0; /* Number of contributions */
1.126     brouard   800: double sw; /* Sum of weights */
                    801: char filerespow[FILENAMELENGTH];
                    802: char fileresilk[FILENAMELENGTH]; /* File of individual contributions to the likelihood */
                    803: FILE *ficresilk;
                    804: FILE *ficgp,*ficresprob,*ficpop, *ficresprobcov, *ficresprobcor;
                    805: FILE *ficresprobmorprev;
                    806: FILE *fichtm, *fichtmcov; /* Html File */
                    807: FILE *ficreseij;
                    808: char filerese[FILENAMELENGTH];
                    809: FILE *ficresstdeij;
                    810: char fileresstde[FILENAMELENGTH];
                    811: FILE *ficrescveij;
                    812: char filerescve[FILENAMELENGTH];
                    813: FILE  *ficresvij;
                    814: char fileresv[FILENAMELENGTH];
                    815: FILE  *ficresvpl;
                    816: char fileresvpl[FILENAMELENGTH];
                    817: char title[MAXLINE];
                    818: char optionfile[FILENAMELENGTH], datafile[FILENAMELENGTH],  filerespl[FILENAMELENGTH];
                    819: char plotcmd[FILENAMELENGTH], pplotcmd[FILENAMELENGTH];
                    820: char tmpout[FILENAMELENGTH],  tmpout2[FILENAMELENGTH]; 
                    821: char command[FILENAMELENGTH];
                    822: int  outcmd=0;
                    823: 
                    824: char fileres[FILENAMELENGTH], filerespij[FILENAMELENGTH], filereso[FILENAMELENGTH], rfileres[FILENAMELENGTH];
1.202     brouard   825: char fileresu[FILENAMELENGTH]; /* fileres without r in front */
1.126     brouard   826: char filelog[FILENAMELENGTH]; /* Log file */
                    827: char filerest[FILENAMELENGTH];
                    828: char fileregp[FILENAMELENGTH];
                    829: char popfile[FILENAMELENGTH];
                    830: 
                    831: char optionfilegnuplot[FILENAMELENGTH], optionfilehtm[FILENAMELENGTH], optionfilehtmcov[FILENAMELENGTH] ;
                    832: 
1.157     brouard   833: /* struct timeval start_time, end_time, curr_time, last_time, forecast_time; */
                    834: /* struct timezone tzp; */
                    835: /* extern int gettimeofday(); */
                    836: struct tm tml, *gmtime(), *localtime();
                    837: 
                    838: extern time_t time();
                    839: 
                    840: struct tm start_time, end_time, curr_time, last_time, forecast_time;
                    841: time_t  rstart_time, rend_time, rcurr_time, rlast_time, rforecast_time; /* raw time */
                    842: struct tm tm;
                    843: 
1.126     brouard   844: char strcurr[80], strfor[80];
                    845: 
                    846: char *endptr;
                    847: long lval;
                    848: double dval;
                    849: 
                    850: #define NR_END 1
                    851: #define FREE_ARG char*
                    852: #define FTOL 1.0e-10
                    853: 
                    854: #define NRANSI 
                    855: #define ITMAX 200 
                    856: 
                    857: #define TOL 2.0e-4 
                    858: 
                    859: #define CGOLD 0.3819660 
                    860: #define ZEPS 1.0e-10 
                    861: #define SHFT(a,b,c,d) (a)=(b);(b)=(c);(c)=(d); 
                    862: 
                    863: #define GOLD 1.618034 
                    864: #define GLIMIT 100.0 
                    865: #define TINY 1.0e-20 
                    866: 
                    867: static double maxarg1,maxarg2;
                    868: #define FMAX(a,b) (maxarg1=(a),maxarg2=(b),(maxarg1)>(maxarg2)? (maxarg1):(maxarg2))
                    869: #define FMIN(a,b) (maxarg1=(a),maxarg2=(b),(maxarg1)<(maxarg2)? (maxarg1):(maxarg2))
                    870:   
                    871: #define SIGN(a,b) ((b)>0.0 ? fabs(a) : -fabs(a))
                    872: #define rint(a) floor(a+0.5)
1.166     brouard   873: /* http://www.thphys.uni-heidelberg.de/~robbers/cmbeasy/doc/html/myutils_8h-source.html */
1.183     brouard   874: #define mytinydouble 1.0e-16
1.166     brouard   875: /* #define DEQUAL(a,b) (fabs((a)-(b))<mytinydouble) */
                    876: /* http://www.thphys.uni-heidelberg.de/~robbers/cmbeasy/doc/html/mynrutils_8h-source.html */
                    877: /* static double dsqrarg; */
                    878: /* #define DSQR(a) (DEQUAL((dsqrarg=(a)),0.0) ? 0.0 : dsqrarg*dsqrarg) */
1.126     brouard   879: static double sqrarg;
                    880: #define SQR(a) ((sqrarg=(a)) == 0.0 ? 0.0 :sqrarg*sqrarg)
                    881: #define SWAP(a,b) {temp=(a);(a)=(b);(b)=temp;} 
                    882: int agegomp= AGEGOMP;
                    883: 
                    884: int imx; 
                    885: int stepm=1;
                    886: /* Stepm, step in month: minimum step interpolation*/
                    887: 
                    888: int estepm;
                    889: /* Estepm, step in month to interpolate survival function in order to approximate Life Expectancy*/
                    890: 
                    891: int m,nb;
                    892: long *num;
1.197     brouard   893: int firstpass=0, lastpass=4,*cod, *cens;
1.192     brouard   894: int *ncodemax;  /* ncodemax[j]= Number of modalities of the j th
                    895:                   covariate for which somebody answered excluding 
                    896:                   undefined. Usually 2: 0 and 1. */
                    897: int *ncodemaxwundef;  /* ncodemax[j]= Number of modalities of the j th
                    898:                             covariate for which somebody answered including 
                    899:                             undefined. Usually 3: -1, 0 and 1. */
1.126     brouard   900: double **agev,*moisnais, *annais, *moisdc, *andc,**mint, **anint;
                    901: double **pmmij, ***probs;
                    902: double *ageexmed,*agecens;
                    903: double dateintmean=0;
                    904: 
                    905: double *weight;
                    906: int **s; /* Status */
1.141     brouard   907: double *agedc;
1.145     brouard   908: double  **covar; /**< covar[j,i], value of jth covariate for individual i,
1.141     brouard   909:                  * covar=matrix(0,NCOVMAX,1,n); 
1.187     brouard   910:                  * cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*age; */
1.141     brouard   911: double  idx; 
                    912: int **nbcode, *Tvar; /**< model=V2 => Tvar[1]= 2 */
1.197     brouard   913: int *Tage;
1.145     brouard   914: int *Ndum; /** Freq of modality (tricode */
1.200     brouard   915: /* int **codtab;*/ /**< codtab=imatrix(1,100,1,10); */
1.141     brouard   916: int **Tvard, *Tprod, cptcovprod, *Tvaraff;
1.126     brouard   917: double *lsurv, *lpop, *tpop;
                    918: 
1.143     brouard   919: double ftol=FTOL; /**< Tolerance for computing Max Likelihood */
                    920: double ftolhess; /**< Tolerance for computing hessian */
1.126     brouard   921: 
                    922: /**************** split *************************/
                    923: static int split( char *path, char *dirc, char *name, char *ext, char *finame )
                    924: {
                    925:   /* From a file name with (full) path (either Unix or Windows) we extract the directory (dirc)
                    926:      the name of the file (name), its extension only (ext) and its first part of the name (finame)
                    927:   */ 
                    928:   char *ss;                            /* pointer */
1.186     brouard   929:   int  l1=0, l2=0;                             /* length counters */
1.126     brouard   930: 
                    931:   l1 = strlen(path );                  /* length of path */
                    932:   if ( l1 == 0 ) return( GLOCK_ERROR_NOPATH );
                    933:   ss= strrchr( path, DIRSEPARATOR );           /* find last / */
                    934:   if ( ss == NULL ) {                  /* no directory, so determine current directory */
                    935:     strcpy( name, path );              /* we got the fullname name because no directory */
                    936:     /*if(strrchr(path, ODIRSEPARATOR )==NULL)
                    937:       printf("Warning you should use %s as a separator\n",DIRSEPARATOR);*/
                    938:     /* get current working directory */
                    939:     /*    extern  char* getcwd ( char *buf , int len);*/
1.184     brouard   940: #ifdef WIN32
                    941:     if (_getcwd( dirc, FILENAME_MAX ) == NULL ) {
                    942: #else
                    943:        if (getcwd(dirc, FILENAME_MAX) == NULL) {
                    944: #endif
1.126     brouard   945:       return( GLOCK_ERROR_GETCWD );
                    946:     }
                    947:     /* got dirc from getcwd*/
                    948:     printf(" DIRC = %s \n",dirc);
1.205     brouard   949:   } else {                             /* strip directory from path */
1.126     brouard   950:     ss++;                              /* after this, the filename */
                    951:     l2 = strlen( ss );                 /* length of filename */
                    952:     if ( l2 == 0 ) return( GLOCK_ERROR_NOPATH );
                    953:     strcpy( name, ss );                /* save file name */
                    954:     strncpy( dirc, path, l1 - l2 );    /* now the directory */
1.186     brouard   955:     dirc[l1-l2] = '\0';                        /* add zero */
1.126     brouard   956:     printf(" DIRC2 = %s \n",dirc);
                    957:   }
                    958:   /* We add a separator at the end of dirc if not exists */
                    959:   l1 = strlen( dirc );                 /* length of directory */
                    960:   if( dirc[l1-1] != DIRSEPARATOR ){
                    961:     dirc[l1] =  DIRSEPARATOR;
                    962:     dirc[l1+1] = 0; 
                    963:     printf(" DIRC3 = %s \n",dirc);
                    964:   }
                    965:   ss = strrchr( name, '.' );           /* find last / */
                    966:   if (ss >0){
                    967:     ss++;
                    968:     strcpy(ext,ss);                    /* save extension */
                    969:     l1= strlen( name);
                    970:     l2= strlen(ss)+1;
                    971:     strncpy( finame, name, l1-l2);
                    972:     finame[l1-l2]= 0;
                    973:   }
                    974: 
                    975:   return( 0 );                         /* we're done */
                    976: }
                    977: 
                    978: 
                    979: /******************************************/
                    980: 
                    981: void replace_back_to_slash(char *s, char*t)
                    982: {
                    983:   int i;
                    984:   int lg=0;
                    985:   i=0;
                    986:   lg=strlen(t);
                    987:   for(i=0; i<= lg; i++) {
                    988:     (s[i] = t[i]);
                    989:     if (t[i]== '\\') s[i]='/';
                    990:   }
                    991: }
                    992: 
1.132     brouard   993: char *trimbb(char *out, char *in)
1.137     brouard   994: { /* Trim multiple blanks in line but keeps first blanks if line starts with blanks */
1.132     brouard   995:   char *s;
                    996:   s=out;
                    997:   while (*in != '\0'){
1.137     brouard   998:     while( *in == ' ' && *(in+1) == ' '){ /* && *(in+1) != '\0'){*/
1.132     brouard   999:       in++;
                   1000:     }
                   1001:     *out++ = *in++;
                   1002:   }
                   1003:   *out='\0';
                   1004:   return s;
                   1005: }
                   1006: 
1.187     brouard  1007: /* char *substrchaine(char *out, char *in, char *chain) */
                   1008: /* { */
                   1009: /*   /\* Substract chain 'chain' from 'in', return and output 'out' *\/ */
                   1010: /*   char *s, *t; */
                   1011: /*   t=in;s=out; */
                   1012: /*   while ((*in != *chain) && (*in != '\0')){ */
                   1013: /*     *out++ = *in++; */
                   1014: /*   } */
                   1015: 
                   1016: /*   /\* *in matches *chain *\/ */
                   1017: /*   while ((*in++ == *chain++) && (*in != '\0')){ */
                   1018: /*     printf("*in = %c, *out= %c *chain= %c \n", *in, *out, *chain);  */
                   1019: /*   } */
                   1020: /*   in--; chain--; */
                   1021: /*   while ( (*in != '\0')){ */
                   1022: /*     printf("Bef *in = %c, *out= %c *chain= %c \n", *in, *out, *chain);  */
                   1023: /*     *out++ = *in++; */
                   1024: /*     printf("Aft *in = %c, *out= %c *chain= %c \n", *in, *out, *chain);  */
                   1025: /*   } */
                   1026: /*   *out='\0'; */
                   1027: /*   out=s; */
                   1028: /*   return out; */
                   1029: /* } */
                   1030: char *substrchaine(char *out, char *in, char *chain)
                   1031: {
                   1032:   /* Substract chain 'chain' from 'in', return and output 'out' */
                   1033:   /* in="V1+V1*age+age*age+V2", chain="age*age" */
                   1034: 
                   1035:   char *strloc;
                   1036: 
                   1037:   strcpy (out, in); 
                   1038:   strloc = strstr(out, chain); /* strloc points to out at age*age+V2 */
                   1039:   printf("Bef strloc=%s chain=%s out=%s \n", strloc, chain, out);
                   1040:   if(strloc != NULL){ 
                   1041:     /* will affect out */ /* strloc+strlenc(chain)=+V2 */ /* Will also work in Unicode */
                   1042:     memmove(strloc,strloc+strlen(chain), strlen(strloc+strlen(chain))+1);
                   1043:     /* strcpy (strloc, strloc +strlen(chain));*/
                   1044:   }
                   1045:   printf("Aft strloc=%s chain=%s in=%s out=%s \n", strloc, chain, in, out);
                   1046:   return out;
                   1047: }
                   1048: 
                   1049: 
1.145     brouard  1050: char *cutl(char *blocc, char *alocc, char *in, char occ)
                   1051: {
1.187     brouard  1052:   /* cuts string in into blocc and alocc where blocc ends before FIRST occurence of char 'occ' 
1.145     brouard  1053:      and alocc starts after first occurence of char 'occ' : ex cutv(blocc,alocc,"abcdef2ghi2j",'2')
1.187     brouard  1054:      gives blocc="abcdef" and alocc="ghi2j".
1.145     brouard  1055:      If occ is not found blocc is null and alocc is equal to in. Returns blocc
                   1056:   */
1.160     brouard  1057:   char *s, *t;
1.145     brouard  1058:   t=in;s=in;
                   1059:   while ((*in != occ) && (*in != '\0')){
                   1060:     *alocc++ = *in++;
                   1061:   }
                   1062:   if( *in == occ){
                   1063:     *(alocc)='\0';
                   1064:     s=++in;
                   1065:   }
                   1066:  
                   1067:   if (s == t) {/* occ not found */
                   1068:     *(alocc-(in-s))='\0';
                   1069:     in=s;
                   1070:   }
                   1071:   while ( *in != '\0'){
                   1072:     *blocc++ = *in++;
                   1073:   }
                   1074: 
                   1075:   *blocc='\0';
                   1076:   return t;
                   1077: }
1.137     brouard  1078: char *cutv(char *blocc, char *alocc, char *in, char occ)
                   1079: {
1.187     brouard  1080:   /* cuts string in into blocc and alocc where blocc ends before LAST occurence of char 'occ' 
1.137     brouard  1081:      and alocc starts after last occurence of char 'occ' : ex cutv(blocc,alocc,"abcdef2ghi2j",'2')
                   1082:      gives blocc="abcdef2ghi" and alocc="j".
                   1083:      If occ is not found blocc is null and alocc is equal to in. Returns alocc
                   1084:   */
                   1085:   char *s, *t;
                   1086:   t=in;s=in;
                   1087:   while (*in != '\0'){
                   1088:     while( *in == occ){
                   1089:       *blocc++ = *in++;
                   1090:       s=in;
                   1091:     }
                   1092:     *blocc++ = *in++;
                   1093:   }
                   1094:   if (s == t) /* occ not found */
                   1095:     *(blocc-(in-s))='\0';
                   1096:   else
                   1097:     *(blocc-(in-s)-1)='\0';
                   1098:   in=s;
                   1099:   while ( *in != '\0'){
                   1100:     *alocc++ = *in++;
                   1101:   }
                   1102: 
                   1103:   *alocc='\0';
                   1104:   return s;
                   1105: }
                   1106: 
1.126     brouard  1107: int nbocc(char *s, char occ)
                   1108: {
                   1109:   int i,j=0;
                   1110:   int lg=20;
                   1111:   i=0;
                   1112:   lg=strlen(s);
                   1113:   for(i=0; i<= lg; i++) {
                   1114:   if  (s[i] == occ ) j++;
                   1115:   }
                   1116:   return j;
                   1117: }
                   1118: 
1.137     brouard  1119: /* void cutv(char *u,char *v, char*t, char occ) */
                   1120: /* { */
                   1121: /*   /\* cuts string t into u and v where u ends before last occurence of char 'occ'  */
                   1122: /*      and v starts after last occurence of char 'occ' : ex cutv(u,v,"abcdef2ghi2j",'2') */
                   1123: /*      gives u="abcdef2ghi" and v="j" *\/ */
                   1124: /*   int i,lg,j,p=0; */
                   1125: /*   i=0; */
                   1126: /*   lg=strlen(t); */
                   1127: /*   for(j=0; j<=lg-1; j++) { */
                   1128: /*     if((t[j]!= occ) && (t[j+1]== occ)) p=j+1; */
                   1129: /*   } */
1.126     brouard  1130: 
1.137     brouard  1131: /*   for(j=0; j<p; j++) { */
                   1132: /*     (u[j] = t[j]); */
                   1133: /*   } */
                   1134: /*      u[p]='\0'; */
1.126     brouard  1135: 
1.137     brouard  1136: /*    for(j=0; j<= lg; j++) { */
                   1137: /*     if (j>=(p+1))(v[j-p-1] = t[j]); */
                   1138: /*   } */
                   1139: /* } */
1.126     brouard  1140: 
1.160     brouard  1141: #ifdef _WIN32
                   1142: char * strsep(char **pp, const char *delim)
                   1143: {
                   1144:   char *p, *q;
                   1145:          
                   1146:   if ((p = *pp) == NULL)
                   1147:     return 0;
                   1148:   if ((q = strpbrk (p, delim)) != NULL)
                   1149:   {
                   1150:     *pp = q + 1;
                   1151:     *q = '\0';
                   1152:   }
                   1153:   else
                   1154:     *pp = 0;
                   1155:   return p;
                   1156: }
                   1157: #endif
                   1158: 
1.126     brouard  1159: /********************** nrerror ********************/
                   1160: 
                   1161: void nrerror(char error_text[])
                   1162: {
                   1163:   fprintf(stderr,"ERREUR ...\n");
                   1164:   fprintf(stderr,"%s\n",error_text);
                   1165:   exit(EXIT_FAILURE);
                   1166: }
                   1167: /*********************** vector *******************/
                   1168: double *vector(int nl, int nh)
                   1169: {
                   1170:   double *v;
                   1171:   v=(double *) malloc((size_t)((nh-nl+1+NR_END)*sizeof(double)));
                   1172:   if (!v) nrerror("allocation failure in vector");
                   1173:   return v-nl+NR_END;
                   1174: }
                   1175: 
                   1176: /************************ free vector ******************/
                   1177: void free_vector(double*v, int nl, int nh)
                   1178: {
                   1179:   free((FREE_ARG)(v+nl-NR_END));
                   1180: }
                   1181: 
                   1182: /************************ivector *******************************/
                   1183: int *ivector(long nl,long nh)
                   1184: {
                   1185:   int *v;
                   1186:   v=(int *) malloc((size_t)((nh-nl+1+NR_END)*sizeof(int)));
                   1187:   if (!v) nrerror("allocation failure in ivector");
                   1188:   return v-nl+NR_END;
                   1189: }
                   1190: 
                   1191: /******************free ivector **************************/
                   1192: void free_ivector(int *v, long nl, long nh)
                   1193: {
                   1194:   free((FREE_ARG)(v+nl-NR_END));
                   1195: }
                   1196: 
                   1197: /************************lvector *******************************/
                   1198: long *lvector(long nl,long nh)
                   1199: {
                   1200:   long *v;
                   1201:   v=(long *) malloc((size_t)((nh-nl+1+NR_END)*sizeof(long)));
                   1202:   if (!v) nrerror("allocation failure in ivector");
                   1203:   return v-nl+NR_END;
                   1204: }
                   1205: 
                   1206: /******************free lvector **************************/
                   1207: void free_lvector(long *v, long nl, long nh)
                   1208: {
                   1209:   free((FREE_ARG)(v+nl-NR_END));
                   1210: }
                   1211: 
                   1212: /******************* imatrix *******************************/
                   1213: int **imatrix(long nrl, long nrh, long ncl, long nch) 
                   1214:      /* allocate a int matrix with subscript range m[nrl..nrh][ncl..nch] */ 
                   1215: { 
                   1216:   long i, nrow=nrh-nrl+1,ncol=nch-ncl+1; 
                   1217:   int **m; 
                   1218:   
                   1219:   /* allocate pointers to rows */ 
                   1220:   m=(int **) malloc((size_t)((nrow+NR_END)*sizeof(int*))); 
                   1221:   if (!m) nrerror("allocation failure 1 in matrix()"); 
                   1222:   m += NR_END; 
                   1223:   m -= nrl; 
                   1224:   
                   1225:   
                   1226:   /* allocate rows and set pointers to them */ 
                   1227:   m[nrl]=(int *) malloc((size_t)((nrow*ncol+NR_END)*sizeof(int))); 
                   1228:   if (!m[nrl]) nrerror("allocation failure 2 in matrix()"); 
                   1229:   m[nrl] += NR_END; 
                   1230:   m[nrl] -= ncl; 
                   1231:   
                   1232:   for(i=nrl+1;i<=nrh;i++) m[i]=m[i-1]+ncol; 
                   1233:   
                   1234:   /* return pointer to array of pointers to rows */ 
                   1235:   return m; 
                   1236: } 
                   1237: 
                   1238: /****************** free_imatrix *************************/
                   1239: void free_imatrix(m,nrl,nrh,ncl,nch)
                   1240:       int **m;
                   1241:       long nch,ncl,nrh,nrl; 
                   1242:      /* free an int matrix allocated by imatrix() */ 
                   1243: { 
                   1244:   free((FREE_ARG) (m[nrl]+ncl-NR_END)); 
                   1245:   free((FREE_ARG) (m+nrl-NR_END)); 
                   1246: } 
                   1247: 
                   1248: /******************* matrix *******************************/
                   1249: double **matrix(long nrl, long nrh, long ncl, long nch)
                   1250: {
                   1251:   long i, nrow=nrh-nrl+1, ncol=nch-ncl+1;
                   1252:   double **m;
                   1253: 
                   1254:   m=(double **) malloc((size_t)((nrow+NR_END)*sizeof(double*)));
                   1255:   if (!m) nrerror("allocation failure 1 in matrix()");
                   1256:   m += NR_END;
                   1257:   m -= nrl;
                   1258: 
                   1259:   m[nrl]=(double *) malloc((size_t)((nrow*ncol+NR_END)*sizeof(double)));
                   1260:   if (!m[nrl]) nrerror("allocation failure 2 in matrix()");
                   1261:   m[nrl] += NR_END;
                   1262:   m[nrl] -= ncl;
                   1263: 
                   1264:   for (i=nrl+1; i<=nrh; i++) m[i]=m[i-1]+ncol;
                   1265:   return m;
1.145     brouard  1266:   /* print *(*(m+1)+70) or print m[1][70]; print m+1 or print &(m[1]) or &(m[1][0])
                   1267: m[i] = address of ith row of the table. &(m[i]) is its value which is another adress
                   1268: that of m[i][0]. In order to get the value p m[i][0] but it is unitialized.
1.126     brouard  1269:    */
                   1270: }
                   1271: 
                   1272: /*************************free matrix ************************/
                   1273: void free_matrix(double **m, long nrl, long nrh, long ncl, long nch)
                   1274: {
                   1275:   free((FREE_ARG)(m[nrl]+ncl-NR_END));
                   1276:   free((FREE_ARG)(m+nrl-NR_END));
                   1277: }
                   1278: 
                   1279: /******************* ma3x *******************************/
                   1280: double ***ma3x(long nrl, long nrh, long ncl, long nch, long nll, long nlh)
                   1281: {
                   1282:   long i, j, nrow=nrh-nrl+1, ncol=nch-ncl+1, nlay=nlh-nll+1;
                   1283:   double ***m;
                   1284: 
                   1285:   m=(double ***) malloc((size_t)((nrow+NR_END)*sizeof(double*)));
                   1286:   if (!m) nrerror("allocation failure 1 in matrix()");
                   1287:   m += NR_END;
                   1288:   m -= nrl;
                   1289: 
                   1290:   m[nrl]=(double **) malloc((size_t)((nrow*ncol+NR_END)*sizeof(double)));
                   1291:   if (!m[nrl]) nrerror("allocation failure 2 in matrix()");
                   1292:   m[nrl] += NR_END;
                   1293:   m[nrl] -= ncl;
                   1294: 
                   1295:   for (i=nrl+1; i<=nrh; i++) m[i]=m[i-1]+ncol;
                   1296: 
                   1297:   m[nrl][ncl]=(double *) malloc((size_t)((nrow*ncol*nlay+NR_END)*sizeof(double)));
                   1298:   if (!m[nrl][ncl]) nrerror("allocation failure 3 in matrix()");
                   1299:   m[nrl][ncl] += NR_END;
                   1300:   m[nrl][ncl] -= nll;
                   1301:   for (j=ncl+1; j<=nch; j++) 
                   1302:     m[nrl][j]=m[nrl][j-1]+nlay;
                   1303:   
                   1304:   for (i=nrl+1; i<=nrh; i++) {
                   1305:     m[i][ncl]=m[i-1l][ncl]+ncol*nlay;
                   1306:     for (j=ncl+1; j<=nch; j++) 
                   1307:       m[i][j]=m[i][j-1]+nlay;
                   1308:   }
                   1309:   return m; 
                   1310:   /*  gdb: p *(m+1) <=> p m[1] and p (m+1) <=> p (m+1) <=> p &(m[1])
                   1311:            &(m[i][j][k]) <=> *((*(m+i) + j)+k)
                   1312:   */
                   1313: }
                   1314: 
                   1315: /*************************free ma3x ************************/
                   1316: void free_ma3x(double ***m, long nrl, long nrh, long ncl, long nch,long nll, long nlh)
                   1317: {
                   1318:   free((FREE_ARG)(m[nrl][ncl]+ nll-NR_END));
                   1319:   free((FREE_ARG)(m[nrl]+ncl-NR_END));
                   1320:   free((FREE_ARG)(m+nrl-NR_END));
                   1321: }
                   1322: 
                   1323: /*************** function subdirf ***********/
                   1324: char *subdirf(char fileres[])
                   1325: {
                   1326:   /* Caution optionfilefiname is hidden */
                   1327:   strcpy(tmpout,optionfilefiname);
                   1328:   strcat(tmpout,"/"); /* Add to the right */
                   1329:   strcat(tmpout,fileres);
                   1330:   return tmpout;
                   1331: }
                   1332: 
                   1333: /*************** function subdirf2 ***********/
                   1334: char *subdirf2(char fileres[], char *preop)
                   1335: {
                   1336:   
                   1337:   /* Caution optionfilefiname is hidden */
                   1338:   strcpy(tmpout,optionfilefiname);
                   1339:   strcat(tmpout,"/");
                   1340:   strcat(tmpout,preop);
                   1341:   strcat(tmpout,fileres);
                   1342:   return tmpout;
                   1343: }
                   1344: 
                   1345: /*************** function subdirf3 ***********/
                   1346: char *subdirf3(char fileres[], char *preop, char *preop2)
                   1347: {
                   1348:   
                   1349:   /* Caution optionfilefiname is hidden */
                   1350:   strcpy(tmpout,optionfilefiname);
                   1351:   strcat(tmpout,"/");
                   1352:   strcat(tmpout,preop);
                   1353:   strcat(tmpout,preop2);
                   1354:   strcat(tmpout,fileres);
                   1355:   return tmpout;
                   1356: }
                   1357: 
1.162     brouard  1358: char *asc_diff_time(long time_sec, char ascdiff[])
                   1359: {
                   1360:   long sec_left, days, hours, minutes;
                   1361:   days = (time_sec) / (60*60*24);
                   1362:   sec_left = (time_sec) % (60*60*24);
                   1363:   hours = (sec_left) / (60*60) ;
                   1364:   sec_left = (sec_left) %(60*60);
                   1365:   minutes = (sec_left) /60;
                   1366:   sec_left = (sec_left) % (60);
                   1367:   sprintf(ascdiff,"%ld day(s) %ld hour(s) %ld minute(s) %ld second(s)",days, hours, minutes, sec_left);  
                   1368:   return ascdiff;
                   1369: }
                   1370: 
1.126     brouard  1371: /***************** f1dim *************************/
                   1372: extern int ncom; 
                   1373: extern double *pcom,*xicom;
                   1374: extern double (*nrfunc)(double []); 
                   1375:  
                   1376: double f1dim(double x) 
                   1377: { 
                   1378:   int j; 
                   1379:   double f;
                   1380:   double *xt; 
                   1381:  
                   1382:   xt=vector(1,ncom); 
                   1383:   for (j=1;j<=ncom;j++) xt[j]=pcom[j]+x*xicom[j]; 
                   1384:   f=(*nrfunc)(xt); 
                   1385:   free_vector(xt,1,ncom); 
                   1386:   return f; 
                   1387: } 
                   1388: 
                   1389: /*****************brent *************************/
                   1390: double brent(double ax, double bx, double cx, double (*f)(double), double tol,         double *xmin) 
1.187     brouard  1391: {
                   1392:   /* Given a function f, and given a bracketing triplet of abscissas ax, bx, cx (such that bx is
                   1393:    * between ax and cx, and f(bx) is less than both f(ax) and f(cx) ), this routine isolates
                   1394:    * the minimum to a fractional precision of about tol using Brent’s method. The abscissa of
                   1395:    * the minimum is returned as xmin, and the minimum function value is returned as brent , the
                   1396:    * returned function value. 
                   1397:   */
1.126     brouard  1398:   int iter; 
                   1399:   double a,b,d,etemp;
1.159     brouard  1400:   double fu=0,fv,fw,fx;
1.164     brouard  1401:   double ftemp=0.;
1.126     brouard  1402:   double p,q,r,tol1,tol2,u,v,w,x,xm; 
                   1403:   double e=0.0; 
                   1404:  
                   1405:   a=(ax < cx ? ax : cx); 
                   1406:   b=(ax > cx ? ax : cx); 
                   1407:   x=w=v=bx; 
                   1408:   fw=fv=fx=(*f)(x); 
                   1409:   for (iter=1;iter<=ITMAX;iter++) { 
                   1410:     xm=0.5*(a+b); 
                   1411:     tol2=2.0*(tol1=tol*fabs(x)+ZEPS); 
                   1412:     /*         if (2.0*fabs(fp-(*fret)) <= ftol*(fabs(fp)+fabs(*fret)))*/
                   1413:     printf(".");fflush(stdout);
                   1414:     fprintf(ficlog,".");fflush(ficlog);
1.162     brouard  1415: #ifdef DEBUGBRENT
1.126     brouard  1416:     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);
                   1417:     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);
                   1418:     /*         if ((fabs(x-xm) <= (tol2-0.5*(b-a)))||(2.0*fabs(fu-ftemp) <= ftol*1.e-2*(fabs(fu)+fabs(ftemp)))) { */
                   1419: #endif
                   1420:     if (fabs(x-xm) <= (tol2-0.5*(b-a))){ 
                   1421:       *xmin=x; 
                   1422:       return fx; 
                   1423:     } 
                   1424:     ftemp=fu;
                   1425:     if (fabs(e) > tol1) { 
                   1426:       r=(x-w)*(fx-fv); 
                   1427:       q=(x-v)*(fx-fw); 
                   1428:       p=(x-v)*q-(x-w)*r; 
                   1429:       q=2.0*(q-r); 
                   1430:       if (q > 0.0) p = -p; 
                   1431:       q=fabs(q); 
                   1432:       etemp=e; 
                   1433:       e=d; 
                   1434:       if (fabs(p) >= fabs(0.5*q*etemp) || p <= q*(a-x) || p >= q*(b-x)) 
                   1435:        d=CGOLD*(e=(x >= xm ? a-x : b-x)); 
                   1436:       else { 
                   1437:        d=p/q; 
                   1438:        u=x+d; 
                   1439:        if (u-a < tol2 || b-u < tol2) 
                   1440:          d=SIGN(tol1,xm-x); 
                   1441:       } 
                   1442:     } else { 
                   1443:       d=CGOLD*(e=(x >= xm ? a-x : b-x)); 
                   1444:     } 
                   1445:     u=(fabs(d) >= tol1 ? x+d : x+SIGN(tol1,d)); 
                   1446:     fu=(*f)(u); 
                   1447:     if (fu <= fx) { 
                   1448:       if (u >= x) a=x; else b=x; 
                   1449:       SHFT(v,w,x,u) 
1.183     brouard  1450:       SHFT(fv,fw,fx,fu) 
                   1451:     } else { 
                   1452:       if (u < x) a=u; else b=u; 
                   1453:       if (fu <= fw || w == x) { 
                   1454:        v=w; 
                   1455:        w=u; 
                   1456:        fv=fw; 
                   1457:        fw=fu; 
                   1458:       } else if (fu <= fv || v == x || v == w) { 
                   1459:        v=u; 
                   1460:        fv=fu; 
                   1461:       } 
                   1462:     } 
1.126     brouard  1463:   } 
                   1464:   nrerror("Too many iterations in brent"); 
                   1465:   *xmin=x; 
                   1466:   return fx; 
                   1467: } 
                   1468: 
                   1469: /****************** mnbrak ***********************/
                   1470: 
                   1471: void mnbrak(double *ax, double *bx, double *cx, double *fa, double *fb, double *fc, 
                   1472:            double (*func)(double)) 
1.183     brouard  1473: { /* Given a function func , and given distinct initial points ax and bx , this routine searches in
                   1474: the downhill direction (defined by the function as evaluated at the initial points) and returns
                   1475: new points ax , bx , cx that bracket a minimum of the function. Also returned are the function
                   1476: values at the three points, fa, fb , and fc such that fa > fb and fb < fc.
                   1477:    */
1.126     brouard  1478:   double ulim,u,r,q, dum;
                   1479:   double fu; 
1.187     brouard  1480: 
                   1481:   double scale=10.;
                   1482:   int iterscale=0;
                   1483: 
                   1484:   *fa=(*func)(*ax); /*  xta[j]=pcom[j]+(*ax)*xicom[j]; fa=f(xta[j])*/
                   1485:   *fb=(*func)(*bx); /*  xtb[j]=pcom[j]+(*bx)*xicom[j]; fb=f(xtb[j]) */
                   1486: 
                   1487: 
                   1488:   /* while(*fb != *fb){ /\* *ax should be ok, reducing distance to *ax *\/ */
                   1489:   /*   printf("Warning mnbrak *fb = %lf, *bx=%lf *ax=%lf *fa==%lf iter=%d\n",*fb, *bx, *ax, *fa, iterscale++); */
                   1490:   /*   *bx = *ax - (*ax - *bx)/scale; */
                   1491:   /*   *fb=(*func)(*bx);  /\*  xtb[j]=pcom[j]+(*bx)*xicom[j]; fb=f(xtb[j]) *\/ */
                   1492:   /* } */
                   1493: 
1.126     brouard  1494:   if (*fb > *fa) { 
                   1495:     SHFT(dum,*ax,*bx,dum) 
1.183     brouard  1496:     SHFT(dum,*fb,*fa,dum) 
                   1497:   } 
1.126     brouard  1498:   *cx=(*bx)+GOLD*(*bx-*ax); 
                   1499:   *fc=(*func)(*cx); 
1.183     brouard  1500: #ifdef DEBUG
                   1501:   printf("mnbrak0 *fb=%.12e *fc=%.12e\n",*fb,*fc);
                   1502:   fprintf(ficlog,"mnbrak0 *fb=%.12e *fc=%.12e\n",*fb,*fc);
                   1503: #endif
                   1504:   while (*fb > *fc) { /* Declining a,b,c with fa> fb > fc */
1.126     brouard  1505:     r=(*bx-*ax)*(*fb-*fc); 
                   1506:     q=(*bx-*cx)*(*fb-*fa); 
                   1507:     u=(*bx)-((*bx-*cx)*q-(*bx-*ax)*r)/ 
1.183     brouard  1508:       (2.0*SIGN(FMAX(fabs(q-r),TINY),q-r)); /* Minimum abscissa of a parabolic estimated from (a,fa), (b,fb) and (c,fc). */
                   1509:     ulim=(*bx)+GLIMIT*(*cx-*bx); /* Maximum abscissa where function should be evaluated */
                   1510:     if ((*bx-u)*(u-*cx) > 0.0) { /* if u_p is between b and c */
1.126     brouard  1511:       fu=(*func)(u); 
1.163     brouard  1512: #ifdef DEBUG
                   1513:       /* f(x)=A(x-u)**2+f(u) */
                   1514:       double A, fparabu; 
                   1515:       A= (*fb - *fa)/(*bx-*ax)/(*bx+*ax-2*u);
                   1516:       fparabu= *fa - A*(*ax-u)*(*ax-u);
                   1517:       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);
                   1518:       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  1519:       /* And thus,it can be that fu > *fc even if fparabu < *fc */
                   1520:       /* mnbrak (*ax=7.666299858533, *fa=299039.693133272231), (*bx=8.595447774979, *fb=298976.598289369489),
                   1521:         (*cx=10.098840694817, *fc=298946.631474258087),  (*u=9.852501168332, fu=298948.773013752128, fparabu=298945.434711494134) */
                   1522:       /* In that case, there is no bracket in the output! Routine is wrong with many consequences.*/
1.163     brouard  1523: #endif 
1.184     brouard  1524: #ifdef MNBRAKORIGINAL
1.183     brouard  1525: #else
1.191     brouard  1526: /*       if (fu > *fc) { */
                   1527: /* #ifdef DEBUG */
                   1528: /*       printf("mnbrak4  fu > fc \n"); */
                   1529: /*       fprintf(ficlog, "mnbrak4 fu > fc\n"); */
                   1530: /* #endif */
                   1531: /*     /\* 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 *\\/  *\/ */
                   1532: /*     /\* SHFT(*fa,*fc,fu,*fc) /\\* (b, u, c) is a bracket while test fb > fc will be fu > fc  will exit *\\/ *\/ */
                   1533: /*     dum=u; /\* Shifting c and u *\/ */
                   1534: /*     u = *cx; */
                   1535: /*     *cx = dum; */
                   1536: /*     dum = fu; */
                   1537: /*     fu = *fc; */
                   1538: /*     *fc =dum; */
                   1539: /*       } else { /\* end *\/ */
                   1540: /* #ifdef DEBUG */
                   1541: /*       printf("mnbrak3  fu < fc \n"); */
                   1542: /*       fprintf(ficlog, "mnbrak3 fu < fc\n"); */
                   1543: /* #endif */
                   1544: /*     dum=u; /\* Shifting c and u *\/ */
                   1545: /*     u = *cx; */
                   1546: /*     *cx = dum; */
                   1547: /*     dum = fu; */
                   1548: /*     fu = *fc; */
                   1549: /*     *fc =dum; */
                   1550: /*       } */
1.183     brouard  1551: #ifdef DEBUG
1.191     brouard  1552:       printf("mnbrak34  fu < or >= fc \n");
                   1553:       fprintf(ficlog, "mnbrak34 fu < fc\n");
1.183     brouard  1554: #endif
1.191     brouard  1555:       dum=u; /* Shifting c and u */
                   1556:       u = *cx;
                   1557:       *cx = dum;
                   1558:       dum = fu;
                   1559:       fu = *fc;
                   1560:       *fc =dum;
1.183     brouard  1561: #endif
1.162     brouard  1562:     } else if ((*cx-u)*(u-ulim) > 0.0) { /* u is after c but before ulim */
1.183     brouard  1563: #ifdef DEBUG
                   1564:       printf("mnbrak2  u after c but before ulim\n");
                   1565:       fprintf(ficlog, "mnbrak2 u after c but before ulim\n");
                   1566: #endif
1.126     brouard  1567:       fu=(*func)(u); 
                   1568:       if (fu < *fc) { 
1.183     brouard  1569: #ifdef DEBUG
                   1570:       printf("mnbrak2  u after c but before ulim AND fu < fc\n");
                   1571:       fprintf(ficlog, "mnbrak2 u after c but before ulim AND fu <fc \n");
                   1572: #endif
1.126     brouard  1573:        SHFT(*bx,*cx,u,*cx+GOLD*(*cx-*bx)) 
1.183     brouard  1574:        SHFT(*fb,*fc,fu,(*func)(u)) 
                   1575:       } 
1.162     brouard  1576:     } else if ((u-ulim)*(ulim-*cx) >= 0.0) { /* u outside ulim (verifying that ulim is beyond c) */
1.183     brouard  1577: #ifdef DEBUG
                   1578:       printf("mnbrak2  u outside ulim (verifying that ulim is beyond c)\n");
                   1579:       fprintf(ficlog, "mnbrak2 u outside ulim (verifying that ulim is beyond c)\n");
                   1580: #endif
1.126     brouard  1581:       u=ulim; 
                   1582:       fu=(*func)(u); 
1.183     brouard  1583:     } else { /* u could be left to b (if r > q parabola has a maximum) */
                   1584: #ifdef DEBUG
                   1585:       printf("mnbrak2  u could be left to b (if r > q parabola has a maximum)\n");
                   1586:       fprintf(ficlog, "mnbrak2  u could be left to b (if r > q parabola has a maximum)\n");
                   1587: #endif
1.126     brouard  1588:       u=(*cx)+GOLD*(*cx-*bx); 
                   1589:       fu=(*func)(u); 
1.183     brouard  1590:     } /* end tests */
1.126     brouard  1591:     SHFT(*ax,*bx,*cx,u) 
1.183     brouard  1592:     SHFT(*fa,*fb,*fc,fu) 
                   1593: #ifdef DEBUG
                   1594:       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);
                   1595:       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);
                   1596: #endif
                   1597:   } /* 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  1598: } 
                   1599: 
                   1600: /*************** linmin ************************/
1.162     brouard  1601: /* Given an n -dimensional point p[1..n] and an n -dimensional direction xi[1..n] , moves and
                   1602: resets p to where the function func(p) takes on a minimum along the direction xi from p ,
                   1603: and replaces xi by the actual vector displacement that p was moved. Also returns as fret
                   1604: the value of func at the returned location p . This is actually all accomplished by calling the
                   1605: routines mnbrak and brent .*/
1.126     brouard  1606: int ncom; 
                   1607: double *pcom,*xicom;
                   1608: double (*nrfunc)(double []); 
                   1609:  
                   1610: void linmin(double p[], double xi[], int n, double *fret,double (*func)(double [])) 
                   1611: { 
                   1612:   double brent(double ax, double bx, double cx, 
                   1613:               double (*f)(double), double tol, double *xmin); 
                   1614:   double f1dim(double x); 
                   1615:   void mnbrak(double *ax, double *bx, double *cx, double *fa, double *fb, 
                   1616:              double *fc, double (*func)(double)); 
                   1617:   int j; 
                   1618:   double xx,xmin,bx,ax; 
                   1619:   double fx,fb,fa;
1.187     brouard  1620: 
1.203     brouard  1621: #ifdef LINMINORIGINAL
                   1622: #else
                   1623:   double scale=10., axs, xxs; /* Scale added for infinity */
                   1624: #endif
                   1625:   
1.126     brouard  1626:   ncom=n; 
                   1627:   pcom=vector(1,n); 
                   1628:   xicom=vector(1,n); 
                   1629:   nrfunc=func; 
                   1630:   for (j=1;j<=n;j++) { 
                   1631:     pcom[j]=p[j]; 
1.202     brouard  1632:     xicom[j]=xi[j]; /* Former scale xi[j] of currrent direction i */
1.126     brouard  1633:   } 
1.187     brouard  1634: 
1.203     brouard  1635: #ifdef LINMINORIGINAL
                   1636:   xx=1.;
                   1637: #else
                   1638:   axs=0.0;
                   1639:   xxs=1.;
                   1640:   do{
                   1641:     xx= xxs;
                   1642: #endif
1.187     brouard  1643:     ax=0.;
                   1644:     mnbrak(&ax,&xx,&bx,&fa,&fx,&fb,f1dim);  /* Outputs: xtx[j]=pcom[j]+(*xx)*xicom[j]; fx=f(xtx[j]) */
                   1645:     /* brackets with inputs ax=0 and xx=1, but points, pcom=p, and directions values, xicom=xi, are sent via f1dim(x) */
                   1646:     /* 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))   */
                   1647:     /* Outputs: fa=f(p(j)) and fx=f(p(j) + xxs * xi(j) ) and f(bx)= f(p(j)+ bx* xi(j)) */
                   1648:     /* Given input ax=axs and xx=xxs, xx might be too far from ax to get a finite f(xx) */
                   1649:     /* Searches on line, outputs (ax, xx, bx) such that fx < min(fa and fb) */
                   1650:     /* 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  1651: #ifdef LINMINORIGINAL
                   1652: #else
                   1653:     if (fx != fx){
                   1654:        xxs=xxs/scale; /* Trying a smaller xx, closer to initial ax=0 */
                   1655:        printf("|");
                   1656:        fprintf(ficlog,"|");
                   1657: #ifdef DEBUGLINMIN
                   1658:        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);
                   1659: #endif
                   1660:     }
                   1661:   }while(fx != fx);
                   1662: #endif
                   1663:   
1.191     brouard  1664: #ifdef DEBUGLINMIN
                   1665:   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  1666:   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  1667: #endif
1.187     brouard  1668:   *fret=brent(ax,xx,bx,f1dim,TOL,&xmin); /* Giving a bracketting triplet (ax, xx, bx), find a minimum, xmin, according to f1dim, *fret(xmin),*/
                   1669:   /* fa = f(p[j] + ax * xi[j]), fx = f(p[j] + xx * xi[j]), fb = f(p[j] + bx * xi[j]) */
                   1670:   /* fmin = f(p[j] + xmin * xi[j]) */
                   1671:   /* P+lambda n in that direction (lambdamin), with TOL between abscisses */
                   1672:   /* f1dim(xmin): for (j=1;j<=ncom;j++) xt[j]=pcom[j]+xmin*xicom[j]; */
1.126     brouard  1673: #ifdef DEBUG
                   1674:   printf("retour brent fret=%.12e xmin=%.12e\n",*fret,xmin);
                   1675:   fprintf(ficlog,"retour brent fret=%.12e xmin=%.12e\n",*fret,xmin);
                   1676: #endif
1.191     brouard  1677: #ifdef DEBUGLINMIN
                   1678:   printf("linmin end ");
1.202     brouard  1679:   fprintf(ficlog,"linmin end ");
1.191     brouard  1680: #endif
1.126     brouard  1681:   for (j=1;j<=n;j++) { 
1.203     brouard  1682: #ifdef LINMINORIGINAL
                   1683:     xi[j] *= xmin; 
                   1684: #else
                   1685: #ifdef DEBUGLINMIN
                   1686:     if(xxs <1.0)
                   1687:       printf(" before xi[%d]=%12.8f", j,xi[j]);
                   1688: #endif
                   1689:     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) */
                   1690: #ifdef DEBUGLINMIN
                   1691:     if(xxs <1.0)
                   1692:       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 );
                   1693: #endif
                   1694: #endif
1.187     brouard  1695:     p[j] += xi[j]; /* Parameters values are updated accordingly */
1.126     brouard  1696:   } 
1.191     brouard  1697: #ifdef DEBUGLINMIN
1.203     brouard  1698:   printf("\n");
1.191     brouard  1699:   printf("Comparing last *frec(xmin=%12.8f)=%12.8f from Brent and frec(0.)=%12.8f \n", xmin, *fret, (*func)(p));
1.202     brouard  1700:   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  1701:   for (j=1;j<=n;j++) { 
1.202     brouard  1702:     printf(" xi[%d]= %14.10f p[%d]= %12.7f",j,xi[j],j,p[j]);
                   1703:     fprintf(ficlog," xi[%d]= %14.10f p[%d]= %12.7f",j,xi[j],j,p[j]);
                   1704:     if(j % ncovmodel == 0){
1.191     brouard  1705:       printf("\n");
1.202     brouard  1706:       fprintf(ficlog,"\n");
                   1707:     }
1.191     brouard  1708:   }
1.203     brouard  1709: #else
1.191     brouard  1710: #endif
1.126     brouard  1711:   free_vector(xicom,1,n); 
                   1712:   free_vector(pcom,1,n); 
                   1713: } 
                   1714: 
                   1715: 
                   1716: /*************** powell ************************/
1.162     brouard  1717: /*
                   1718: Minimization of a function func of n variables. Input consists of an initial starting point
                   1719: p[1..n] ; an initial matrix xi[1..n][1..n] , whose columns contain the initial set of di-
                   1720: rections (usually the n unit vectors); and ftol , the fractional tolerance in the function value
                   1721: such that failure to decrease by more than this amount on one iteration signals doneness. On
                   1722: output, p is set to the best point found, xi is the then-current direction set, fret is the returned
                   1723: function value at p , and iter is the number of iterations taken. The routine linmin is used.
                   1724:  */
1.126     brouard  1725: void powell(double p[], double **xi, int n, double ftol, int *iter, double *fret, 
                   1726:            double (*func)(double [])) 
                   1727: { 
                   1728:   void linmin(double p[], double xi[], int n, double *fret, 
                   1729:              double (*func)(double [])); 
                   1730:   int i,ibig,j; 
                   1731:   double del,t,*pt,*ptt,*xit;
1.181     brouard  1732:   double directest;
1.126     brouard  1733:   double fp,fptt;
                   1734:   double *xits;
                   1735:   int niterf, itmp;
                   1736: 
                   1737:   pt=vector(1,n); 
                   1738:   ptt=vector(1,n); 
                   1739:   xit=vector(1,n); 
                   1740:   xits=vector(1,n); 
                   1741:   *fret=(*func)(p); 
                   1742:   for (j=1;j<=n;j++) pt[j]=p[j]; 
1.202     brouard  1743:   rcurr_time = time(NULL);  
1.126     brouard  1744:   for (*iter=1;;++(*iter)) { 
1.187     brouard  1745:     fp=(*fret); /* From former iteration or initial value */
1.126     brouard  1746:     ibig=0; 
                   1747:     del=0.0; 
1.157     brouard  1748:     rlast_time=rcurr_time;
                   1749:     /* (void) gettimeofday(&curr_time,&tzp); */
                   1750:     rcurr_time = time(NULL);  
                   1751:     curr_time = *localtime(&rcurr_time);
                   1752:     printf("\nPowell iter=%d -2*LL=%.12f %ld sec. %ld sec.",*iter,*fret, rcurr_time-rlast_time, rcurr_time-rstart_time);fflush(stdout);
                   1753:     fprintf(ficlog,"\nPowell iter=%d -2*LL=%.12f %ld sec. %ld sec.",*iter,*fret,rcurr_time-rlast_time, rcurr_time-rstart_time); fflush(ficlog);
                   1754: /*     fprintf(ficrespow,"%d %.12f %ld",*iter,*fret,curr_time.tm_sec-start_time.tm_sec); */
1.192     brouard  1755:     for (i=1;i<=n;i++) {
1.126     brouard  1756:       printf(" %d %.12f",i, p[i]);
                   1757:       fprintf(ficlog," %d %.12lf",i, p[i]);
                   1758:       fprintf(ficrespow," %.12lf", p[i]);
                   1759:     }
                   1760:     printf("\n");
                   1761:     fprintf(ficlog,"\n");
                   1762:     fprintf(ficrespow,"\n");fflush(ficrespow);
                   1763:     if(*iter <=3){
1.157     brouard  1764:       tml = *localtime(&rcurr_time);
                   1765:       strcpy(strcurr,asctime(&tml));
                   1766:       rforecast_time=rcurr_time; 
1.126     brouard  1767:       itmp = strlen(strcurr);
                   1768:       if(strcurr[itmp-1]=='\n')  /* Windows outputs with a new line */
                   1769:        strcurr[itmp-1]='\0';
1.162     brouard  1770:       printf("\nConsidering the time needed for the last iteration #%d: %ld seconds,\n",*iter,rcurr_time-rlast_time);
1.157     brouard  1771:       fprintf(ficlog,"\nConsidering the time needed for this last iteration #%d: %ld seconds,\n",*iter,rcurr_time-rlast_time);
1.126     brouard  1772:       for(niterf=10;niterf<=30;niterf+=10){
1.157     brouard  1773:        rforecast_time=rcurr_time+(niterf-*iter)*(rcurr_time-rlast_time);
                   1774:        forecast_time = *localtime(&rforecast_time);
                   1775:        strcpy(strfor,asctime(&forecast_time));
1.126     brouard  1776:        itmp = strlen(strfor);
                   1777:        if(strfor[itmp-1]=='\n')
                   1778:        strfor[itmp-1]='\0';
1.157     brouard  1779:        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);
                   1780:        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  1781:       }
                   1782:     }
1.187     brouard  1783:     for (i=1;i<=n;i++) { /* For each direction i */
                   1784:       for (j=1;j<=n;j++) xit[j]=xi[j][i]; /* Directions stored from previous iteration with previous scales */
1.126     brouard  1785:       fptt=(*fret); 
                   1786: #ifdef DEBUG
1.203     brouard  1787:       printf("fret=%lf, %lf, %lf \n", *fret, *fret, *fret);
                   1788:       fprintf(ficlog, "fret=%lf, %lf, %lf \n", *fret, *fret, *fret);
1.126     brouard  1789: #endif
1.203     brouard  1790:       printf("%d",i);fflush(stdout); /* print direction (parameter) i */
1.126     brouard  1791:       fprintf(ficlog,"%d",i);fflush(ficlog);
1.188     brouard  1792:       linmin(p,xit,n,fret,func); /* Point p[n]. xit[n] has been loaded for direction i as input.*/
                   1793:                                    /* Outputs are fret(new point p) p is updated and xit rescaled */
                   1794:       if (fabs(fptt-(*fret)) > del) { /* We are keeping the max gain on each of the n directions */
                   1795:        /* because that direction will be replaced unless the gain del is small */
                   1796:        /* in comparison with the 'probable' gain, mu^2, with the last average direction. */
                   1797:        /* Unless the n directions are conjugate some gain in the determinant may be obtained */
                   1798:        /* with the new direction. */
1.126     brouard  1799:        del=fabs(fptt-(*fret)); 
                   1800:        ibig=i; 
                   1801:       } 
                   1802: #ifdef DEBUG
                   1803:       printf("%d %.12e",i,(*fret));
                   1804:       fprintf(ficlog,"%d %.12e",i,(*fret));
                   1805:       for (j=1;j<=n;j++) {
                   1806:        xits[j]=FMAX(fabs(p[j]-pt[j]),1.e-5);
                   1807:        printf(" x(%d)=%.12e",j,xit[j]);
                   1808:        fprintf(ficlog," x(%d)=%.12e",j,xit[j]);
                   1809:       }
                   1810:       for(j=1;j<=n;j++) {
1.162     brouard  1811:        printf(" p(%d)=%.12e",j,p[j]);
                   1812:        fprintf(ficlog," p(%d)=%.12e",j,p[j]);
1.126     brouard  1813:       }
                   1814:       printf("\n");
                   1815:       fprintf(ficlog,"\n");
                   1816: #endif
1.187     brouard  1817:     } /* end loop on each direction i */
                   1818:     /* Convergence test will use last linmin estimation (fret) and compare former iteration (fp) */ 
1.188     brouard  1819:     /* But p and xit have been updated at the end of linmin, *fret corresponds to new p, xit  */
1.187     brouard  1820:     /* New value of last point Pn is not computed, P(n-1) */
1.182     brouard  1821:     if (2.0*fabs(fp-(*fret)) <= ftol*(fabs(fp)+fabs(*fret))) { /* Did we reach enough precision? */
1.188     brouard  1822:       /* We could compare with a chi^2. chisquare(0.95,ddl=1)=3.84 */
                   1823:       /* By adding age*age in a model, the new -2LL should be lower and the difference follows a */
                   1824:       /* a chisquare statistics with 1 degree. To be significant at the 95% level, it should have */
                   1825:       /* decreased of more than 3.84  */
                   1826:       /* By adding age*age and V1*age the gain (-2LL) should be more than 5.99 (ddl=2) */
                   1827:       /* By using V1+V2+V3, the gain should be  7.82, compared with basic 1+age. */
                   1828:       /* By adding 10 parameters more the gain should be 18.31 */
                   1829: 
                   1830:       /* Starting the program with initial values given by a former maximization will simply change */
                   1831:       /* the scales of the directions and the directions, because the are reset to canonical directions */
                   1832:       /* Thus the first calls to linmin will give new points and better maximizations until fp-(*fret) is */
                   1833:       /* under the tolerance value. If the tolerance is very small 1.e-9, it could last long.  */
1.126     brouard  1834: #ifdef DEBUG
                   1835:       int k[2],l;
                   1836:       k[0]=1;
                   1837:       k[1]=-1;
                   1838:       printf("Max: %.12e",(*func)(p));
                   1839:       fprintf(ficlog,"Max: %.12e",(*func)(p));
                   1840:       for (j=1;j<=n;j++) {
                   1841:        printf(" %.12e",p[j]);
                   1842:        fprintf(ficlog," %.12e",p[j]);
                   1843:       }
                   1844:       printf("\n");
                   1845:       fprintf(ficlog,"\n");
                   1846:       for(l=0;l<=1;l++) {
                   1847:        for (j=1;j<=n;j++) {
                   1848:          ptt[j]=p[j]+(p[j]-pt[j])*k[l];
                   1849:          printf("l=%d j=%d ptt=%.12e, xits=%.12e, p=%.12e, xit=%.12e", l,j,ptt[j],xits[j],p[j],xit[j]);
                   1850:          fprintf(ficlog,"l=%d j=%d ptt=%.12e, xits=%.12e, p=%.12e, xit=%.12e", l,j,ptt[j],xits[j],p[j],xit[j]);
                   1851:        }
                   1852:        printf("func(ptt)=%.12e, deriv=%.12e\n",(*func)(ptt),(ptt[j]-p[j])/((*func)(ptt)-(*func)(p)));
                   1853:        fprintf(ficlog,"func(ptt)=%.12e, deriv=%.12e\n",(*func)(ptt),(ptt[j]-p[j])/((*func)(ptt)-(*func)(p)));
                   1854:       }
                   1855: #endif
                   1856: 
                   1857: 
                   1858:       free_vector(xit,1,n); 
                   1859:       free_vector(xits,1,n); 
                   1860:       free_vector(ptt,1,n); 
                   1861:       free_vector(pt,1,n); 
                   1862:       return; 
1.192     brouard  1863:     } /* enough precision */ 
1.126     brouard  1864:     if (*iter == ITMAX) nrerror("powell exceeding maximum iterations."); 
1.181     brouard  1865:     for (j=1;j<=n;j++) { /* Computes the extrapolated point P_0 + 2 (P_n-P_0) */
1.126     brouard  1866:       ptt[j]=2.0*p[j]-pt[j]; 
                   1867:       xit[j]=p[j]-pt[j]; 
                   1868:       pt[j]=p[j]; 
                   1869:     } 
1.181     brouard  1870:     fptt=(*func)(ptt); /* f_3 */
1.192     brouard  1871: #ifdef POWELLF1F3
                   1872: #else
1.161     brouard  1873:     if (fptt < fp) { /* If extrapolated point is better, decide if we keep that new direction or not */
1.192     brouard  1874: #endif
1.162     brouard  1875:       /* (x1 f1=fp), (x2 f2=*fret), (x3 f3=fptt), (xm fm) */
1.161     brouard  1876:       /* From x1 (P0) distance of x2 is at h and x3 is 2h */
1.162     brouard  1877:       /* Let f"(x2) be the 2nd derivative equal everywhere.  */
                   1878:       /* Then the parabolic through (x1,f1), (x2,f2) and (x3,f3) */
                   1879:       /* will reach at f3 = fm + h^2/2 f"m  ; f" = (f1 -2f2 +f3 ) / h**2 */
1.181     brouard  1880:       /* Conditional for using this new direction is that mu^2 = (f1-2f2+f3)^2 /2 < del */
1.161     brouard  1881:       /* t=2.0*(fp-2.0*(*fret)+fptt)*SQR(fp-(*fret)-del)-del*SQR(fp-fptt); */
1.183     brouard  1882: #ifdef NRCORIGINAL
                   1883:       t=2.0*(fp-2.0*(*fret)+fptt)*SQR(fp-(*fret)-del)- del*SQR(fp-fptt); /* Original Numerical Recipes in C*/
                   1884: #else
                   1885:       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  1886:       t= t- del*SQR(fp-fptt);
1.183     brouard  1887: #endif
1.202     brouard  1888:       directest = fp-2.0*(*fret)+fptt - 2.0 * del; /* If delta was big enough we change it for a new direction */
1.161     brouard  1889: #ifdef DEBUG
1.181     brouard  1890:       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);
                   1891:       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  1892:       printf("t3= %.12lf, t4= %.12lf, t3*= %.12lf, t4*= %.12lf\n",SQR(fp-(*fret)-del),SQR(fp-fptt),
                   1893:             (fp-(*fret)-del)*(fp-(*fret)-del),(fp-fptt)*(fp-fptt));
                   1894:       fprintf(ficlog,"t3= %.12lf, t4= %.12lf, t3*= %.12lf, t4*= %.12lf\n",SQR(fp-(*fret)-del),SQR(fp-fptt),
                   1895:             (fp-(*fret)-del)*(fp-(*fret)-del),(fp-fptt)*(fp-fptt));
                   1896:       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);
                   1897:       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);
                   1898: #endif
1.183     brouard  1899: #ifdef POWELLORIGINAL
                   1900:       if (t < 0.0) { /* Then we use it for new direction */
                   1901: #else
1.182     brouard  1902:       if (directest*t < 0.0) { /* Contradiction between both tests */
1.202     brouard  1903:        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  1904:         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  1905:         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  1906:         fprintf(ficlog,"f1-2f2+f3= %.12lf, f1-f2-del= %.12lf, f1-f3= %.12lf\n",fp-2.0*(*fret)+fptt, fp -(*fret) -del, fp-fptt);
                   1907:       } 
1.181     brouard  1908:       if (directest < 0.0) { /* Then we use it for new direction */
                   1909: #endif
1.191     brouard  1910: #ifdef DEBUGLINMIN
                   1911:        printf("Before linmin in direction P%d-P0\n",n);
                   1912:        for (j=1;j<=n;j++) { 
1.202     brouard  1913:          printf(" Before xit[%d]= %12.7f p[%d]= %12.7f",j,xit[j],j,p[j]);
                   1914:          fprintf(ficlog," Before xit[%d]= %12.7f p[%d]= %12.7f",j,xit[j],j,p[j]);
                   1915:          if(j % ncovmodel == 0){
1.191     brouard  1916:            printf("\n");
1.202     brouard  1917:            fprintf(ficlog,"\n");
                   1918:          }
1.191     brouard  1919:        }
                   1920: #endif
1.187     brouard  1921:        linmin(p,xit,n,fret,func); /* computes minimum on the extrapolated direction: changes p and rescales xit.*/
1.191     brouard  1922: #ifdef DEBUGLINMIN
                   1923:        for (j=1;j<=n;j++) { 
                   1924:          printf("After xit[%d]= %12.7f p[%d]= %12.7f",j,xit[j],j,p[j]);
1.202     brouard  1925:          fprintf(ficlog,"After xit[%d]= %12.7f p[%d]= %12.7f",j,xit[j],j,p[j]);
                   1926:          if(j % ncovmodel == 0){
1.191     brouard  1927:            printf("\n");
1.202     brouard  1928:            fprintf(ficlog,"\n");
                   1929:          }
1.191     brouard  1930:        }
                   1931: #endif
1.126     brouard  1932:        for (j=1;j<=n;j++) { 
1.181     brouard  1933:          xi[j][ibig]=xi[j][n]; /* Replace direction with biggest decrease by last direction n */
                   1934:          xi[j][n]=xit[j];      /* and this nth direction by the by the average p_0 p_n */
1.126     brouard  1935:        }
1.181     brouard  1936:        printf("Gaining to use new average direction of P0 P%d instead of biggest increase direction %d :\n",n,ibig);
                   1937:        fprintf(ficlog,"Gaining to use new average direction of P0 P%d instead of biggest increase direction %d :\n",n,ibig);
1.161     brouard  1938: 
1.126     brouard  1939: #ifdef DEBUG
1.164     brouard  1940:        printf("Direction changed  last moved %d in place of ibig=%d, new last is the average:\n",n,ibig);
                   1941:        fprintf(ficlog,"Direction changed  last moved %d in place of ibig=%d, new last is the average:\n",n,ibig);
1.126     brouard  1942:        for(j=1;j<=n;j++){
                   1943:          printf(" %.12e",xit[j]);
                   1944:          fprintf(ficlog," %.12e",xit[j]);
                   1945:        }
                   1946:        printf("\n");
                   1947:        fprintf(ficlog,"\n");
                   1948: #endif
1.192     brouard  1949:       } /* end of t or directest negative */
                   1950: #ifdef POWELLF1F3
                   1951: #else
1.162     brouard  1952:     } /* end if (fptt < fp)  */
1.192     brouard  1953: #endif
                   1954:   } /* loop iteration */ 
1.126     brouard  1955: } 
                   1956: 
                   1957: /**** Prevalence limit (stable or period prevalence)  ****************/
                   1958: 
1.203     brouard  1959: double **prevalim(double **prlim, int nlstate, double x[], double age, double **oldm, double **savm, double ftolpl, int *ncvyear, int ij)
1.126     brouard  1960: {
                   1961:   /* Computes the prevalence limit in each live state at age x by left multiplying the unit
1.203     brouard  1962:      matrix by transitions matrix until convergence is reached with precision ftolpl */
1.206   ! brouard  1963:   /* Wx= Wx-1 Px-1= Wx-2 Px-2 Px-1  = Wx-n Px-n ... Px-2 Px-1 I */
        !          1964:   /* Wx is row vector: population in state 1, population in state 2, population dead */
        !          1965:   /* or prevalence in state 1, prevalence in state 2, 0 */
        !          1966:   /* newm is the matrix after multiplications, its rows are identical at a factor */
        !          1967:   /* Initial matrix pimij */
        !          1968:   /* {0.85204250825084937, 0.13044499163996345, 0.017512500109187184, */
        !          1969:   /* 0.090851990222114765, 0.88271245433047185, 0.026435555447413338, */
        !          1970:   /*  0,                   0                  , 1} */
        !          1971:   /*
        !          1972:    * and after some iteration: */
        !          1973:   /* {0.45504275246439968, 0.42731458730878791, 0.11764266022681241, */
        !          1974:   /*  0.45201005341706885, 0.42865420071559901, 0.11933574586733192, */
        !          1975:   /*  0,                   0                  , 1} */
        !          1976:   /* And prevalence by suppressing the deaths are close to identical rows in prlim: */
        !          1977:   /* {0.51571254859325999, 0.4842874514067399, */
        !          1978:   /*  0.51326036147820708, 0.48673963852179264} */
        !          1979:   /* If we start from prlim again, prlim tends to a constant matrix */
        !          1980: 
1.126     brouard  1981:   int i, ii,j,k;
                   1982:   double min, max, maxmin, maxmax,sumnew=0.;
1.145     brouard  1983:   /* double **matprod2(); */ /* test */
1.131     brouard  1984:   double **out, cov[NCOVMAX+1], **pmij();
1.126     brouard  1985:   double **newm;
1.202     brouard  1986:   double agefin, delaymax=100 ; /* Max number of years to converge */
1.203     brouard  1987:   int ncvloop=0;
1.169     brouard  1988:   
1.126     brouard  1989:   for (ii=1;ii<=nlstate+ndeath;ii++)
                   1990:     for (j=1;j<=nlstate+ndeath;j++){
                   1991:       oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   1992:     }
1.169     brouard  1993:   
                   1994:   cov[1]=1.;
                   1995:   
                   1996:   /* Even if hstepm = 1, at least one multiplication by the unit matrix */
1.202     brouard  1997:   /* Start at agefin= age, computes the matrix of passage and loops decreasing agefin until convergence is reached */
1.126     brouard  1998:   for(agefin=age-stepm/YEARM; agefin>=age-delaymax; agefin=agefin-stepm/YEARM){
1.202     brouard  1999:     ncvloop++;
1.126     brouard  2000:     newm=savm;
                   2001:     /* Covariates have to be included here again */
1.138     brouard  2002:     cov[2]=agefin;
1.187     brouard  2003:     if(nagesqr==1)
                   2004:       cov[3]= agefin*agefin;;
1.138     brouard  2005:     for (k=1; k<=cptcovn;k++) {
1.200     brouard  2006:       /* cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(ij,Tvar[k])]; */
                   2007:       cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(ij,k)];
1.198     brouard  2008:       /* 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  2009:     }
1.186     brouard  2010:     /*wrong? for (k=1; k<=cptcovage;k++) cov[2+Tage[k]]=cov[2+Tage[k]]*cov[2]; */
1.200     brouard  2011:     /* for (k=1; k<=cptcovage;k++) cov[2+nagesqr+Tage[k]]=nbcode[Tvar[k]][codtabm(ij,Tvar[k])]*cov[2]; */
                   2012:     for (k=1; k<=cptcovage;k++) cov[2+nagesqr+Tage[k]]=nbcode[Tvar[k]][codtabm(ij,k)]*cov[2];
1.186     brouard  2013:     for (k=1; k<=cptcovprod;k++) /* Useless */
1.200     brouard  2014:       /* cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,Tvard[k][1])] * nbcode[Tvard[k][2]][codtabm(ij,Tvard[k][2])]; */
                   2015:       cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,k)] * nbcode[Tvard[k][2]][codtabm(ij,k)];
1.138     brouard  2016:     
                   2017:     /*printf("ij=%d cptcovprod=%d tvar=%d ", ij, cptcovprod, Tvar[1]);*/
                   2018:     /*printf("ij=%d cov[3]=%lf cov[4]=%lf \n",ij, cov[3],cov[4]);*/
                   2019:     /*printf("ij=%d cov[3]=%lf \n",ij, cov[3]);*/
1.145     brouard  2020:     /* savm=pmij(pmmij,cov,ncovmodel,x,nlstate); */
                   2021:     /* out=matprod2(newm, pmij(pmmij,cov,ncovmodel,x,nlstate),1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, oldm); /\* Bug Valgrind *\/ */
1.142     brouard  2022:     out=matprod2(newm, pmij(pmmij,cov,ncovmodel,x,nlstate),1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, oldm); /* Bug Valgrind */
1.138     brouard  2023:     
1.126     brouard  2024:     savm=oldm;
                   2025:     oldm=newm;
                   2026:     maxmax=0.;
                   2027:     for(j=1;j<=nlstate;j++){
                   2028:       min=1.;
                   2029:       max=0.;
                   2030:       for(i=1; i<=nlstate; i++) {
                   2031:        sumnew=0;
                   2032:        for(k=1; k<=ndeath; k++) sumnew+=newm[i][nlstate+k];
                   2033:        prlim[i][j]= newm[i][j]/(1-sumnew);
                   2034:        max=FMAX(max,prlim[i][j]);
                   2035:        min=FMIN(min,prlim[i][j]);
1.206   ! brouard  2036:         printf(" age= %d prevalim i=%d, j=%d, prmlim[%d][%d]=%f, agefin=%d max=%f min=%f\n", (int)age, i, j, i, j, prlim[i][j],(int)agefin, max, min);
1.126     brouard  2037:       }
1.203     brouard  2038:       maxmin=(max-min)/(max+min)*2;
1.126     brouard  2039:       maxmax=FMAX(maxmax,maxmin);
1.169     brouard  2040:     } /* j loop */
1.203     brouard  2041:     *ncvyear= (int)age- (int)agefin;
1.206   ! brouard  2042:     printf("maxmax=%lf maxmin=%lf ncvloop=%ld, age=%d, agefin=%d ncvyear=%d \n", maxmax, maxmin, ncvloop, (int)age, (int)agefin, *ncvyear);
1.126     brouard  2043:     if(maxmax < ftolpl){
1.203     brouard  2044:       /* printf("maxmax=%lf maxmin=%lf ncvloop=%ld, age=%d, agefin=%d ncvyear=%d \n", maxmax, maxmin, ncvloop, (int)age, (int)agefin, *ncvyear); */
1.126     brouard  2045:       return prlim;
                   2046:     }
1.169     brouard  2047:   } /* age loop */
1.203     brouard  2048:   printf("Warning: the stable prevalence at age %d did not converge with the required precision %g > ftolpl=%g. \n\
                   2049: Earliest age to start was %d-%d=%d, ncvloop=%d, ncvyear=%d\n", (int)age, maxmax, ftolpl, (int)age, (int)delaymax, (int)agefin, ncvloop, *ncvyear);
                   2050: /* 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); */
1.169     brouard  2051:   return prlim; /* should not reach here */
1.126     brouard  2052: }
                   2053: 
                   2054: /*************** transition probabilities ***************/ 
                   2055: 
                   2056: double **pmij(double **ps, double *cov, int ncovmodel, double *x, int nlstate )
                   2057: {
1.138     brouard  2058:   /* According to parameters values stored in x and the covariate's values stored in cov,
                   2059:      computes the probability to be observed in state j being in state i by appying the
                   2060:      model to the ncovmodel covariates (including constant and age).
                   2061:      lnpijopii=ln(pij/pii)= aij+bij*age+cij*v1+dij*v2+... = sum_nc=1^ncovmodel xij(nc)*cov[nc]
                   2062:      and, according on how parameters are entered, the position of the coefficient xij(nc) of the
                   2063:      ncth covariate in the global vector x is given by the formula:
                   2064:      j<i nc+((i-1)*(nlstate+ndeath-1)+j-1)*ncovmodel
                   2065:      j>=i nc + ((i-1)*(nlstate+ndeath-1)+(j-2))*ncovmodel
                   2066:      Computes ln(pij/pii) (lnpijopii), deduces pij/pii by exponentiation,
                   2067:      sums on j different of i to get 1-pii/pii, deduces pii, and then all pij.
                   2068:      Outputs ps[i][j] the probability to be observed in j being in j according to
                   2069:      the values of the covariates cov[nc] and corresponding parameter values x[nc+shiftij]
                   2070:   */
                   2071:   double s1, lnpijopii;
1.126     brouard  2072:   /*double t34;*/
1.164     brouard  2073:   int i,j, nc, ii, jj;
1.126     brouard  2074: 
                   2075:     for(i=1; i<= nlstate; i++){
                   2076:       for(j=1; j<i;j++){
1.138     brouard  2077:        for (nc=1, lnpijopii=0.;nc <=ncovmodel; nc++){
                   2078:          /*lnpijopii += param[i][j][nc]*cov[nc];*/
                   2079:          lnpijopii += x[nc+((i-1)*(nlstate+ndeath-1)+j-1)*ncovmodel]*cov[nc];
                   2080: /*      printf("Int j<i s1=%.17e, lnpijopii=%.17e\n",s1,lnpijopii); */
1.126     brouard  2081:        }
1.138     brouard  2082:        ps[i][j]=lnpijopii; /* In fact ln(pij/pii) */
                   2083: /*     printf("s1=%.17e, lnpijopii=%.17e\n",s1,lnpijopii); */
1.126     brouard  2084:       }
                   2085:       for(j=i+1; j<=nlstate+ndeath;j++){
1.138     brouard  2086:        for (nc=1, lnpijopii=0.;nc <=ncovmodel; nc++){
                   2087:          /*lnpijopii += x[(i-1)*nlstate*ncovmodel+(j-2)*ncovmodel+nc+(i-1)*(ndeath-1)*ncovmodel]*cov[nc];*/
                   2088:          lnpijopii += x[nc + ((i-1)*(nlstate+ndeath-1)+(j-2))*ncovmodel]*cov[nc];
                   2089: /*       printf("Int j>i s1=%.17e, lnpijopii=%.17e %lx %lx\n",s1,lnpijopii,s1,lnpijopii); */
1.126     brouard  2090:        }
1.138     brouard  2091:        ps[i][j]=lnpijopii; /* In fact ln(pij/pii) */
1.126     brouard  2092:       }
                   2093:     }
                   2094:     
                   2095:     for(i=1; i<= nlstate; i++){
                   2096:       s1=0;
1.131     brouard  2097:       for(j=1; j<i; j++){
1.138     brouard  2098:        s1+=exp(ps[i][j]); /* In fact sums pij/pii */
1.131     brouard  2099:        /*printf("debug1 %d %d ps=%lf exp(ps)=%lf s1+=%lf\n",i,j,ps[i][j],exp(ps[i][j]),s1); */
                   2100:       }
                   2101:       for(j=i+1; j<=nlstate+ndeath; j++){
1.138     brouard  2102:        s1+=exp(ps[i][j]); /* In fact sums pij/pii */
1.131     brouard  2103:        /*printf("debug2 %d %d ps=%lf exp(ps)=%lf s1+=%lf\n",i,j,ps[i][j],exp(ps[i][j]),s1); */
                   2104:       }
1.138     brouard  2105:       /* s1= sum_{j<>i} pij/pii=(1-pii)/pii and thus pii is known from s1 */
1.126     brouard  2106:       ps[i][i]=1./(s1+1.);
1.138     brouard  2107:       /* Computing other pijs */
1.126     brouard  2108:       for(j=1; j<i; j++)
                   2109:        ps[i][j]= exp(ps[i][j])*ps[i][i];
                   2110:       for(j=i+1; j<=nlstate+ndeath; j++)
                   2111:        ps[i][j]= exp(ps[i][j])*ps[i][i];
                   2112:       /* ps[i][nlstate+1]=1.-s1- ps[i][i];*/ /* Sum should be 1 */
                   2113:     } /* end i */
                   2114:     
                   2115:     for(ii=nlstate+1; ii<= nlstate+ndeath; ii++){
                   2116:       for(jj=1; jj<= nlstate+ndeath; jj++){
                   2117:        ps[ii][jj]=0;
                   2118:        ps[ii][ii]=1;
                   2119:       }
                   2120:     }
                   2121:     
1.145     brouard  2122:     
                   2123:     /* for(ii=1; ii<= nlstate+ndeath; ii++){ */
                   2124:     /*   for(jj=1; jj<= nlstate+ndeath; jj++){ */
                   2125:     /*         printf(" pmij  ps[%d][%d]=%lf ",ii,jj,ps[ii][jj]); */
                   2126:     /*   } */
                   2127:     /*   printf("\n "); */
                   2128:     /* } */
                   2129:     /* printf("\n ");printf("%lf ",cov[2]);*/
                   2130:     /*
1.126     brouard  2131:       for(i=1; i<= npar; i++) printf("%f ",x[i]);
                   2132:       goto end;*/
                   2133:     return ps;
                   2134: }
                   2135: 
                   2136: /**************** Product of 2 matrices ******************/
                   2137: 
1.145     brouard  2138: double **matprod2(double **out, double **in,int nrl, int nrh, int ncl, int nch, int ncolol, int ncoloh, double **b)
1.126     brouard  2139: {
                   2140:   /* Computes the matrix product of in(1,nrh-nrl+1)(1,nch-ncl+1) times
                   2141:      b(1,nch-ncl+1)(1,ncoloh-ncolol+1) into out(...) */
                   2142:   /* in, b, out are matrice of pointers which should have been initialized 
                   2143:      before: only the contents of out is modified. The function returns
                   2144:      a pointer to pointers identical to out */
1.145     brouard  2145:   int i, j, k;
1.126     brouard  2146:   for(i=nrl; i<= nrh; i++)
1.145     brouard  2147:     for(k=ncolol; k<=ncoloh; k++){
                   2148:       out[i][k]=0.;
                   2149:       for(j=ncl; j<=nch; j++)
                   2150:        out[i][k] +=in[i][j]*b[j][k];
                   2151:     }
1.126     brouard  2152:   return out;
                   2153: }
                   2154: 
                   2155: 
                   2156: /************* Higher Matrix Product ***************/
                   2157: 
                   2158: double ***hpxij(double ***po, int nhstepm, double age, int hstepm, double *x, int nlstate, int stepm, double **oldm, double **savm, int ij )
                   2159: {
                   2160:   /* Computes the transition matrix starting at age 'age' over 
                   2161:      'nhstepm*hstepm*stepm' months (i.e. until
                   2162:      age (in years)  age+nhstepm*hstepm*stepm/12) by multiplying 
                   2163:      nhstepm*hstepm matrices. 
                   2164:      Output is stored in matrix po[i][j][h] for h every 'hstepm' step 
                   2165:      (typically every 2 years instead of every month which is too big 
                   2166:      for the memory).
                   2167:      Model is determined by parameters x and covariates have to be 
                   2168:      included manually here. 
                   2169: 
                   2170:      */
                   2171: 
                   2172:   int i, j, d, h, k;
1.131     brouard  2173:   double **out, cov[NCOVMAX+1];
1.126     brouard  2174:   double **newm;
1.187     brouard  2175:   double agexact;
1.126     brouard  2176: 
                   2177:   /* Hstepm could be zero and should return the unit matrix */
                   2178:   for (i=1;i<=nlstate+ndeath;i++)
                   2179:     for (j=1;j<=nlstate+ndeath;j++){
                   2180:       oldm[i][j]=(i==j ? 1.0 : 0.0);
                   2181:       po[i][j][0]=(i==j ? 1.0 : 0.0);
                   2182:     }
                   2183:   /* Even if hstepm = 1, at least one multiplication by the unit matrix */
                   2184:   for(h=1; h <=nhstepm; h++){
                   2185:     for(d=1; d <=hstepm; d++){
                   2186:       newm=savm;
                   2187:       /* Covariates have to be included here again */
                   2188:       cov[1]=1.;
1.187     brouard  2189:       agexact=age+((h-1)*hstepm + (d-1))*stepm/YEARM;
                   2190:       cov[2]=agexact;
                   2191:       if(nagesqr==1)
                   2192:        cov[3]= agexact*agexact;
1.131     brouard  2193:       for (k=1; k<=cptcovn;k++) 
1.200     brouard  2194:        cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(ij,k)];
                   2195:        /* cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(ij,Tvar[k])]; */
1.186     brouard  2196:       for (k=1; k<=cptcovage;k++) /* Should start at cptcovn+1 */
                   2197:        /* cov[2+Tage[k]]=cov[2+Tage[k]]*cov[2]; */
1.200     brouard  2198:        cov[2+nagesqr+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(ij,k)]*cov[2];
                   2199:        /* cov[2+nagesqr+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(ij,Tvar[Tage[k]])]*cov[2]; */
1.145     brouard  2200:       for (k=1; k<=cptcovprod;k++) /* Useless because included in cptcovn */
1.200     brouard  2201:        cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,k)]*nbcode[Tvard[k][2]][codtabm(ij,k)];
                   2202:        /* 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  2203: 
                   2204: 
                   2205:       /*printf("hxi cptcov=%d cptcode=%d\n",cptcov,cptcode);*/
                   2206:       /*printf("h=%d d=%d age=%f cov=%f\n",h,d,age,cov[2]);*/
                   2207:       out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, 
                   2208:                   pmij(pmmij,cov,ncovmodel,x,nlstate));
                   2209:       savm=oldm;
                   2210:       oldm=newm;
                   2211:     }
                   2212:     for(i=1; i<=nlstate+ndeath; i++)
                   2213:       for(j=1;j<=nlstate+ndeath;j++) {
                   2214:        po[i][j][h]=newm[i][j];
1.128     brouard  2215:        /*if(h==nhstepm) printf("po[%d][%d][%d]=%f ",i,j,h,po[i][j][h]);*/
1.126     brouard  2216:       }
1.128     brouard  2217:     /*printf("h=%d ",h);*/
1.126     brouard  2218:   } /* end h */
1.128     brouard  2219: /*     printf("\n H=%d \n",h); */
1.126     brouard  2220:   return po;
                   2221: }
                   2222: 
1.162     brouard  2223: #ifdef NLOPT
                   2224:   double  myfunc(unsigned n, const double *p1, double *grad, void *pd){
                   2225:   double fret;
                   2226:   double *xt;
                   2227:   int j;
                   2228:   myfunc_data *d2 = (myfunc_data *) pd;
                   2229: /* xt = (p1-1); */
                   2230:   xt=vector(1,n); 
                   2231:   for (j=1;j<=n;j++)   xt[j]=p1[j-1]; /* xt[1]=p1[0] */
                   2232: 
                   2233:   fret=(d2->function)(xt); /*  p xt[1]@8 is fine */
                   2234:   /* fret=(*func)(xt); /\*  p xt[1]@8 is fine *\/ */
                   2235:   printf("Function = %.12lf ",fret);
                   2236:   for (j=1;j<=n;j++) printf(" %d %.8lf", j, xt[j]); 
                   2237:   printf("\n");
                   2238:  free_vector(xt,1,n);
                   2239:   return fret;
                   2240: }
                   2241: #endif
1.126     brouard  2242: 
                   2243: /*************** log-likelihood *************/
                   2244: double func( double *x)
                   2245: {
                   2246:   int i, ii, j, k, mi, d, kk;
1.131     brouard  2247:   double l, ll[NLSTATEMAX+1], cov[NCOVMAX+1];
1.126     brouard  2248:   double **out;
                   2249:   double sw; /* Sum of weights */
                   2250:   double lli; /* Individual log likelihood */
                   2251:   int s1, s2;
                   2252:   double bbh, survp;
                   2253:   long ipmx;
1.187     brouard  2254:   double agexact;
1.126     brouard  2255:   /*extern weight */
                   2256:   /* We are differentiating ll according to initial status */
                   2257:   /*  for (i=1;i<=npar;i++) printf("%f ", x[i]);*/
                   2258:   /*for(i=1;i<imx;i++) 
                   2259:     printf(" %d\n",s[4][i]);
                   2260:   */
1.162     brouard  2261: 
                   2262:   ++countcallfunc;
                   2263: 
1.126     brouard  2264:   cov[1]=1.;
                   2265: 
                   2266:   for(k=1; k<=nlstate; k++) ll[k]=0.;
                   2267: 
                   2268:   if(mle==1){
                   2269:     for (i=1,ipmx=0, sw=0.; i<=imx; i++){
1.138     brouard  2270:       /* Computes the values of the ncovmodel covariates of the model
                   2271:         depending if the covariates are fixed or variying (age dependent) and stores them in cov[]
                   2272:         Then computes with function pmij which return a matrix p[i][j] giving the elementary probability
                   2273:         to be observed in j being in i according to the model.
                   2274:        */
1.145     brouard  2275:       for (k=1; k<=cptcovn;k++){ /* Simple and product covariates without age* products */
1.187     brouard  2276:          cov[2+nagesqr+k]=covar[Tvar[k]][i];
1.145     brouard  2277:       }
1.137     brouard  2278:       /* In model V2+V1*V4+age*V3+V3*V2 Tvar[1] is V2, Tvar[2=V1*V4] 
1.138     brouard  2279:         is 6, Tvar[3=age*V3] should not be computed because of age Tvar[4=V3*V2] 
1.137     brouard  2280:         has been calculated etc */
1.126     brouard  2281:       for(mi=1; mi<= wav[i]-1; mi++){
                   2282:        for (ii=1;ii<=nlstate+ndeath;ii++)
                   2283:          for (j=1;j<=nlstate+ndeath;j++){
                   2284:            oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   2285:            savm[ii][j]=(ii==j ? 1.0 : 0.0);
                   2286:          }
                   2287:        for(d=0; d<dh[mi][i]; d++){
                   2288:          newm=savm;
1.187     brouard  2289:          agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;
                   2290:          cov[2]=agexact;
                   2291:          if(nagesqr==1)
                   2292:            cov[3]= agexact*agexact;
1.126     brouard  2293:          for (kk=1; kk<=cptcovage;kk++) {
1.187     brouard  2294:            cov[Tage[kk]+2+nagesqr]=covar[Tvar[Tage[kk]]][i]*agexact; /* Tage[kk] gives the data-covariate associated with age */
1.126     brouard  2295:          }
                   2296:          out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
                   2297:                       1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
                   2298:          savm=oldm;
                   2299:          oldm=newm;
                   2300:        } /* end mult */
                   2301:       
                   2302:        /*lli=log(out[s[mw[mi][i]][i]][s[mw[mi+1][i]][i]]);*/ /* Original formula */
                   2303:        /* But now since version 0.9 we anticipate for bias at large stepm.
                   2304:         * If stepm is larger than one month (smallest stepm) and if the exact delay 
                   2305:         * (in months) between two waves is not a multiple of stepm, we rounded to 
                   2306:         * the nearest (and in case of equal distance, to the lowest) interval but now
                   2307:         * we keep into memory the bias bh[mi][i] and also the previous matrix product
                   2308:         * (i.e to dh[mi][i]-1) saved in 'savm'. Then we inter(extra)polate the
                   2309:         * probability in order to take into account the bias as a fraction of the way
                   2310:         * from savm to out if bh is negative or even beyond if bh is positive. bh varies
                   2311:         * -stepm/2 to stepm/2 .
                   2312:         * For stepm=1 the results are the same as for previous versions of Imach.
                   2313:         * For stepm > 1 the results are less biased than in previous versions. 
                   2314:         */
                   2315:        s1=s[mw[mi][i]][i];
                   2316:        s2=s[mw[mi+1][i]][i];
                   2317:        bbh=(double)bh[mi][i]/(double)stepm; 
                   2318:        /* bias bh is positive if real duration
                   2319:         * is higher than the multiple of stepm and negative otherwise.
                   2320:         */
                   2321:        /* lli= (savm[s1][s2]>1.e-8 ?(1.+bbh)*log(out[s1][s2])- bbh*log(savm[s1][s2]):log((1.+bbh)*out[s1][s2]));*/
                   2322:        if( s2 > nlstate){ 
                   2323:          /* i.e. if s2 is a death state and if the date of death is known 
                   2324:             then the contribution to the likelihood is the probability to 
                   2325:             die between last step unit time and current  step unit time, 
                   2326:             which is also equal to probability to die before dh 
                   2327:             minus probability to die before dh-stepm . 
                   2328:             In version up to 0.92 likelihood was computed
                   2329:        as if date of death was unknown. Death was treated as any other
                   2330:        health state: the date of the interview describes the actual state
                   2331:        and not the date of a change in health state. The former idea was
                   2332:        to consider that at each interview the state was recorded
                   2333:        (healthy, disable or death) and IMaCh was corrected; but when we
                   2334:        introduced the exact date of death then we should have modified
                   2335:        the contribution of an exact death to the likelihood. This new
                   2336:        contribution is smaller and very dependent of the step unit
                   2337:        stepm. It is no more the probability to die between last interview
                   2338:        and month of death but the probability to survive from last
                   2339:        interview up to one month before death multiplied by the
                   2340:        probability to die within a month. Thanks to Chris
                   2341:        Jackson for correcting this bug.  Former versions increased
                   2342:        mortality artificially. The bad side is that we add another loop
                   2343:        which slows down the processing. The difference can be up to 10%
                   2344:        lower mortality.
                   2345:          */
1.183     brouard  2346:        /* If, at the beginning of the maximization mostly, the
                   2347:           cumulative probability or probability to be dead is
                   2348:           constant (ie = 1) over time d, the difference is equal to
                   2349:           0.  out[s1][3] = savm[s1][3]: probability, being at state
                   2350:           s1 at precedent wave, to be dead a month before current
                   2351:           wave is equal to probability, being at state s1 at
                   2352:           precedent wave, to be dead at mont of the current
                   2353:           wave. Then the observed probability (that this person died)
                   2354:           is null according to current estimated parameter. In fact,
                   2355:           it should be very low but not zero otherwise the log go to
                   2356:           infinity.
                   2357:        */
                   2358: /* #ifdef INFINITYORIGINAL */
                   2359: /*         lli=log(out[s1][s2] - savm[s1][s2]); */
                   2360: /* #else */
                   2361: /*       if ((out[s1][s2] - savm[s1][s2]) < mytinydouble)  */
                   2362: /*         lli=log(mytinydouble); */
                   2363: /*       else */
                   2364: /*         lli=log(out[s1][s2] - savm[s1][s2]); */
                   2365: /* #endif */
                   2366:            lli=log(out[s1][s2] - savm[s1][s2]);
1.126     brouard  2367: 
                   2368:        } else if  (s2==-2) {
                   2369:          for (j=1,survp=0. ; j<=nlstate; j++) 
                   2370:            survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j];
                   2371:          /*survp += out[s1][j]; */
                   2372:          lli= log(survp);
                   2373:        }
                   2374:        
                   2375:        else if  (s2==-4) { 
                   2376:          for (j=3,survp=0. ; j<=nlstate; j++)  
                   2377:            survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j];
                   2378:          lli= log(survp); 
                   2379:        } 
                   2380: 
                   2381:        else if  (s2==-5) { 
                   2382:          for (j=1,survp=0. ; j<=2; j++)  
                   2383:            survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j];
                   2384:          lli= log(survp); 
                   2385:        } 
                   2386:        
                   2387:        else{
                   2388:          lli= log((1.+bbh)*out[s1][s2]- bbh*savm[s1][s2]); /* linear interpolation */
                   2389:          /*  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 */
                   2390:        } 
                   2391:        /*lli=(1.+bbh)*log(out[s1][s2])- bbh*log(savm[s1][s2]);*/
                   2392:        /*if(lli ==000.0)*/
                   2393:        /*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); */
                   2394:        ipmx +=1;
                   2395:        sw += weight[i];
                   2396:        ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
1.183     brouard  2397:        /* if (lli < log(mytinydouble)){ */
                   2398:        /*   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); */
                   2399:        /*   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]); */
                   2400:        /* } */
1.126     brouard  2401:       } /* end of wave */
                   2402:     } /* end of individual */
                   2403:   }  else if(mle==2){
                   2404:     for (i=1,ipmx=0, sw=0.; i<=imx; i++){
1.187     brouard  2405:       for (k=1; k<=cptcovn;k++) cov[2+nagesqr+k]=covar[Tvar[k]][i];
1.126     brouard  2406:       for(mi=1; mi<= wav[i]-1; mi++){
                   2407:        for (ii=1;ii<=nlstate+ndeath;ii++)
                   2408:          for (j=1;j<=nlstate+ndeath;j++){
                   2409:            oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   2410:            savm[ii][j]=(ii==j ? 1.0 : 0.0);
                   2411:          }
                   2412:        for(d=0; d<=dh[mi][i]; d++){
                   2413:          newm=savm;
1.187     brouard  2414:          agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;
                   2415:          cov[2]=agexact;
                   2416:          if(nagesqr==1)
                   2417:            cov[3]= agexact*agexact;
1.126     brouard  2418:          for (kk=1; kk<=cptcovage;kk++) {
1.187     brouard  2419:            cov[Tage[kk]+2+nagesqr]=covar[Tvar[Tage[kk]]][i]*agexact;
1.126     brouard  2420:          }
                   2421:          out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
                   2422:                       1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
                   2423:          savm=oldm;
                   2424:          oldm=newm;
                   2425:        } /* end mult */
                   2426:       
                   2427:        s1=s[mw[mi][i]][i];
                   2428:        s2=s[mw[mi+1][i]][i];
                   2429:        bbh=(double)bh[mi][i]/(double)stepm; 
                   2430:        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 */
                   2431:        ipmx +=1;
                   2432:        sw += weight[i];
                   2433:        ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
                   2434:       } /* end of wave */
                   2435:     } /* end of individual */
                   2436:   }  else if(mle==3){  /* exponential inter-extrapolation */
                   2437:     for (i=1,ipmx=0, sw=0.; i<=imx; i++){
1.187     brouard  2438:       for (k=1; k<=cptcovn;k++) cov[2+nagesqr+k]=covar[Tvar[k]][i];
1.126     brouard  2439:       for(mi=1; mi<= wav[i]-1; mi++){
                   2440:        for (ii=1;ii<=nlstate+ndeath;ii++)
                   2441:          for (j=1;j<=nlstate+ndeath;j++){
                   2442:            oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   2443:            savm[ii][j]=(ii==j ? 1.0 : 0.0);
                   2444:          }
                   2445:        for(d=0; d<dh[mi][i]; d++){
                   2446:          newm=savm;
1.187     brouard  2447:          agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;
                   2448:          cov[2]=agexact;
                   2449:          if(nagesqr==1)
                   2450:            cov[3]= agexact*agexact;
1.126     brouard  2451:          for (kk=1; kk<=cptcovage;kk++) {
1.187     brouard  2452:            cov[Tage[kk]+2+nagesqr]=covar[Tvar[Tage[kk]]][i]*agexact;
1.126     brouard  2453:          }
                   2454:          out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
                   2455:                       1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
                   2456:          savm=oldm;
                   2457:          oldm=newm;
                   2458:        } /* end mult */
                   2459:       
                   2460:        s1=s[mw[mi][i]][i];
                   2461:        s2=s[mw[mi+1][i]][i];
                   2462:        bbh=(double)bh[mi][i]/(double)stepm; 
                   2463:        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 */
                   2464:        ipmx +=1;
                   2465:        sw += weight[i];
                   2466:        ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
                   2467:       } /* end of wave */
                   2468:     } /* end of individual */
                   2469:   }else if (mle==4){  /* ml=4 no inter-extrapolation */
                   2470:     for (i=1,ipmx=0, sw=0.; i<=imx; i++){
1.187     brouard  2471:       for (k=1; k<=cptcovn;k++) cov[2+nagesqr+k]=covar[Tvar[k]][i];
1.126     brouard  2472:       for(mi=1; mi<= wav[i]-1; mi++){
                   2473:        for (ii=1;ii<=nlstate+ndeath;ii++)
                   2474:          for (j=1;j<=nlstate+ndeath;j++){
                   2475:            oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   2476:            savm[ii][j]=(ii==j ? 1.0 : 0.0);
                   2477:          }
                   2478:        for(d=0; d<dh[mi][i]; d++){
                   2479:          newm=savm;
1.187     brouard  2480:          agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;
                   2481:          cov[2]=agexact;
                   2482:          if(nagesqr==1)
                   2483:            cov[3]= agexact*agexact;
1.126     brouard  2484:          for (kk=1; kk<=cptcovage;kk++) {
1.187     brouard  2485:            cov[Tage[kk]+2+nagesqr]=covar[Tvar[Tage[kk]]][i]*agexact;
1.126     brouard  2486:          }
                   2487:        
                   2488:          out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
                   2489:                       1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
                   2490:          savm=oldm;
                   2491:          oldm=newm;
                   2492:        } /* end mult */
                   2493:       
                   2494:        s1=s[mw[mi][i]][i];
                   2495:        s2=s[mw[mi+1][i]][i];
                   2496:        if( s2 > nlstate){ 
                   2497:          lli=log(out[s1][s2] - savm[s1][s2]);
                   2498:        }else{
                   2499:          lli=log(out[s[mw[mi][i]][i]][s[mw[mi+1][i]][i]]); /* Original formula */
                   2500:        }
                   2501:        ipmx +=1;
                   2502:        sw += weight[i];
                   2503:        ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
                   2504: /*     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]); */
                   2505:       } /* end of wave */
                   2506:     } /* end of individual */
                   2507:   }else{  /* ml=5 no inter-extrapolation no jackson =0.8a */
                   2508:     for (i=1,ipmx=0, sw=0.; i<=imx; i++){
1.187     brouard  2509:       for (k=1; k<=cptcovn;k++) cov[2+nagesqr+k]=covar[Tvar[k]][i];
1.126     brouard  2510:       for(mi=1; mi<= wav[i]-1; mi++){
                   2511:        for (ii=1;ii<=nlstate+ndeath;ii++)
                   2512:          for (j=1;j<=nlstate+ndeath;j++){
                   2513:            oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   2514:            savm[ii][j]=(ii==j ? 1.0 : 0.0);
                   2515:          }
                   2516:        for(d=0; d<dh[mi][i]; d++){
                   2517:          newm=savm;
1.187     brouard  2518:          agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;
                   2519:          cov[2]=agexact;
                   2520:          if(nagesqr==1)
                   2521:            cov[3]= agexact*agexact;
1.126     brouard  2522:          for (kk=1; kk<=cptcovage;kk++) {
1.187     brouard  2523:            cov[Tage[kk]+2+nagesqr]=covar[Tvar[Tage[kk]]][i]*agexact;
1.126     brouard  2524:          }
                   2525:        
                   2526:          out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
                   2527:                       1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
                   2528:          savm=oldm;
                   2529:          oldm=newm;
                   2530:        } /* end mult */
                   2531:       
                   2532:        s1=s[mw[mi][i]][i];
                   2533:        s2=s[mw[mi+1][i]][i];
                   2534:        lli=log(out[s[mw[mi][i]][i]][s[mw[mi+1][i]][i]]); /* Original formula */
                   2535:        ipmx +=1;
                   2536:        sw += weight[i];
                   2537:        ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
                   2538:        /*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]);*/
                   2539:       } /* end of wave */
                   2540:     } /* end of individual */
                   2541:   } /* End of if */
                   2542:   for(k=1,l=0.; k<=nlstate; k++) l += ll[k];
                   2543:   /* printf("l1=%f l2=%f ",ll[1],ll[2]); */
                   2544:   l= l*ipmx/sw; /* To get the same order of magnitude as if weight=1 for every body */
                   2545:   return -l;
                   2546: }
                   2547: 
                   2548: /*************** log-likelihood *************/
                   2549: double funcone( double *x)
                   2550: {
                   2551:   /* Same as likeli but slower because of a lot of printf and if */
                   2552:   int i, ii, j, k, mi, d, kk;
1.131     brouard  2553:   double l, ll[NLSTATEMAX+1], cov[NCOVMAX+1];
1.126     brouard  2554:   double **out;
                   2555:   double lli; /* Individual log likelihood */
                   2556:   double llt;
                   2557:   int s1, s2;
                   2558:   double bbh, survp;
1.187     brouard  2559:   double agexact;
1.126     brouard  2560:   /*extern weight */
                   2561:   /* We are differentiating ll according to initial status */
                   2562:   /*  for (i=1;i<=npar;i++) printf("%f ", x[i]);*/
                   2563:   /*for(i=1;i<imx;i++) 
                   2564:     printf(" %d\n",s[4][i]);
                   2565:   */
                   2566:   cov[1]=1.;
                   2567: 
                   2568:   for(k=1; k<=nlstate; k++) ll[k]=0.;
                   2569: 
                   2570:   for (i=1,ipmx=0, sw=0.; i<=imx; i++){
1.187     brouard  2571:     for (k=1; k<=cptcovn;k++) cov[2+nagesqr+k]=covar[Tvar[k]][i];
1.126     brouard  2572:     for(mi=1; mi<= wav[i]-1; mi++){
                   2573:       for (ii=1;ii<=nlstate+ndeath;ii++)
                   2574:        for (j=1;j<=nlstate+ndeath;j++){
                   2575:          oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   2576:          savm[ii][j]=(ii==j ? 1.0 : 0.0);
                   2577:        }
                   2578:       for(d=0; d<dh[mi][i]; d++){
                   2579:        newm=savm;
1.187     brouard  2580:        agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;
                   2581:        cov[2]=agexact;
                   2582:        if(nagesqr==1)
                   2583:          cov[3]= agexact*agexact;
1.126     brouard  2584:        for (kk=1; kk<=cptcovage;kk++) {
1.187     brouard  2585:          cov[Tage[kk]+2+nagesqr]=covar[Tvar[Tage[kk]]][i]*agexact;
1.126     brouard  2586:        }
1.187     brouard  2587: 
1.145     brouard  2588:        /* savm=pmij(pmmij,cov,ncovmodel,x,nlstate); */
1.126     brouard  2589:        out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
                   2590:                     1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
1.145     brouard  2591:        /* out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath, */
                   2592:        /*           1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate)); */
1.126     brouard  2593:        savm=oldm;
                   2594:        oldm=newm;
                   2595:       } /* end mult */
                   2596:       
                   2597:       s1=s[mw[mi][i]][i];
                   2598:       s2=s[mw[mi+1][i]][i];
                   2599:       bbh=(double)bh[mi][i]/(double)stepm; 
                   2600:       /* bias is positive if real duration
                   2601:        * is higher than the multiple of stepm and negative otherwise.
                   2602:        */
                   2603:       if( s2 > nlstate && (mle <5) ){  /* Jackson */
                   2604:        lli=log(out[s1][s2] - savm[s1][s2]);
                   2605:       } else if  (s2==-2) {
                   2606:        for (j=1,survp=0. ; j<=nlstate; j++) 
                   2607:          survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j];
                   2608:        lli= log(survp);
                   2609:       }else if (mle==1){
                   2610:        lli= log((1.+bbh)*out[s1][s2]- bbh*savm[s1][s2]); /* linear interpolation */
                   2611:       } else if(mle==2){
                   2612:        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 */
                   2613:       } else if(mle==3){  /* exponential inter-extrapolation */
                   2614:        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 */
                   2615:       } else if (mle==4){  /* mle=4 no inter-extrapolation */
                   2616:        lli=log(out[s1][s2]); /* Original formula */
1.136     brouard  2617:       } else{  /* mle=0 back to 1 */
                   2618:        lli= log((1.+bbh)*out[s1][s2]- bbh*savm[s1][s2]); /* linear interpolation */
                   2619:        /*lli=log(out[s1][s2]); */ /* Original formula */
1.126     brouard  2620:       } /* End of if */
                   2621:       ipmx +=1;
                   2622:       sw += weight[i];
                   2623:       ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
1.132     brouard  2624:       /*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  2625:       if(globpr){
1.205     brouard  2626:        fprintf(ficresilk,"%9ld %6.1f %6d %2d %2d %2d %2d %3d %11.6f %8.4f %8.3f\
1.126     brouard  2627:  %11.6f %11.6f %11.6f ", \
1.205     brouard  2628:                num[i], agexact, i,s1,s2,mi,mw[mi][i],dh[mi][i],exp(lli),weight[i],weight[i]*gipmx/gsw,
1.126     brouard  2629:                2*weight[i]*lli,out[s1][s2],savm[s1][s2]);
                   2630:        for(k=1,llt=0.,l=0.; k<=nlstate; k++){
                   2631:          llt +=ll[k]*gipmx/gsw;
                   2632:          fprintf(ficresilk," %10.6f",-ll[k]*gipmx/gsw);
                   2633:        }
                   2634:        fprintf(ficresilk," %10.6f\n", -llt);
                   2635:       }
                   2636:     } /* end of wave */
                   2637:   } /* end of individual */
                   2638:   for(k=1,l=0.; k<=nlstate; k++) l += ll[k];
                   2639:   /* printf("l1=%f l2=%f ",ll[1],ll[2]); */
                   2640:   l= l*ipmx/sw; /* To get the same order of magnitude as if weight=1 for every body */
                   2641:   if(globpr==0){ /* First time we count the contributions and weights */
                   2642:     gipmx=ipmx;
                   2643:     gsw=sw;
                   2644:   }
                   2645:   return -l;
                   2646: }
                   2647: 
                   2648: 
                   2649: /*************** function likelione ***********/
                   2650: void likelione(FILE *ficres,double p[], int npar, int nlstate, int *globpri, long *ipmx, double *sw, double *fretone, double (*funcone)(double []))
                   2651: {
                   2652:   /* This routine should help understanding what is done with 
                   2653:      the selection of individuals/waves and
                   2654:      to check the exact contribution to the likelihood.
                   2655:      Plotting could be done.
                   2656:    */
                   2657:   int k;
                   2658: 
                   2659:   if(*globpri !=0){ /* Just counts and sums, no printings */
1.201     brouard  2660:     strcpy(fileresilk,"ILK_"); 
1.202     brouard  2661:     strcat(fileresilk,fileresu);
1.126     brouard  2662:     if((ficresilk=fopen(fileresilk,"w"))==NULL) {
                   2663:       printf("Problem with resultfile: %s\n", fileresilk);
                   2664:       fprintf(ficlog,"Problem with resultfile: %s\n", fileresilk);
                   2665:     }
1.205     brouard  2666:     fprintf(ficresilk, "#individual(line's_record) count age 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");
                   2667:     fprintf(ficresilk, "#num_i age i s1 s2 mi mw dh likeli weight %weight 2wlli out sav ");
1.126     brouard  2668:     /*         i,s1,s2,mi,mw[mi][i],dh[mi][i],exp(lli),weight[i],2*weight[i]*lli,out[s1][s2],savm[s1][s2]); */
                   2669:     for(k=1; k<=nlstate; k++) 
                   2670:       fprintf(ficresilk," -2*gipw/gsw*weight*ll[%d]++",k);
                   2671:     fprintf(ficresilk," -2*gipw/gsw*weight*ll(total)\n");
                   2672:   }
                   2673: 
                   2674:   *fretone=(*funcone)(p);
                   2675:   if(*globpri !=0){
                   2676:     fclose(ficresilk);
1.205     brouard  2677:     if (mle ==0)
                   2678:       fprintf(fichtm,"\n<br>File of contributions to the likelihood computed with initial parameters and mle = %d.",mle);
                   2679:     else if(mle >=1)
                   2680:       fprintf(fichtm,"\n<br>File of contributions to the likelihood computed with optimized parameters mle = %d.",mle);
                   2681:     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));
                   2682: 
                   2683:       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  2684: <img src=\"%s-ori.png\">",subdirf2(optionfilefiname,"ILK_"),subdirf2(optionfilefiname,"ILK_"),subdirf2(optionfilefiname,"ILK_"));
1.205     brouard  2685:       fprintf(fichtm,"<br>- and by state of destination <a href=\"%s-dest.png\">%s-dest.png</a><br> \
1.204     brouard  2686: <img src=\"%s-dest.png\">",subdirf2(optionfilefiname,"ILK_"),subdirf2(optionfilefiname,"ILK_"),subdirf2(optionfilefiname,"ILK_"));
1.205     brouard  2687:       fflush(fichtm);
                   2688:       
                   2689:       for (k=1; k<= nlstate ; k++) {
                   2690:        fprintf(fichtm,"<br>- Probability p%dj by origin %d and destination j <a href=\"%s-p%dj.png\">%s-p%dj.png</a><br> \
1.204     brouard  2691: <img src=\"%s-p%dj.png\">",k,k,subdirf2(optionfilefiname,"ILK_"),k,subdirf2(optionfilefiname,"ILK_"),k,subdirf2(optionfilefiname,"ILK_"),k);
1.205     brouard  2692:       }
                   2693:   }
1.126     brouard  2694:   return;
                   2695: }
                   2696: 
                   2697: 
                   2698: /*********** Maximum Likelihood Estimation ***************/
                   2699: 
                   2700: void mlikeli(FILE *ficres,double p[], int npar, int ncovmodel, int nlstate, double ftol, double (*func)(double []))
                   2701: {
1.165     brouard  2702:   int i,j, iter=0;
1.126     brouard  2703:   double **xi;
                   2704:   double fret;
                   2705:   double fretone; /* Only one call to likelihood */
                   2706:   /*  char filerespow[FILENAMELENGTH];*/
1.162     brouard  2707: 
                   2708: #ifdef NLOPT
                   2709:   int creturn;
                   2710:   nlopt_opt opt;
                   2711:   /* double lb[9] = { -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL }; /\* lower bounds *\/ */
                   2712:   double *lb;
                   2713:   double minf; /* the minimum objective value, upon return */
                   2714:   double * p1; /* Shifted parameters from 0 instead of 1 */
                   2715:   myfunc_data dinst, *d = &dinst;
                   2716: #endif
                   2717: 
                   2718: 
1.126     brouard  2719:   xi=matrix(1,npar,1,npar);
                   2720:   for (i=1;i<=npar;i++)
                   2721:     for (j=1;j<=npar;j++)
                   2722:       xi[i][j]=(i==j ? 1.0 : 0.0);
                   2723:   printf("Powell\n");  fprintf(ficlog,"Powell\n");
1.201     brouard  2724:   strcpy(filerespow,"POW_"); 
1.126     brouard  2725:   strcat(filerespow,fileres);
                   2726:   if((ficrespow=fopen(filerespow,"w"))==NULL) {
                   2727:     printf("Problem with resultfile: %s\n", filerespow);
                   2728:     fprintf(ficlog,"Problem with resultfile: %s\n", filerespow);
                   2729:   }
                   2730:   fprintf(ficrespow,"# Powell\n# iter -2*LL");
                   2731:   for (i=1;i<=nlstate;i++)
                   2732:     for(j=1;j<=nlstate+ndeath;j++)
                   2733:       if(j!=i)fprintf(ficrespow," p%1d%1d",i,j);
                   2734:   fprintf(ficrespow,"\n");
1.162     brouard  2735: #ifdef POWELL
1.126     brouard  2736:   powell(p,xi,npar,ftol,&iter,&fret,func);
1.162     brouard  2737: #endif
1.126     brouard  2738: 
1.162     brouard  2739: #ifdef NLOPT
                   2740: #ifdef NEWUOA
                   2741:   opt = nlopt_create(NLOPT_LN_NEWUOA,npar);
                   2742: #else
                   2743:   opt = nlopt_create(NLOPT_LN_BOBYQA,npar);
                   2744: #endif
                   2745:   lb=vector(0,npar-1);
                   2746:   for (i=0;i<npar;i++) lb[i]= -HUGE_VAL;
                   2747:   nlopt_set_lower_bounds(opt, lb);
                   2748:   nlopt_set_initial_step1(opt, 0.1);
                   2749:   
                   2750:   p1= (p+1); /*  p *(p+1)@8 and p *(p1)@8 are equal p1[0]=p[1] */
                   2751:   d->function = func;
                   2752:   printf(" Func %.12lf \n",myfunc(npar,p1,NULL,d));
                   2753:   nlopt_set_min_objective(opt, myfunc, d);
                   2754:   nlopt_set_xtol_rel(opt, ftol);
                   2755:   if ((creturn=nlopt_optimize(opt, p1, &minf)) < 0) {
                   2756:     printf("nlopt failed! %d\n",creturn); 
                   2757:   }
                   2758:   else {
                   2759:     printf("found minimum after %d evaluations (NLOPT=%d)\n", countcallfunc ,NLOPT);
                   2760:     printf("found minimum at f(%g,%g) = %0.10g\n", p[0], p[1], minf);
                   2761:     iter=1; /* not equal */
                   2762:   }
                   2763:   nlopt_destroy(opt);
                   2764: #endif
1.126     brouard  2765:   free_matrix(xi,1,npar,1,npar);
                   2766:   fclose(ficrespow);
1.203     brouard  2767:   printf("\n#Number of iterations & function calls = %d & %d, -2 Log likelihood = %.12f\n",iter, countcallfunc,func(p));
                   2768:   fprintf(ficlog,"\n#Number of iterations & function calls = %d & %d, -2 Log likelihood = %.12f\n",iter, countcallfunc,func(p));
1.180     brouard  2769:   fprintf(ficres,"#Number of iterations & function calls = %d & %d, -2 Log likelihood = %.12f\n",iter, countcallfunc,func(p));
1.126     brouard  2770: 
                   2771: }
                   2772: 
                   2773: /**** Computes Hessian and covariance matrix ***/
1.203     brouard  2774: void hesscov(double **matcov, double **hess, double p[], int npar, double delti[], double ftolhess, double (*func)(double []))
1.126     brouard  2775: {
                   2776:   double  **a,**y,*x,pd;
1.203     brouard  2777:   /* double **hess; */
1.164     brouard  2778:   int i, j;
1.126     brouard  2779:   int *indx;
                   2780: 
                   2781:   double hessii(double p[], double delta, int theta, double delti[],double (*func)(double []),int npar);
1.203     brouard  2782:   double hessij(double p[], double **hess, double delti[], int i, int j,double (*func)(double []),int npar);
1.126     brouard  2783:   void lubksb(double **a, int npar, int *indx, double b[]) ;
                   2784:   void ludcmp(double **a, int npar, int *indx, double *d) ;
                   2785:   double gompertz(double p[]);
1.203     brouard  2786:   /* hess=matrix(1,npar,1,npar); */
1.126     brouard  2787: 
                   2788:   printf("\nCalculation of the hessian matrix. Wait...\n");
                   2789:   fprintf(ficlog,"\nCalculation of the hessian matrix. Wait...\n");
                   2790:   for (i=1;i<=npar;i++){
1.203     brouard  2791:     printf("%d-",i);fflush(stdout);
                   2792:     fprintf(ficlog,"%d-",i);fflush(ficlog);
1.126     brouard  2793:    
                   2794:      hess[i][i]=hessii(p,ftolhess,i,delti,func,npar);
                   2795:     
                   2796:     /*  printf(" %f ",p[i]);
                   2797:        printf(" %lf %lf %lf",hess[i][i],ftolhess,delti[i]);*/
                   2798:   }
                   2799:   
                   2800:   for (i=1;i<=npar;i++) {
                   2801:     for (j=1;j<=npar;j++)  {
                   2802:       if (j>i) { 
1.203     brouard  2803:        printf(".%d-%d",i,j);fflush(stdout);
                   2804:        fprintf(ficlog,".%d-%d",i,j);fflush(ficlog);
                   2805:        hess[i][j]=hessij(p,hess, delti,i,j,func,npar);
1.126     brouard  2806:        
                   2807:        hess[j][i]=hess[i][j];    
                   2808:        /*printf(" %lf ",hess[i][j]);*/
                   2809:       }
                   2810:     }
                   2811:   }
                   2812:   printf("\n");
                   2813:   fprintf(ficlog,"\n");
                   2814: 
                   2815:   printf("\nInverting the hessian to get the covariance matrix. Wait...\n");
                   2816:   fprintf(ficlog,"\nInverting the hessian to get the covariance matrix. Wait...\n");
                   2817:   
                   2818:   a=matrix(1,npar,1,npar);
                   2819:   y=matrix(1,npar,1,npar);
                   2820:   x=vector(1,npar);
                   2821:   indx=ivector(1,npar);
                   2822:   for (i=1;i<=npar;i++)
                   2823:     for (j=1;j<=npar;j++) a[i][j]=hess[i][j];
                   2824:   ludcmp(a,npar,indx,&pd);
                   2825: 
                   2826:   for (j=1;j<=npar;j++) {
                   2827:     for (i=1;i<=npar;i++) x[i]=0;
                   2828:     x[j]=1;
                   2829:     lubksb(a,npar,indx,x);
                   2830:     for (i=1;i<=npar;i++){ 
                   2831:       matcov[i][j]=x[i];
                   2832:     }
                   2833:   }
                   2834: 
                   2835:   printf("\n#Hessian matrix#\n");
                   2836:   fprintf(ficlog,"\n#Hessian matrix#\n");
                   2837:   for (i=1;i<=npar;i++) { 
                   2838:     for (j=1;j<=npar;j++) { 
1.203     brouard  2839:       printf("%.6e ",hess[i][j]);
                   2840:       fprintf(ficlog,"%.6e ",hess[i][j]);
1.126     brouard  2841:     }
                   2842:     printf("\n");
                   2843:     fprintf(ficlog,"\n");
                   2844:   }
                   2845: 
1.203     brouard  2846:   /* printf("\n#Covariance matrix#\n"); */
                   2847:   /* fprintf(ficlog,"\n#Covariance matrix#\n"); */
                   2848:   /* for (i=1;i<=npar;i++) {  */
                   2849:   /*   for (j=1;j<=npar;j++) {  */
                   2850:   /*     printf("%.6e ",matcov[i][j]); */
                   2851:   /*     fprintf(ficlog,"%.6e ",matcov[i][j]); */
                   2852:   /*   } */
                   2853:   /*   printf("\n"); */
                   2854:   /*   fprintf(ficlog,"\n"); */
                   2855:   /* } */
                   2856: 
1.126     brouard  2857:   /* Recompute Inverse */
1.203     brouard  2858:   /* for (i=1;i<=npar;i++) */
                   2859:   /*   for (j=1;j<=npar;j++) a[i][j]=matcov[i][j]; */
                   2860:   /* ludcmp(a,npar,indx,&pd); */
                   2861: 
                   2862:   /*  printf("\n#Hessian matrix recomputed#\n"); */
                   2863: 
                   2864:   /* for (j=1;j<=npar;j++) { */
                   2865:   /*   for (i=1;i<=npar;i++) x[i]=0; */
                   2866:   /*   x[j]=1; */
                   2867:   /*   lubksb(a,npar,indx,x); */
                   2868:   /*   for (i=1;i<=npar;i++){  */
                   2869:   /*     y[i][j]=x[i]; */
                   2870:   /*     printf("%.3e ",y[i][j]); */
                   2871:   /*     fprintf(ficlog,"%.3e ",y[i][j]); */
                   2872:   /*   } */
                   2873:   /*   printf("\n"); */
                   2874:   /*   fprintf(ficlog,"\n"); */
                   2875:   /* } */
                   2876: 
                   2877:   /* Verifying the inverse matrix */
                   2878: #ifdef DEBUGHESS
                   2879:   y=matprod2(y,hess,1,npar,1,npar,1,npar,matcov);
1.126     brouard  2880: 
1.203     brouard  2881:    printf("\n#Verification: multiplying the matrix of covariance by the Hessian matrix, should be unity:#\n");
                   2882:    fprintf(ficlog,"\n#Verification: multiplying the matrix of covariance by the Hessian matrix. Should be unity:#\n");
1.126     brouard  2883: 
                   2884:   for (j=1;j<=npar;j++) {
                   2885:     for (i=1;i<=npar;i++){ 
1.203     brouard  2886:       printf("%.2f ",y[i][j]);
                   2887:       fprintf(ficlog,"%.2f ",y[i][j]);
1.126     brouard  2888:     }
                   2889:     printf("\n");
                   2890:     fprintf(ficlog,"\n");
                   2891:   }
1.203     brouard  2892: #endif
1.126     brouard  2893: 
                   2894:   free_matrix(a,1,npar,1,npar);
                   2895:   free_matrix(y,1,npar,1,npar);
                   2896:   free_vector(x,1,npar);
                   2897:   free_ivector(indx,1,npar);
1.203     brouard  2898:   /* free_matrix(hess,1,npar,1,npar); */
1.126     brouard  2899: 
                   2900: 
                   2901: }
                   2902: 
                   2903: /*************** hessian matrix ****************/
                   2904: double hessii(double x[], double delta, int theta, double delti[], double (*func)(double []), int npar)
1.203     brouard  2905: { /* Around values of x, computes the function func and returns the scales delti and hessian */
1.126     brouard  2906:   int i;
                   2907:   int l=1, lmax=20;
1.203     brouard  2908:   double k1,k2, res, fx;
1.132     brouard  2909:   double p2[MAXPARM+1]; /* identical to x */
1.126     brouard  2910:   double delt=0.0001, delts, nkhi=10.,nkhif=1., khi=1.e-4;
                   2911:   int k=0,kmax=10;
                   2912:   double l1;
                   2913: 
                   2914:   fx=func(x);
                   2915:   for (i=1;i<=npar;i++) p2[i]=x[i];
1.145     brouard  2916:   for(l=0 ; l <=lmax; l++){  /* Enlarging the zone around the Maximum */
1.126     brouard  2917:     l1=pow(10,l);
                   2918:     delts=delt;
                   2919:     for(k=1 ; k <kmax; k=k+1){
                   2920:       delt = delta*(l1*k);
                   2921:       p2[theta]=x[theta] +delt;
1.145     brouard  2922:       k1=func(p2)-fx;   /* Might be negative if too close to the theoretical maximum */
1.126     brouard  2923:       p2[theta]=x[theta]-delt;
                   2924:       k2=func(p2)-fx;
                   2925:       /*res= (k1-2.0*fx+k2)/delt/delt; */
1.203     brouard  2926:       res= (k1+k2)/delt/delt/2.; /* Divided by 2 because L and not 2*L */
1.126     brouard  2927:       
1.203     brouard  2928: #ifdef DEBUGHESSII
1.126     brouard  2929:       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);
                   2930:       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);
                   2931: #endif
                   2932:       /*if(fabs(k1-2.0*fx+k2) <1.e-13){ */
                   2933:       if((k1 <khi/nkhi/2.) || (k2 <khi/nkhi/2.)){
                   2934:        k=kmax;
                   2935:       }
                   2936:       else if((k1 >khi/nkhif) || (k2 >khi/nkhif)){ /* Keeps lastvalue before 3.84/2 KHI2 5% 1d.f. */
1.164     brouard  2937:        k=kmax; l=lmax*10;
1.126     brouard  2938:       }
                   2939:       else if((k1 >khi/nkhi) || (k2 >khi/nkhi)){ 
                   2940:        delts=delt;
                   2941:       }
1.203     brouard  2942:     } /* End loop k */
1.126     brouard  2943:   }
                   2944:   delti[theta]=delts;
                   2945:   return res; 
                   2946:   
                   2947: }
                   2948: 
1.203     brouard  2949: double hessij( double x[], double **hess, double delti[], int thetai,int thetaj,double (*func)(double []),int npar)
1.126     brouard  2950: {
                   2951:   int i;
1.164     brouard  2952:   int l=1, lmax=20;
1.126     brouard  2953:   double k1,k2,k3,k4,res,fx;
1.132     brouard  2954:   double p2[MAXPARM+1];
1.203     brouard  2955:   int k, kmax=1;
                   2956:   double v1, v2, cv12, lc1, lc2;
                   2957:   
1.126     brouard  2958:   fx=func(x);
1.203     brouard  2959:   for (k=1; k<=kmax; k=k+10) {
1.126     brouard  2960:     for (i=1;i<=npar;i++) p2[i]=x[i];
1.203     brouard  2961:     p2[thetai]=x[thetai]+delti[thetai]*k;
                   2962:     p2[thetaj]=x[thetaj]+delti[thetaj]*k;
1.126     brouard  2963:     k1=func(p2)-fx;
                   2964:   
1.203     brouard  2965:     p2[thetai]=x[thetai]+delti[thetai]*k;
                   2966:     p2[thetaj]=x[thetaj]-delti[thetaj]*k;
1.126     brouard  2967:     k2=func(p2)-fx;
                   2968:   
1.203     brouard  2969:     p2[thetai]=x[thetai]-delti[thetai]*k;
                   2970:     p2[thetaj]=x[thetaj]+delti[thetaj]*k;
1.126     brouard  2971:     k3=func(p2)-fx;
                   2972:   
1.203     brouard  2973:     p2[thetai]=x[thetai]-delti[thetai]*k;
                   2974:     p2[thetaj]=x[thetaj]-delti[thetaj]*k;
1.126     brouard  2975:     k4=func(p2)-fx;
1.203     brouard  2976:     res=(k1-k2-k3+k4)/4.0/delti[thetai]/k/delti[thetaj]/k/2.; /* Because of L not 2*L */
                   2977:     if(k1*k2*k3*k4 <0.){
                   2978:       kmax=kmax+10;
                   2979:       if(kmax >=10){
                   2980:       printf("Warning: directions %d-%d, you are not estimating the Hessian at the exact maximum likelihood; increase ftol=%.2e\n",thetai,thetaj, ftol);
                   2981:       fprintf(ficlog,"Warning: directions %d-%d, you are not estimating the Hessian at the exact maximum likelihood; increase ftol=%.2e\n",thetai,thetaj, ftol);
                   2982:       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);
                   2983:       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);
                   2984:       }
                   2985:     }
                   2986: #ifdef DEBUGHESSIJ
                   2987:     v1=hess[thetai][thetai];
                   2988:     v2=hess[thetaj][thetaj];
                   2989:     cv12=res;
                   2990:     /* Computing eigen value of Hessian matrix */
                   2991:     lc1=((v1+v2)+sqrt((v1+v2)*(v1+v2) - 4*(v1*v2-cv12*cv12)))/2.;
                   2992:     lc2=((v1+v2)-sqrt((v1+v2)*(v1+v2) - 4*(v1*v2-cv12*cv12)))/2.;
                   2993:     if ((lc2 <0) || (lc1 <0) ){
                   2994:       printf("Warning: sub Hessian matrix '%d%d' does not have positive eigen values \n",thetai,thetaj);
                   2995:       fprintf(ficlog, "Warning: sub Hessian matrix '%d%d' does not have positive eigen values \n",thetai,thetaj);
                   2996:       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);
                   2997:       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);
                   2998:     }
1.126     brouard  2999: #endif
                   3000:   }
                   3001:   return res;
                   3002: }
                   3003: 
1.203     brouard  3004:     /* Not done yet: Was supposed to fix if not exactly at the maximum */
                   3005: /* double hessij( double x[], double delti[], int thetai,int thetaj,double (*func)(double []),int npar) */
                   3006: /* { */
                   3007: /*   int i; */
                   3008: /*   int l=1, lmax=20; */
                   3009: /*   double k1,k2,k3,k4,res,fx; */
                   3010: /*   double p2[MAXPARM+1]; */
                   3011: /*   double delt=0.0001, delts, nkhi=10.,nkhif=1., khi=1.e-4; */
                   3012: /*   int k=0,kmax=10; */
                   3013: /*   double l1; */
                   3014:   
                   3015: /*   fx=func(x); */
                   3016: /*   for(l=0 ; l <=lmax; l++){  /\* Enlarging the zone around the Maximum *\/ */
                   3017: /*     l1=pow(10,l); */
                   3018: /*     delts=delt; */
                   3019: /*     for(k=1 ; k <kmax; k=k+1){ */
                   3020: /*       delt = delti*(l1*k); */
                   3021: /*       for (i=1;i<=npar;i++) p2[i]=x[i]; */
                   3022: /*       p2[thetai]=x[thetai]+delti[thetai]/k; */
                   3023: /*       p2[thetaj]=x[thetaj]+delti[thetaj]/k; */
                   3024: /*       k1=func(p2)-fx; */
                   3025:       
                   3026: /*       p2[thetai]=x[thetai]+delti[thetai]/k; */
                   3027: /*       p2[thetaj]=x[thetaj]-delti[thetaj]/k; */
                   3028: /*       k2=func(p2)-fx; */
                   3029:       
                   3030: /*       p2[thetai]=x[thetai]-delti[thetai]/k; */
                   3031: /*       p2[thetaj]=x[thetaj]+delti[thetaj]/k; */
                   3032: /*       k3=func(p2)-fx; */
                   3033:       
                   3034: /*       p2[thetai]=x[thetai]-delti[thetai]/k; */
                   3035: /*       p2[thetaj]=x[thetaj]-delti[thetaj]/k; */
                   3036: /*       k4=func(p2)-fx; */
                   3037: /*       res=(k1-k2-k3+k4)/4.0/delti[thetai]*k/delti[thetaj]*k/2.; /\* Because of L not 2*L *\/ */
                   3038: /* #ifdef DEBUGHESSIJ */
                   3039: /*       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); */
                   3040: /*       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); */
                   3041: /* #endif */
                   3042: /*       if((k1 <khi/nkhi/2.) || (k2 <khi/nkhi/2.)|| (k4 <khi/nkhi/2.)|| (k4 <khi/nkhi/2.)){ */
                   3043: /*     k=kmax; */
                   3044: /*       } */
                   3045: /*       else if((k1 >khi/nkhif) || (k2 >khi/nkhif) || (k4 >khi/nkhif) || (k4 >khi/nkhif)){ /\* Keeps lastvalue before 3.84/2 KHI2 5% 1d.f. *\/ */
                   3046: /*     k=kmax; l=lmax*10; */
                   3047: /*       } */
                   3048: /*       else if((k1 >khi/nkhi) || (k2 >khi/nkhi)){  */
                   3049: /*     delts=delt; */
                   3050: /*       } */
                   3051: /*     } /\* End loop k *\/ */
                   3052: /*   } */
                   3053: /*   delti[theta]=delts; */
                   3054: /*   return res;  */
                   3055: /* } */
                   3056: 
                   3057: 
1.126     brouard  3058: /************** Inverse of matrix **************/
                   3059: void ludcmp(double **a, int n, int *indx, double *d) 
                   3060: { 
                   3061:   int i,imax,j,k; 
                   3062:   double big,dum,sum,temp; 
                   3063:   double *vv; 
                   3064:  
                   3065:   vv=vector(1,n); 
                   3066:   *d=1.0; 
                   3067:   for (i=1;i<=n;i++) { 
                   3068:     big=0.0; 
                   3069:     for (j=1;j<=n;j++) 
                   3070:       if ((temp=fabs(a[i][j])) > big) big=temp; 
                   3071:     if (big == 0.0) nrerror("Singular matrix in routine ludcmp"); 
                   3072:     vv[i]=1.0/big; 
                   3073:   } 
                   3074:   for (j=1;j<=n;j++) { 
                   3075:     for (i=1;i<j;i++) { 
                   3076:       sum=a[i][j]; 
                   3077:       for (k=1;k<i;k++) sum -= a[i][k]*a[k][j]; 
                   3078:       a[i][j]=sum; 
                   3079:     } 
                   3080:     big=0.0; 
                   3081:     for (i=j;i<=n;i++) { 
                   3082:       sum=a[i][j]; 
                   3083:       for (k=1;k<j;k++) 
                   3084:        sum -= a[i][k]*a[k][j]; 
                   3085:       a[i][j]=sum; 
                   3086:       if ( (dum=vv[i]*fabs(sum)) >= big) { 
                   3087:        big=dum; 
                   3088:        imax=i; 
                   3089:       } 
                   3090:     } 
                   3091:     if (j != imax) { 
                   3092:       for (k=1;k<=n;k++) { 
                   3093:        dum=a[imax][k]; 
                   3094:        a[imax][k]=a[j][k]; 
                   3095:        a[j][k]=dum; 
                   3096:       } 
                   3097:       *d = -(*d); 
                   3098:       vv[imax]=vv[j]; 
                   3099:     } 
                   3100:     indx[j]=imax; 
                   3101:     if (a[j][j] == 0.0) a[j][j]=TINY; 
                   3102:     if (j != n) { 
                   3103:       dum=1.0/(a[j][j]); 
                   3104:       for (i=j+1;i<=n;i++) a[i][j] *= dum; 
                   3105:     } 
                   3106:   } 
                   3107:   free_vector(vv,1,n);  /* Doesn't work */
                   3108: ;
                   3109: } 
                   3110: 
                   3111: void lubksb(double **a, int n, int *indx, double b[]) 
                   3112: { 
                   3113:   int i,ii=0,ip,j; 
                   3114:   double sum; 
                   3115:  
                   3116:   for (i=1;i<=n;i++) { 
                   3117:     ip=indx[i]; 
                   3118:     sum=b[ip]; 
                   3119:     b[ip]=b[i]; 
                   3120:     if (ii) 
                   3121:       for (j=ii;j<=i-1;j++) sum -= a[i][j]*b[j]; 
                   3122:     else if (sum) ii=i; 
                   3123:     b[i]=sum; 
                   3124:   } 
                   3125:   for (i=n;i>=1;i--) { 
                   3126:     sum=b[i]; 
                   3127:     for (j=i+1;j<=n;j++) sum -= a[i][j]*b[j]; 
                   3128:     b[i]=sum/a[i][i]; 
                   3129:   } 
                   3130: } 
                   3131: 
                   3132: void pstamp(FILE *fichier)
                   3133: {
1.196     brouard  3134:   fprintf(fichier,"# %s.%s\n#IMaCh version %s, %s\n#%s\n# %s", optionfilefiname,optionfilext,version,copyright, fullversion, strstart);
1.126     brouard  3135: }
                   3136: 
                   3137: /************ Frequencies ********************/
                   3138: void  freqsummary(char fileres[], int iagemin, int iagemax, int **s, double **agev, int nlstate, int imx, int *Tvaraff, int **nbcode, int *ncodemax,double **mint,double **anint, char strstart[])
                   3139: {  /* Some frequencies */
                   3140:   
1.164     brouard  3141:   int i, m, jk, j1, bool, z1,j;
1.126     brouard  3142:   int first;
                   3143:   double ***freq; /* Frequencies */
                   3144:   double *pp, **prop;
                   3145:   double pos,posprop, k2, dateintsum=0,k2cpt=0;
                   3146:   char fileresp[FILENAMELENGTH];
                   3147:   
                   3148:   pp=vector(1,nlstate);
                   3149:   prop=matrix(1,nlstate,iagemin,iagemax+3);
1.201     brouard  3150:   strcpy(fileresp,"P_");
                   3151:   strcat(fileresp,fileresu);
1.126     brouard  3152:   if((ficresp=fopen(fileresp,"w"))==NULL) {
                   3153:     printf("Problem with prevalence resultfile: %s\n", fileresp);
                   3154:     fprintf(ficlog,"Problem with prevalence resultfile: %s\n", fileresp);
                   3155:     exit(0);
                   3156:   }
                   3157:   freq= ma3x(-5,nlstate+ndeath,-5,nlstate+ndeath,iagemin,iagemax+3);
                   3158:   j1=0;
                   3159:   
                   3160:   j=cptcoveff;
                   3161:   if (cptcovn<1) {j=1;ncodemax[1]=1;}
                   3162: 
                   3163:   first=1;
                   3164: 
1.169     brouard  3165:   /* for(k1=1; k1<=j ; k1++){ */  /* Loop on covariates */
                   3166:   /*  for(i1=1; i1<=ncodemax[k1];i1++){ */ /* Now it is 2 */
                   3167:   /*    j1++; */
1.145     brouard  3168:   for (j1 = 1; j1 <= (int) pow(2,cptcoveff); j1++){
1.126     brouard  3169:       /*printf("cptcoveff=%d Tvaraff=%d", cptcoveff,Tvaraff[1]);
                   3170:        scanf("%d", i);*/
                   3171:       for (i=-5; i<=nlstate+ndeath; i++)  
                   3172:        for (jk=-5; jk<=nlstate+ndeath; jk++)  
                   3173:          for(m=iagemin; m <= iagemax+3; m++)
                   3174:            freq[i][jk][m]=0;
1.143     brouard  3175:       
                   3176:       for (i=1; i<=nlstate; i++)  
                   3177:        for(m=iagemin; m <= iagemax+3; m++)
                   3178:          prop[i][m]=0;
1.126     brouard  3179:       
                   3180:       dateintsum=0;
                   3181:       k2cpt=0;
                   3182:       for (i=1; i<=imx; i++) {
                   3183:        bool=1;
1.144     brouard  3184:        if  (cptcovn>0) { /* Filter is here: Must be looked at for model=V1+V2+V3+V4 */
                   3185:          for (z1=1; z1<=cptcoveff; z1++)       
1.198     brouard  3186:             if (covar[Tvaraff[z1]][i]!= nbcode[Tvaraff[z1]][codtabm(j1,z1)]){
1.145     brouard  3187:                 /* Tests if the value of each of the covariates of i is equal to filter j1 */
1.144     brouard  3188:               bool=0;
1.198     brouard  3189:               /* 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", 
                   3190:                 bool,i,z1, z1, Tvaraff[z1],i,covar[Tvaraff[z1]][i],j1,z1,codtabm(j1,z1),
                   3191:                 j1,z1,nbcode[Tvaraff[z1]][codtabm(j1,z1)],j1);*/
                   3192:               /* For j1=7 in V1+V2+V3+V4 = 0 1 1 0 and codtabm(7,3)=1 and nbcde[3][?]=1*/
1.144     brouard  3193:             } 
1.126     brouard  3194:        }
1.144     brouard  3195:  
1.126     brouard  3196:        if (bool==1){
                   3197:          for(m=firstpass; m<=lastpass; m++){
                   3198:            k2=anint[m][i]+(mint[m][i]/12.);
                   3199:            /*if ((k2>=dateprev1) && (k2<=dateprev2)) {*/
                   3200:              if(agev[m][i]==0) agev[m][i]=iagemax+1;
                   3201:              if(agev[m][i]==1) agev[m][i]=iagemax+2;
                   3202:              if (s[m][i]>0 && s[m][i]<=nlstate) prop[s[m][i]][(int)agev[m][i]] += weight[i];
                   3203:              if (m<lastpass) {
                   3204:                freq[s[m][i]][s[m+1][i]][(int)agev[m][i]] += weight[i];
                   3205:                freq[s[m][i]][s[m+1][i]][iagemax+3] += weight[i];
                   3206:              }
                   3207:              
                   3208:              if ((agev[m][i]>1) && (agev[m][i]< (iagemax+3))) {
                   3209:                dateintsum=dateintsum+k2;
                   3210:                k2cpt++;
                   3211:              }
                   3212:              /*}*/
                   3213:          }
                   3214:        }
1.145     brouard  3215:       } /* end i */
1.126     brouard  3216:        
                   3217:       /*      fprintf(ficresp, "#Count between %.lf/%.lf/%.lf and %.lf/%.lf/%.lf\n",jprev1, mprev1,anprev1,jprev2, mprev2,anprev2);*/
                   3218:       pstamp(ficresp);
                   3219:       if  (cptcovn>0) {
                   3220:        fprintf(ficresp, "\n#********** Variable "); 
1.198     brouard  3221:        for (z1=1; z1<=cptcoveff; z1++) fprintf(ficresp, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
1.126     brouard  3222:        fprintf(ficresp, "**********\n#");
1.143     brouard  3223:        fprintf(ficlog, "\n#********** Variable "); 
1.198     brouard  3224:        for (z1=1; z1<=cptcoveff; z1++) fprintf(ficlog, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
1.143     brouard  3225:        fprintf(ficlog, "**********\n#");
1.126     brouard  3226:       }
                   3227:       for(i=1; i<=nlstate;i++) 
                   3228:        fprintf(ficresp, " Age Prev(%d) N(%d) N",i,i);
                   3229:       fprintf(ficresp, "\n");
                   3230:       
                   3231:       for(i=iagemin; i <= iagemax+3; i++){
                   3232:        if(i==iagemax+3){
                   3233:          fprintf(ficlog,"Total");
                   3234:        }else{
                   3235:          if(first==1){
                   3236:            first=0;
                   3237:            printf("See log file for details...\n");
                   3238:          }
                   3239:          fprintf(ficlog,"Age %d", i);
                   3240:        }
                   3241:        for(jk=1; jk <=nlstate ; jk++){
                   3242:          for(m=-1, pp[jk]=0; m <=nlstate+ndeath ; m++)
                   3243:            pp[jk] += freq[jk][m][i]; 
                   3244:        }
                   3245:        for(jk=1; jk <=nlstate ; jk++){
                   3246:          for(m=-1, pos=0; m <=0 ; m++)
                   3247:            pos += freq[jk][m][i];
                   3248:          if(pp[jk]>=1.e-10){
                   3249:            if(first==1){
1.132     brouard  3250:              printf(" %d.=%.0f loss[%d]=%.1f%%",jk,pp[jk],jk,100*pos/pp[jk]);
1.126     brouard  3251:            }
                   3252:            fprintf(ficlog," %d.=%.0f loss[%d]=%.1f%%",jk,pp[jk],jk,100*pos/pp[jk]);
                   3253:          }else{
                   3254:            if(first==1)
                   3255:              printf(" %d.=%.0f loss[%d]=NaNQ%%",jk,pp[jk],jk);
                   3256:            fprintf(ficlog," %d.=%.0f loss[%d]=NaNQ%%",jk,pp[jk],jk);
                   3257:          }
                   3258:        }
                   3259: 
                   3260:        for(jk=1; jk <=nlstate ; jk++){
                   3261:          for(m=0, pp[jk]=0; m <=nlstate+ndeath; m++)
                   3262:            pp[jk] += freq[jk][m][i];
                   3263:        }       
                   3264:        for(jk=1,pos=0,posprop=0; jk <=nlstate ; jk++){
                   3265:          pos += pp[jk];
                   3266:          posprop += prop[jk][i];
                   3267:        }
                   3268:        for(jk=1; jk <=nlstate ; jk++){
                   3269:          if(pos>=1.e-5){
                   3270:            if(first==1)
                   3271:              printf(" %d.=%.0f prev[%d]=%.1f%%",jk,pp[jk],jk,100*pp[jk]/pos);
                   3272:            fprintf(ficlog," %d.=%.0f prev[%d]=%.1f%%",jk,pp[jk],jk,100*pp[jk]/pos);
                   3273:          }else{
                   3274:            if(first==1)
                   3275:              printf(" %d.=%.0f prev[%d]=NaNQ%%",jk,pp[jk],jk);
                   3276:            fprintf(ficlog," %d.=%.0f prev[%d]=NaNQ%%",jk,pp[jk],jk);
                   3277:          }
                   3278:          if( i <= iagemax){
                   3279:            if(pos>=1.e-5){
                   3280:              fprintf(ficresp," %d %.5f %.0f %.0f",i,prop[jk][i]/posprop, prop[jk][i],posprop);
                   3281:              /*probs[i][jk][j1]= pp[jk]/pos;*/
                   3282:              /*printf("\ni=%d jk=%d j1=%d %.5f %.0f %.0f %f",i,jk,j1,pp[jk]/pos, pp[jk],pos,probs[i][jk][j1]);*/
                   3283:            }
                   3284:            else
                   3285:              fprintf(ficresp," %d NaNq %.0f %.0f",i,prop[jk][i],posprop);
                   3286:          }
                   3287:        }
                   3288:        
                   3289:        for(jk=-1; jk <=nlstate+ndeath; jk++)
                   3290:          for(m=-1; m <=nlstate+ndeath; m++)
                   3291:            if(freq[jk][m][i] !=0 ) {
                   3292:            if(first==1)
                   3293:              printf(" %d%d=%.0f",jk,m,freq[jk][m][i]);
                   3294:              fprintf(ficlog," %d%d=%.0f",jk,m,freq[jk][m][i]);
                   3295:            }
                   3296:        if(i <= iagemax)
                   3297:          fprintf(ficresp,"\n");
                   3298:        if(first==1)
                   3299:          printf("Others in log...\n");
                   3300:        fprintf(ficlog,"\n");
                   3301:       }
1.145     brouard  3302:       /*}*/
1.126     brouard  3303:   }
                   3304:   dateintmean=dateintsum/k2cpt; 
                   3305:  
                   3306:   fclose(ficresp);
                   3307:   free_ma3x(freq,-5,nlstate+ndeath,-5,nlstate+ndeath, iagemin, iagemax+3);
                   3308:   free_vector(pp,1,nlstate);
                   3309:   free_matrix(prop,1,nlstate,iagemin, iagemax+3);
                   3310:   /* End of Freq */
                   3311: }
                   3312: 
                   3313: /************ Prevalence ********************/
                   3314: 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)
                   3315: {  
                   3316:   /* Compute observed prevalence between dateprev1 and dateprev2 by counting the number of people
                   3317:      in each health status at the date of interview (if between dateprev1 and dateprev2).
                   3318:      We still use firstpass and lastpass as another selection.
                   3319:   */
                   3320:  
1.164     brouard  3321:   int i, m, jk, j1, bool, z1,j;
                   3322: 
                   3323:   double **prop;
                   3324:   double posprop; 
1.126     brouard  3325:   double  y2; /* in fractional years */
                   3326:   int iagemin, iagemax;
1.145     brouard  3327:   int first; /** to stop verbosity which is redirected to log file */
1.126     brouard  3328: 
                   3329:   iagemin= (int) agemin;
                   3330:   iagemax= (int) agemax;
                   3331:   /*pp=vector(1,nlstate);*/
                   3332:   prop=matrix(1,nlstate,iagemin,iagemax+3); 
                   3333:   /*  freq=ma3x(-1,nlstate+ndeath,-1,nlstate+ndeath,iagemin,iagemax+3);*/
                   3334:   j1=0;
                   3335:   
1.145     brouard  3336:   /*j=cptcoveff;*/
1.126     brouard  3337:   if (cptcovn<1) {j=1;ncodemax[1]=1;}
                   3338:   
1.145     brouard  3339:   first=1;
                   3340:   for(j1=1; j1<= (int) pow(2,cptcoveff);j1++){
                   3341:     /*for(i1=1; i1<=ncodemax[k1];i1++){
                   3342:       j1++;*/
1.126     brouard  3343:       
                   3344:       for (i=1; i<=nlstate; i++)  
                   3345:        for(m=iagemin; m <= iagemax+3; m++)
                   3346:          prop[i][m]=0.0;
                   3347:      
                   3348:       for (i=1; i<=imx; i++) { /* Each individual */
                   3349:        bool=1;
                   3350:        if  (cptcovn>0) {
                   3351:          for (z1=1; z1<=cptcoveff; z1++) 
1.198     brouard  3352:            if (covar[Tvaraff[z1]][i]!= nbcode[Tvaraff[z1]][codtabm(j1,z1)]) 
1.126     brouard  3353:              bool=0;
                   3354:        } 
                   3355:        if (bool==1) { 
                   3356:          for(m=firstpass; m<=lastpass; m++){/* Other selection (we can limit to certain interviews*/
                   3357:            y2=anint[m][i]+(mint[m][i]/12.); /* Fractional date in year */
                   3358:            if ((y2>=dateprev1) && (y2<=dateprev2)) { /* Here is the main selection (fractional years) */
                   3359:              if(agev[m][i]==0) agev[m][i]=iagemax+1;
                   3360:              if(agev[m][i]==1) agev[m][i]=iagemax+2;
                   3361:              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); 
                   3362:              if (s[m][i]>0 && s[m][i]<=nlstate) { 
                   3363:                /*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]]);*/
                   3364:                prop[s[m][i]][(int)agev[m][i]] += weight[i];
                   3365:                prop[s[m][i]][iagemax+3] += weight[i]; 
                   3366:              } 
                   3367:            }
                   3368:          } /* end selection of waves */
                   3369:        }
                   3370:       }
                   3371:       for(i=iagemin; i <= iagemax+3; i++){  
                   3372:        for(jk=1,posprop=0; jk <=nlstate ; jk++) { 
                   3373:          posprop += prop[jk][i]; 
                   3374:        } 
1.145     brouard  3375:        
1.126     brouard  3376:        for(jk=1; jk <=nlstate ; jk++){     
                   3377:          if( i <=  iagemax){ 
                   3378:            if(posprop>=1.e-5){ 
                   3379:              probs[i][jk][j1]= prop[jk][i]/posprop;
1.145     brouard  3380:            } else{
                   3381:              if(first==1){
                   3382:                first=0;
                   3383:                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]);
                   3384:              }
                   3385:            }
1.126     brouard  3386:          } 
                   3387:        }/* end jk */ 
                   3388:       }/* end i */ 
1.145     brouard  3389:     /*} *//* end i1 */
                   3390:   } /* end j1 */
1.126     brouard  3391:   
                   3392:   /*  free_ma3x(freq,-1,nlstate+ndeath,-1,nlstate+ndeath, iagemin, iagemax+3);*/
                   3393:   /*free_vector(pp,1,nlstate);*/
                   3394:   free_matrix(prop,1,nlstate, iagemin,iagemax+3);
                   3395: }  /* End of prevalence */
                   3396: 
                   3397: /************* Waves Concatenation ***************/
                   3398: 
                   3399: 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)
                   3400: {
                   3401:   /* Concatenates waves: wav[i] is the number of effective (useful waves) of individual i.
                   3402:      Death is a valid wave (if date is known).
                   3403:      mw[mi][i] is the mi (mi=1 to wav[i])  effective wave of individual i
                   3404:      dh[m][i] or dh[mw[mi][i]][i] is the delay between two effective waves m=mw[mi][i]
                   3405:      and mw[mi+1][i]. dh depends on stepm.
                   3406:      */
                   3407: 
                   3408:   int i, mi, m;
                   3409:   /* int j, k=0,jk, ju, jl,jmin=1e+5, jmax=-1;
                   3410:      double sum=0., jmean=0.;*/
                   3411:   int first;
                   3412:   int j, k=0,jk, ju, jl;
                   3413:   double sum=0.;
                   3414:   first=0;
1.164     brouard  3415:   jmin=100000;
1.126     brouard  3416:   jmax=-1;
                   3417:   jmean=0.;
                   3418:   for(i=1; i<=imx; i++){
                   3419:     mi=0;
                   3420:     m=firstpass;
                   3421:     while(s[m][i] <= nlstate){
                   3422:       if(s[m][i]>=1 || s[m][i]==-2 || s[m][i]==-4 || s[m][i]==-5)
                   3423:        mw[++mi][i]=m;
                   3424:       if(m >=lastpass)
                   3425:        break;
                   3426:       else
                   3427:        m++;
                   3428:     }/* end while */
                   3429:     if (s[m][i] > nlstate){
                   3430:       mi++;    /* Death is another wave */
                   3431:       /* if(mi==0)  never been interviewed correctly before death */
                   3432:         /* Only death is a correct wave */
                   3433:       mw[mi][i]=m;
                   3434:     }
                   3435: 
                   3436:     wav[i]=mi;
                   3437:     if(mi==0){
                   3438:       nbwarn++;
                   3439:       if(first==0){
                   3440:        printf("Warning! No valid information for individual %ld line=%d (skipped) and may be others, see log file\n",num[i],i);
                   3441:        first=1;
                   3442:       }
                   3443:       if(first==1){
                   3444:        fprintf(ficlog,"Warning! No valid information for individual %ld line=%d (skipped)\n",num[i],i);
                   3445:       }
                   3446:     } /* end mi==0 */
                   3447:   } /* End individuals */
                   3448: 
                   3449:   for(i=1; i<=imx; i++){
                   3450:     for(mi=1; mi<wav[i];mi++){
                   3451:       if (stepm <=0)
                   3452:        dh[mi][i]=1;
                   3453:       else{
                   3454:        if (s[mw[mi+1][i]][i] > nlstate) { /* A death */
                   3455:          if (agedc[i] < 2*AGESUP) {
                   3456:            j= rint(agedc[i]*12-agev[mw[mi][i]][i]*12); 
                   3457:            if(j==0) j=1;  /* Survives at least one month after exam */
                   3458:            else if(j<0){
                   3459:              nberr++;
                   3460:              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]);
                   3461:              j=1; /* Temporary Dangerous patch */
                   3462:              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);
                   3463:              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]);
                   3464:              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);
                   3465:            }
                   3466:            k=k+1;
                   3467:            if (j >= jmax){
                   3468:              jmax=j;
                   3469:              ijmax=i;
                   3470:            }
                   3471:            if (j <= jmin){
                   3472:              jmin=j;
                   3473:              ijmin=i;
                   3474:            }
                   3475:            sum=sum+j;
                   3476:            /*if (j<0) printf("j=%d num=%d \n",j,i);*/
                   3477:            /*    printf("%d %d %d %d\n", s[mw[mi][i]][i] ,s[mw[mi+1][i]][i],j,i);*/
                   3478:          }
                   3479:        }
                   3480:        else{
                   3481:          j= rint( (agev[mw[mi+1][i]][i]*12 - agev[mw[mi][i]][i]*12));
                   3482: /*       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]); */
                   3483: 
                   3484:          k=k+1;
                   3485:          if (j >= jmax) {
                   3486:            jmax=j;
                   3487:            ijmax=i;
                   3488:          }
                   3489:          else if (j <= jmin){
                   3490:            jmin=j;
                   3491:            ijmin=i;
                   3492:          }
                   3493:          /*        if (j<10) printf("j=%d jmin=%d num=%d ",j,jmin,i); */
                   3494:          /*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]);*/
                   3495:          if(j<0){
                   3496:            nberr++;
                   3497:            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]);
                   3498:            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]);
                   3499:          }
                   3500:          sum=sum+j;
                   3501:        }
                   3502:        jk= j/stepm;
                   3503:        jl= j -jk*stepm;
                   3504:        ju= j -(jk+1)*stepm;
                   3505:        if(mle <=1){ /* only if we use a the linear-interpoloation pseudo-likelihood */
                   3506:          if(jl==0){
                   3507:            dh[mi][i]=jk;
                   3508:            bh[mi][i]=0;
                   3509:          }else{ /* We want a negative bias in order to only have interpolation ie
1.136     brouard  3510:                  * to avoid the price of an extra matrix product in likelihood */
1.126     brouard  3511:            dh[mi][i]=jk+1;
                   3512:            bh[mi][i]=ju;
                   3513:          }
                   3514:        }else{
                   3515:          if(jl <= -ju){
                   3516:            dh[mi][i]=jk;
                   3517:            bh[mi][i]=jl;       /* bias is positive if real duration
                   3518:                                 * is higher than the multiple of stepm and negative otherwise.
                   3519:                                 */
                   3520:          }
                   3521:          else{
                   3522:            dh[mi][i]=jk+1;
                   3523:            bh[mi][i]=ju;
                   3524:          }
                   3525:          if(dh[mi][i]==0){
                   3526:            dh[mi][i]=1; /* At least one step */
                   3527:            bh[mi][i]=ju; /* At least one step */
                   3528:            /*  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);*/
                   3529:          }
                   3530:        } /* end if mle */
                   3531:       }
                   3532:     } /* end wave */
                   3533:   }
                   3534:   jmean=sum/k;
                   3535:   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  3536:   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  3537:  }
                   3538: 
                   3539: /*********** Tricode ****************************/
1.145     brouard  3540: void tricode(int *Tvar, int **nbcode, int imx, int *Ndum)
1.126     brouard  3541: {
1.144     brouard  3542:   /**< Uses cptcovn+2*cptcovprod as the number of covariates */
                   3543:   /*     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  3544:    * Boring subroutine which should only output nbcode[Tvar[j]][k]
1.145     brouard  3545:    * Tvar[5] in V2+V1+V3*age+V2*V4 is 2 (V2)
1.169     brouard  3546:    * nbcode[Tvar[j]][1]= 
1.144     brouard  3547:   */
1.130     brouard  3548: 
1.145     brouard  3549:   int ij=1, k=0, j=0, i=0, maxncov=NCOVMAX;
1.136     brouard  3550:   int modmaxcovj=0; /* Modality max of covariates j */
1.145     brouard  3551:   int cptcode=0; /* Modality max of covariates j */
                   3552:   int modmincovj=0; /* Modality min of covariates j */
                   3553: 
                   3554: 
1.126     brouard  3555:   cptcoveff=0; 
                   3556:  
1.144     brouard  3557:   for (k=1; k <= maxncov; k++) ncodemax[k]=0; /* Horrible constant again replaced by NCOVMAX */
1.126     brouard  3558: 
1.145     brouard  3559:   /* Loop on covariates without age and products */
1.186     brouard  3560:   for (j=1; j<=(cptcovs); j++) { /* From model V1 + V2*age+ V3 + V3*V4 keeps V1 + V3 = 2 only */
1.192     brouard  3561:     for (k=-1; k < maxncov; k++) Ndum[k]=0;
1.186     brouard  3562:     for (i=1; i<=imx; i++) { /* Loop on individuals: reads the data file to get the maximum value of the 
1.136     brouard  3563:                               modality of this covariate Vj*/ 
1.145     brouard  3564:       ij=(int)(covar[Tvar[j]][i]); /* ij=0 or 1 or -1. Value of the covariate Tvar[j] for individual i
                   3565:                                    * If product of Vn*Vm, still boolean *:
                   3566:                                    * If it was coded 1, 2, 3, 4 should be splitted into 3 boolean variables
                   3567:                                    * 1 => 0 0 0, 2 => 0 0 1, 3 => 0 1 1, 4=1 0 0   */
                   3568:       /* Finds for covariate j, n=Tvar[j] of Vn . ij is the
1.136     brouard  3569:                                      modality of the nth covariate of individual i. */
1.145     brouard  3570:       if (ij > modmaxcovj)
                   3571:         modmaxcovj=ij; 
                   3572:       else if (ij < modmincovj) 
                   3573:        modmincovj=ij; 
                   3574:       if ((ij < -1) && (ij > NCOVMAX)){
                   3575:        printf( "Error: minimal is less than -1 or maximal is bigger than %d. Exiting. \n", NCOVMAX );
                   3576:        exit(1);
                   3577:       }else
1.136     brouard  3578:       Ndum[ij]++; /*counts and stores the occurence of this modality 0, 1, -1*/
1.145     brouard  3579:       /*  If coded 1, 2, 3 , counts the number of 1 Ndum[1], number of 2, Ndum[2], etc */
1.126     brouard  3580:       /*printf("i=%d ij=%d Ndum[ij]=%d imx=%d",i,ij,Ndum[ij],imx);*/
1.136     brouard  3581:       /* getting the maximum value of the modality of the covariate
                   3582:         (should be 0 or 1 now) Tvar[j]. If V=sex and male is coded 0 and
                   3583:         female is 1, then modmaxcovj=1.*/
1.192     brouard  3584:     } /* end for loop on individuals i */
1.145     brouard  3585:     printf(" Minimal and maximal values of %d th covariate V%d: min=%d max=%d \n", j, Tvar[j], modmincovj, modmaxcovj);
1.192     brouard  3586:     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  3587:     cptcode=modmaxcovj;
1.137     brouard  3588:     /* Ndum[0] = frequency of 0 for model-covariate j, Ndum[1] frequency of 1 etc. */
1.145     brouard  3589:    /*for (i=0; i<=cptcode; i++) {*/
1.192     brouard  3590:     for (k=modmincovj;  k<=modmaxcovj; k++) { /* k=-1 ? 0 and 1*//* For each value k of the modality of model-cov j */
                   3591:       printf("Frequencies of covariates %d ie V%d with value %d: %d\n", j, Tvar[j], k, Ndum[k]);
                   3592:       fprintf(ficlog, "Frequencies of covariates %d ie V%d with value %d: %d\n", j, Tvar[j], k, Ndum[k]);
                   3593:       if( Ndum[k] != 0 ){ /* Counts if nobody answered modality k ie empty modality, we skip it and reorder */
                   3594:        if( k != -1){
                   3595:          ncodemax[j]++;  /* ncodemax[j]= Number of modalities of the j th
                   3596:                             covariate for which somebody answered excluding 
                   3597:                             undefined. Usually 2: 0 and 1. */
                   3598:        }
                   3599:        ncodemaxwundef[j]++; /* ncodemax[j]= Number of modalities of the j th
                   3600:                             covariate for which somebody answered including 
                   3601:                             undefined. Usually 3: -1, 0 and 1. */
1.145     brouard  3602:       }
                   3603:       /* In fact  ncodemax[j]=2 (dichotom. variables only) but it could be more for
                   3604:         historical reasons: 3 if coded 1, 2, 3 and 4 and Ndum[2]=0 */
1.131     brouard  3605:     } /* Ndum[-1] number of undefined modalities */
1.126     brouard  3606: 
1.136     brouard  3607:     /* j is a covariate, n=Tvar[j] of Vn; Fills nbcode */
1.186     brouard  3608:     /* For covariate j, modalities could be 1, 2, 3, 4, 5, 6, 7. 
                   3609:        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  3610:        modmincovj=3; modmaxcovj = 7;
1.186     brouard  3611:        There are only 3 modalities non empty 3, 6, 7 (or 2 if 27 is too few) : ncodemax[j]=3;
                   3612:        which will be coded 0, 1, 2 which in binary on 2=3-1 digits are 0=00 1=01, 2=10;
                   3613:        defining two dummy variables: variables V1_1 and V1_2.
1.145     brouard  3614:        nbcode[Tvar[j]][ij]=k;
                   3615:        nbcode[Tvar[j]][1]=0;
                   3616:        nbcode[Tvar[j]][2]=1;
                   3617:        nbcode[Tvar[j]][3]=2;
1.197     brouard  3618:        To be continued (not working yet).
1.145     brouard  3619:     */
1.197     brouard  3620:     ij=0; /* ij is similar to i but can jump over null modalities */
                   3621:     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*/
                   3622:        if (Ndum[i] == 0) { /* If nobody responded to this modality k */
1.192     brouard  3623:          break;
                   3624:        }
                   3625:        ij++;
1.197     brouard  3626:        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  3627:        cptcode = ij; /* New max modality for covar j */
                   3628:     } /* end of loop on modality i=-1 to 1 or more */
                   3629:       
                   3630:     /*   for (k=0; k<= cptcode; k++) { /\* k=-1 ? k=0 to 1 *\//\* Could be 1 to 4 *\//\* cptcode=modmaxcovj *\/ */
                   3631:     /*         /\*recode from 0 *\/ */
                   3632:     /*                                      k is a modality. If we have model=V1+V1*sex  */
                   3633:     /*                                      then: nbcode[1][1]=0 ; nbcode[1][2]=1; nbcode[2][1]=0 ; nbcode[2][2]=1; */
                   3634:     /*                                   But if some modality were not used, it is recoded from 0 to a newer modmaxcovj=cptcode *\/ */
                   3635:     /*         } */
                   3636:     /*         /\* cptcode = ij; *\/ /\* New max modality for covar j *\/ */
                   3637:     /*         if (ij > ncodemax[j]) { */
                   3638:     /*           printf( " Error ij=%d > ncodemax[%d]=%d\n", ij, j, ncodemax[j]);  */
                   3639:     /*           fprintf(ficlog, " Error ij=%d > ncodemax[%d]=%d\n", ij, j, ncodemax[j]); */
                   3640:     /*           break; */
                   3641:     /*         } */
                   3642:     /*   }  /\* end of loop on modality k *\/ */
1.137     brouard  3643:   } /* end of loop on model-covariate j. nbcode[Tvarj][1]=0 and nbcode[Tvarj][2]=1 sets the value of covariate j*/  
                   3644:   
1.145     brouard  3645:  for (k=-1; k< maxncov; k++) Ndum[k]=0; 
1.137     brouard  3646:   
1.187     brouard  3647:   for (i=1; i<=ncovmodel-2-nagesqr; i++) { /* -2, cste and age and eventually age*age */ 
1.145     brouard  3648:    /* Listing of all covariables in statement model to see if some covariates appear twice. For example, V1 appears twice in V1+V1*V2.*/ 
                   3649:    ij=Tvar[i]; /* Tvar might be -1 if status was unknown */ 
1.187     brouard  3650:    Ndum[ij]++; /* Might be supersed V1 + V1*age */
1.145     brouard  3651:  } 
1.126     brouard  3652: 
1.192     brouard  3653:  ij=0;
1.145     brouard  3654:  for (i=0; i<=  maxncov-1; i++) { /* modmaxcovj is unknown here. Only Ndum[2(V2),3(age*V3), 5(V3*V2) 6(V1*V4) */
                   3655:    /*printf("Ndum[%d]=%d\n",i, Ndum[i]);*/
1.126     brouard  3656:    if((Ndum[i]!=0) && (i<=ncovcol)){
1.192     brouard  3657:      ij++;
1.145     brouard  3658:      /*printf("diff Ndum[%d]=%d\n",i, Ndum[i]);*/
                   3659:      Tvaraff[ij]=i; /*For printing (unclear) */
1.192     brouard  3660:    }else{
                   3661:        /* Tvaraff[ij]=0; */
                   3662:    }
1.126     brouard  3663:  }
1.192     brouard  3664:  /* ij--; */
1.144     brouard  3665:  cptcoveff=ij; /*Number of total covariates*/
1.145     brouard  3666: 
1.126     brouard  3667: }
                   3668: 
1.145     brouard  3669: 
1.126     brouard  3670: /*********** Health Expectancies ****************/
                   3671: 
1.127     brouard  3672: 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  3673: 
                   3674: {
                   3675:   /* Health expectancies, no variances */
1.164     brouard  3676:   int i, j, nhstepm, hstepm, h, nstepm;
1.126     brouard  3677:   int nhstepma, nstepma; /* Decreasing with age */
                   3678:   double age, agelim, hf;
                   3679:   double ***p3mat;
                   3680:   double eip;
                   3681: 
                   3682:   pstamp(ficreseij);
                   3683:   fprintf(ficreseij,"# (a) Life expectancies by health status at initial age and (b) health expectancies by health status at initial age\n");
                   3684:   fprintf(ficreseij,"# Age");
                   3685:   for(i=1; i<=nlstate;i++){
                   3686:     for(j=1; j<=nlstate;j++){
                   3687:       fprintf(ficreseij," e%1d%1d ",i,j);
                   3688:     }
                   3689:     fprintf(ficreseij," e%1d. ",i);
                   3690:   }
                   3691:   fprintf(ficreseij,"\n");
                   3692: 
                   3693:   
                   3694:   if(estepm < stepm){
                   3695:     printf ("Problem %d lower than %d\n",estepm, stepm);
                   3696:   }
                   3697:   else  hstepm=estepm;   
                   3698:   /* We compute the life expectancy from trapezoids spaced every estepm months
                   3699:    * This is mainly to measure the difference between two models: for example
                   3700:    * if stepm=24 months pijx are given only every 2 years and by summing them
                   3701:    * we are calculating an estimate of the Life Expectancy assuming a linear 
                   3702:    * progression in between and thus overestimating or underestimating according
                   3703:    * to the curvature of the survival function. If, for the same date, we 
                   3704:    * estimate the model with stepm=1 month, we can keep estepm to 24 months
                   3705:    * to compare the new estimate of Life expectancy with the same linear 
                   3706:    * hypothesis. A more precise result, taking into account a more precise
                   3707:    * curvature will be obtained if estepm is as small as stepm. */
                   3708: 
                   3709:   /* For example we decided to compute the life expectancy with the smallest unit */
                   3710:   /* hstepm beeing the number of stepms, if hstepm=1 the length of hstepm is stepm. 
                   3711:      nhstepm is the number of hstepm from age to agelim 
                   3712:      nstepm is the number of stepm from age to agelin. 
                   3713:      Look at hpijx to understand the reason of that which relies in memory size
                   3714:      and note for a fixed period like estepm months */
                   3715:   /* We decided (b) to get a life expectancy respecting the most precise curvature of the
                   3716:      survival function given by stepm (the optimization length). Unfortunately it
                   3717:      means that if the survival funtion is printed only each two years of age and if
                   3718:      you sum them up and add 1 year (area under the trapezoids) you won't get the same 
                   3719:      results. So we changed our mind and took the option of the best precision.
                   3720:   */
                   3721:   hstepm=hstepm/stepm; /* Typically in stepm units, if stepm=6 & estepm=24 , = 24/6 months = 4 */ 
                   3722: 
                   3723:   agelim=AGESUP;
                   3724:   /* If stepm=6 months */
                   3725:     /* Computed by stepm unit matrices, product of hstepm matrices, stored
                   3726:        in an array of nhstepm length: nhstepm=10, hstepm=4, stepm=6 months */
                   3727:     
                   3728: /* nhstepm age range expressed in number of stepm */
                   3729:   nstepm=(int) rint((agelim-bage)*YEARM/stepm); /* Biggest nstepm */
                   3730:   /* Typically if 20 years nstepm = 20*12/6=40 stepm */ 
                   3731:   /* if (stepm >= YEARM) hstepm=1;*/
                   3732:   nhstepm = nstepm/hstepm;/* Expressed in hstepm, typically nhstepm=40/4=10 */
                   3733:   p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   3734: 
                   3735:   for (age=bage; age<=fage; age ++){ 
                   3736:     nstepma=(int) rint((agelim-bage)*YEARM/stepm); /* Biggest nstepm */
                   3737:     /* Typically if 20 years nstepm = 20*12/6=40 stepm */ 
                   3738:     /* if (stepm >= YEARM) hstepm=1;*/
                   3739:     nhstepma = nstepma/hstepm;/* Expressed in hstepm, typically nhstepma=40/4=10 */
                   3740: 
                   3741:     /* If stepm=6 months */
                   3742:     /* Computed by stepm unit matrices, product of hstepma matrices, stored
                   3743:        in an array of nhstepma length: nhstepma=10, hstepm=4, stepm=6 months */
                   3744:     
                   3745:     hpxij(p3mat,nhstepma,age,hstepm,x,nlstate,stepm,oldm, savm, cij);  
                   3746:     
                   3747:     hf=hstepm*stepm/YEARM;  /* Duration of hstepm expressed in year unit. */
                   3748:     
                   3749:     printf("%d|",(int)age);fflush(stdout);
                   3750:     fprintf(ficlog,"%d|",(int)age);fflush(ficlog);
                   3751:     
                   3752:     /* Computing expectancies */
                   3753:     for(i=1; i<=nlstate;i++)
                   3754:       for(j=1; j<=nlstate;j++)
                   3755:        for (h=0, eij[i][j][(int)age]=0; h<=nhstepm-1; h++){
                   3756:          eij[i][j][(int)age] += (p3mat[i][j][h]+p3mat[i][j][h+1])/2.0*hf;
                   3757:          
                   3758:          /* 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]);*/
                   3759: 
                   3760:        }
                   3761: 
                   3762:     fprintf(ficreseij,"%3.0f",age );
                   3763:     for(i=1; i<=nlstate;i++){
                   3764:       eip=0;
                   3765:       for(j=1; j<=nlstate;j++){
                   3766:        eip +=eij[i][j][(int)age];
                   3767:        fprintf(ficreseij,"%9.4f", eij[i][j][(int)age] );
                   3768:       }
                   3769:       fprintf(ficreseij,"%9.4f", eip );
                   3770:     }
                   3771:     fprintf(ficreseij,"\n");
                   3772:     
                   3773:   }
                   3774:   free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   3775:   printf("\n");
                   3776:   fprintf(ficlog,"\n");
                   3777:   
                   3778: }
                   3779: 
1.127     brouard  3780: 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  3781: 
                   3782: {
                   3783:   /* Covariances of health expectancies eij and of total life expectancies according
                   3784:    to initial status i, ei. .
                   3785:   */
                   3786:   int i, j, nhstepm, hstepm, h, nstepm, k, cptj, cptj2, i2, j2, ij, ji;
                   3787:   int nhstepma, nstepma; /* Decreasing with age */
                   3788:   double age, agelim, hf;
                   3789:   double ***p3matp, ***p3matm, ***varhe;
                   3790:   double **dnewm,**doldm;
                   3791:   double *xp, *xm;
                   3792:   double **gp, **gm;
                   3793:   double ***gradg, ***trgradg;
                   3794:   int theta;
                   3795: 
                   3796:   double eip, vip;
                   3797: 
                   3798:   varhe=ma3x(1,nlstate*nlstate,1,nlstate*nlstate,(int) bage, (int) fage);
                   3799:   xp=vector(1,npar);
                   3800:   xm=vector(1,npar);
                   3801:   dnewm=matrix(1,nlstate*nlstate,1,npar);
                   3802:   doldm=matrix(1,nlstate*nlstate,1,nlstate*nlstate);
                   3803:   
                   3804:   pstamp(ficresstdeij);
                   3805:   fprintf(ficresstdeij,"# Health expectancies with standard errors\n");
                   3806:   fprintf(ficresstdeij,"# Age");
                   3807:   for(i=1; i<=nlstate;i++){
                   3808:     for(j=1; j<=nlstate;j++)
                   3809:       fprintf(ficresstdeij," e%1d%1d (SE)",i,j);
                   3810:     fprintf(ficresstdeij," e%1d. ",i);
                   3811:   }
                   3812:   fprintf(ficresstdeij,"\n");
                   3813: 
                   3814:   pstamp(ficrescveij);
                   3815:   fprintf(ficrescveij,"# Subdiagonal matrix of covariances of health expectancies by age: cov(eij,ekl)\n");
                   3816:   fprintf(ficrescveij,"# Age");
                   3817:   for(i=1; i<=nlstate;i++)
                   3818:     for(j=1; j<=nlstate;j++){
                   3819:       cptj= (j-1)*nlstate+i;
                   3820:       for(i2=1; i2<=nlstate;i2++)
                   3821:        for(j2=1; j2<=nlstate;j2++){
                   3822:          cptj2= (j2-1)*nlstate+i2;
                   3823:          if(cptj2 <= cptj)
                   3824:            fprintf(ficrescveij,"  %1d%1d,%1d%1d",i,j,i2,j2);
                   3825:        }
                   3826:     }
                   3827:   fprintf(ficrescveij,"\n");
                   3828:   
                   3829:   if(estepm < stepm){
                   3830:     printf ("Problem %d lower than %d\n",estepm, stepm);
                   3831:   }
                   3832:   else  hstepm=estepm;   
                   3833:   /* We compute the life expectancy from trapezoids spaced every estepm months
                   3834:    * This is mainly to measure the difference between two models: for example
                   3835:    * if stepm=24 months pijx are given only every 2 years and by summing them
                   3836:    * we are calculating an estimate of the Life Expectancy assuming a linear 
                   3837:    * progression in between and thus overestimating or underestimating according
                   3838:    * to the curvature of the survival function. If, for the same date, we 
                   3839:    * estimate the model with stepm=1 month, we can keep estepm to 24 months
                   3840:    * to compare the new estimate of Life expectancy with the same linear 
                   3841:    * hypothesis. A more precise result, taking into account a more precise
                   3842:    * curvature will be obtained if estepm is as small as stepm. */
                   3843: 
                   3844:   /* For example we decided to compute the life expectancy with the smallest unit */
                   3845:   /* hstepm beeing the number of stepms, if hstepm=1 the length of hstepm is stepm. 
                   3846:      nhstepm is the number of hstepm from age to agelim 
                   3847:      nstepm is the number of stepm from age to agelin. 
                   3848:      Look at hpijx to understand the reason of that which relies in memory size
                   3849:      and note for a fixed period like estepm months */
                   3850:   /* We decided (b) to get a life expectancy respecting the most precise curvature of the
                   3851:      survival function given by stepm (the optimization length). Unfortunately it
                   3852:      means that if the survival funtion is printed only each two years of age and if
                   3853:      you sum them up and add 1 year (area under the trapezoids) you won't get the same 
                   3854:      results. So we changed our mind and took the option of the best precision.
                   3855:   */
                   3856:   hstepm=hstepm/stepm; /* Typically in stepm units, if stepm=6 & estepm=24 , = 24/6 months = 4 */ 
                   3857: 
                   3858:   /* If stepm=6 months */
                   3859:   /* nhstepm age range expressed in number of stepm */
                   3860:   agelim=AGESUP;
                   3861:   nstepm=(int) rint((agelim-bage)*YEARM/stepm); 
                   3862:   /* Typically if 20 years nstepm = 20*12/6=40 stepm */ 
                   3863:   /* if (stepm >= YEARM) hstepm=1;*/
                   3864:   nhstepm = nstepm/hstepm;/* Expressed in hstepm, typically nhstepm=40/4=10 */
                   3865:   
                   3866:   p3matp=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   3867:   p3matm=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   3868:   gradg=ma3x(0,nhstepm,1,npar,1,nlstate*nlstate);
                   3869:   trgradg =ma3x(0,nhstepm,1,nlstate*nlstate,1,npar);
                   3870:   gp=matrix(0,nhstepm,1,nlstate*nlstate);
                   3871:   gm=matrix(0,nhstepm,1,nlstate*nlstate);
                   3872: 
                   3873:   for (age=bage; age<=fage; age ++){ 
                   3874:     nstepma=(int) rint((agelim-bage)*YEARM/stepm); /* Biggest nstepm */
                   3875:     /* Typically if 20 years nstepm = 20*12/6=40 stepm */ 
                   3876:     /* if (stepm >= YEARM) hstepm=1;*/
                   3877:     nhstepma = nstepma/hstepm;/* Expressed in hstepm, typically nhstepma=40/4=10 */
                   3878: 
                   3879:     /* If stepm=6 months */
                   3880:     /* Computed by stepm unit matrices, product of hstepma matrices, stored
                   3881:        in an array of nhstepma length: nhstepma=10, hstepm=4, stepm=6 months */
                   3882:     
                   3883:     hf=hstepm*stepm/YEARM;  /* Duration of hstepm expressed in year unit. */
                   3884: 
                   3885:     /* Computing  Variances of health expectancies */
                   3886:     /* Gradient is computed with plus gp and minus gm. Code is duplicated in order to
                   3887:        decrease memory allocation */
                   3888:     for(theta=1; theta <=npar; theta++){
                   3889:       for(i=1; i<=npar; i++){ 
                   3890:        xp[i] = x[i] + (i==theta ?delti[theta]:0);
                   3891:        xm[i] = x[i] - (i==theta ?delti[theta]:0);
                   3892:       }
                   3893:       hpxij(p3matp,nhstepm,age,hstepm,xp,nlstate,stepm,oldm,savm, cij);  
                   3894:       hpxij(p3matm,nhstepm,age,hstepm,xm,nlstate,stepm,oldm,savm, cij);  
                   3895:   
                   3896:       for(j=1; j<= nlstate; j++){
                   3897:        for(i=1; i<=nlstate; i++){
                   3898:          for(h=0; h<=nhstepm-1; h++){
                   3899:            gp[h][(j-1)*nlstate + i] = (p3matp[i][j][h]+p3matp[i][j][h+1])/2.;
                   3900:            gm[h][(j-1)*nlstate + i] = (p3matm[i][j][h]+p3matm[i][j][h+1])/2.;
                   3901:          }
                   3902:        }
                   3903:       }
                   3904:      
                   3905:       for(ij=1; ij<= nlstate*nlstate; ij++)
                   3906:        for(h=0; h<=nhstepm-1; h++){
                   3907:          gradg[h][theta][ij]= (gp[h][ij]-gm[h][ij])/2./delti[theta];
                   3908:        }
                   3909:     }/* End theta */
                   3910:     
                   3911:     
                   3912:     for(h=0; h<=nhstepm-1; h++)
                   3913:       for(j=1; j<=nlstate*nlstate;j++)
                   3914:        for(theta=1; theta <=npar; theta++)
                   3915:          trgradg[h][j][theta]=gradg[h][theta][j];
                   3916:     
                   3917: 
                   3918:      for(ij=1;ij<=nlstate*nlstate;ij++)
                   3919:       for(ji=1;ji<=nlstate*nlstate;ji++)
                   3920:        varhe[ij][ji][(int)age] =0.;
                   3921: 
                   3922:      printf("%d|",(int)age);fflush(stdout);
                   3923:      fprintf(ficlog,"%d|",(int)age);fflush(ficlog);
                   3924:      for(h=0;h<=nhstepm-1;h++){
                   3925:       for(k=0;k<=nhstepm-1;k++){
                   3926:        matprod2(dnewm,trgradg[h],1,nlstate*nlstate,1,npar,1,npar,matcov);
                   3927:        matprod2(doldm,dnewm,1,nlstate*nlstate,1,npar,1,nlstate*nlstate,gradg[k]);
                   3928:        for(ij=1;ij<=nlstate*nlstate;ij++)
                   3929:          for(ji=1;ji<=nlstate*nlstate;ji++)
                   3930:            varhe[ij][ji][(int)age] += doldm[ij][ji]*hf*hf;
                   3931:       }
                   3932:     }
                   3933: 
                   3934:     /* Computing expectancies */
                   3935:     hpxij(p3matm,nhstepm,age,hstepm,x,nlstate,stepm,oldm, savm, cij);  
                   3936:     for(i=1; i<=nlstate;i++)
                   3937:       for(j=1; j<=nlstate;j++)
                   3938:        for (h=0, eij[i][j][(int)age]=0; h<=nhstepm-1; h++){
                   3939:          eij[i][j][(int)age] += (p3matm[i][j][h]+p3matm[i][j][h+1])/2.0*hf;
                   3940:          
                   3941:          /* 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]);*/
                   3942: 
                   3943:        }
                   3944: 
                   3945:     fprintf(ficresstdeij,"%3.0f",age );
                   3946:     for(i=1; i<=nlstate;i++){
                   3947:       eip=0.;
                   3948:       vip=0.;
                   3949:       for(j=1; j<=nlstate;j++){
                   3950:        eip += eij[i][j][(int)age];
                   3951:        for(k=1; k<=nlstate;k++) /* Sum on j and k of cov(eij,eik) */
                   3952:          vip += varhe[(j-1)*nlstate+i][(k-1)*nlstate+i][(int)age];
                   3953:        fprintf(ficresstdeij," %9.4f (%.4f)", eij[i][j][(int)age], sqrt(varhe[(j-1)*nlstate+i][(j-1)*nlstate+i][(int)age]) );
                   3954:       }
                   3955:       fprintf(ficresstdeij," %9.4f (%.4f)", eip, sqrt(vip));
                   3956:     }
                   3957:     fprintf(ficresstdeij,"\n");
                   3958: 
                   3959:     fprintf(ficrescveij,"%3.0f",age );
                   3960:     for(i=1; i<=nlstate;i++)
                   3961:       for(j=1; j<=nlstate;j++){
                   3962:        cptj= (j-1)*nlstate+i;
                   3963:        for(i2=1; i2<=nlstate;i2++)
                   3964:          for(j2=1; j2<=nlstate;j2++){
                   3965:            cptj2= (j2-1)*nlstate+i2;
                   3966:            if(cptj2 <= cptj)
                   3967:              fprintf(ficrescveij," %.4f", varhe[cptj][cptj2][(int)age]);
                   3968:          }
                   3969:       }
                   3970:     fprintf(ficrescveij,"\n");
                   3971:    
                   3972:   }
                   3973:   free_matrix(gm,0,nhstepm,1,nlstate*nlstate);
                   3974:   free_matrix(gp,0,nhstepm,1,nlstate*nlstate);
                   3975:   free_ma3x(gradg,0,nhstepm,1,npar,1,nlstate*nlstate);
                   3976:   free_ma3x(trgradg,0,nhstepm,1,nlstate*nlstate,1,npar);
                   3977:   free_ma3x(p3matm,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   3978:   free_ma3x(p3matp,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   3979:   printf("\n");
                   3980:   fprintf(ficlog,"\n");
                   3981: 
                   3982:   free_vector(xm,1,npar);
                   3983:   free_vector(xp,1,npar);
                   3984:   free_matrix(dnewm,1,nlstate*nlstate,1,npar);
                   3985:   free_matrix(doldm,1,nlstate*nlstate,1,nlstate*nlstate);
                   3986:   free_ma3x(varhe,1,nlstate*nlstate,1,nlstate*nlstate,(int) bage, (int)fage);
                   3987: }
                   3988: 
                   3989: /************ Variance ******************/
1.203     brouard  3990:  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 *ncvyear, int ij, int estepm, int cptcov, int cptcod, int popbased, int mobilav, char strstart[])
1.126     brouard  3991: {
                   3992:   /* Variance of health expectancies */
                   3993:   /*  double **prevalim(double **prlim, int nlstate, double *xp, double age, double **oldm, double ** savm,double ftolpl);*/
                   3994:   /* double **newm;*/
1.169     brouard  3995:   /* int movingaverage(double ***probs, double bage,double fage, double ***mobaverage, int mobilav)*/
                   3996:   
                   3997:   int movingaverage();
1.126     brouard  3998:   double **dnewm,**doldm;
                   3999:   double **dnewmp,**doldmp;
                   4000:   int i, j, nhstepm, hstepm, h, nstepm ;
1.164     brouard  4001:   int k;
1.126     brouard  4002:   double *xp;
                   4003:   double **gp, **gm;  /* for var eij */
                   4004:   double ***gradg, ***trgradg; /*for var eij */
                   4005:   double **gradgp, **trgradgp; /* for var p point j */
                   4006:   double *gpp, *gmp; /* for var p point j */
                   4007:   double **varppt; /* for var p point j nlstate to nlstate+ndeath */
                   4008:   double ***p3mat;
                   4009:   double age,agelim, hf;
                   4010:   double ***mobaverage;
                   4011:   int theta;
                   4012:   char digit[4];
                   4013:   char digitp[25];
                   4014: 
                   4015:   char fileresprobmorprev[FILENAMELENGTH];
                   4016: 
                   4017:   if(popbased==1){
                   4018:     if(mobilav!=0)
1.201     brouard  4019:       strcpy(digitp,"-POPULBASED-MOBILAV_");
                   4020:     else strcpy(digitp,"-POPULBASED-NOMOBIL_");
1.126     brouard  4021:   }
                   4022:   else 
1.201     brouard  4023:     strcpy(digitp,"-STABLBASED_");
1.126     brouard  4024: 
                   4025:   if (mobilav!=0) {
                   4026:     mobaverage= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
                   4027:     if (movingaverage(probs, bage, fage, mobaverage,mobilav)!=0){
                   4028:       fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav);
                   4029:       printf(" Error in movingaverage mobilav=%d\n",mobilav);
                   4030:     }
                   4031:   }
                   4032: 
1.201     brouard  4033:   strcpy(fileresprobmorprev,"PRMORPREV-"); 
1.126     brouard  4034:   sprintf(digit,"%-d",ij);
                   4035:   /*printf("DIGIT=%s, ij=%d ijr=%-d|\n",digit, ij,ij);*/
                   4036:   strcat(fileresprobmorprev,digit); /* Tvar to be done */
                   4037:   strcat(fileresprobmorprev,digitp); /* Popbased or not, mobilav or not */
1.202     brouard  4038:   strcat(fileresprobmorprev,fileresu);
1.126     brouard  4039:   if((ficresprobmorprev=fopen(fileresprobmorprev,"w"))==NULL) {
                   4040:     printf("Problem with resultfile: %s\n", fileresprobmorprev);
                   4041:     fprintf(ficlog,"Problem with resultfile: %s\n", fileresprobmorprev);
                   4042:   }
                   4043:   printf("Computing total mortality p.j=w1*p1j+w2*p2j+..: result on file '%s' \n",fileresprobmorprev);
                   4044:  
                   4045:   fprintf(ficlog,"Computing total mortality p.j=w1*p1j+w2*p2j+..: result on file '%s' \n",fileresprobmorprev);
                   4046:   pstamp(ficresprobmorprev);
                   4047:   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);
                   4048:   fprintf(ficresprobmorprev,"# Age cov=%-d",ij);
                   4049:   for(j=nlstate+1; j<=(nlstate+ndeath);j++){
                   4050:     fprintf(ficresprobmorprev," p.%-d SE",j);
                   4051:     for(i=1; i<=nlstate;i++)
                   4052:       fprintf(ficresprobmorprev," w%1d p%-d%-d",i,i,j);
                   4053:   }  
                   4054:   fprintf(ficresprobmorprev,"\n");
                   4055:   fprintf(ficgp,"\n# Routine varevsij");
1.200     brouard  4056:   fprintf(ficgp,"\nunset title \n");
                   4057: /* fprintf(fichtm, "#Local time at start: %s", strstart);*/
1.126     brouard  4058:   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");
                   4059:   fprintf(fichtm,"\n<br>%s  <br>\n",digitp);
                   4060: /*   } */
                   4061:   varppt = matrix(nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);
                   4062:   pstamp(ficresvij);
                   4063:   fprintf(ficresvij,"# Variance and covariance of health expectancies e.j \n#  (weighted average of eij where weights are ");
                   4064:   if(popbased==1)
1.128     brouard  4065:     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  4066:   else
                   4067:     fprintf(ficresvij,"the age specific period (stable) prevalences in each health state \n");
                   4068:   fprintf(ficresvij,"# Age");
                   4069:   for(i=1; i<=nlstate;i++)
                   4070:     for(j=1; j<=nlstate;j++)
                   4071:       fprintf(ficresvij," Cov(e.%1d, e.%1d)",i,j);
                   4072:   fprintf(ficresvij,"\n");
                   4073: 
                   4074:   xp=vector(1,npar);
                   4075:   dnewm=matrix(1,nlstate,1,npar);
                   4076:   doldm=matrix(1,nlstate,1,nlstate);
                   4077:   dnewmp= matrix(nlstate+1,nlstate+ndeath,1,npar);
                   4078:   doldmp= matrix(nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);
                   4079: 
                   4080:   gradgp=matrix(1,npar,nlstate+1,nlstate+ndeath);
                   4081:   gpp=vector(nlstate+1,nlstate+ndeath);
                   4082:   gmp=vector(nlstate+1,nlstate+ndeath);
                   4083:   trgradgp =matrix(nlstate+1,nlstate+ndeath,1,npar); /* mu or p point j*/
                   4084:   
                   4085:   if(estepm < stepm){
                   4086:     printf ("Problem %d lower than %d\n",estepm, stepm);
                   4087:   }
                   4088:   else  hstepm=estepm;   
                   4089:   /* For example we decided to compute the life expectancy with the smallest unit */
                   4090:   /* hstepm beeing the number of stepms, if hstepm=1 the length of hstepm is stepm. 
                   4091:      nhstepm is the number of hstepm from age to agelim 
                   4092:      nstepm is the number of stepm from age to agelin. 
1.128     brouard  4093:      Look at function hpijx to understand why (it is linked to memory size questions) */
1.126     brouard  4094:   /* We decided (b) to get a life expectancy respecting the most precise curvature of the
                   4095:      survival function given by stepm (the optimization length). Unfortunately it
                   4096:      means that if the survival funtion is printed every two years of age and if
                   4097:      you sum them up and add 1 year (area under the trapezoids) you won't get the same 
                   4098:      results. So we changed our mind and took the option of the best precision.
                   4099:   */
                   4100:   hstepm=hstepm/stepm; /* Typically in stepm units, if stepm=6 & estepm=24 , = 24/6 months = 4 */ 
                   4101:   agelim = AGESUP;
                   4102:   for (age=bage; age<=fage; age ++){ /* If stepm=6 months */
                   4103:     nstepm=(int) rint((agelim-age)*YEARM/stepm); /* Typically 20 years = 20*12/6=40 */ 
                   4104:     nhstepm = nstepm/hstepm;/* Expressed in hstepm, typically nhstepm=40/4=10 */
                   4105:     p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   4106:     gradg=ma3x(0,nhstepm,1,npar,1,nlstate);
                   4107:     gp=matrix(0,nhstepm,1,nlstate);
                   4108:     gm=matrix(0,nhstepm,1,nlstate);
                   4109: 
                   4110: 
                   4111:     for(theta=1; theta <=npar; theta++){
                   4112:       for(i=1; i<=npar; i++){ /* Computes gradient x + delta*/
                   4113:        xp[i] = x[i] + (i==theta ?delti[theta]:0);
                   4114:       }
                   4115:       hpxij(p3mat,nhstepm,age,hstepm,xp,nlstate,stepm,oldm,savm, ij);  
1.203     brouard  4116:       prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ncvyear,ij);
1.126     brouard  4117: 
                   4118:       if (popbased==1) {
                   4119:        if(mobilav ==0){
                   4120:          for(i=1; i<=nlstate;i++)
                   4121:            prlim[i][i]=probs[(int)age][i][ij];
                   4122:        }else{ /* mobilav */ 
                   4123:          for(i=1; i<=nlstate;i++)
                   4124:            prlim[i][i]=mobaverage[(int)age][i][ij];
                   4125:        }
                   4126:       }
                   4127:   
                   4128:       for(j=1; j<= nlstate; j++){
                   4129:        for(h=0; h<=nhstepm; h++){
                   4130:          for(i=1, gp[h][j]=0.;i<=nlstate;i++)
                   4131:            gp[h][j] += prlim[i][i]*p3mat[i][j][h];
                   4132:        }
                   4133:       }
                   4134:       /* This for computing probability of death (h=1 means
                   4135:          computed over hstepm matrices product = hstepm*stepm months) 
                   4136:          as a weighted average of prlim.
                   4137:       */
                   4138:       for(j=nlstate+1;j<=nlstate+ndeath;j++){
                   4139:        for(i=1,gpp[j]=0.; i<= nlstate; i++)
                   4140:          gpp[j] += prlim[i][i]*p3mat[i][j][1];
                   4141:       }    
                   4142:       /* end probability of death */
                   4143: 
                   4144:       for(i=1; i<=npar; i++) /* Computes gradient x - delta */
                   4145:        xp[i] = x[i] - (i==theta ?delti[theta]:0);
                   4146:       hpxij(p3mat,nhstepm,age,hstepm,xp,nlstate,stepm,oldm,savm, ij);  
1.203     brouard  4147:       prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ncvyear, ij);
1.126     brouard  4148:  
                   4149:       if (popbased==1) {
                   4150:        if(mobilav ==0){
                   4151:          for(i=1; i<=nlstate;i++)
                   4152:            prlim[i][i]=probs[(int)age][i][ij];
                   4153:        }else{ /* mobilav */ 
                   4154:          for(i=1; i<=nlstate;i++)
                   4155:            prlim[i][i]=mobaverage[(int)age][i][ij];
                   4156:        }
                   4157:       }
                   4158: 
1.128     brouard  4159:       for(j=1; j<= nlstate; j++){  /* Sum of wi * eij = e.j */
1.126     brouard  4160:        for(h=0; h<=nhstepm; h++){
                   4161:          for(i=1, gm[h][j]=0.;i<=nlstate;i++)
                   4162:            gm[h][j] += prlim[i][i]*p3mat[i][j][h];
                   4163:        }
                   4164:       }
                   4165:       /* This for computing probability of death (h=1 means
                   4166:          computed over hstepm matrices product = hstepm*stepm months) 
                   4167:          as a weighted average of prlim.
                   4168:       */
                   4169:       for(j=nlstate+1;j<=nlstate+ndeath;j++){
                   4170:        for(i=1,gmp[j]=0.; i<= nlstate; i++)
                   4171:          gmp[j] += prlim[i][i]*p3mat[i][j][1];
                   4172:       }    
                   4173:       /* end probability of death */
                   4174: 
                   4175:       for(j=1; j<= nlstate; j++) /* vareij */
                   4176:        for(h=0; h<=nhstepm; h++){
                   4177:          gradg[h][theta][j]= (gp[h][j]-gm[h][j])/2./delti[theta];
                   4178:        }
                   4179: 
                   4180:       for(j=nlstate+1; j<= nlstate+ndeath; j++){ /* var mu */
                   4181:        gradgp[theta][j]= (gpp[j]-gmp[j])/2./delti[theta];
                   4182:       }
                   4183: 
                   4184:     } /* End theta */
                   4185: 
                   4186:     trgradg =ma3x(0,nhstepm,1,nlstate,1,npar); /* veij */
                   4187: 
                   4188:     for(h=0; h<=nhstepm; h++) /* veij */
                   4189:       for(j=1; j<=nlstate;j++)
                   4190:        for(theta=1; theta <=npar; theta++)
                   4191:          trgradg[h][j][theta]=gradg[h][theta][j];
                   4192: 
                   4193:     for(j=nlstate+1; j<=nlstate+ndeath;j++) /* mu */
                   4194:       for(theta=1; theta <=npar; theta++)
                   4195:        trgradgp[j][theta]=gradgp[theta][j];
                   4196:   
                   4197: 
                   4198:     hf=hstepm*stepm/YEARM;  /* Duration of hstepm expressed in year unit. */
                   4199:     for(i=1;i<=nlstate;i++)
                   4200:       for(j=1;j<=nlstate;j++)
                   4201:        vareij[i][j][(int)age] =0.;
                   4202: 
                   4203:     for(h=0;h<=nhstepm;h++){
                   4204:       for(k=0;k<=nhstepm;k++){
                   4205:        matprod2(dnewm,trgradg[h],1,nlstate,1,npar,1,npar,matcov);
                   4206:        matprod2(doldm,dnewm,1,nlstate,1,npar,1,nlstate,gradg[k]);
                   4207:        for(i=1;i<=nlstate;i++)
                   4208:          for(j=1;j<=nlstate;j++)
                   4209:            vareij[i][j][(int)age] += doldm[i][j]*hf*hf;
                   4210:       }
                   4211:     }
                   4212:   
                   4213:     /* pptj */
                   4214:     matprod2(dnewmp,trgradgp,nlstate+1,nlstate+ndeath,1,npar,1,npar,matcov);
                   4215:     matprod2(doldmp,dnewmp,nlstate+1,nlstate+ndeath,1,npar,nlstate+1,nlstate+ndeath,gradgp);
                   4216:     for(j=nlstate+1;j<=nlstate+ndeath;j++)
                   4217:       for(i=nlstate+1;i<=nlstate+ndeath;i++)
                   4218:        varppt[j][i]=doldmp[j][i];
                   4219:     /* end ppptj */
                   4220:     /*  x centered again */
                   4221:     hpxij(p3mat,nhstepm,age,hstepm,x,nlstate,stepm,oldm,savm, ij);  
1.203     brouard  4222:     prevalim(prlim,nlstate,x,age,oldm,savm,ftolpl,ncvyear,ij);
1.126     brouard  4223:  
                   4224:     if (popbased==1) {
                   4225:       if(mobilav ==0){
                   4226:        for(i=1; i<=nlstate;i++)
                   4227:          prlim[i][i]=probs[(int)age][i][ij];
                   4228:       }else{ /* mobilav */ 
                   4229:        for(i=1; i<=nlstate;i++)
                   4230:          prlim[i][i]=mobaverage[(int)age][i][ij];
                   4231:       }
                   4232:     }
                   4233:              
                   4234:     /* This for computing probability of death (h=1 means
                   4235:        computed over hstepm (estepm) matrices product = hstepm*stepm months) 
                   4236:        as a weighted average of prlim.
                   4237:     */
                   4238:     for(j=nlstate+1;j<=nlstate+ndeath;j++){
                   4239:       for(i=1,gmp[j]=0.;i<= nlstate; i++) 
                   4240:        gmp[j] += prlim[i][i]*p3mat[i][j][1]; 
                   4241:     }    
                   4242:     /* end probability of death */
                   4243: 
                   4244:     fprintf(ficresprobmorprev,"%3d %d ",(int) age, ij);
                   4245:     for(j=nlstate+1; j<=(nlstate+ndeath);j++){
                   4246:       fprintf(ficresprobmorprev," %11.3e %11.3e",gmp[j], sqrt(varppt[j][j]));
                   4247:       for(i=1; i<=nlstate;i++){
                   4248:        fprintf(ficresprobmorprev," %11.3e %11.3e ",prlim[i][i],p3mat[i][j][1]);
                   4249:       }
                   4250:     } 
                   4251:     fprintf(ficresprobmorprev,"\n");
                   4252: 
                   4253:     fprintf(ficresvij,"%.0f ",age );
                   4254:     for(i=1; i<=nlstate;i++)
                   4255:       for(j=1; j<=nlstate;j++){
                   4256:        fprintf(ficresvij," %.4f", vareij[i][j][(int)age]);
                   4257:       }
                   4258:     fprintf(ficresvij,"\n");
                   4259:     free_matrix(gp,0,nhstepm,1,nlstate);
                   4260:     free_matrix(gm,0,nhstepm,1,nlstate);
                   4261:     free_ma3x(gradg,0,nhstepm,1,npar,1,nlstate);
                   4262:     free_ma3x(trgradg,0,nhstepm,1,nlstate,1,npar);
                   4263:     free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   4264:   } /* End age */
                   4265:   free_vector(gpp,nlstate+1,nlstate+ndeath);
                   4266:   free_vector(gmp,nlstate+1,nlstate+ndeath);
                   4267:   free_matrix(gradgp,1,npar,nlstate+1,nlstate+ndeath);
                   4268:   free_matrix(trgradgp,nlstate+1,nlstate+ndeath,1,npar); /* mu or p point j*/
1.199     brouard  4269:   /* fprintf(ficgp,"\nunset parametric;unset label; set ter png small size 320, 240"); */
                   4270:   fprintf(ficgp,"\nunset parametric;unset label; set ter svg size 640, 480");
1.126     brouard  4271:   /* for(j=nlstate+1; j<= nlstate+ndeath; j++){ *//* Only the first actually */
1.131     brouard  4272:   fprintf(ficgp,"\n set log y; unset log x;set xlabel \"Age\"; set ylabel \"Force of mortality (year-1)\";");
1.201     brouard  4273:   fprintf(ficgp,"\nset out \"%s%s.svg\";",subdirf3(optionfilefiname,"VARMUPTJGR-",digitp),digit);
1.126     brouard  4274: /*   fprintf(ficgp,"\n plot \"%s\"  u 1:($3*%6.3f) not w l 1 ",fileresprobmorprev,YEARM/estepm); */
                   4275: /*   fprintf(ficgp,"\n replot \"%s\"  u 1:(($3+1.96*$4)*%6.3f) t \"95\%% interval\" w l 2 ",fileresprobmorprev,YEARM/estepm); */
                   4276: /*   fprintf(ficgp,"\n replot \"%s\"  u 1:(($3-1.96*$4)*%6.3f) not w l 2 ",fileresprobmorprev,YEARM/estepm); */
1.145     brouard  4277:   fprintf(ficgp,"\n plot \"%s\"  u 1:($3) not w l lt 1 ",subdirf(fileresprobmorprev));
1.170     brouard  4278:   fprintf(ficgp,"\n replot \"%s\"  u 1:(($3+1.96*$4)) t \"95%% interval\" w l lt 2 ",subdirf(fileresprobmorprev));
1.145     brouard  4279:   fprintf(ficgp,"\n replot \"%s\"  u 1:(($3-1.96*$4)) not w l lt 2 ",subdirf(fileresprobmorprev));
1.126     brouard  4280:   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  4281:   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  4282:   /*  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  4283: */
1.199     brouard  4284: /*   fprintf(ficgp,"\nset out \"varmuptjgr%s%s%s.svg\";replot;",digitp,optionfilefiname,digit); */
1.201     brouard  4285:   fprintf(ficgp,"\nset out;\nset out \"%s%s.svg\";replot;set out;\n",subdirf3(optionfilefiname,"VARMUPTJGR-",digitp),digit);
1.126     brouard  4286: 
                   4287:   free_vector(xp,1,npar);
                   4288:   free_matrix(doldm,1,nlstate,1,nlstate);
                   4289:   free_matrix(dnewm,1,nlstate,1,npar);
                   4290:   free_matrix(doldmp,nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);
                   4291:   free_matrix(dnewmp,nlstate+1,nlstate+ndeath,1,npar);
                   4292:   free_matrix(varppt,nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);
                   4293:   if (mobilav!=0) free_ma3x(mobaverage,1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
                   4294:   fclose(ficresprobmorprev);
                   4295:   fflush(ficgp);
                   4296:   fflush(fichtm); 
                   4297: }  /* end varevsij */
                   4298: 
                   4299: /************ Variance of prevlim ******************/
1.203     brouard  4300:  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 *ncvyear, int ij, char strstart[])
1.126     brouard  4301: {
1.205     brouard  4302:   /* Variance of prevalence limit  for each state ij using current parameters x[] and estimates of neighbourhood give by delti*/
1.126     brouard  4303:   /*  double **prevalim(double **prlim, int nlstate, double *xp, double age, double **oldm, double **savm,double ftolpl);*/
1.164     brouard  4304: 
1.126     brouard  4305:   double **dnewm,**doldm;
                   4306:   int i, j, nhstepm, hstepm;
                   4307:   double *xp;
                   4308:   double *gp, *gm;
                   4309:   double **gradg, **trgradg;
                   4310:   double age,agelim;
                   4311:   int theta;
                   4312:   
                   4313:   pstamp(ficresvpl);
                   4314:   fprintf(ficresvpl,"# Standard deviation of period (stable) prevalences \n");
                   4315:   fprintf(ficresvpl,"# Age");
                   4316:   for(i=1; i<=nlstate;i++)
                   4317:       fprintf(ficresvpl," %1d-%1d",i,i);
                   4318:   fprintf(ficresvpl,"\n");
                   4319: 
                   4320:   xp=vector(1,npar);
                   4321:   dnewm=matrix(1,nlstate,1,npar);
                   4322:   doldm=matrix(1,nlstate,1,nlstate);
                   4323:   
                   4324:   hstepm=1*YEARM; /* Every year of age */
                   4325:   hstepm=hstepm/stepm; /* Typically in stepm units, if j= 2 years, = 2/6 months = 4 */ 
                   4326:   agelim = AGESUP;
                   4327:   for (age=bage; age<=fage; age ++){ /* If stepm=6 months */
                   4328:     nhstepm=(int) rint((agelim-age)*YEARM/stepm); /* Typically 20 years = 20*12/6=40 */ 
                   4329:     if (stepm >= YEARM) hstepm=1;
                   4330:     nhstepm = nhstepm/hstepm; /* Typically 40/4=10 */
                   4331:     gradg=matrix(1,npar,1,nlstate);
                   4332:     gp=vector(1,nlstate);
                   4333:     gm=vector(1,nlstate);
                   4334: 
                   4335:     for(theta=1; theta <=npar; theta++){
                   4336:       for(i=1; i<=npar; i++){ /* Computes gradient */
                   4337:        xp[i] = x[i] + (i==theta ?delti[theta]:0);
                   4338:       }
1.203     brouard  4339:       prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ncvyear,ij);
1.126     brouard  4340:       for(i=1;i<=nlstate;i++)
                   4341:        gp[i] = prlim[i][i];
                   4342:     
                   4343:       for(i=1; i<=npar; i++) /* Computes gradient */
                   4344:        xp[i] = x[i] - (i==theta ?delti[theta]:0);
1.203     brouard  4345:       prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ncvyear,ij);
1.126     brouard  4346:       for(i=1;i<=nlstate;i++)
                   4347:        gm[i] = prlim[i][i];
                   4348: 
                   4349:       for(i=1;i<=nlstate;i++)
                   4350:        gradg[theta][i]= (gp[i]-gm[i])/2./delti[theta];
                   4351:     } /* End theta */
                   4352: 
                   4353:     trgradg =matrix(1,nlstate,1,npar);
                   4354: 
                   4355:     for(j=1; j<=nlstate;j++)
                   4356:       for(theta=1; theta <=npar; theta++)
                   4357:        trgradg[j][theta]=gradg[theta][j];
                   4358: 
                   4359:     for(i=1;i<=nlstate;i++)
                   4360:       varpl[i][(int)age] =0.;
1.205     brouard  4361:     if((int)age==67 ||(int)age== 66 ){
                   4362:     matprod2(dnewm,trgradg,1,nlstate,1,npar,1,npar,matcov);
                   4363:     matprod2(doldm,dnewm,1,nlstate,1,npar,1,nlstate,gradg);
                   4364:     }else{
1.126     brouard  4365:     matprod2(dnewm,trgradg,1,nlstate,1,npar,1,npar,matcov);
                   4366:     matprod2(doldm,dnewm,1,nlstate,1,npar,1,nlstate,gradg);
1.205     brouard  4367:     }
1.126     brouard  4368:     for(i=1;i<=nlstate;i++)
                   4369:       varpl[i][(int)age] = doldm[i][i]; /* Covariances are useless */
                   4370: 
                   4371:     fprintf(ficresvpl,"%.0f ",age );
                   4372:     for(i=1; i<=nlstate;i++)
                   4373:       fprintf(ficresvpl," %.5f (%.5f)",prlim[i][i],sqrt(varpl[i][(int)age]));
                   4374:     fprintf(ficresvpl,"\n");
                   4375:     free_vector(gp,1,nlstate);
                   4376:     free_vector(gm,1,nlstate);
                   4377:     free_matrix(gradg,1,npar,1,nlstate);
                   4378:     free_matrix(trgradg,1,nlstate,1,npar);
                   4379:   } /* End age */
                   4380: 
                   4381:   free_vector(xp,1,npar);
                   4382:   free_matrix(doldm,1,nlstate,1,npar);
                   4383:   free_matrix(dnewm,1,nlstate,1,nlstate);
                   4384: 
                   4385: }
                   4386: 
                   4387: /************ Variance of one-step probabilities  ******************/
                   4388: 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[])
                   4389: {
1.164     brouard  4390:   int i, j=0,  k1, l1, tj;
1.126     brouard  4391:   int k2, l2, j1,  z1;
1.164     brouard  4392:   int k=0, l;
1.145     brouard  4393:   int first=1, first1, first2;
1.126     brouard  4394:   double cv12, mu1, mu2, lc1, lc2, v12, v21, v11, v22,v1,v2, c12, tnalp;
                   4395:   double **dnewm,**doldm;
                   4396:   double *xp;
                   4397:   double *gp, *gm;
                   4398:   double **gradg, **trgradg;
                   4399:   double **mu;
1.164     brouard  4400:   double age, cov[NCOVMAX+1];
1.126     brouard  4401:   double std=2.0; /* Number of standard deviation wide of confidence ellipsoids */
                   4402:   int theta;
                   4403:   char fileresprob[FILENAMELENGTH];
                   4404:   char fileresprobcov[FILENAMELENGTH];
                   4405:   char fileresprobcor[FILENAMELENGTH];
                   4406:   double ***varpij;
                   4407: 
1.201     brouard  4408:   strcpy(fileresprob,"PROB_"); 
1.126     brouard  4409:   strcat(fileresprob,fileres);
                   4410:   if((ficresprob=fopen(fileresprob,"w"))==NULL) {
                   4411:     printf("Problem with resultfile: %s\n", fileresprob);
                   4412:     fprintf(ficlog,"Problem with resultfile: %s\n", fileresprob);
                   4413:   }
1.201     brouard  4414:   strcpy(fileresprobcov,"PROBCOV_"); 
1.202     brouard  4415:   strcat(fileresprobcov,fileresu);
1.126     brouard  4416:   if((ficresprobcov=fopen(fileresprobcov,"w"))==NULL) {
                   4417:     printf("Problem with resultfile: %s\n", fileresprobcov);
                   4418:     fprintf(ficlog,"Problem with resultfile: %s\n", fileresprobcov);
                   4419:   }
1.201     brouard  4420:   strcpy(fileresprobcor,"PROBCOR_"); 
1.202     brouard  4421:   strcat(fileresprobcor,fileresu);
1.126     brouard  4422:   if((ficresprobcor=fopen(fileresprobcor,"w"))==NULL) {
                   4423:     printf("Problem with resultfile: %s\n", fileresprobcor);
                   4424:     fprintf(ficlog,"Problem with resultfile: %s\n", fileresprobcor);
                   4425:   }
                   4426:   printf("Computing standard deviation of one-step probabilities: result on file '%s' \n",fileresprob);
                   4427:   fprintf(ficlog,"Computing standard deviation of one-step probabilities: result on file '%s' \n",fileresprob);
                   4428:   printf("Computing matrix of variance covariance of one-step probabilities: result on file '%s' \n",fileresprobcov);
                   4429:   fprintf(ficlog,"Computing matrix of variance covariance of one-step probabilities: result on file '%s' \n",fileresprobcov);
                   4430:   printf("and correlation matrix of one-step probabilities: result on file '%s' \n",fileresprobcor);
                   4431:   fprintf(ficlog,"and correlation matrix of one-step probabilities: result on file '%s' \n",fileresprobcor);
                   4432:   pstamp(ficresprob);
                   4433:   fprintf(ficresprob,"#One-step probabilities and stand. devi in ()\n");
                   4434:   fprintf(ficresprob,"# Age");
                   4435:   pstamp(ficresprobcov);
                   4436:   fprintf(ficresprobcov,"#One-step probabilities and covariance matrix\n");
                   4437:   fprintf(ficresprobcov,"# Age");
                   4438:   pstamp(ficresprobcor);
                   4439:   fprintf(ficresprobcor,"#One-step probabilities and correlation matrix\n");
                   4440:   fprintf(ficresprobcor,"# Age");
                   4441: 
                   4442: 
                   4443:   for(i=1; i<=nlstate;i++)
                   4444:     for(j=1; j<=(nlstate+ndeath);j++){
                   4445:       fprintf(ficresprob," p%1d-%1d (SE)",i,j);
                   4446:       fprintf(ficresprobcov," p%1d-%1d ",i,j);
                   4447:       fprintf(ficresprobcor," p%1d-%1d ",i,j);
                   4448:     }  
                   4449:  /* fprintf(ficresprob,"\n");
                   4450:   fprintf(ficresprobcov,"\n");
                   4451:   fprintf(ficresprobcor,"\n");
                   4452:  */
1.131     brouard  4453:   xp=vector(1,npar);
1.126     brouard  4454:   dnewm=matrix(1,(nlstate)*(nlstate+ndeath),1,npar);
                   4455:   doldm=matrix(1,(nlstate)*(nlstate+ndeath),1,(nlstate)*(nlstate+ndeath));
                   4456:   mu=matrix(1,(nlstate)*(nlstate+ndeath), (int) bage, (int)fage);
                   4457:   varpij=ma3x(1,nlstate*(nlstate+ndeath),1,nlstate*(nlstate+ndeath),(int) bage, (int) fage);
                   4458:   first=1;
                   4459:   fprintf(ficgp,"\n# Routine varprob");
                   4460:   fprintf(fichtm,"\n<li><h4> Computing and drawing one step probabilities with their confidence intervals</h4></li>\n");
                   4461:   fprintf(fichtm,"\n");
                   4462: 
1.200     brouard  4463:   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  4464:   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);
                   4465:   fprintf(fichtmcov,"\nEllipsoids of confidence centered on point (p<inf>ij</inf>, p<inf>kl</inf>) are estimated \
1.126     brouard  4466: and drawn. It helps understanding how is the covariance between two incidences.\
                   4467:  They are expressed in year<sup>-1</sup> in order to be less dependent of stepm.<br>\n");
                   4468:   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. \
                   4469: It can be understood this way: if pij and pkl where uncorrelated the (2x2) matrix of covariance \
                   4470: would have been (1/(var pij), 0 , 0, 1/(var pkl)), and the confidence interval would be 2 \
                   4471: standard deviations wide on each axis. <br>\
                   4472:  Now, if both incidences are correlated (usual case) we diagonalised the inverse of the covariance matrix\
                   4473:  and made the appropriate rotation to look at the uncorrelated principal directions.<br>\
                   4474: To be simple, these graphs help to understand the significativity of each parameter in relation to a second other one.<br> \n");
                   4475: 
                   4476:   cov[1]=1;
1.145     brouard  4477:   /* tj=cptcoveff; */
                   4478:   tj = (int) pow(2,cptcoveff);
1.126     brouard  4479:   if (cptcovn<1) {tj=1;ncodemax[1]=1;}
                   4480:   j1=0;
1.145     brouard  4481:   for(j1=1; j1<=tj;j1++){
                   4482:     /*for(i1=1; i1<=ncodemax[t];i1++){ */
                   4483:     /*j1++;*/
1.126     brouard  4484:       if  (cptcovn>0) {
                   4485:        fprintf(ficresprob, "\n#********** Variable "); 
1.198     brouard  4486:        for (z1=1; z1<=cptcoveff; z1++) fprintf(ficresprob, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
1.126     brouard  4487:        fprintf(ficresprob, "**********\n#\n");
                   4488:        fprintf(ficresprobcov, "\n#********** Variable "); 
1.198     brouard  4489:        for (z1=1; z1<=cptcoveff; z1++) fprintf(ficresprobcov, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
1.126     brouard  4490:        fprintf(ficresprobcov, "**********\n#\n");
                   4491:        
                   4492:        fprintf(ficgp, "\n#********** Variable "); 
1.198     brouard  4493:        for (z1=1; z1<=cptcoveff; z1++) fprintf(ficgp, " V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
1.126     brouard  4494:        fprintf(ficgp, "**********\n#\n");
                   4495:        
                   4496:        
                   4497:        fprintf(fichtmcov, "\n<hr  size=\"2\" color=\"#EC5E5E\">********** Variable "); 
1.198     brouard  4498:        for (z1=1; z1<=cptcoveff; z1++) fprintf(fichtm, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
1.126     brouard  4499:        fprintf(fichtmcov, "**********\n<hr size=\"2\" color=\"#EC5E5E\">");
                   4500:        
                   4501:        fprintf(ficresprobcor, "\n#********** Variable ");    
1.198     brouard  4502:        for (z1=1; z1<=cptcoveff; z1++) fprintf(ficresprobcor, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
1.126     brouard  4503:        fprintf(ficresprobcor, "**********\n#");    
                   4504:       }
                   4505:       
1.145     brouard  4506:       gradg=matrix(1,npar,1,(nlstate)*(nlstate+ndeath));
                   4507:       trgradg=matrix(1,(nlstate)*(nlstate+ndeath),1,npar);
                   4508:       gp=vector(1,(nlstate)*(nlstate+ndeath));
                   4509:       gm=vector(1,(nlstate)*(nlstate+ndeath));
1.126     brouard  4510:       for (age=bage; age<=fage; age ++){ 
                   4511:        cov[2]=age;
1.187     brouard  4512:        if(nagesqr==1)
                   4513:          cov[3]= age*age;
1.126     brouard  4514:        for (k=1; k<=cptcovn;k++) {
1.200     brouard  4515:          cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(j1,k)];
                   4516:          /*cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(j1,Tvar[k])];*//* j1 1 2 3 4
1.145     brouard  4517:                                                         * 1  1 1 1 1
                   4518:                                                         * 2  2 1 1 1
                   4519:                                                         * 3  1 2 1 1
                   4520:                                                         */
                   4521:          /* nbcode[1][1]=0 nbcode[1][2]=1;*/
1.126     brouard  4522:        }
1.186     brouard  4523:        /* for (k=1; k<=cptcovage;k++) cov[2+Tage[k]]=cov[2+Tage[k]]*cov[2]; */
1.200     brouard  4524:        for (k=1; k<=cptcovage;k++) cov[2+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(ij,k)]*cov[2];
1.126     brouard  4525:        for (k=1; k<=cptcovprod;k++)
1.200     brouard  4526:          cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,k)]*nbcode[Tvard[k][2]][codtabm(ij,k)];
1.126     brouard  4527:        
                   4528:     
                   4529:        for(theta=1; theta <=npar; theta++){
                   4530:          for(i=1; i<=npar; i++)
                   4531:            xp[i] = x[i] + (i==theta ?delti[theta]:(double)0);
                   4532:          
                   4533:          pmij(pmmij,cov,ncovmodel,xp,nlstate);
                   4534:          
                   4535:          k=0;
                   4536:          for(i=1; i<= (nlstate); i++){
                   4537:            for(j=1; j<=(nlstate+ndeath);j++){
                   4538:              k=k+1;
                   4539:              gp[k]=pmmij[i][j];
                   4540:            }
                   4541:          }
                   4542:          
                   4543:          for(i=1; i<=npar; i++)
                   4544:            xp[i] = x[i] - (i==theta ?delti[theta]:(double)0);
                   4545:     
                   4546:          pmij(pmmij,cov,ncovmodel,xp,nlstate);
                   4547:          k=0;
                   4548:          for(i=1; i<=(nlstate); i++){
                   4549:            for(j=1; j<=(nlstate+ndeath);j++){
                   4550:              k=k+1;
                   4551:              gm[k]=pmmij[i][j];
                   4552:            }
                   4553:          }
                   4554:      
                   4555:          for(i=1; i<= (nlstate)*(nlstate+ndeath); i++) 
                   4556:            gradg[theta][i]=(gp[i]-gm[i])/(double)2./delti[theta];  
                   4557:        }
                   4558: 
                   4559:        for(j=1; j<=(nlstate)*(nlstate+ndeath);j++)
                   4560:          for(theta=1; theta <=npar; theta++)
                   4561:            trgradg[j][theta]=gradg[theta][j];
                   4562:        
                   4563:        matprod2(dnewm,trgradg,1,(nlstate)*(nlstate+ndeath),1,npar,1,npar,matcov); 
                   4564:        matprod2(doldm,dnewm,1,(nlstate)*(nlstate+ndeath),1,npar,1,(nlstate)*(nlstate+ndeath),gradg);
                   4565: 
                   4566:        pmij(pmmij,cov,ncovmodel,x,nlstate);
                   4567:        
                   4568:        k=0;
                   4569:        for(i=1; i<=(nlstate); i++){
                   4570:          for(j=1; j<=(nlstate+ndeath);j++){
                   4571:            k=k+1;
                   4572:            mu[k][(int) age]=pmmij[i][j];
                   4573:          }
                   4574:        }
                   4575:        for(i=1;i<=(nlstate)*(nlstate+ndeath);i++)
                   4576:          for(j=1;j<=(nlstate)*(nlstate+ndeath);j++)
                   4577:            varpij[i][j][(int)age] = doldm[i][j];
                   4578: 
                   4579:        /*printf("\n%d ",(int)age);
                   4580:          for (i=1; i<=(nlstate)*(nlstate+ndeath);i++){
                   4581:          printf("%e [%e ;%e] ",gm[i],gm[i]-2*sqrt(doldm[i][i]),gm[i]+2*sqrt(doldm[i][i]));
                   4582:          fprintf(ficlog,"%e [%e ;%e] ",gm[i],gm[i]-2*sqrt(doldm[i][i]),gm[i]+2*sqrt(doldm[i][i]));
                   4583:          }*/
                   4584: 
                   4585:        fprintf(ficresprob,"\n%d ",(int)age);
                   4586:        fprintf(ficresprobcov,"\n%d ",(int)age);
                   4587:        fprintf(ficresprobcor,"\n%d ",(int)age);
                   4588: 
                   4589:        for (i=1; i<=(nlstate)*(nlstate+ndeath);i++)
                   4590:          fprintf(ficresprob,"%11.3e (%11.3e) ",mu[i][(int) age],sqrt(varpij[i][i][(int)age]));
                   4591:        for (i=1; i<=(nlstate)*(nlstate+ndeath);i++){
                   4592:          fprintf(ficresprobcov,"%11.3e ",mu[i][(int) age]);
                   4593:          fprintf(ficresprobcor,"%11.3e ",mu[i][(int) age]);
                   4594:        }
                   4595:        i=0;
                   4596:        for (k=1; k<=(nlstate);k++){
                   4597:          for (l=1; l<=(nlstate+ndeath);l++){ 
1.145     brouard  4598:            i++;
1.126     brouard  4599:            fprintf(ficresprobcov,"\n%d %d-%d",(int)age,k,l);
                   4600:            fprintf(ficresprobcor,"\n%d %d-%d",(int)age,k,l);
                   4601:            for (j=1; j<=i;j++){
1.145     brouard  4602:              /* printf(" k=%d l=%d i=%d j=%d\n",k,l,i,j);fflush(stdout); */
1.126     brouard  4603:              fprintf(ficresprobcov," %11.3e",varpij[i][j][(int)age]);
                   4604:              fprintf(ficresprobcor," %11.3e",varpij[i][j][(int) age]/sqrt(varpij[i][i][(int) age])/sqrt(varpij[j][j][(int)age]));
                   4605:            }
                   4606:          }
                   4607:        }/* end of loop for state */
                   4608:       } /* end of loop for age */
1.145     brouard  4609:       free_vector(gp,1,(nlstate+ndeath)*(nlstate+ndeath));
                   4610:       free_vector(gm,1,(nlstate+ndeath)*(nlstate+ndeath));
                   4611:       free_matrix(trgradg,1,(nlstate+ndeath)*(nlstate+ndeath),1,npar);
                   4612:       free_matrix(gradg,1,(nlstate+ndeath)*(nlstate+ndeath),1,npar);
                   4613:       
1.126     brouard  4614:       /* Confidence intervalle of pij  */
                   4615:       /*
1.131     brouard  4616:        fprintf(ficgp,"\nunset parametric;unset label");
1.126     brouard  4617:        fprintf(ficgp,"\nset log y;unset log x; set xlabel \"Age\";set ylabel \"probability (year-1)\"");
                   4618:        fprintf(ficgp,"\nset ter png small\nset size 0.65,0.65");
                   4619:        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);
                   4620:        fprintf(fichtm,"\n<br><img src=\"pijgr%s.png\"> ",optionfilefiname);
                   4621:        fprintf(ficgp,"\nset out \"pijgr%s.png\"",optionfilefiname);
                   4622:        fprintf(ficgp,"\nplot \"%s\" every :::%d::%d u 1:2 \"\%%lf",k1,k2,xfilevarprob);
                   4623:       */
                   4624: 
                   4625:       /* Drawing ellipsoids of confidence of two variables p(k1-l1,k2-l2)*/
1.145     brouard  4626:       first1=1;first2=2;
1.126     brouard  4627:       for (k2=1; k2<=(nlstate);k2++){
                   4628:        for (l2=1; l2<=(nlstate+ndeath);l2++){ 
                   4629:          if(l2==k2) continue;
                   4630:          j=(k2-1)*(nlstate+ndeath)+l2;
                   4631:          for (k1=1; k1<=(nlstate);k1++){
                   4632:            for (l1=1; l1<=(nlstate+ndeath);l1++){ 
                   4633:              if(l1==k1) continue;
                   4634:              i=(k1-1)*(nlstate+ndeath)+l1;
                   4635:              if(i<=j) continue;
                   4636:              for (age=bage; age<=fage; age ++){ 
                   4637:                if ((int)age %5==0){
                   4638:                  v1=varpij[i][i][(int)age]/stepm*YEARM/stepm*YEARM;
                   4639:                  v2=varpij[j][j][(int)age]/stepm*YEARM/stepm*YEARM;
                   4640:                  cv12=varpij[i][j][(int)age]/stepm*YEARM/stepm*YEARM;
                   4641:                  mu1=mu[i][(int) age]/stepm*YEARM ;
                   4642:                  mu2=mu[j][(int) age]/stepm*YEARM;
                   4643:                  c12=cv12/sqrt(v1*v2);
                   4644:                  /* Computing eigen value of matrix of covariance */
                   4645:                  lc1=((v1+v2)+sqrt((v1+v2)*(v1+v2) - 4*(v1*v2-cv12*cv12)))/2.;
                   4646:                  lc2=((v1+v2)-sqrt((v1+v2)*(v1+v2) - 4*(v1*v2-cv12*cv12)))/2.;
1.135     brouard  4647:                  if ((lc2 <0) || (lc1 <0) ){
1.145     brouard  4648:                    if(first2==1){
                   4649:                      first1=0;
                   4650:                    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);
                   4651:                    }
                   4652:                    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);
                   4653:                    /* lc1=fabs(lc1); */ /* If we want to have them positive */
                   4654:                    /* lc2=fabs(lc2); */
1.135     brouard  4655:                  }
                   4656: 
1.126     brouard  4657:                  /* Eigen vectors */
                   4658:                  v11=(1./sqrt(1+(v1-lc1)*(v1-lc1)/cv12/cv12));
                   4659:                  /*v21=sqrt(1.-v11*v11); *//* error */
                   4660:                  v21=(lc1-v1)/cv12*v11;
                   4661:                  v12=-v21;
                   4662:                  v22=v11;
                   4663:                  tnalp=v21/v11;
                   4664:                  if(first1==1){
                   4665:                    first1=0;
                   4666:                    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);
                   4667:                  }
                   4668:                  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);
                   4669:                  /*printf(fignu*/
                   4670:                  /* mu1+ v11*lc1*cost + v12*lc2*sin(t) */
                   4671:                  /* mu2+ v21*lc1*cost + v22*lc2*sin(t) */
                   4672:                  if(first==1){
                   4673:                    first=0;
1.200     brouard  4674:                    fprintf(ficgp,"\n# Ellipsoids of confidence\n#\n");
1.126     brouard  4675:                    fprintf(ficgp,"\nset parametric;unset label");
                   4676:                    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  4677:                    fprintf(ficgp,"\nset ter svg size 640, 480");
1.126     brouard  4678:                    fprintf(fichtmcov,"\n<br>Ellipsoids of confidence cov(p%1d%1d,p%1d%1d) expressed in year<sup>-1</sup>\
1.201     brouard  4679:  :<a href=\"%s_%d%1d%1d-%1d%1d.svg\">\
                   4680: %s_%d%1d%1d-%1d%1d.svg</A>, ",k1,l1,k2,l2,\
                   4681:                            subdirf2(optionfilefiname,"VARPIJGR_"), j1,k1,l1,k2,l2,\
                   4682:                            subdirf2(optionfilefiname,"VARPIJGR_"), j1,k1,l1,k2,l2);
                   4683:                    fprintf(fichtmcov,"\n<br><img src=\"%s_%d%1d%1d-%1d%1d.svg\"> ",subdirf2(optionfilefiname,"VARPIJGR_"), j1,k1,l1,k2,l2);
1.126     brouard  4684:                    fprintf(fichtmcov,"\n<br> Correlation at age %d (%.3f),",(int) age, c12);
1.201     brouard  4685:                    fprintf(ficgp,"\nset out \"%s_%d%1d%1d-%1d%1d.svg\"",subdirf2(optionfilefiname,"VARPIJGR_"), j1,k1,l1,k2,l2);
1.126     brouard  4686:                    fprintf(ficgp,"\nset label \"%d\" at %11.3e,%11.3e center",(int) age, mu1,mu2);
                   4687:                    fprintf(ficgp,"\n# Age %d, p%1d%1d - p%1d%1d",(int) age, k1,l1,k2,l2);
                   4688:                    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",\
                   4689:                            mu1,std,v11,sqrt(lc1),v12,sqrt(lc2),\
                   4690:                            mu2,std,v21,sqrt(lc1),v22,sqrt(lc2));
                   4691:                  }else{
                   4692:                    first=0;
                   4693:                    fprintf(fichtmcov," %d (%.3f),",(int) age, c12);
                   4694:                    fprintf(ficgp,"\n# Age %d, p%1d%1d - p%1d%1d",(int) age, k1,l1,k2,l2);
                   4695:                    fprintf(ficgp,"\nset label \"%d\" at %11.3e,%11.3e center",(int) age, mu1,mu2);
                   4696:                    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",\
                   4697:                            mu1,std,v11,sqrt(lc1),v12,sqrt(lc2),\
                   4698:                            mu2,std,v21,sqrt(lc1),v22,sqrt(lc2));
                   4699:                  }/* if first */
                   4700:                } /* age mod 5 */
                   4701:              } /* end loop age */
1.201     brouard  4702:              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  4703:              first=1;
                   4704:            } /*l12 */
                   4705:          } /* k12 */
                   4706:        } /*l1 */
                   4707:       }/* k1 */
1.169     brouard  4708:       /* } */ /* loop covariates */
1.126     brouard  4709:   }
                   4710:   free_ma3x(varpij,1,nlstate,1,nlstate+ndeath,(int) bage, (int)fage);
                   4711:   free_matrix(mu,1,(nlstate+ndeath)*(nlstate+ndeath),(int) bage, (int)fage);
                   4712:   free_matrix(doldm,1,(nlstate)*(nlstate+ndeath),1,(nlstate)*(nlstate+ndeath));
                   4713:   free_matrix(dnewm,1,(nlstate)*(nlstate+ndeath),1,npar);
                   4714:   free_vector(xp,1,npar);
                   4715:   fclose(ficresprob);
                   4716:   fclose(ficresprobcov);
                   4717:   fclose(ficresprobcor);
                   4718:   fflush(ficgp);
                   4719:   fflush(fichtmcov);
                   4720: }
                   4721: 
                   4722: 
                   4723: /******************* Printing html file ***********/
1.201     brouard  4724: void printinghtml(char fileresu[], char title[], char datafile[], int firstpass, \
1.126     brouard  4725:                  int lastpass, int stepm, int weightopt, char model[],\
                   4726:                  int imx,int jmin, int jmax, double jmeanint,char rfileres[],\
                   4727:                  int popforecast, int estepm ,\
                   4728:                  double jprev1, double mprev1,double anprev1, \
                   4729:                  double jprev2, double mprev2,double anprev2){
                   4730:   int jj1, k1, i1, cpt;
                   4731: 
                   4732:    fprintf(fichtm,"<ul><li><a href='#firstorder'>Result files (first order: no variance)</a>\n \
                   4733:    <li><a href='#secondorder'>Result files (second order (variance)</a>\n \
                   4734: </ul>");
                   4735:    fprintf(fichtm,"<ul><li><h4><a name='firstorder'>Result files (first order: no variance)</a></h4>\n \
                   4736:  - Observed prevalence in each state (during the period defined between %.lf/%.lf/%.lf and %.lf/%.lf/%.lf): <a href=\"%s\">%s</a> <br>\n ",
1.201     brouard  4737:           jprev1, mprev1,anprev1,jprev2, mprev2,anprev2,subdirf2(fileresu,"P_"),subdirf2(fileresu,"P_"));
1.126     brouard  4738:    fprintf(fichtm,"\
                   4739:  - Estimated transition probabilities over %d (stepm) months: <a href=\"%s\">%s</a><br>\n ",
1.201     brouard  4740:           stepm,subdirf2(fileresu,"PIJ_"),subdirf2(fileresu,"PIJ_"));
1.126     brouard  4741:    fprintf(fichtm,"\
                   4742:  - Period (stable) prevalence in each health state: <a href=\"%s\">%s</a> <br>\n",
1.201     brouard  4743:           subdirf2(fileresu,"PL_"),subdirf2(fileresu,"PL_"));
1.126     brouard  4744:    fprintf(fichtm,"\
1.128     brouard  4745:  - (a) Life expectancies by health status at initial age, ei. (b) health expectancies by health status at initial age, eij . 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  4746:    <a href=\"%s\">%s</a> <br>\n",
1.201     brouard  4747:           estepm,subdirf2(fileresu,"E_"),subdirf2(fileresu,"E_"));
1.126     brouard  4748:    fprintf(fichtm,"\
                   4749:  - Population projections by age and states: \
1.201     brouard  4750:    <a href=\"%s\">%s</a> <br>\n</li>", subdirf2(fileresu,"F_"),subdirf2(fileresu,"F_"));
1.126     brouard  4751: 
                   4752: fprintf(fichtm," \n<ul><li><b>Graphs</b></li><p>");
                   4753: 
1.145     brouard  4754:  m=pow(2,cptcoveff);
1.126     brouard  4755:  if (cptcovn < 1) {m=1;ncodemax[1]=1;}
                   4756: 
                   4757:  jj1=0;
                   4758:  for(k1=1; k1<=m;k1++){
1.192     brouard  4759:    /* for(i1=1; i1<=ncodemax[k1];i1++){ */
1.126     brouard  4760:      jj1++;
                   4761:      if (cptcovn > 0) {
                   4762:        fprintf(fichtm,"<hr  size=\"2\" color=\"#EC5E5E\">************ Results for covariates");
1.192     brouard  4763:        for (cpt=1; cpt<=cptcoveff;cpt++){ 
1.198     brouard  4764:         fprintf(fichtm," V%d=%d ",Tvaraff[cpt],nbcode[Tvaraff[cpt]][codtabm(jj1,cpt)]);
                   4765:         printf(" V%d=%d ",Tvaraff[cpt],nbcode[Tvaraff[cpt]][codtabm(jj1,cpt)]);fflush(stdout);
1.192     brouard  4766:        }
1.126     brouard  4767:        fprintf(fichtm," ************\n<hr size=\"2\" color=\"#EC5E5E\">");
                   4768:      }
1.201     brouard  4769:      /* aij, bij */
                   4770:      fprintf(fichtm,"<br>- Logit model, 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> \
                   4771: <img src=\"%s_%d-1.svg\">",subdirf2(optionfilefiname,"PE_"),jj1,subdirf2(optionfilefiname,"PE_"),jj1,subdirf2(optionfilefiname,"PE_"),jj1);
1.126     brouard  4772:      /* Pij */
1.202     brouard  4773:      fprintf(fichtm,"<br>\n- Pij 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  4774: <img src=\"%s_%d-2.svg\">",stepm,subdirf2(optionfilefiname,"PE_"),jj1,subdirf2(optionfilefiname,"PE_"),jj1,subdirf2(optionfilefiname,"PE_"),jj1);     
1.126     brouard  4775:      /* Quasi-incidences */
1.201     brouard  4776:      fprintf(fichtm,"<br>\n- Iij or Conditional probabilities to be observed in state j being in state i %d (stepm) months\
                   4777:  before but expressed in per year i.e. quasi incidences if stepm is small and probabilities too,\
                   4778:  incidence (rates) are the limit when h tends to zero of the ratio of the probability hPij \
                   4779: divided by h: hPij/h : <a href=\"%s_%d-3.svg\">%s_%d-3.svg</a><br> \
                   4780: <img src=\"%s_%d-3.svg\">",stepm,subdirf2(optionfilefiname,"PE_"),jj1,subdirf2(optionfilefiname,"PE_"),jj1,subdirf2(optionfilefiname,"PE_"),jj1); 
                   4781:      /* Survival functions (period) in state j */
                   4782:      for(cpt=1; cpt<=nlstate;cpt++){
                   4783:        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> \
                   4784: <img src=\"%s_%d-%d.svg\">", cpt, cpt, nlstate, subdirf2(optionfilefiname,"LIJ_"),cpt,jj1,subdirf2(optionfilefiname,"LIJ_"),cpt,jj1,subdirf2(optionfilefiname,"LIJ_"),cpt,jj1);
                   4785:      }
                   4786:      /* State specific survival functions (period) */
                   4787:      for(cpt=1; cpt<=nlstate;cpt++){
                   4788:        fprintf(fichtm,"<br>\n- Survival functions from state %d in any different live states and total.\
                   4789:  Or probability to survive in various states (1 to %d) being in state %d at different ages.\
                   4790:  <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);
                   4791:      }
                   4792:      /* Period (stable) prevalence in each health state */
                   4793:      for(cpt=1; cpt<=nlstate;cpt++){
                   4794:        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> \
                   4795: <img src=\"%s_%d-%d.svg\">", cpt, cpt, nlstate, subdirf2(optionfilefiname,"P_"),cpt,jj1,subdirf2(optionfilefiname,"P_"),cpt,jj1,subdirf2(optionfilefiname,"P_"),cpt,jj1);
                   4796:      }
1.126     brouard  4797:      for(cpt=1; cpt<=nlstate;cpt++) {
1.205     brouard  4798:        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  4799: <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  4800:      }
1.192     brouard  4801:    /* } /\* end i1 *\/ */
1.126     brouard  4802:  }/* End k1 */
                   4803:  fprintf(fichtm,"</ul>");
                   4804: 
                   4805:  fprintf(fichtm,"\
                   4806: \n<br><li><h4> <a name='secondorder'>Result files (second order: variances)</a></h4>\n\
1.193     brouard  4807:  - Parameter file with estimated parameters and covariance matrix: <a href=\"%s\">%s</a> <br> \
1.203     brouard  4808:  - 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  4809: But because parameters are usually highly correlated (a higher incidence of disability \
                   4810: and a higher incidence of recovery can give very close observed transition) it might \
                   4811: be very useful to look not only at linear confidence intervals estimated from the \
                   4812: variances but at the covariance matrix. And instead of looking at the estimated coefficients \
                   4813: (parameters) of the logistic regression, it might be more meaningful to visualize the \
                   4814: covariance matrix of the one-step probabilities. \
                   4815: See page 'Matrix of variance-covariance of one-step probabilities' below. \n", rfileres,rfileres);
1.126     brouard  4816: 
1.193     brouard  4817:  fprintf(fichtm," - Standard deviation of one-step probabilities: <a href=\"%s\">%s</a> <br>\n",
1.201     brouard  4818:         subdirf2(fileresu,"PROB_"),subdirf2(fileresu,"PROB_"));
1.126     brouard  4819:  fprintf(fichtm,"\
                   4820:  - Variance-covariance of one-step probabilities: <a href=\"%s\">%s</a> <br>\n",
1.201     brouard  4821:         subdirf2(fileresu,"PROBCOV_"),subdirf2(fileresu,"PROBCOV_"));
1.126     brouard  4822: 
                   4823:  fprintf(fichtm,"\
                   4824:  - Correlation matrix of one-step probabilities: <a href=\"%s\">%s</a> <br>\n",
1.201     brouard  4825:         subdirf2(fileresu,"PROBCOR_"),subdirf2(fileresu,"PROBCOR_"));
1.126     brouard  4826:  fprintf(fichtm,"\
                   4827:  - 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): \
                   4828:    <a href=\"%s\">%s</a> <br>\n</li>",
1.201     brouard  4829:           estepm,subdirf2(fileresu,"CVE_"),subdirf2(fileresu,"CVE_"));
1.126     brouard  4830:  fprintf(fichtm,"\
                   4831:  - (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): \
                   4832:    <a href=\"%s\">%s</a> <br>\n</li>",
1.201     brouard  4833:           estepm,subdirf2(fileresu,"STDE_"),subdirf2(fileresu,"STDE_"));
1.126     brouard  4834:  fprintf(fichtm,"\
1.128     brouard  4835:  - 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  4836:         estepm, subdirf2(fileresu,"V_"),subdirf2(fileresu,"V_"));
1.126     brouard  4837:  fprintf(fichtm,"\
1.128     brouard  4838:  - 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  4839:         estepm, subdirf2(fileresu,"T_"),subdirf2(fileresu,"T_"));
1.126     brouard  4840:  fprintf(fichtm,"\
                   4841:  - Standard deviation of period (stable) prevalences: <a href=\"%s\">%s</a> <br>\n",\
1.201     brouard  4842:         subdirf2(fileresu,"VPL_"),subdirf2(fileresu,"VPL_"));
1.126     brouard  4843: 
                   4844: /*  if(popforecast==1) fprintf(fichtm,"\n */
                   4845: /*  - Prevalences forecasting: <a href=\"f%s\">f%s</a> <br>\n */
                   4846: /*  - Population forecasting (if popforecast=1): <a href=\"pop%s\">pop%s</a> <br>\n */
                   4847: /*     <br>",fileres,fileres,fileres,fileres); */
                   4848: /*  else  */
                   4849: /*    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); */
                   4850:  fflush(fichtm);
                   4851:  fprintf(fichtm," <ul><li><b>Graphs</b></li><p>");
                   4852: 
1.145     brouard  4853:  m=pow(2,cptcoveff);
1.126     brouard  4854:  if (cptcovn < 1) {m=1;ncodemax[1]=1;}
                   4855: 
                   4856:  jj1=0;
                   4857:  for(k1=1; k1<=m;k1++){
1.192     brouard  4858:    /* for(i1=1; i1<=ncodemax[k1];i1++){ */
1.126     brouard  4859:      jj1++;
                   4860:      if (cptcovn > 0) {
                   4861:        fprintf(fichtm,"<hr  size=\"2\" color=\"#EC5E5E\">************ Results for covariates");
                   4862:        for (cpt=1; cpt<=cptcoveff;cpt++) 
1.198     brouard  4863:         fprintf(fichtm," V%d=%d ",Tvaraff[cpt],nbcode[Tvaraff[cpt]][codtabm(jj1,cpt)]);
1.126     brouard  4864:        fprintf(fichtm," ************\n<hr size=\"2\" color=\"#EC5E5E\">");
                   4865:      }
                   4866:      for(cpt=1; cpt<=nlstate;cpt++) {
                   4867:        fprintf(fichtm,"<br>- Observed (cross-sectional) and period (incidence based) \
1.205     brouard  4868: prevalence (with 95%% confidence interval) in state (%d): <a href=\"%s_%d%d.svg\"> %s_%d-%d.svg <br>\
                   4869: <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  4870:      }
                   4871:      fprintf(fichtm,"\n<br>- Total life expectancy by age and \
1.128     brouard  4872: health expectancies in states (1) and (2). If popbased=1 the smooth (due to the model) \
                   4873: true period expectancies (those weighted with period prevalences are also\
                   4874:  drawn in addition to the population based expectancies computed using\
1.205     brouard  4875:  observed and cahotic prevalences:  <a href=\"%s_%d.svg\">%s_%d.svg<br>\
                   4876: <img src=\"%s_%d.svg\">",subdirf2(optionfilefiname,"E_"),jj1,subdirf2(optionfilefiname,"E_"),jj1,subdirf2(optionfilefiname,"E_"),jj1);
1.192     brouard  4877:    /* } /\* end i1 *\/ */
1.126     brouard  4878:  }/* End k1 */
                   4879:  fprintf(fichtm,"</ul>");
                   4880:  fflush(fichtm);
                   4881: }
                   4882: 
                   4883: /******************* Gnuplot file **************/
1.201     brouard  4884: void printinggnuplot(char fileresu[], char optionfilefiname[], double ageminpar, double agemaxpar, double fage , char pathc[], double p[]){
1.126     brouard  4885: 
                   4886:   char dirfileres[132],optfileres[132];
1.164     brouard  4887:   int cpt=0,k1=0,i=0,k=0,j=0,jk=0,k2=0,k3=0,ij=0,l=0;
1.130     brouard  4888:   int ng=0;
1.201     brouard  4889:   int vpopbased;
1.126     brouard  4890: /*   if((ficgp=fopen(optionfilegnuplot,"a"))==NULL) { */
                   4891: /*     printf("Problem with file %s",optionfilegnuplot); */
                   4892: /*     fprintf(ficlog,"Problem with file %s",optionfilegnuplot); */
                   4893: /*   } */
                   4894: 
                   4895:   /*#ifdef windows */
                   4896:   fprintf(ficgp,"cd \"%s\" \n",pathc);
                   4897:     /*#endif */
                   4898:   m=pow(2,cptcoveff);
                   4899: 
1.202     brouard  4900:   /* Contribution to likelihood */
                   4901:   /* Plot the probability implied in the likelihood */
                   4902:     fprintf(ficgp,"\n# Contributions to the Likelihood, mle >=1. For mle=4 no interpolation, pure matrix products.\n#\n");
                   4903:     fprintf(ficgp,"\n set log y; unset log x;set xlabel \"Age\"; set ylabel \"Likelihood (-2Log(L))\";");
                   4904:     /* fprintf(ficgp,"\nset ter svg size 640, 480"); */ /* Too big for svg */
1.205     brouard  4905:     fprintf(ficgp,"\nset ter pngcairo size 640, 480");
1.204     brouard  4906: /* nice for mle=4 plot by number of matrix products.
1.202     brouard  4907:    replot  "rrtest1/toto.txt" u 2:($4 == 1 && $5==2 ? $9 : 1/0):5 t "p12" with point lc 1 */
                   4908: /* replot exp(p1+p2*x)/(1+exp(p1+p2*x)+exp(p3+p4*x)+exp(p5+p6*x)) t "p12(x)"  */
                   4909:     /* fprintf(ficgp,"\nset out \"%s.svg\";",subdirf2(optionfilefiname,"ILK_")); */
1.204     brouard  4910:     fprintf(ficgp,"\nset out \"%s-dest.png\";",subdirf2(optionfilefiname,"ILK_"));
1.205     brouard  4911:     fprintf(ficgp,"\nset log y;plot  \"%s\" u 2:(-$12):5 t \"All sample, transitions colored by destination\" with dots lc variable; set out;\n",subdirf(fileresilk));
1.204     brouard  4912:     fprintf(ficgp,"\nset out \"%s-ori.png\";",subdirf2(optionfilefiname,"ILK_"));
1.205     brouard  4913:     fprintf(ficgp,"\nset log y;plot  \"%s\" u 2:(-$12):4 t \"All sample, transitions colored by origin\" with dots lc variable; set out;\n\n",subdirf(fileresilk));
1.204     brouard  4914:     for (i=1; i<= nlstate ; i ++) {
                   4915:       fprintf(ficgp,"\nset out \"%s-p%dj.png\";set ylabel \"Probability for each individual/wave\";",subdirf2(optionfilefiname,"ILK_"),i);
1.205     brouard  4916:       fprintf(ficgp,"unset log;\n# plot weighted, mean weight should have point size of 0.5\n plot  \"%s\"",subdirf(fileresilk));
                   4917:       fprintf(ficgp,"  u  2:($4 == %d && $5==%d ? $9 : 1/0):($11/4.):5 t \"p%d%d\" with points pointtype 7 ps variable lc variable \\\n",i,1,i,1);
1.204     brouard  4918:       for (j=2; j<= nlstate+ndeath ; j ++) {
1.205     brouard  4919:        fprintf(ficgp,",\\\n \"\" u  2:($4 == %d && $5==%d ? $9 : 1/0):($11/4.):5 t \"p%d%d\" with points pointtype 7 ps variable lc variable ",i,j,i,j);
1.204     brouard  4920:       }
                   4921:       fprintf(ficgp,";\nset out; unset ylabel;\n"); 
                   4922:     }
                   4923:     /* 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 */             
                   4924:     /* fprintf(ficgp,"\nset log y;plot  \"%s\" u 2:(-$11):3 t \"All sample, all transitions\" with dots lc variable",subdirf(fileresilk)); */
                   4925:     /* 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  4926:     fprintf(ficgp,"\nset out;unset log\n");
1.202     brouard  4927:     /* fprintf(ficgp,"\nset out \"%s.svg\"; replot; set out; # bug gnuplot",subdirf2(optionfilefiname,"ILK_")); */
                   4928: 
1.126     brouard  4929:   strcpy(dirfileres,optionfilefiname);
                   4930:   strcpy(optfileres,"vpl");
                   4931:  /* 1eme*/
1.201     brouard  4932:   fprintf(ficgp,"\n# 1st: Period (stable) prevalence with CI: 'VPL_' files\n");
1.126     brouard  4933:   for (cpt=1; cpt<= nlstate ; cpt ++) {
1.145     brouard  4934:     for (k1=1; k1<= m ; k1 ++) { /* plot [100000000000000000000:-100000000000000000000] "mysbiaspar/vplrmysbiaspar.txt to check */
1.201     brouard  4935:      fprintf(ficgp,"\nset out \"%s_%d-%d.svg\" \n",subdirf2(optionfilefiname,"V_"),cpt,k1);
                   4936:      fprintf(ficgp,"\n#set out \"V_%s_%d-%d.svg\" \n",optionfilefiname,cpt,k1);
1.126     brouard  4937:      fprintf(ficgp,"set xlabel \"Age\" \n\
                   4938: set ylabel \"Probability\" \n\
1.199     brouard  4939: set ter svg size 640, 480\n\
1.201     brouard  4940: plot [%.f:%.f] \"%s\" every :::%d::%d u 1:2 \"%%lf",ageminpar,fage,subdirf2(fileresu,"VPL_"),k1-1,k1-1);
1.126     brouard  4941: 
                   4942:      for (i=1; i<= nlstate ; i ++) {
1.170     brouard  4943:        if (i==cpt) fprintf(ficgp," %%lf (%%lf)");
                   4944:        else        fprintf(ficgp," %%*lf (%%*lf)");
1.126     brouard  4945:      }
1.201     brouard  4946:      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  4947:      for (i=1; i<= nlstate ; i ++) {
1.170     brouard  4948:        if (i==cpt) fprintf(ficgp," %%lf (%%lf)");
                   4949:        else fprintf(ficgp," %%*lf (%%*lf)");
1.126     brouard  4950:      } 
1.201     brouard  4951:      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  4952:      for (i=1; i<= nlstate ; i ++) {
1.170     brouard  4953:        if (i==cpt) fprintf(ficgp," %%lf (%%lf)");
                   4954:        else fprintf(ficgp," %%*lf (%%*lf)");
1.126     brouard  4955:      }  
1.201     brouard  4956:      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));
                   4957:      fprintf(ficgp,"\nset out \n");
                   4958:     } /* k1 */
                   4959:   } /* cpt */
1.126     brouard  4960:   /*2 eme*/
1.153     brouard  4961:   fprintf(ficgp,"\n# 2nd: Total life expectancy with CI: 't' files\n");
1.126     brouard  4962:   for (k1=1; k1<= m ; k1 ++) { 
1.201     brouard  4963:     fprintf(ficgp,"\nset out \"%s_%d.svg\" \n",subdirf2(optionfilefiname,"E_"),k1);
                   4964:     for(vpopbased=0; vpopbased <= popbased; vpopbased++){ /* Done for vpopbased=0 and vpopbased=1 if popbased==1*/
                   4965:       if(vpopbased==0)
                   4966:        fprintf(ficgp,"set ylabel \"Years\" \nset ter svg size 640, 480\nplot [%.f:%.f] ",ageminpar,fage);
                   4967:       else
                   4968:        fprintf(ficgp,"\nreplot ");
                   4969:       for (i=1; i<= nlstate+1 ; i ++) {
                   4970:        k=2*i;
                   4971:        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);
                   4972:        for (j=1; j<= nlstate+1 ; j ++) {
                   4973:          if (j==i) fprintf(ficgp," %%lf (%%lf)");
                   4974:          else fprintf(ficgp," %%*lf (%%*lf)");
                   4975:        }   
                   4976:        if (i== 1) fprintf(ficgp,"\" t\"TLE\" w l lt %d, \\\n",i);
                   4977:        else fprintf(ficgp,"\" t\"LE in state (%d)\" w l lt %d, \\\n",i-1,i+1);
                   4978:        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);
                   4979:        for (j=1; j<= nlstate+1 ; j ++) {
                   4980:          if (j==i) fprintf(ficgp," %%lf (%%lf)");
                   4981:          else fprintf(ficgp," %%*lf (%%*lf)");
                   4982:        }   
                   4983:        fprintf(ficgp,"\" t\"\" w l lt 0,");
                   4984:        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);
                   4985:        for (j=1; j<= nlstate+1 ; j ++) {
                   4986:          if (j==i) fprintf(ficgp," %%lf (%%lf)");
                   4987:          else fprintf(ficgp," %%*lf (%%*lf)");
                   4988:        }   
                   4989:        if (i== (nlstate+1)) fprintf(ficgp,"\" t\"\" w l lt 0");
                   4990:        else fprintf(ficgp,"\" t\"\" w l lt 0,\\\n");
                   4991:       } /* state */
                   4992:     } /* vpopbased */
                   4993:     fprintf(ficgp,"\nset out;set out \"%s_%d.svg\"; replot; set out; \n",subdirf2(optionfilefiname,"E_"),k1); /* Buggy gnuplot */
                   4994:   } /* k1 */
1.126     brouard  4995:   /*3eme*/
                   4996:   
                   4997:   for (k1=1; k1<= m ; k1 ++) { 
                   4998:     for (cpt=1; cpt<= nlstate ; cpt ++) {
                   4999:       /*       k=2+nlstate*(2*cpt-2); */
                   5000:       k=2+(nlstate+1)*(cpt-1);
1.201     brouard  5001:       fprintf(ficgp,"\nset out \"%s_%d%d.svg\" \n",subdirf2(optionfilefiname,"EXP_"),cpt,k1);
1.199     brouard  5002:       fprintf(ficgp,"set ter svg size 640, 480\n\
1.201     brouard  5003: 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  5004:       /*fprintf(ficgp,",\"e%s\" every :::%d::%d u 1:($%d-2*$%d) \"\%%lf ",fileres,k1-1,k1-1,k,k+1);
                   5005:        for (i=1; i<= nlstate*2 ; i ++) fprintf(ficgp,"\%%lf (\%%lf) ");
                   5006:        fprintf(ficgp,"\" t \"e%d1\" w l",cpt);
                   5007:        fprintf(ficgp,",\"e%s\" every :::%d::%d u 1:($%d+2*$%d) \"\%%lf ",fileres,k1-1,k1-1,k,k+1);
                   5008:        for (i=1; i<= nlstate*2 ; i ++) fprintf(ficgp,"\%%lf (\%%lf) ");
                   5009:        fprintf(ficgp,"\" t \"e%d1\" w l",cpt);
                   5010:        
                   5011:       */
                   5012:       for (i=1; i< nlstate ; i ++) {
1.201     brouard  5013:        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  5014:        /*      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);*/
                   5015:        
                   5016:       } 
1.201     brouard  5017:       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  5018:     }
                   5019:   }
                   5020:   
1.201     brouard  5021:   /* Survival functions (period) from state i in state j by initial state i */
                   5022:   for (k1=1; k1<= m ; k1 ++) { /* For each multivariate if any */
                   5023:     for (cpt=1; cpt<=nlstate ; cpt ++) { /* For each life state */
                   5024:       k=3;
                   5025:       fprintf(ficgp,"\n#\n#\n# Survival functions in state j : 'lij' files, cov=%d state=%d",k1, cpt);
                   5026:       fprintf(ficgp,"\nset out \"%s_%d-%d.svg\" \n",subdirf2(optionfilefiname,"LIJ_"),cpt,k1);
                   5027:       fprintf(ficgp,"set xlabel \"Age\" \nset ylabel \"Probability to be alive\" \n\
                   5028: set ter svg size 640, 480\n\
                   5029: unset log y\n\
                   5030: plot [%.f:%.f]  ", ageminpar, agemaxpar);
                   5031:       for (i=1; i<= nlstate ; i ++){
                   5032:        if(i==1)
                   5033:          fprintf(ficgp,"\"%s\"",subdirf2(fileresu,"PIJ_"));
                   5034:        else
                   5035:          fprintf(ficgp,", '' ");
                   5036:        l=(nlstate+ndeath)*(i-1)+1;
                   5037:        fprintf(ficgp," u ($1==%d ? ($3):1/0):($%d/($%d",k1,k+l+(cpt-1),k+l);
                   5038:        for (j=2; j<= nlstate+ndeath ; j ++)
                   5039:          fprintf(ficgp,"+$%d",k+l+j-1);
                   5040:        fprintf(ficgp,")) t \"l(%d,%d)\" w l",i,cpt);
                   5041:       } /* nlstate */
                   5042:       fprintf(ficgp,"\nset out\n");
                   5043:     } /* end cpt state*/ 
                   5044:   } /* end covariate */  
                   5045: 
                   5046:   /* Survival functions (period) from state i in state j by final state j */
1.202     brouard  5047:   for (k1=1; k1<= m ; k1 ++) { /* For each covariate if any */
1.201     brouard  5048:     for (cpt=1; cpt<=nlstate ; cpt ++) { /* For each inital state  */
                   5049:       k=3;
                   5050:       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);
                   5051:       fprintf(ficgp,"\nset out \"%s_%d-%d.svg\" \n",subdirf2(optionfilefiname,"LIJT_"),cpt,k1);
                   5052:       fprintf(ficgp,"set xlabel \"Age\" \nset ylabel \"Probability to be alive\" \n\
                   5053: set ter svg size 640, 480\n\
                   5054: unset log y\n\
                   5055: plot [%.f:%.f]  ", ageminpar, agemaxpar);
                   5056:       for (j=1; j<= nlstate ; j ++){ /* Lived in state j */
                   5057:        if(j==1)
                   5058:          fprintf(ficgp,"\"%s\"",subdirf2(fileresu,"PIJ_"));
                   5059:        else
                   5060:          fprintf(ficgp,", '' ");
                   5061:        l=(nlstate+ndeath)*(cpt-1) +j;
                   5062:        fprintf(ficgp," u (($1==%d && (floor($2)%%5 == 0)) ? ($3):1/0):($%d",k1,k+l);
                   5063:        /* for (i=2; i<= nlstate+ndeath ; i ++) */
                   5064:        /*   fprintf(ficgp,"+$%d",k+l+i-1); */
                   5065:        fprintf(ficgp,") t \"l(%d,%d)\" w l",cpt,j);
                   5066:       } /* nlstate */
                   5067:       fprintf(ficgp,", '' ");
                   5068:       fprintf(ficgp," u (($1==%d && (floor($2)%%5 == 0)) ? ($3):1/0):(",k1);
                   5069:       for (j=1; j<= nlstate ; j ++){ /* Lived in state j */
                   5070:        l=(nlstate+ndeath)*(cpt-1) +j;
                   5071:        if(j < nlstate)
                   5072:          fprintf(ficgp,"$%d +",k+l);
                   5073:        else
                   5074:          fprintf(ficgp,"$%d) t\"l(%d,.)\" w l",k+l,cpt);
                   5075:       }
                   5076:       fprintf(ficgp,"\nset out\n");
                   5077:     } /* end cpt state*/ 
                   5078:   } /* end covariate */  
                   5079: 
1.202     brouard  5080:   /* CV preval stable (period) for each covariate */
                   5081:   for (k1=1; k1<= m ; k1 ++) { /* For each covariate if any */
1.153     brouard  5082:     for (cpt=1; cpt<=nlstate ; cpt ++) { /* For each life state */
1.126     brouard  5083:       k=3;
1.153     brouard  5084:       fprintf(ficgp,"\n#\n#\n#CV preval stable (period): 'pij' files, cov=%d state=%d",k1, cpt);
1.201     brouard  5085:       fprintf(ficgp,"\nset out \"%s_%d-%d.svg\" \n",subdirf2(optionfilefiname,"P_"),cpt,k1);
1.126     brouard  5086:       fprintf(ficgp,"set xlabel \"Age\" \nset ylabel \"Probability\" \n\
1.199     brouard  5087: set ter svg size 640, 480\n\
1.126     brouard  5088: unset log y\n\
1.153     brouard  5089: plot [%.f:%.f]  ", ageminpar, agemaxpar);
                   5090:       for (i=1; i<= nlstate ; i ++){
                   5091:        if(i==1)
1.201     brouard  5092:          fprintf(ficgp,"\"%s\"",subdirf2(fileresu,"PIJ_"));
1.153     brouard  5093:        else
                   5094:          fprintf(ficgp,", '' ");
1.154     brouard  5095:        l=(nlstate+ndeath)*(i-1)+1;
                   5096:        fprintf(ficgp," u ($1==%d ? ($3):1/0):($%d/($%d",k1,k+l+(cpt-1),k+l);
1.201     brouard  5097:        for (j=2; j<= nlstate ; j ++)
                   5098:          fprintf(ficgp,"+$%d",k+l+j-1);
1.153     brouard  5099:        fprintf(ficgp,")) t \"prev(%d,%d)\" w l",i,cpt);
                   5100:       } /* nlstate */
1.201     brouard  5101:       fprintf(ficgp,"\nset out\n");
1.153     brouard  5102:     } /* end cpt state*/ 
                   5103:   } /* end covariate */  
1.201     brouard  5104: 
1.126     brouard  5105:   /* proba elementaires */
1.187     brouard  5106:   fprintf(ficgp,"\n##############\n#MLE estimated parameters\n#############\n");
1.126     brouard  5107:   for(i=1,jk=1; i <=nlstate; i++){
1.187     brouard  5108:     fprintf(ficgp,"# initial state %d\n",i);
1.126     brouard  5109:     for(k=1; k <=(nlstate+ndeath); k++){
                   5110:       if (k != i) {
1.187     brouard  5111:        fprintf(ficgp,"#   current state %d\n",k);
1.126     brouard  5112:        for(j=1; j <=ncovmodel; j++){
1.187     brouard  5113:          fprintf(ficgp,"p%d=%f; ",jk,p[jk]);
1.126     brouard  5114:          jk++; 
                   5115:        }
1.187     brouard  5116:        fprintf(ficgp,"\n");
1.126     brouard  5117:       }
                   5118:     }
                   5119:    }
1.187     brouard  5120:   fprintf(ficgp,"##############\n#\n");
                   5121: 
1.145     brouard  5122:   /*goto avoid;*/
1.200     brouard  5123:   fprintf(ficgp,"\n##############\n#Graphics of probabilities or incidences\n#############\n");
1.187     brouard  5124:   fprintf(ficgp,"# logi(p12/p11)=a12+b12*age+c12age*age+d12*V1+e12*V1*age\n");
                   5125:   fprintf(ficgp,"# logi(p12/p11)=p1 +p2*age +p3*age*age+ p4*V1+ p5*V1*age\n");
                   5126:   fprintf(ficgp,"# logi(p13/p11)=a13+b13*age+c13age*age+d13*V1+e13*V1*age\n");
                   5127:   fprintf(ficgp,"# logi(p13/p11)=p6 +p7*age +p8*age*age+ p9*V1+ p10*V1*age\n");
                   5128:   fprintf(ficgp,"# p12+p13+p14+p11=1=p11(1+exp(a12+b12*age+c12age*age+d12*V1+e12*V1*age)\n");
                   5129:   fprintf(ficgp,"#                      +exp(a13+b13*age+c13age*age+d13*V1+e13*V1*age)+...)\n");
                   5130:   fprintf(ficgp,"# p11=1/(1+exp(a12+b12*age+c12age*age+d12*V1+e12*V1*age)\n");
                   5131:   fprintf(ficgp,"#                      +exp(a13+b13*age+c13age*age+d13*V1+e13*V1*age)+...)\n");
                   5132:   fprintf(ficgp,"# p12=exp(a12+b12*age+c12age*age+d12*V1+e12*V1*age)/\n");
                   5133:   fprintf(ficgp,"#     (1+exp(a12+b12*age+c12age*age+d12*V1+e12*V1*age)\n");
                   5134:   fprintf(ficgp,"#       +exp(a13+b13*age+c13age*age+d13*V1+e13*V1*age))\n");
                   5135:   fprintf(ficgp,"#       +exp(a14+b14*age+c14age*age+d14*V1+e14*V1*age)+...)\n");
                   5136:   fprintf(ficgp,"#\n");
1.201     brouard  5137:    for(ng=1; ng<=3;ng++){ /* Number of graphics: first is logit, 2nd is probabilities, third is incidences per year*/
1.187     brouard  5138:      fprintf(ficgp,"# ng=%d\n",ng);
                   5139:      fprintf(ficgp,"#   jk=1 to 2^%d=%d\n",cptcoveff,m);
1.126     brouard  5140:      for(jk=1; jk <=m; jk++) {
1.187     brouard  5141:        fprintf(ficgp,"#    jk=%d\n",jk);
1.201     brouard  5142:        fprintf(ficgp,"\nset out \"%s_%d-%d.svg\" ",subdirf2(optionfilefiname,"PE_"),jk,ng);
                   5143:        fprintf(ficgp,"\nset ter svg size 640, 480 ");
                   5144:        if (ng==1){
                   5145:         fprintf(ficgp,"\nset ylabel \"Value of the logit of the model\"\n"); /* exp(a12+b12*x) could be nice */
                   5146:         fprintf(ficgp,"\nunset log y");
                   5147:        }else if (ng==2){
                   5148:         fprintf(ficgp,"\nset ylabel \"Probability\"\n");
                   5149:         fprintf(ficgp,"\nset log y");
                   5150:        }else if (ng==3){
1.126     brouard  5151:         fprintf(ficgp,"\nset ylabel \"Quasi-incidence per year\"\n");
1.201     brouard  5152:         fprintf(ficgp,"\nset log y");
                   5153:        }else
                   5154:         fprintf(ficgp,"\nunset title ");
                   5155:        fprintf(ficgp,"\nplot  [%.f:%.f] ",ageminpar,agemaxpar);
1.126     brouard  5156:        i=1;
                   5157:        for(k2=1; k2<=nlstate; k2++) {
                   5158:         k3=i;
                   5159:         for(k=1; k<=(nlstate+ndeath); k++) {
                   5160:           if (k != k2){
1.201     brouard  5161:             switch( ng) {
                   5162:             case 1:
1.187     brouard  5163:               if(nagesqr==0)
1.201     brouard  5164:                 fprintf(ficgp," p%d+p%d*x",i,i+1);
1.187     brouard  5165:               else /* nagesqr =1 */
1.201     brouard  5166:                 fprintf(ficgp," p%d+p%d*x+p%d*x*x",i,i+1,i+1+nagesqr);
                   5167:               break;
                   5168:             case 2: /* ng=2 */
1.187     brouard  5169:               if(nagesqr==0)
                   5170:                 fprintf(ficgp," exp(p%d+p%d*x",i,i+1);
                   5171:               else /* nagesqr =1 */
1.201     brouard  5172:                   fprintf(ficgp," exp(p%d+p%d*x+p%d*x*x",i,i+1,i+1+nagesqr);
                   5173:               break;
                   5174:             case 3:
                   5175:               if(nagesqr==0)
                   5176:                 fprintf(ficgp," %f*exp(p%d+p%d*x",YEARM/stepm,i,i+1);
                   5177:               else /* nagesqr =1 */
                   5178:                 fprintf(ficgp," %f*exp(p%d+p%d*x+p%d*x*x",YEARM/stepm,i,i+1,i+1+nagesqr);
                   5179:               break;
                   5180:             }
1.141     brouard  5181:             ij=1;/* To be checked else nbcode[0][0] wrong */
1.187     brouard  5182:             for(j=3; j <=ncovmodel-nagesqr; j++) {
1.197     brouard  5183:               /* printf("Tage[%d]=%d, j=%d\n", ij, Tage[ij], j); */
                   5184:               if(ij <=cptcovage) { /* Bug valgrind */
                   5185:                 if((j-2)==Tage[ij]) { /* Bug valgrind */
1.200     brouard  5186:                   fprintf(ficgp,"+p%d*%d*x",i+j+nagesqr-1,nbcode[Tvar[j-2]][codtabm(jk,j-2)]);
                   5187:                   /* fprintf(ficgp,"+p%d*%d*x",i+j+nagesqr-1,nbcode[Tvar[j-2]][codtabm(jk,Tvar[j-2])]); */
1.197     brouard  5188:                   ij++;
                   5189:                 }
1.186     brouard  5190:               }
                   5191:               else
1.198     brouard  5192:                 fprintf(ficgp,"+p%d*%d",i+j+nagesqr-1,nbcode[Tvar[j-2]][codtabm(jk,j-2)]);
1.126     brouard  5193:             }
1.201     brouard  5194:             if(ng != 1){
                   5195:               fprintf(ficgp,")/(1");
1.126     brouard  5196:             
1.201     brouard  5197:               for(k1=1; k1 <=nlstate; k1++){ 
                   5198:                 if(nagesqr==0)
                   5199:                   fprintf(ficgp,"+exp(p%d+p%d*x",k3+(k1-1)*ncovmodel,k3+(k1-1)*ncovmodel+1);
                   5200:                 else /* nagesqr =1 */
                   5201:                   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);
                   5202:                 
                   5203:                 ij=1;
                   5204:                 for(j=3; j <=ncovmodel-nagesqr; j++){
                   5205:                   if(ij <=cptcovage) { /* Bug valgrind */
                   5206:                     if((j-2)==Tage[ij]) { /* Bug valgrind */
                   5207:                       fprintf(ficgp,"+p%d*%d*x",k3+(k1-1)*ncovmodel+1+j-2+nagesqr,nbcode[Tvar[j-2]][codtabm(jk,j-2)]);
                   5208:                       /* fprintf(ficgp,"+p%d*%d*x",k3+(k1-1)*ncovmodel+1+j-2+nagesqr,nbcode[Tvar[j-2]][codtabm(jk,Tvar[j-2])]); */
                   5209:                       ij++;
                   5210:                     }
1.197     brouard  5211:                   }
1.201     brouard  5212:                   else
                   5213:                     fprintf(ficgp,"+p%d*%d",k3+(k1-1)*ncovmodel+1+j-2+nagesqr,nbcode[Tvar[j-2]][codtabm(jk,j-2)]);
1.186     brouard  5214:                 }
1.201     brouard  5215:                 fprintf(ficgp,")");
1.126     brouard  5216:               }
                   5217:               fprintf(ficgp,")");
1.201     brouard  5218:               if(ng ==2)
                   5219:                 fprintf(ficgp," t \"p%d%d\" ", k2,k);
                   5220:               else /* ng= 3 */
                   5221:                 fprintf(ficgp," t \"i%d%d\" ", k2,k);
                   5222:             }else{ /* end ng <> 1 */
                   5223:               fprintf(ficgp," t \"logit(p%d%d)\" ", k2,k);
1.126     brouard  5224:             }
                   5225:             if ((k+k2)!= (nlstate*2+ndeath)) fprintf(ficgp,",");
                   5226:             i=i+ncovmodel;
                   5227:           }
                   5228:         } /* end k */
                   5229:        } /* end k2 */
1.201     brouard  5230:        fprintf(ficgp,"\n set out\n");
1.126     brouard  5231:      } /* end jk */
                   5232:    } /* end ng */
1.164     brouard  5233:  /* avoid: */
1.126     brouard  5234:    fflush(ficgp); 
                   5235: }  /* end gnuplot */
                   5236: 
                   5237: 
                   5238: /*************** Moving average **************/
                   5239: int movingaverage(double ***probs, double bage,double fage, double ***mobaverage, int mobilav){
                   5240: 
                   5241:   int i, cpt, cptcod;
                   5242:   int modcovmax =1;
                   5243:   int mobilavrange, mob;
                   5244:   double age;
                   5245: 
                   5246:   modcovmax=2*cptcoveff;/* Max number of modalities. We suppose 
                   5247:                           a covariate has 2 modalities */
                   5248:   if (cptcovn<1) modcovmax=1; /* At least 1 pass */
                   5249: 
                   5250:   if(mobilav==1||mobilav ==3 ||mobilav==5 ||mobilav== 7){
                   5251:     if(mobilav==1) mobilavrange=5; /* default */
                   5252:     else mobilavrange=mobilav;
                   5253:     for (age=bage; age<=fage; age++)
                   5254:       for (i=1; i<=nlstate;i++)
                   5255:        for (cptcod=1;cptcod<=modcovmax;cptcod++)
                   5256:          mobaverage[(int)age][i][cptcod]=probs[(int)age][i][cptcod];
                   5257:     /* We keep the original values on the extreme ages bage, fage and for 
                   5258:        fage+1 and bage-1 we use a 3 terms moving average; for fage+2 bage+2
                   5259:        we use a 5 terms etc. until the borders are no more concerned. 
                   5260:     */ 
                   5261:     for (mob=3;mob <=mobilavrange;mob=mob+2){
                   5262:       for (age=bage+(mob-1)/2; age<=fage-(mob-1)/2; age++){
                   5263:        for (i=1; i<=nlstate;i++){
                   5264:          for (cptcod=1;cptcod<=modcovmax;cptcod++){
                   5265:            mobaverage[(int)age][i][cptcod] =probs[(int)age][i][cptcod];
                   5266:              for (cpt=1;cpt<=(mob-1)/2;cpt++){
                   5267:                mobaverage[(int)age][i][cptcod] +=probs[(int)age-cpt][i][cptcod];
                   5268:                mobaverage[(int)age][i][cptcod] +=probs[(int)age+cpt][i][cptcod];
                   5269:              }
                   5270:            mobaverage[(int)age][i][cptcod]=mobaverage[(int)age][i][cptcod]/mob;
                   5271:          }
                   5272:        }
                   5273:       }/* end age */
                   5274:     }/* end mob */
                   5275:   }else return -1;
                   5276:   return 0;
                   5277: }/* End movingaverage */
                   5278: 
                   5279: 
                   5280: /************** Forecasting ******************/
1.169     brouard  5281: 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  5282:   /* proj1, year, month, day of starting projection 
                   5283:      agemin, agemax range of age
                   5284:      dateprev1 dateprev2 range of dates during which prevalence is computed
                   5285:      anproj2 year of en of projection (same day and month as proj1).
                   5286:   */
1.164     brouard  5287:   int yearp, stepsize, hstepm, nhstepm, j, k, cptcod, i, h, i1;
1.126     brouard  5288:   double agec; /* generic age */
                   5289:   double agelim, ppij, yp,yp1,yp2,jprojmean,mprojmean,anprojmean;
                   5290:   double *popeffectif,*popcount;
                   5291:   double ***p3mat;
                   5292:   double ***mobaverage;
                   5293:   char fileresf[FILENAMELENGTH];
                   5294: 
                   5295:   agelim=AGESUP;
                   5296:   prevalence(probs, ageminpar, agemax, s, agev, nlstate, imx, Tvar, nbcode, ncodemax, mint, anint, dateprev1, dateprev2, firstpass, lastpass);
                   5297:  
1.201     brouard  5298:   strcpy(fileresf,"F_"); 
                   5299:   strcat(fileresf,fileresu);
1.126     brouard  5300:   if((ficresf=fopen(fileresf,"w"))==NULL) {
                   5301:     printf("Problem with forecast resultfile: %s\n", fileresf);
                   5302:     fprintf(ficlog,"Problem with forecast resultfile: %s\n", fileresf);
                   5303:   }
                   5304:   printf("Computing forecasting: result on file '%s' \n", fileresf);
                   5305:   fprintf(ficlog,"Computing forecasting: result on file '%s' \n", fileresf);
                   5306: 
                   5307:   if (cptcoveff==0) ncodemax[cptcoveff]=1;
                   5308: 
                   5309:   if (mobilav!=0) {
                   5310:     mobaverage= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
                   5311:     if (movingaverage(probs, ageminpar, fage, mobaverage,mobilav)!=0){
                   5312:       fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav);
                   5313:       printf(" Error in movingaverage mobilav=%d\n",mobilav);
                   5314:     }
                   5315:   }
                   5316: 
                   5317:   stepsize=(int) (stepm+YEARM-1)/YEARM;
                   5318:   if (stepm<=12) stepsize=1;
                   5319:   if(estepm < stepm){
                   5320:     printf ("Problem %d lower than %d\n",estepm, stepm);
                   5321:   }
                   5322:   else  hstepm=estepm;   
                   5323: 
                   5324:   hstepm=hstepm/stepm; 
                   5325:   yp1=modf(dateintmean,&yp);/* extracts integral of datemean in yp  and
                   5326:                                fractional in yp1 */
                   5327:   anprojmean=yp;
                   5328:   yp2=modf((yp1*12),&yp);
                   5329:   mprojmean=yp;
                   5330:   yp1=modf((yp2*30.5),&yp);
                   5331:   jprojmean=yp;
                   5332:   if(jprojmean==0) jprojmean=1;
                   5333:   if(mprojmean==0) jprojmean=1;
                   5334: 
                   5335:   i1=cptcoveff;
                   5336:   if (cptcovn < 1){i1=1;}
                   5337:   
                   5338:   fprintf(ficresf,"# Mean day of interviews %.lf/%.lf/%.lf (%.2f) between %.2f and %.2f \n",jprojmean,mprojmean,anprojmean,dateintmean,dateprev1,dateprev2); 
                   5339:   
                   5340:   fprintf(ficresf,"#****** Routine prevforecast **\n");
                   5341: 
                   5342: /*           if (h==(int)(YEARM*yearp)){ */
                   5343:   for(cptcov=1, k=0;cptcov<=i1;cptcov++){
                   5344:     for(cptcod=1;cptcod<=ncodemax[cptcoveff];cptcod++){
                   5345:       k=k+1;
                   5346:       fprintf(ficresf,"\n#******");
                   5347:       for(j=1;j<=cptcoveff;j++) {
1.198     brouard  5348:        fprintf(ficresf," V%d=%d, hpijx=probability over h years, hp.jx is weighted by observed prev ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
1.126     brouard  5349:       }
                   5350:       fprintf(ficresf,"******\n");
                   5351:       fprintf(ficresf,"# Covariate valuofcovar yearproj age");
                   5352:       for(j=1; j<=nlstate+ndeath;j++){ 
                   5353:        for(i=1; i<=nlstate;i++)              
                   5354:           fprintf(ficresf," p%d%d",i,j);
                   5355:        fprintf(ficresf," p.%d",j);
                   5356:       }
                   5357:       for (yearp=0; yearp<=(anproj2-anproj1);yearp +=stepsize) { 
                   5358:        fprintf(ficresf,"\n");
                   5359:        fprintf(ficresf,"\n# Forecasting at date %.lf/%.lf/%.lf ",jproj1,mproj1,anproj1+yearp);   
                   5360: 
                   5361:        for (agec=fage; agec>=(ageminpar-1); agec--){ 
                   5362:          nhstepm=(int) rint((agelim-agec)*YEARM/stepm); 
                   5363:          nhstepm = nhstepm/hstepm; 
                   5364:          p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   5365:          oldm=oldms;savm=savms;
                   5366:          hpxij(p3mat,nhstepm,agec,hstepm,p,nlstate,stepm,oldm,savm, k);  
                   5367:        
                   5368:          for (h=0; h<=nhstepm; h++){
                   5369:            if (h*hstepm/YEARM*stepm ==yearp) {
                   5370:               fprintf(ficresf,"\n");
                   5371:               for(j=1;j<=cptcoveff;j++) 
1.198     brouard  5372:                 fprintf(ficresf,"%d %d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
1.126     brouard  5373:              fprintf(ficresf,"%.f %.f ",anproj1+yearp,agec+h*hstepm/YEARM*stepm);
                   5374:            } 
                   5375:            for(j=1; j<=nlstate+ndeath;j++) {
                   5376:              ppij=0.;
                   5377:              for(i=1; i<=nlstate;i++) {
                   5378:                if (mobilav==1) 
                   5379:                  ppij=ppij+p3mat[i][j][h]*mobaverage[(int)agec][i][cptcod];
                   5380:                else {
                   5381:                  ppij=ppij+p3mat[i][j][h]*probs[(int)(agec)][i][cptcod];
                   5382:                }
                   5383:                if (h*hstepm/YEARM*stepm== yearp) {
                   5384:                  fprintf(ficresf," %.3f", p3mat[i][j][h]);
                   5385:                }
                   5386:              } /* end i */
                   5387:              if (h*hstepm/YEARM*stepm==yearp) {
                   5388:                fprintf(ficresf," %.3f", ppij);
                   5389:              }
                   5390:            }/* end j */
                   5391:          } /* end h */
                   5392:          free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   5393:        } /* end agec */
                   5394:       } /* end yearp */
                   5395:     } /* end cptcod */
                   5396:   } /* end  cptcov */
                   5397:        
                   5398:   if (mobilav!=0) free_ma3x(mobaverage,1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
                   5399: 
                   5400:   fclose(ficresf);
                   5401: }
                   5402: 
                   5403: /************** Forecasting *****not tested NB*************/
1.169     brouard  5404: 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  5405:   
                   5406:   int cpt, stepsize, hstepm, nhstepm, j,k,c, cptcod, i,h;
                   5407:   int *popage;
                   5408:   double calagedatem, agelim, kk1, kk2;
                   5409:   double *popeffectif,*popcount;
                   5410:   double ***p3mat,***tabpop,***tabpopprev;
                   5411:   double ***mobaverage;
                   5412:   char filerespop[FILENAMELENGTH];
                   5413: 
                   5414:   tabpop= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
                   5415:   tabpopprev= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
                   5416:   agelim=AGESUP;
                   5417:   calagedatem=(anpyram+mpyram/12.+jpyram/365.-dateintmean)*YEARM;
                   5418:   
                   5419:   prevalence(probs, ageminpar, agemax, s, agev, nlstate, imx, Tvar, nbcode, ncodemax, mint, anint, dateprev1, dateprev2, firstpass, lastpass);
                   5420:   
                   5421:   
1.201     brouard  5422:   strcpy(filerespop,"POP_"); 
                   5423:   strcat(filerespop,fileresu);
1.126     brouard  5424:   if((ficrespop=fopen(filerespop,"w"))==NULL) {
                   5425:     printf("Problem with forecast resultfile: %s\n", filerespop);
                   5426:     fprintf(ficlog,"Problem with forecast resultfile: %s\n", filerespop);
                   5427:   }
                   5428:   printf("Computing forecasting: result on file '%s' \n", filerespop);
                   5429:   fprintf(ficlog,"Computing forecasting: result on file '%s' \n", filerespop);
                   5430: 
                   5431:   if (cptcoveff==0) ncodemax[cptcoveff]=1;
                   5432: 
                   5433:   if (mobilav!=0) {
                   5434:     mobaverage= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
                   5435:     if (movingaverage(probs, ageminpar, fage, mobaverage,mobilav)!=0){
                   5436:       fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav);
                   5437:       printf(" Error in movingaverage mobilav=%d\n",mobilav);
                   5438:     }
                   5439:   }
                   5440: 
                   5441:   stepsize=(int) (stepm+YEARM-1)/YEARM;
                   5442:   if (stepm<=12) stepsize=1;
                   5443:   
                   5444:   agelim=AGESUP;
                   5445:   
                   5446:   hstepm=1;
                   5447:   hstepm=hstepm/stepm; 
                   5448:   
                   5449:   if (popforecast==1) {
                   5450:     if((ficpop=fopen(popfile,"r"))==NULL) {
                   5451:       printf("Problem with population file : %s\n",popfile);exit(0);
                   5452:       fprintf(ficlog,"Problem with population file : %s\n",popfile);exit(0);
                   5453:     } 
                   5454:     popage=ivector(0,AGESUP);
                   5455:     popeffectif=vector(0,AGESUP);
                   5456:     popcount=vector(0,AGESUP);
                   5457:     
                   5458:     i=1;   
                   5459:     while ((c=fscanf(ficpop,"%d %lf\n",&popage[i],&popcount[i])) != EOF) i=i+1;
                   5460:    
                   5461:     imx=i;
                   5462:     for (i=1; i<imx;i++) popeffectif[popage[i]]=popcount[i];
                   5463:   }
                   5464: 
                   5465:   for(cptcov=1,k=0;cptcov<=i2;cptcov++){
                   5466:    for(cptcod=1;cptcod<=ncodemax[cptcoveff];cptcod++){
                   5467:       k=k+1;
                   5468:       fprintf(ficrespop,"\n#******");
                   5469:       for(j=1;j<=cptcoveff;j++) {
1.198     brouard  5470:        fprintf(ficrespop," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
1.126     brouard  5471:       }
                   5472:       fprintf(ficrespop,"******\n");
                   5473:       fprintf(ficrespop,"# Age");
                   5474:       for(j=1; j<=nlstate+ndeath;j++) fprintf(ficrespop," P.%d",j);
                   5475:       if (popforecast==1)  fprintf(ficrespop," [Population]");
                   5476:       
                   5477:       for (cpt=0; cpt<=0;cpt++) { 
                   5478:        fprintf(ficrespop,"\n\n# Forecasting at date %.lf/%.lf/%.lf ",jpyram,mpyram,anpyram+cpt);   
                   5479:        
                   5480:        for (agedeb=(fage-((int)calagedatem %12/12.)); agedeb>=(ageminpar-((int)calagedatem %12)/12.); agedeb--){ 
                   5481:          nhstepm=(int) rint((agelim-agedeb)*YEARM/stepm); 
                   5482:          nhstepm = nhstepm/hstepm; 
                   5483:          
                   5484:          p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   5485:          oldm=oldms;savm=savms;
                   5486:          hpxij(p3mat,nhstepm,agedeb,hstepm,p,nlstate,stepm,oldm,savm, k);  
                   5487:        
                   5488:          for (h=0; h<=nhstepm; h++){
                   5489:            if (h==(int) (calagedatem+YEARM*cpt)) {
                   5490:              fprintf(ficrespop,"\n %3.f ",agedeb+h*hstepm/YEARM*stepm);
                   5491:            } 
                   5492:            for(j=1; j<=nlstate+ndeath;j++) {
                   5493:              kk1=0.;kk2=0;
                   5494:              for(i=1; i<=nlstate;i++) {              
                   5495:                if (mobilav==1) 
                   5496:                  kk1=kk1+p3mat[i][j][h]*mobaverage[(int)agedeb+1][i][cptcod];
                   5497:                else {
                   5498:                  kk1=kk1+p3mat[i][j][h]*probs[(int)(agedeb+1)][i][cptcod];
                   5499:                }
                   5500:              }
                   5501:              if (h==(int)(calagedatem+12*cpt)){
                   5502:                tabpop[(int)(agedeb)][j][cptcod]=kk1;
                   5503:                  /*fprintf(ficrespop," %.3f", kk1);
                   5504:                    if (popforecast==1) fprintf(ficrespop," [%.f]", kk1*popeffectif[(int)agedeb+1]);*/
                   5505:              }
                   5506:            }
                   5507:            for(i=1; i<=nlstate;i++){
                   5508:              kk1=0.;
                   5509:                for(j=1; j<=nlstate;j++){
                   5510:                  kk1= kk1+tabpop[(int)(agedeb)][j][cptcod]; 
                   5511:                }
                   5512:                  tabpopprev[(int)(agedeb)][i][cptcod]=tabpop[(int)(agedeb)][i][cptcod]/kk1*popeffectif[(int)(agedeb+(calagedatem+12*cpt)*hstepm/YEARM*stepm-1)];
                   5513:            }
                   5514: 
                   5515:            if (h==(int)(calagedatem+12*cpt)) for(j=1; j<=nlstate;j++) 
                   5516:              fprintf(ficrespop," %15.2f",tabpopprev[(int)(agedeb+1)][j][cptcod]);
                   5517:          }
                   5518:          free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   5519:        }
                   5520:       }
                   5521:  
                   5522:   /******/
                   5523: 
                   5524:       for (cpt=1; cpt<=(anpyram1-anpyram);cpt++) { 
                   5525:        fprintf(ficrespop,"\n\n# Forecasting at date %.lf/%.lf/%.lf ",jpyram,mpyram,anpyram+cpt);   
                   5526:        for (agedeb=(fage-((int)calagedatem %12/12.)); agedeb>=(ageminpar-((int)calagedatem %12)/12.); agedeb--){ 
                   5527:          nhstepm=(int) rint((agelim-agedeb)*YEARM/stepm); 
                   5528:          nhstepm = nhstepm/hstepm; 
                   5529:          
                   5530:          p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   5531:          oldm=oldms;savm=savms;
                   5532:          hpxij(p3mat,nhstepm,agedeb,hstepm,p,nlstate,stepm,oldm,savm, k);  
                   5533:          for (h=0; h<=nhstepm; h++){
                   5534:            if (h==(int) (calagedatem+YEARM*cpt)) {
                   5535:              fprintf(ficresf,"\n %3.f ",agedeb+h*hstepm/YEARM*stepm);
                   5536:            } 
                   5537:            for(j=1; j<=nlstate+ndeath;j++) {
                   5538:              kk1=0.;kk2=0;
                   5539:              for(i=1; i<=nlstate;i++) {              
                   5540:                kk1=kk1+p3mat[i][j][h]*tabpopprev[(int)agedeb+1][i][cptcod];    
                   5541:              }
                   5542:              if (h==(int)(calagedatem+12*cpt)) fprintf(ficresf," %15.2f", kk1);        
                   5543:            }
                   5544:          }
                   5545:          free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   5546:        }
                   5547:       }
                   5548:    } 
                   5549:   }
                   5550:  
                   5551:   if (mobilav!=0) free_ma3x(mobaverage,1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
                   5552: 
                   5553:   if (popforecast==1) {
                   5554:     free_ivector(popage,0,AGESUP);
                   5555:     free_vector(popeffectif,0,AGESUP);
                   5556:     free_vector(popcount,0,AGESUP);
                   5557:   }
                   5558:   free_ma3x(tabpop,1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
                   5559:   free_ma3x(tabpopprev,1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
                   5560:   fclose(ficrespop);
                   5561: } /* End of popforecast */
                   5562: 
                   5563: int fileappend(FILE *fichier, char *optionfich)
                   5564: {
                   5565:   if((fichier=fopen(optionfich,"a"))==NULL) {
                   5566:     printf("Problem with file: %s\n", optionfich);
                   5567:     fprintf(ficlog,"Problem with file: %s\n", optionfich);
                   5568:     return (0);
                   5569:   }
                   5570:   fflush(fichier);
                   5571:   return (1);
                   5572: }
                   5573: 
                   5574: 
                   5575: /**************** function prwizard **********************/
                   5576: void prwizard(int ncovmodel, int nlstate, int ndeath,  char model[], FILE *ficparo)
                   5577: {
                   5578: 
                   5579:   /* Wizard to print covariance matrix template */
                   5580: 
1.164     brouard  5581:   char ca[32], cb[32];
                   5582:   int i,j, k, li, lj, lk, ll, jj, npar, itimes;
1.126     brouard  5583:   int numlinepar;
                   5584: 
                   5585:   printf("# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
                   5586:   fprintf(ficparo,"# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
                   5587:   for(i=1; i <=nlstate; i++){
                   5588:     jj=0;
                   5589:     for(j=1; j <=nlstate+ndeath; j++){
                   5590:       if(j==i) continue;
                   5591:       jj++;
                   5592:       /*ca[0]= k+'a'-1;ca[1]='\0';*/
                   5593:       printf("%1d%1d",i,j);
                   5594:       fprintf(ficparo,"%1d%1d",i,j);
                   5595:       for(k=1; k<=ncovmodel;k++){
                   5596:        /*        printf(" %lf",param[i][j][k]); */
                   5597:        /*        fprintf(ficparo," %lf",param[i][j][k]); */
                   5598:        printf(" 0.");
                   5599:        fprintf(ficparo," 0.");
                   5600:       }
                   5601:       printf("\n");
                   5602:       fprintf(ficparo,"\n");
                   5603:     }
                   5604:   }
                   5605:   printf("# Scales (for hessian or gradient estimation)\n");
                   5606:   fprintf(ficparo,"# Scales (for hessian or gradient estimation)\n");
                   5607:   npar= (nlstate+ndeath-1)*nlstate*ncovmodel; /* Number of parameters*/ 
                   5608:   for(i=1; i <=nlstate; i++){
                   5609:     jj=0;
                   5610:     for(j=1; j <=nlstate+ndeath; j++){
                   5611:       if(j==i) continue;
                   5612:       jj++;
                   5613:       fprintf(ficparo,"%1d%1d",i,j);
                   5614:       printf("%1d%1d",i,j);
                   5615:       fflush(stdout);
                   5616:       for(k=1; k<=ncovmodel;k++){
                   5617:        /*      printf(" %le",delti3[i][j][k]); */
                   5618:        /*      fprintf(ficparo," %le",delti3[i][j][k]); */
                   5619:        printf(" 0.");
                   5620:        fprintf(ficparo," 0.");
                   5621:       }
                   5622:       numlinepar++;
                   5623:       printf("\n");
                   5624:       fprintf(ficparo,"\n");
                   5625:     }
                   5626:   }
                   5627:   printf("# Covariance matrix\n");
                   5628: /* # 121 Var(a12)\n\ */
                   5629: /* # 122 Cov(b12,a12) Var(b12)\n\ */
                   5630: /* # 131 Cov(a13,a12) Cov(a13,b12, Var(a13)\n\ */
                   5631: /* # 132 Cov(b13,a12) Cov(b13,b12, Cov(b13,a13) Var(b13)\n\ */
                   5632: /* # 212 Cov(a21,a12) Cov(a21,b12, Cov(a21,a13) Cov(a21,b13) Var(a21)\n\ */
                   5633: /* # 212 Cov(b21,a12) Cov(b21,b12, Cov(b21,a13) Cov(b21,b13) Cov(b21,a21) Var(b21)\n\ */
                   5634: /* # 232 Cov(a23,a12) Cov(a23,b12, Cov(a23,a13) Cov(a23,b13) Cov(a23,a21) Cov(a23,b21) Var(a23)\n\ */
                   5635: /* # 232 Cov(b23,a12) Cov(b23,b12) ... Var (b23)\n" */
                   5636:   fflush(stdout);
                   5637:   fprintf(ficparo,"# Covariance matrix\n");
                   5638:   /* # 121 Var(a12)\n\ */
                   5639:   /* # 122 Cov(b12,a12) Var(b12)\n\ */
                   5640:   /* #   ...\n\ */
                   5641:   /* # 232 Cov(b23,a12)  Cov(b23,b12) ... Var (b23)\n" */
                   5642:   
                   5643:   for(itimes=1;itimes<=2;itimes++){
                   5644:     jj=0;
                   5645:     for(i=1; i <=nlstate; i++){
                   5646:       for(j=1; j <=nlstate+ndeath; j++){
                   5647:        if(j==i) continue;
                   5648:        for(k=1; k<=ncovmodel;k++){
                   5649:          jj++;
                   5650:          ca[0]= k+'a'-1;ca[1]='\0';
                   5651:          if(itimes==1){
                   5652:            printf("#%1d%1d%d",i,j,k);
                   5653:            fprintf(ficparo,"#%1d%1d%d",i,j,k);
                   5654:          }else{
                   5655:            printf("%1d%1d%d",i,j,k);
                   5656:            fprintf(ficparo,"%1d%1d%d",i,j,k);
                   5657:            /*  printf(" %.5le",matcov[i][j]); */
                   5658:          }
                   5659:          ll=0;
                   5660:          for(li=1;li <=nlstate; li++){
                   5661:            for(lj=1;lj <=nlstate+ndeath; lj++){
                   5662:              if(lj==li) continue;
                   5663:              for(lk=1;lk<=ncovmodel;lk++){
                   5664:                ll++;
                   5665:                if(ll<=jj){
                   5666:                  cb[0]= lk +'a'-1;cb[1]='\0';
                   5667:                  if(ll<jj){
                   5668:                    if(itimes==1){
                   5669:                      printf(" Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
                   5670:                      fprintf(ficparo," Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
                   5671:                    }else{
                   5672:                      printf(" 0.");
                   5673:                      fprintf(ficparo," 0.");
                   5674:                    }
                   5675:                  }else{
                   5676:                    if(itimes==1){
                   5677:                      printf(" Var(%s%1d%1d)",ca,i,j);
                   5678:                      fprintf(ficparo," Var(%s%1d%1d)",ca,i,j);
                   5679:                    }else{
                   5680:                      printf(" 0.");
                   5681:                      fprintf(ficparo," 0.");
                   5682:                    }
                   5683:                  }
                   5684:                }
                   5685:              } /* end lk */
                   5686:            } /* end lj */
                   5687:          } /* end li */
                   5688:          printf("\n");
                   5689:          fprintf(ficparo,"\n");
                   5690:          numlinepar++;
                   5691:        } /* end k*/
                   5692:       } /*end j */
                   5693:     } /* end i */
                   5694:   } /* end itimes */
                   5695: 
                   5696: } /* end of prwizard */
                   5697: /******************* Gompertz Likelihood ******************************/
                   5698: double gompertz(double x[])
                   5699: { 
                   5700:   double A,B,L=0.0,sump=0.,num=0.;
                   5701:   int i,n=0; /* n is the size of the sample */
                   5702: 
                   5703:   for (i=0;i<=imx-1 ; i++) {
                   5704:     sump=sump+weight[i];
                   5705:     /*    sump=sump+1;*/
                   5706:     num=num+1;
                   5707:   }
                   5708:  
                   5709:  
                   5710:   /* for (i=0; i<=imx; i++) 
                   5711:      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]);*/
                   5712: 
                   5713:   for (i=1;i<=imx ; i++)
                   5714:     {
                   5715:       if (cens[i] == 1 && wav[i]>1)
                   5716:        A=-x[1]/(x[2])*(exp(x[2]*(agecens[i]-agegomp))-exp(x[2]*(ageexmed[i]-agegomp)));
                   5717:       
                   5718:       if (cens[i] == 0 && wav[i]>1)
                   5719:        A=-x[1]/(x[2])*(exp(x[2]*(agedc[i]-agegomp))-exp(x[2]*(ageexmed[i]-agegomp)))
                   5720:             +log(x[1]/YEARM)+x[2]*(agedc[i]-agegomp)+log(YEARM);  
                   5721:       
                   5722:       /*if (wav[i] > 1 && agecens[i] > 15) {*/ /* ??? */
                   5723:       if (wav[i] > 1 ) { /* ??? */
                   5724:        L=L+A*weight[i];
                   5725:        /*      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]);*/
                   5726:       }
                   5727:     }
                   5728: 
                   5729:  /*printf("x1=%2.9f x2=%2.9f x3=%2.9f L=%f\n",x[1],x[2],x[3],L);*/
                   5730:  
                   5731:   return -2*L*num/sump;
                   5732: }
                   5733: 
1.136     brouard  5734: #ifdef GSL
                   5735: /******************* Gompertz_f Likelihood ******************************/
                   5736: double gompertz_f(const gsl_vector *v, void *params)
                   5737: { 
                   5738:   double A,B,LL=0.0,sump=0.,num=0.;
                   5739:   double *x= (double *) v->data;
                   5740:   int i,n=0; /* n is the size of the sample */
                   5741: 
                   5742:   for (i=0;i<=imx-1 ; i++) {
                   5743:     sump=sump+weight[i];
                   5744:     /*    sump=sump+1;*/
                   5745:     num=num+1;
                   5746:   }
                   5747:  
                   5748:  
                   5749:   /* for (i=0; i<=imx; i++) 
                   5750:      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]);*/
                   5751:   printf("x[0]=%lf x[1]=%lf\n",x[0],x[1]);
                   5752:   for (i=1;i<=imx ; i++)
                   5753:     {
                   5754:       if (cens[i] == 1 && wav[i]>1)
                   5755:        A=-x[0]/(x[1])*(exp(x[1]*(agecens[i]-agegomp))-exp(x[1]*(ageexmed[i]-agegomp)));
                   5756:       
                   5757:       if (cens[i] == 0 && wav[i]>1)
                   5758:        A=-x[0]/(x[1])*(exp(x[1]*(agedc[i]-agegomp))-exp(x[1]*(ageexmed[i]-agegomp)))
                   5759:             +log(x[0]/YEARM)+x[1]*(agedc[i]-agegomp)+log(YEARM);  
                   5760:       
                   5761:       /*if (wav[i] > 1 && agecens[i] > 15) {*/ /* ??? */
                   5762:       if (wav[i] > 1 ) { /* ??? */
                   5763:        LL=LL+A*weight[i];
                   5764:        /*      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]);*/
                   5765:       }
                   5766:     }
                   5767: 
                   5768:  /*printf("x1=%2.9f x2=%2.9f x3=%2.9f L=%f\n",x[1],x[2],x[3],L);*/
                   5769:   printf("x[0]=%lf x[1]=%lf -2*LL*num/sump=%lf\n",x[0],x[1],-2*LL*num/sump);
                   5770:  
                   5771:   return -2*LL*num/sump;
                   5772: }
                   5773: #endif
                   5774: 
1.126     brouard  5775: /******************* Printing html file ***********/
1.201     brouard  5776: void printinghtmlmort(char fileresu[], char title[], char datafile[], int firstpass, \
1.126     brouard  5777:                  int lastpass, int stepm, int weightopt, char model[],\
                   5778:                  int imx,  double p[],double **matcov,double agemortsup){
                   5779:   int i,k;
                   5780: 
                   5781:   fprintf(fichtm,"<ul><li><h4>Result files </h4>\n Force of mortality. Parameters of the Gompertz fit (with confidence interval in brackets):<br>");
                   5782:   fprintf(fichtm,"  mu(age) =%lf*exp(%lf*(age-%d)) per year<br><br>",p[1],p[2],agegomp);
                   5783:   for (i=1;i<=2;i++) 
                   5784:     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  5785:   fprintf(fichtm,"<br><br><img src=\"graphmort.svg\">");
1.126     brouard  5786:   fprintf(fichtm,"</ul>");
                   5787: 
                   5788: fprintf(fichtm,"<ul><li><h4>Life table</h4>\n <br>");
                   5789: 
                   5790:  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>");
                   5791: 
                   5792:  for (k=agegomp;k<(agemortsup-2);k++) 
                   5793:    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]);
                   5794: 
                   5795:  
                   5796:   fflush(fichtm);
                   5797: }
                   5798: 
                   5799: /******************* Gnuplot file **************/
1.201     brouard  5800: void printinggnuplotmort(char fileresu[], char optionfilefiname[], double ageminpar, double agemaxpar, double fage , char pathc[], double p[]){
1.126     brouard  5801: 
                   5802:   char dirfileres[132],optfileres[132];
1.164     brouard  5803: 
1.126     brouard  5804:   int ng;
                   5805: 
                   5806: 
                   5807:   /*#ifdef windows */
                   5808:   fprintf(ficgp,"cd \"%s\" \n",pathc);
                   5809:     /*#endif */
                   5810: 
                   5811: 
                   5812:   strcpy(dirfileres,optionfilefiname);
                   5813:   strcpy(optfileres,"vpl");
1.199     brouard  5814:   fprintf(ficgp,"set out \"graphmort.svg\"\n "); 
1.126     brouard  5815:   fprintf(ficgp,"set xlabel \"Age\"\n set ylabel \"Force of mortality (per year)\" \n "); 
1.199     brouard  5816:   fprintf(ficgp, "set ter svg size 640, 480\n set log y\n"); 
1.145     brouard  5817:   /* fprintf(ficgp, "set size 0.65,0.65\n"); */
1.126     brouard  5818:   fprintf(ficgp,"plot [%d:100] %lf*exp(%lf*(x-%d))",agegomp,p[1],p[2],agegomp);
                   5819: 
                   5820: } 
                   5821: 
1.136     brouard  5822: int readdata(char datafile[], int firstobs, int lastobs, int *imax)
                   5823: {
1.126     brouard  5824: 
1.136     brouard  5825:   /*-------- data file ----------*/
                   5826:   FILE *fic;
                   5827:   char dummy[]="                         ";
1.164     brouard  5828:   int i=0, j=0, n=0;
1.136     brouard  5829:   int linei, month, year,iout;
                   5830:   char line[MAXLINE], linetmp[MAXLINE];
1.164     brouard  5831:   char stra[MAXLINE], strb[MAXLINE];
1.136     brouard  5832:   char *stratrunc;
                   5833:   int lstra;
1.126     brouard  5834: 
                   5835: 
1.136     brouard  5836:   if((fic=fopen(datafile,"r"))==NULL)    {
1.195     brouard  5837:     printf("Problem while opening datafile: %s\n", datafile);fflush(stdout);
                   5838:     fprintf(ficlog,"Problem while opening datafile: %s\n", datafile);fflush(ficlog);return 1;
1.136     brouard  5839:   }
1.126     brouard  5840: 
1.136     brouard  5841:   i=1;
                   5842:   linei=0;
                   5843:   while ((fgets(line, MAXLINE, fic) != NULL) &&((i >= firstobs) && (i <=lastobs))) {
                   5844:     linei=linei+1;
                   5845:     for(j=strlen(line); j>=0;j--){  /* Untabifies line */
                   5846:       if(line[j] == '\t')
                   5847:        line[j] = ' ';
                   5848:     }
                   5849:     for(j=strlen(line)-1; (line[j]==' ')||(line[j]==10)||(line[j]==13);j--){
                   5850:       ;
                   5851:     };
                   5852:     line[j+1]=0;  /* Trims blanks at end of line */
                   5853:     if(line[0]=='#'){
                   5854:       fprintf(ficlog,"Comment line\n%s\n",line);
                   5855:       printf("Comment line\n%s\n",line);
                   5856:       continue;
                   5857:     }
                   5858:     trimbb(linetmp,line); /* Trims multiple blanks in line */
1.164     brouard  5859:     strcpy(line, linetmp);
1.136     brouard  5860:   
1.126     brouard  5861: 
1.136     brouard  5862:     for (j=maxwav;j>=1;j--){
1.137     brouard  5863:       cutv(stra, strb, line, ' '); 
1.136     brouard  5864:       if(strb[0]=='.') { /* Missing status */
                   5865:        lval=-1;
                   5866:       }else{
                   5867:        errno=0;
                   5868:        lval=strtol(strb,&endptr,10); 
                   5869:       /*       if (errno == ERANGE && (lval == LONG_MAX || lval == LONG_MIN))*/
                   5870:        if( strb[0]=='\0' || (*endptr != '\0')){
1.141     brouard  5871:          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);
                   5872:          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  5873:          return 1;
                   5874:        }
                   5875:       }
                   5876:       s[j][i]=lval;
                   5877:       
                   5878:       strcpy(line,stra);
                   5879:       cutv(stra, strb,line,' ');
1.169     brouard  5880:       if( (iout=sscanf(strb,"%d/%d",&month, &year)) != 0){
1.136     brouard  5881:       }
1.169     brouard  5882:       else  if( (iout=sscanf(strb,"%s.",dummy)) != 0){
1.136     brouard  5883:        month=99;
                   5884:        year=9999;
                   5885:       }else{
1.141     brouard  5886:        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);
                   5887:        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  5888:        return 1;
                   5889:       }
                   5890:       anint[j][i]= (double) year; 
                   5891:       mint[j][i]= (double)month; 
                   5892:       strcpy(line,stra);
                   5893:     } /* ENd Waves */
                   5894:     
                   5895:     cutv(stra, strb,line,' '); 
1.169     brouard  5896:     if( (iout=sscanf(strb,"%d/%d",&month, &year)) != 0){
1.136     brouard  5897:     }
1.169     brouard  5898:     else  if( (iout=sscanf(strb,"%s.",dummy)) != 0){
1.136     brouard  5899:       month=99;
                   5900:       year=9999;
                   5901:     }else{
1.141     brouard  5902:       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);
                   5903:        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  5904:        return 1;
                   5905:     }
                   5906:     andc[i]=(double) year; 
                   5907:     moisdc[i]=(double) month; 
                   5908:     strcpy(line,stra);
                   5909:     
                   5910:     cutv(stra, strb,line,' '); 
1.169     brouard  5911:     if( (iout=sscanf(strb,"%d/%d",&month, &year)) != 0){
1.136     brouard  5912:     }
1.169     brouard  5913:     else  if( (iout=sscanf(strb,"%s.", dummy)) != 0){
1.136     brouard  5914:       month=99;
                   5915:       year=9999;
                   5916:     }else{
1.141     brouard  5917:       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);
                   5918:       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  5919:        return 1;
                   5920:     }
                   5921:     if (year==9999) {
1.141     brouard  5922:       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);
                   5923:       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  5924:        return 1;
1.126     brouard  5925: 
1.136     brouard  5926:     }
                   5927:     annais[i]=(double)(year);
                   5928:     moisnais[i]=(double)(month); 
                   5929:     strcpy(line,stra);
                   5930:     
                   5931:     cutv(stra, strb,line,' '); 
                   5932:     errno=0;
                   5933:     dval=strtod(strb,&endptr); 
                   5934:     if( strb[0]=='\0' || (*endptr != '\0')){
1.141     brouard  5935:       printf("Error reading data around '%f' at line number %d, \"%s\" for individual %d\nShould be a weight.  Exiting.\n",dval, i,line,linei);
                   5936:       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  5937:       fflush(ficlog);
                   5938:       return 1;
                   5939:     }
                   5940:     weight[i]=dval; 
                   5941:     strcpy(line,stra);
                   5942:     
                   5943:     for (j=ncovcol;j>=1;j--){
                   5944:       cutv(stra, strb,line,' '); 
                   5945:       if(strb[0]=='.') { /* Missing status */
                   5946:        lval=-1;
                   5947:       }else{
                   5948:        errno=0;
                   5949:        lval=strtol(strb,&endptr,10); 
                   5950:        if( strb[0]=='\0' || (*endptr != '\0')){
1.141     brouard  5951:          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);
                   5952:          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  5953:          return 1;
                   5954:        }
                   5955:       }
                   5956:       if(lval <-1 || lval >1){
1.141     brouard  5957:        printf("Error reading data around '%ld' at line number %d for individual %d, '%s'\n \
1.136     brouard  5958:  Should be a value of %d(nth) covariate (0 should be the value for the reference and 1\n \
                   5959:  for the alternative. IMaCh does not build design variables automatically, do it yourself.\n \
                   5960:  For example, for multinomial values like 1, 2 and 3,\n \
                   5961:  build V1=0 V2=0 for the reference value (1),\n \
                   5962:         V1=1 V2=0 for (2) \n \
                   5963:  and V1=0 V2=1 for (3). V1=1 V2=1 should not exist and the corresponding\n \
                   5964:  output of IMaCh is often meaningless.\n \
                   5965:  Exiting.\n",lval,linei, i,line,j);
1.141     brouard  5966:        fprintf(ficlog,"Error reading data around '%ld' at line number %d for individual %d, '%s'\n \
1.136     brouard  5967:  Should be a value of %d(nth) covariate (0 should be the value for the reference and 1\n \
                   5968:  for the alternative. IMaCh does not build design variables automatically, do it yourself.\n \
                   5969:  For example, for multinomial values like 1, 2 and 3,\n \
                   5970:  build V1=0 V2=0 for the reference value (1),\n \
                   5971:         V1=1 V2=0 for (2) \n \
                   5972:  and V1=0 V2=1 for (3). V1=1 V2=1 should not exist and the corresponding\n \
                   5973:  output of IMaCh is often meaningless.\n \
                   5974:  Exiting.\n",lval,linei, i,line,j);fflush(ficlog);
                   5975:        return 1;
                   5976:       }
                   5977:       covar[j][i]=(double)(lval);
                   5978:       strcpy(line,stra);
                   5979:     }  
                   5980:     lstra=strlen(stra);
                   5981:      
                   5982:     if(lstra > 9){ /* More than 2**32 or max of what printf can write with %ld */
                   5983:       stratrunc = &(stra[lstra-9]);
                   5984:       num[i]=atol(stratrunc);
                   5985:     }
                   5986:     else
                   5987:       num[i]=atol(stra);
                   5988:     /*if((s[2][i]==2) && (s[3][i]==-1)&&(s[4][i]==9)){
                   5989:       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;}*/
                   5990:     
                   5991:     i=i+1;
                   5992:   } /* End loop reading  data */
1.126     brouard  5993: 
1.136     brouard  5994:   *imax=i-1; /* Number of individuals */
                   5995:   fclose(fic);
                   5996:  
                   5997:   return (0);
1.164     brouard  5998:   /* endread: */
1.136     brouard  5999:     printf("Exiting readdata: ");
                   6000:     fclose(fic);
                   6001:     return (1);
1.126     brouard  6002: 
                   6003: 
                   6004: 
1.136     brouard  6005: }
1.145     brouard  6006: void removespace(char *str) {
                   6007:   char *p1 = str, *p2 = str;
                   6008:   do
                   6009:     while (*p2 == ' ')
                   6010:       p2++;
1.169     brouard  6011:   while (*p1++ == *p2++);
1.145     brouard  6012: }
                   6013: 
                   6014: int decodemodel ( char model[], int lastobs) /**< This routine decode the model and returns:
1.187     brouard  6015:    * Model  V1+V2+V3+V8+V7*V8+V5*V6+V8*age+V3*age+age*age
                   6016:    * - nagesqr = 1 if age*age in the model, otherwise 0.
                   6017:    * - cptcovt total number of covariates of the model nbocc(+)+1 = 8 excepting constant and age and age*age
                   6018:    * - cptcovn or number of covariates k of the models excluding age*products =6 and age*age
1.145     brouard  6019:    * - cptcovage number of covariates with age*products =2
                   6020:    * - cptcovs number of simple covariates
                   6021:    * - 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
                   6022:    *     which is a new column after the 9 (ncovcol) variables. 
                   6023:    * - if k is a product Vn*Vm covar[k][i] is filled with correct values for each individual
                   6024:    * - Tprod[l] gives the kth covariates of the product Vn*Vm l=1 to cptcovprod-cptcovage
                   6025:    *    Tprod[1]@2 {5, 6}: position of first product V7*V8 is 5, and second V5*V6 is 6.
                   6026:    * - Tvard[k]  p Tvard[1][1]@4 {7, 8, 5, 6} for V7*V8 and V5*V6 .
                   6027:  */
1.136     brouard  6028: {
1.145     brouard  6029:   int i, j, k, ks;
1.164     brouard  6030:   int  j1, k1, k2;
1.136     brouard  6031:   char modelsav[80];
1.145     brouard  6032:   char stra[80], strb[80], strc[80], strd[80],stre[80];
1.187     brouard  6033:   char *strpt;
1.136     brouard  6034: 
1.145     brouard  6035:   /*removespace(model);*/
1.136     brouard  6036:   if (strlen(model) >1){ /* If there is at least 1 covariate */
1.145     brouard  6037:     j=0, j1=0, k1=0, k2=-1, ks=0, cptcovn=0;
1.137     brouard  6038:     if (strstr(model,"AGE") !=0){
1.192     brouard  6039:       printf("Error. AGE must be in lower case 'age' model=1+age+%s. ",model);
                   6040:       fprintf(ficlog,"Error. AGE must be in lower case model=1+age+%s. ",model);fflush(ficlog);
1.136     brouard  6041:       return 1;
                   6042:     }
1.141     brouard  6043:     if (strstr(model,"v") !=0){
                   6044:       printf("Error. 'v' must be in upper case 'V' model=%s ",model);
                   6045:       fprintf(ficlog,"Error. 'v' must be in upper case model=%s ",model);fflush(ficlog);
                   6046:       return 1;
                   6047:     }
1.187     brouard  6048:     strcpy(modelsav,model); 
                   6049:     if ((strpt=strstr(model,"age*age")) !=0){
                   6050:       printf(" strpt=%s, model=%s\n",strpt, model);
                   6051:       if(strpt != model){
                   6052:       printf("Error in model: 'model=%s'; 'age*age' should in first place before other covariates\n \
1.192     brouard  6053:  'model=1+age+age*age+V1.' or 'model=1+age+age*age+V1+V1*age.', please swap as well as \n \
1.187     brouard  6054:  corresponding column of parameters.\n",model);
                   6055:       fprintf(ficlog,"Error in model: 'model=%s'; 'age*age' should in first place before other covariates\n \
1.192     brouard  6056:  'model=1+age+age*age+V1.' or 'model=1+age+age*age+V1+V1*age.', please swap as well as \n \
1.187     brouard  6057:  corresponding column of parameters.\n",model); fflush(ficlog);
                   6058:       return 1;
                   6059:     }
                   6060: 
                   6061:       nagesqr=1;
                   6062:       if (strstr(model,"+age*age") !=0)
                   6063:        substrchaine(modelsav, model, "+age*age");
                   6064:       else if (strstr(model,"age*age+") !=0)
                   6065:        substrchaine(modelsav, model, "age*age+");
                   6066:       else 
                   6067:        substrchaine(modelsav, model, "age*age");
                   6068:     }else
                   6069:       nagesqr=0;
                   6070:     if (strlen(modelsav) >1){
                   6071:       j=nbocc(modelsav,'+'); /**< j=Number of '+' */
                   6072:       j1=nbocc(modelsav,'*'); /**< j1=Number of '*' */
                   6073:       cptcovs=j+1-j1; /**<  Number of simple covariates V1+V1*age+V3 +V3*V4+age*age=> V1 + V3 =2  */
                   6074:       cptcovt= j+1; /* Number of total covariates in the model, not including
                   6075:                   * cst, age and age*age 
                   6076:                   * V1+V1*age+ V3 + V3*V4+age*age=> 4*/
                   6077:                   /* including age products which are counted in cptcovage.
                   6078:                  * but the covariates which are products must be treated 
                   6079:                  * separately: ncovn=4- 2=2 (V1+V3). */
                   6080:       cptcovprod=j1; /**< Number of products  V1*V2 +v3*age = 2 */
                   6081:       cptcovprodnoage=0; /**< Number of covariate products without age: V3*V4 =1  */
                   6082: 
                   6083:     
                   6084:       /*   Design
                   6085:        *  V1   V2   V3   V4  V5  V6  V7  V8  V9 Weight
                   6086:        *  <          ncovcol=8                >
                   6087:        * Model V2 + V1 + V3*age + V3 + V5*V6 + V7*V8 + V8*age + V8
                   6088:        *   k=  1    2      3       4     5       6      7        8
                   6089:        *  cptcovn number of covariates (not including constant and age ) = # of + plus 1 = 7+1=8
                   6090:        *  covar[k,i], value of kth covariate if not including age for individual i:
                   6091:        *       covar[1][i]= (V2), covar[4][i]=(V3), covar[8][i]=(V8)
                   6092:        *  Tvar[k] # of the kth covariate:  Tvar[1]=2  Tvar[4]=3 Tvar[8]=8
                   6093:        *       if multiplied by age: V3*age Tvar[3=V3*age]=3 (V3) Tvar[7]=8 and 
                   6094:        *  Tage[++cptcovage]=k
                   6095:        *       if products, new covar are created after ncovcol with k1
                   6096:        *  Tvar[k]=ncovcol+k1; # of the kth covariate product:  Tvar[5]=ncovcol+1=10  Tvar[6]=ncovcol+1=11
                   6097:        *  Tprod[k1]=k; Tprod[1]=5 Tprod[2]= 6; gives the position of the k1th product
                   6098:        *  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
                   6099:        *  Tvar[cptcovn+k2]=Tvard[k1][1];Tvar[cptcovn+k2+1]=Tvard[k1][2];
                   6100:        *  Tvar[8+1]=5;Tvar[8+2]=6;Tvar[8+3]=7;Tvar[8+4]=8 inverted
                   6101:        *  V1   V2   V3   V4  V5  V6  V7  V8  V9  V10  V11
                   6102:        *  <          ncovcol=8                >
                   6103:        *       Model V2 + V1 + V3*age + V3 + V5*V6 + V7*V8 + V8*age + V8    d1   d1   d2  d2
                   6104:        *          k=  1    2      3       4     5       6      7        8    9   10   11  12
                   6105:        *     Tvar[k]= 2    1      3       3    10      11      8        8    5    6    7   8
                   6106:        * p Tvar[1]@12={2,   1,     3,      3,   11,     10,     8,       8,   7,   8,   5,  6}
                   6107:        * p Tprod[1]@2={                         6, 5}
                   6108:        *p Tvard[1][1]@4= {7, 8, 5, 6}
                   6109:        * covar[k][i]= V2   V1      ?      V3    V5*V6?   V7*V8?  ?       V8   
                   6110:        *  cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*cov[2];
                   6111:        *How to reorganize?
                   6112:        * Model V1 + V2 + V3 + V8 + V5*V6 + V7*V8 + V3*age + V8*age
                   6113:        * Tvars {2,   1,     3,      3,   11,     10,     8,       8,   7,   8,   5,  6}
                   6114:        *       {2,   1,     4,      8,    5,      6,     3,       7}
                   6115:        * Struct []
                   6116:        */
1.145     brouard  6117: 
1.187     brouard  6118:       /* This loop fills the array Tvar from the string 'model'.*/
                   6119:       /* j is the number of + signs in the model V1+V2+V3 j=2 i=3 to 1 */
                   6120:       /*   modelsav=V2+V1+V4+age*V3 strb=age*V3 stra=V2+V1+V4  */
                   6121:       /*       k=4 (age*V3) Tvar[k=4]= 3 (from V3) Tage[cptcovage=1]=4 */
                   6122:       /*       k=3 V4 Tvar[k=3]= 4 (from V4) */
                   6123:       /*       k=2 V1 Tvar[k=2]= 1 (from V1) */
                   6124:       /*       k=1 Tvar[1]=2 (from V2) */
                   6125:       /*       k=5 Tvar[5] */
                   6126:       /* for (k=1; k<=cptcovn;k++) { */
1.198     brouard  6127:       /*       cov[2+k]=nbcode[Tvar[k]][codtabm(ij,Tvar[k])]; */
1.187     brouard  6128:       /*       } */
1.198     brouard  6129:       /* for (k=1; k<=cptcovage;k++) cov[2+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(ij,Tvar[Tage[k])]]*cov[2]; */
1.187     brouard  6130:       /*
                   6131:        * Treating invertedly V2+V1+V3*age+V2*V4 is as if written V2*V4 +V3*age + V1 + V2 */
                   6132:       for(k=cptcovt; k>=1;k--) /**< Number of covariates */
1.145     brouard  6133:         Tvar[k]=0;
1.187     brouard  6134:       cptcovage=0;
                   6135:       for(k=1; k<=cptcovt;k++){ /* Loop on total covariates of the model */
                   6136:        cutl(stra,strb,modelsav,'+'); /* keeps in strb after the first '+' 
                   6137:                                         modelsav==V2+V1+V4+V3*age strb=V3*age stra=V2+V1+V4 */ 
                   6138:        if (nbocc(modelsav,'+')==0) strcpy(strb,modelsav); /* and analyzes it */
                   6139:        /*      printf("i=%d a=%s b=%s sav=%s\n",i, stra,strb,modelsav);*/
                   6140:        /*scanf("%d",i);*/
                   6141:        if (strchr(strb,'*')) {  /**< Model includes a product V2+V1+V4+V3*age strb=V3*age */
                   6142:          cutl(strc,strd,strb,'*'); /**< strd*strc  Vm*Vn: strb=V3*age(input) strc=age strd=V3 ; V3*V2 strc=V2, strd=V3 */
                   6143:          if (strcmp(strc,"age")==0) { /**< Model includes age: Vn*age */
                   6144:            /* covar is not filled and then is empty */
                   6145:            cptcovprod--;
                   6146:            cutl(stre,strb,strd,'V'); /* strd=V3(input): stre="3" */
                   6147:            Tvar[k]=atoi(stre);  /* V2+V1+V4+V3*age Tvar[4]=3 ; V1+V2*age Tvar[2]=2; V1+V1*age Tvar[2]=1 */
                   6148:            cptcovage++; /* Sums the number of covariates which include age as a product */
                   6149:            Tage[cptcovage]=k;  /* Tvar[4]=3, Tage[1] = 4 or V1+V1*age Tvar[2]=1, Tage[1]=2 */
                   6150:            /*printf("stre=%s ", stre);*/
                   6151:          } else if (strcmp(strd,"age")==0) { /* or age*Vn */
                   6152:            cptcovprod--;
                   6153:            cutl(stre,strb,strc,'V');
                   6154:            Tvar[k]=atoi(stre);
                   6155:            cptcovage++;
                   6156:            Tage[cptcovage]=k;
                   6157:          } else {  /* Age is not in the model product V2+V1+V1*V4+V3*age+V3*V2  strb=V3*V2*/
                   6158:            /* loops on k1=1 (V3*V2) and k1=2 V4*V3 */
                   6159:            cptcovn++;
                   6160:            cptcovprodnoage++;k1++;
                   6161:            cutl(stre,strb,strc,'V'); /* strc= Vn, stre is n; strb=V3*V2 stre=3 strc=*/
                   6162:            Tvar[k]=ncovcol+k1; /* For model-covariate k tells which data-covariate to use but
                   6163:                                   because this model-covariate is a construction we invent a new column
                   6164:                                   ncovcol + k1
                   6165:                                   If already ncovcol=4 and model=V2+V1+V1*V4+age*V3+V3*V2
                   6166:                                   Tvar[3=V1*V4]=4+1 Tvar[5=V3*V2]=4 + 2= 6, etc */
                   6167:            cutl(strc,strb,strd,'V'); /* strd was Vm, strc is m */
                   6168:            Tprod[k1]=k;  /* Tprod[1]=3(=V1*V4) for V2+V1+V1*V4+age*V3+V3*V2  */
                   6169:            Tvard[k1][1] =atoi(strc); /* m 1 for V1*/
                   6170:            Tvard[k1][2] =atoi(stre); /* n 4 for V4*/
                   6171:            k2=k2+2;
                   6172:            Tvar[cptcovt+k2]=Tvard[k1][1]; /* Tvar[(cptcovt=4+k2=1)=5]= 1 (V1) */
                   6173:            Tvar[cptcovt+k2+1]=Tvard[k1][2];  /* Tvar[(cptcovt=4+(k2=1)+1)=6]= 4 (V4) */
                   6174:            for (i=1; i<=lastobs;i++){
                   6175:              /* Computes the new covariate which is a product of
                   6176:                 covar[n][i]* covar[m][i] and stores it at ncovol+k1 May not be defined */
                   6177:              covar[ncovcol+k1][i]=covar[atoi(stre)][i]*covar[atoi(strc)][i];
                   6178:            }
                   6179:          } /* End age is not in the model */
                   6180:        } /* End if model includes a product */
                   6181:        else { /* no more sum */
                   6182:          /*printf("d=%s c=%s b=%s\n", strd,strc,strb);*/
                   6183:          /*  scanf("%d",i);*/
                   6184:          cutl(strd,strc,strb,'V');
                   6185:          ks++; /**< Number of simple covariates */
1.145     brouard  6186:          cptcovn++;
1.187     brouard  6187:          Tvar[k]=atoi(strd);
                   6188:        }
                   6189:        strcpy(modelsav,stra);  /* modelsav=V2+V1+V4 stra=V2+V1+V4 */ 
                   6190:        /*printf("a=%s b=%s sav=%s\n", stra,strb,modelsav);
                   6191:          scanf("%d",i);*/
                   6192:       } /* end of loop + on total covariates */
                   6193:     } /* end if strlen(modelsave == 0) age*age might exist */
                   6194:   } /* end if strlen(model == 0) */
1.136     brouard  6195:   
                   6196:   /*The number n of Vn is stored in Tvar. cptcovage =number of age covariate. Tage gives the position of age. cptcovprod= number of products.
                   6197:     If model=V1+V1*age then Tvar[1]=1 Tvar[2]=1 cptcovage=1 Tage[1]=2 cptcovprod=0*/
                   6198: 
                   6199:   /* printf("tvar1=%d tvar2=%d tvar3=%d cptcovage=%d Tage=%d",Tvar[1],Tvar[2],Tvar[3],cptcovage,Tage[1]);
                   6200:   printf("cptcovprod=%d ", cptcovprod);
                   6201:   fprintf(ficlog,"cptcovprod=%d ", cptcovprod);
                   6202: 
                   6203:   scanf("%d ",i);*/
                   6204: 
                   6205: 
1.137     brouard  6206:   return (0); /* with covar[new additional covariate if product] and Tage if age */ 
1.164     brouard  6207:   /*endread:*/
1.136     brouard  6208:     printf("Exiting decodemodel: ");
                   6209:     return (1);
                   6210: }
                   6211: 
1.169     brouard  6212: int calandcheckages(int imx, int maxwav, double *agemin, double *agemax, int *nberr, int *nbwarn )
1.136     brouard  6213: {
                   6214:   int i, m;
                   6215: 
                   6216:   for (i=1; i<=imx; i++) {
                   6217:     for(m=2; (m<= maxwav); m++) {
                   6218:       if (((int)mint[m][i]== 99) && (s[m][i] <= nlstate)){
                   6219:        anint[m][i]=9999;
                   6220:        s[m][i]=-1;
                   6221:       }
                   6222:       if((int)moisdc[i]==99 && (int)andc[i]==9999 && s[m][i]>nlstate){
1.169     brouard  6223:        *nberr = *nberr + 1;
                   6224:        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);
                   6225:        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  6226:        s[m][i]=-1;
                   6227:       }
                   6228:       if((int)moisdc[i]==99 && (int)andc[i]!=9999 && s[m][i]>nlstate){
1.169     brouard  6229:        (*nberr)++;
1.136     brouard  6230:        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]); 
                   6231:        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]); 
                   6232:        s[m][i]=-1; /* We prefer to skip it (and to skip it in version 0.8a1 too */
                   6233:       }
                   6234:     }
                   6235:   }
                   6236: 
                   6237:   for (i=1; i<=imx; i++)  {
                   6238:     agedc[i]=(moisdc[i]/12.+andc[i])-(moisnais[i]/12.+annais[i]);
                   6239:     for(m=firstpass; (m<= lastpass); m++){
                   6240:       if(s[m][i] >0 || s[m][i]==-2 || s[m][i]==-4 || s[m][i]==-5){
                   6241:        if (s[m][i] >= nlstate+1) {
1.169     brouard  6242:          if(agedc[i]>0){
                   6243:            if((int)moisdc[i]!=99 && (int)andc[i]!=9999){
1.136     brouard  6244:              agev[m][i]=agedc[i];
                   6245:          /*if(moisdc[i]==99 && andc[i]==9999) s[m][i]=-1;*/
1.169     brouard  6246:            }else {
1.136     brouard  6247:              if ((int)andc[i]!=9999){
                   6248:                nbwarn++;
                   6249:                printf("Warning negative age at death: %ld line:%d\n",num[i],i);
                   6250:                fprintf(ficlog,"Warning negative age at death: %ld line:%d\n",num[i],i);
                   6251:                agev[m][i]=-1;
                   6252:              }
                   6253:            }
1.169     brouard  6254:          } /* agedc > 0 */
1.136     brouard  6255:        }
                   6256:        else if(s[m][i] !=9){ /* Standard case, age in fractional
                   6257:                                 years but with the precision of a month */
                   6258:          agev[m][i]=(mint[m][i]/12.+1./24.+anint[m][i])-(moisnais[i]/12.+1./24.+annais[i]);
                   6259:          if((int)mint[m][i]==99 || (int)anint[m][i]==9999)
                   6260:            agev[m][i]=1;
                   6261:          else if(agev[m][i] < *agemin){ 
                   6262:            *agemin=agev[m][i];
                   6263:            printf(" Min anint[%d][%d]=%.2f annais[%d]=%.2f, agemin=%.2f\n",m,i,anint[m][i], i,annais[i], *agemin);
                   6264:          }
                   6265:          else if(agev[m][i] >*agemax){
                   6266:            *agemax=agev[m][i];
1.156     brouard  6267:            /* printf(" Max anint[%d][%d]=%.0f annais[%d]=%.0f, agemax=%.2f\n",m,i,anint[m][i], i,annais[i], *agemax);*/
1.136     brouard  6268:          }
                   6269:          /*agev[m][i]=anint[m][i]-annais[i];*/
                   6270:          /*     agev[m][i] = age[i]+2*m;*/
                   6271:        }
                   6272:        else { /* =9 */
                   6273:          agev[m][i]=1;
                   6274:          s[m][i]=-1;
                   6275:        }
                   6276:       }
                   6277:       else /*= 0 Unknown */
                   6278:        agev[m][i]=1;
                   6279:     }
                   6280:     
                   6281:   }
                   6282:   for (i=1; i<=imx; i++)  {
                   6283:     for(m=firstpass; (m<=lastpass); m++){
                   6284:       if (s[m][i] > (nlstate+ndeath)) {
1.169     brouard  6285:        (*nberr)++;
1.136     brouard  6286:        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);     
                   6287:        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);     
                   6288:        return 1;
                   6289:       }
                   6290:     }
                   6291:   }
                   6292: 
                   6293:   /*for (i=1; i<=imx; i++){
                   6294:   for (m=firstpass; (m<lastpass); m++){
                   6295:      printf("%ld %d %.lf %d %d\n", num[i],(covar[1][i]),agev[m][i],s[m][i],s[m+1][i]);
                   6296: }
                   6297: 
                   6298: }*/
                   6299: 
                   6300: 
1.139     brouard  6301:   printf("Total number of individuals= %d, Agemin = %.2f, Agemax= %.2f\n\n", imx, *agemin, *agemax);
                   6302:   fprintf(ficlog,"Total number of individuals= %d, Agemin = %.2f, Agemax= %.2f\n\n", imx, *agemin, *agemax); 
1.136     brouard  6303: 
                   6304:   return (0);
1.164     brouard  6305:  /* endread:*/
1.136     brouard  6306:     printf("Exiting calandcheckages: ");
                   6307:     return (1);
                   6308: }
                   6309: 
1.172     brouard  6310: #if defined(_MSC_VER)
                   6311: /*printf("Visual C++ compiler: %s \n;", _MSC_FULL_VER);*/
                   6312: /*fprintf(ficlog, "Visual C++ compiler: %s \n;", _MSC_FULL_VER);*/
                   6313: //#include "stdafx.h"
                   6314: //#include <stdio.h>
                   6315: //#include <tchar.h>
                   6316: //#include <windows.h>
                   6317: //#include <iostream>
                   6318: typedef BOOL(WINAPI *LPFN_ISWOW64PROCESS) (HANDLE, PBOOL);
                   6319: 
                   6320: LPFN_ISWOW64PROCESS fnIsWow64Process;
                   6321: 
                   6322: BOOL IsWow64()
                   6323: {
                   6324:        BOOL bIsWow64 = FALSE;
                   6325: 
                   6326:        //typedef BOOL (APIENTRY *LPFN_ISWOW64PROCESS)
                   6327:        //  (HANDLE, PBOOL);
                   6328: 
                   6329:        //LPFN_ISWOW64PROCESS fnIsWow64Process;
                   6330: 
                   6331:        HMODULE module = GetModuleHandle(_T("kernel32"));
                   6332:        const char funcName[] = "IsWow64Process";
                   6333:        fnIsWow64Process = (LPFN_ISWOW64PROCESS)
                   6334:                GetProcAddress(module, funcName);
                   6335: 
                   6336:        if (NULL != fnIsWow64Process)
                   6337:        {
                   6338:                if (!fnIsWow64Process(GetCurrentProcess(),
                   6339:                        &bIsWow64))
                   6340:                        //throw std::exception("Unknown error");
                   6341:                        printf("Unknown error\n");
                   6342:        }
                   6343:        return bIsWow64 != FALSE;
                   6344: }
                   6345: #endif
1.177     brouard  6346: 
1.191     brouard  6347: void syscompilerinfo(int logged)
1.167     brouard  6348:  {
                   6349:    /* #include "syscompilerinfo.h"*/
1.185     brouard  6350:    /* command line Intel compiler 32bit windows, XP compatible:*/
                   6351:    /* /GS /W3 /Gy
                   6352:       /Zc:wchar_t /Zi /O2 /Fd"Release\vc120.pdb" /D "WIN32" /D "NDEBUG" /D
                   6353:       "_CONSOLE" /D "_LIB" /D "_USING_V110_SDK71_" /D "_UNICODE" /D
                   6354:       "UNICODE" /Qipo /Zc:forScope /Gd /Oi /MT /Fa"Release\" /EHsc /nologo
1.186     brouard  6355:       /Fo"Release\" /Qprof-dir "Release\" /Fp"Release\IMaCh.pch"
                   6356:    */ 
                   6357:    /* 64 bits */
1.185     brouard  6358:    /*
                   6359:      /GS /W3 /Gy
                   6360:      /Zc:wchar_t /Zi /O2 /Fd"x64\Release\vc120.pdb" /D "WIN32" /D "NDEBUG"
                   6361:      /D "_CONSOLE" /D "_LIB" /D "_UNICODE" /D "UNICODE" /Qipo /Zc:forScope
                   6362:      /Oi /MD /Fa"x64\Release\" /EHsc /nologo /Fo"x64\Release\" /Qprof-dir
                   6363:      "x64\Release\" /Fp"x64\Release\IMaCh.pch" */
                   6364:    /* Optimization are useless and O3 is slower than O2 */
                   6365:    /*
                   6366:      /GS /W3 /Gy /Zc:wchar_t /Zi /O3 /Fd"x64\Release\vc120.pdb" /D "WIN32" 
                   6367:      /D "NDEBUG" /D "_CONSOLE" /D "_LIB" /D "_UNICODE" /D "UNICODE" /Qipo 
                   6368:      /Zc:forScope /Oi /MD /Fa"x64\Release\" /EHsc /nologo /Qparallel 
                   6369:      /Fo"x64\Release\" /Qprof-dir "x64\Release\" /Fp"x64\Release\IMaCh.pch" 
                   6370:    */
1.186     brouard  6371:    /* Link is */ /* /OUT:"visual studio
1.185     brouard  6372:       2013\Projects\IMaCh\Release\IMaCh.exe" /MANIFEST /NXCOMPAT
                   6373:       /PDB:"visual studio
                   6374:       2013\Projects\IMaCh\Release\IMaCh.pdb" /DYNAMICBASE
                   6375:       "kernel32.lib" "user32.lib" "gdi32.lib" "winspool.lib"
                   6376:       "comdlg32.lib" "advapi32.lib" "shell32.lib" "ole32.lib"
                   6377:       "oleaut32.lib" "uuid.lib" "odbc32.lib" "odbccp32.lib"
                   6378:       /MACHINE:X86 /OPT:REF /SAFESEH /INCREMENTAL:NO
                   6379:       /SUBSYSTEM:CONSOLE",5.01" /MANIFESTUAC:"level='asInvoker'
                   6380:       uiAccess='false'"
                   6381:       /ManifestFile:"Release\IMaCh.exe.intermediate.manifest" /OPT:ICF
                   6382:       /NOLOGO /TLBID:1
                   6383:    */
1.177     brouard  6384: #if defined __INTEL_COMPILER
1.178     brouard  6385: #if defined(__GNUC__)
                   6386:        struct utsname sysInfo;  /* For Intel on Linux and OS/X */
                   6387: #endif
1.177     brouard  6388: #elif defined(__GNUC__) 
1.179     brouard  6389: #ifndef  __APPLE__
1.174     brouard  6390: #include <gnu/libc-version.h>  /* Only on gnu */
1.179     brouard  6391: #endif
1.177     brouard  6392:    struct utsname sysInfo;
1.178     brouard  6393:    int cross = CROSS;
                   6394:    if (cross){
                   6395:           printf("Cross-");
1.191     brouard  6396:           if(logged) fprintf(ficlog, "Cross-");
1.178     brouard  6397:    }
1.174     brouard  6398: #endif
                   6399: 
1.171     brouard  6400: #include <stdint.h>
1.178     brouard  6401: 
1.191     brouard  6402:    printf("Compiled with:");if(logged)fprintf(ficlog,"Compiled with:");
1.169     brouard  6403: #if defined(__clang__)
1.191     brouard  6404:    printf(" Clang/LLVM");if(logged)fprintf(ficlog," Clang/LLVM");      /* Clang/LLVM. ---------------------------------------------- */
1.169     brouard  6405: #endif
                   6406: #if defined(__ICC) || defined(__INTEL_COMPILER)
1.191     brouard  6407:    printf(" Intel ICC/ICPC");if(logged)fprintf(ficlog," Intel ICC/ICPC");/* Intel ICC/ICPC. ------------------------------------------ */
1.169     brouard  6408: #endif
                   6409: #if defined(__GNUC__) || defined(__GNUG__)
1.191     brouard  6410:    printf(" GNU GCC/G++");if(logged)fprintf(ficlog," GNU GCC/G++");/* GNU GCC/G++. --------------------------------------------- */
1.169     brouard  6411: #endif
                   6412: #if defined(__HP_cc) || defined(__HP_aCC)
1.191     brouard  6413:    printf(" Hewlett-Packard C/aC++");if(logged)fprintf(fcilog," Hewlett-Packard C/aC++"); /* Hewlett-Packard C/aC++. ---------------------------------- */
1.169     brouard  6414: #endif
                   6415: #if defined(__IBMC__) || defined(__IBMCPP__)
1.191     brouard  6416:    printf(" IBM XL C/C++"); if(logged) fprintf(ficlog," IBM XL C/C++");/* IBM XL C/C++. -------------------------------------------- */
1.169     brouard  6417: #endif
                   6418: #if defined(_MSC_VER)
1.191     brouard  6419:    printf(" Microsoft Visual Studio");if(logged)fprintf(ficlog," Microsoft Visual Studio");/* Microsoft Visual Studio. --------------------------------- */
1.169     brouard  6420: #endif
                   6421: #if defined(__PGI)
1.191     brouard  6422:    printf(" Portland Group PGCC/PGCPP");if(logged) fprintf(ficlog," Portland Group PGCC/PGCPP");/* Portland Group PGCC/PGCPP. ------------------------------- */
1.169     brouard  6423: #endif
                   6424: #if defined(__SUNPRO_C) || defined(__SUNPRO_CC)
1.191     brouard  6425:    printf(" Oracle Solaris Studio");if(logged)fprintf(ficlog," Oracle Solaris Studio\n");/* Oracle Solaris Studio. ----------------------------------- */
1.167     brouard  6426: #endif
1.191     brouard  6427:    printf(" for "); if (logged) fprintf(ficlog, " for ");
1.169     brouard  6428:    
1.167     brouard  6429: // http://stackoverflow.com/questions/4605842/how-to-identify-platform-compiler-from-preprocessor-macros
                   6430: #ifdef _WIN32 // note the underscore: without it, it's not msdn official!
                   6431:     // Windows (x64 and x86)
1.191     brouard  6432:    printf("Windows (x64 and x86) ");if(logged) fprintf(ficlog,"Windows (x64 and x86) ");
1.167     brouard  6433: #elif __unix__ // all unices, not all compilers
                   6434:     // Unix
1.191     brouard  6435:    printf("Unix ");if(logged) fprintf(ficlog,"Unix ");
1.167     brouard  6436: #elif __linux__
                   6437:     // linux
1.191     brouard  6438:    printf("linux ");if(logged) fprintf(ficlog,"linux ");
1.167     brouard  6439: #elif __APPLE__
1.174     brouard  6440:     // Mac OS, not sure if this is covered by __posix__ and/or __unix__ though..
1.191     brouard  6441:    printf("Mac OS ");if(logged) fprintf(ficlog,"Mac OS ");
1.167     brouard  6442: #endif
                   6443: 
                   6444: /*  __MINGW32__          */
                   6445: /*  __CYGWIN__  */
                   6446: /* __MINGW64__  */
                   6447: // http://msdn.microsoft.com/en-us/library/b0084kay.aspx
                   6448: /* _MSC_VER  //the Visual C++ compiler is 17.00.51106.1, the _MSC_VER macro evaluates to 1700. Type cl /?  */
                   6449: /* _MSC_FULL_VER //the Visual C++ compiler is 15.00.20706.01, the _MSC_FULL_VER macro evaluates to 150020706 */
                   6450: /* _WIN64  // Defined for applications for Win64. */
                   6451: /* _M_X64 // Defined for compilations that target x64 processors. */
                   6452: /* _DEBUG // Defined when you compile with /LDd, /MDd, and /MTd. */
1.171     brouard  6453: 
1.167     brouard  6454: #if UINTPTR_MAX == 0xffffffff
1.191     brouard  6455:    printf(" 32-bit"); if(logged) fprintf(ficlog," 32-bit");/* 32-bit */
1.167     brouard  6456: #elif UINTPTR_MAX == 0xffffffffffffffff
1.191     brouard  6457:    printf(" 64-bit"); if(logged) fprintf(ficlog," 64-bit");/* 64-bit */
1.167     brouard  6458: #else
1.191     brouard  6459:    printf(" wtf-bit"); if(logged) fprintf(ficlog," wtf-bit");/* wtf */
1.167     brouard  6460: #endif
                   6461: 
1.169     brouard  6462: #if defined(__GNUC__)
                   6463: # if defined(__GNUC_PATCHLEVEL__)
                   6464: #  define __GNUC_VERSION__ (__GNUC__ * 10000 \
                   6465:                             + __GNUC_MINOR__ * 100 \
                   6466:                             + __GNUC_PATCHLEVEL__)
                   6467: # else
                   6468: #  define __GNUC_VERSION__ (__GNUC__ * 10000 \
                   6469:                             + __GNUC_MINOR__ * 100)
                   6470: # endif
1.174     brouard  6471:    printf(" using GNU C version %d.\n", __GNUC_VERSION__);
1.191     brouard  6472:    if(logged) fprintf(ficlog, " using GNU C version %d.\n", __GNUC_VERSION__);
1.176     brouard  6473: 
                   6474:    if (uname(&sysInfo) != -1) {
                   6475:      printf("Running on: %s %s %s %s %s\n",sysInfo.sysname, sysInfo.nodename, sysInfo.release, sysInfo.version, sysInfo.machine);
1.191     brouard  6476:         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  6477:    }
                   6478:    else
                   6479:       perror("uname() error");
1.179     brouard  6480:    //#ifndef __INTEL_COMPILER 
                   6481: #if !defined (__INTEL_COMPILER) && !defined(__APPLE__)
1.174     brouard  6482:    printf("GNU libc version: %s\n", gnu_get_libc_version()); 
1.191     brouard  6483:    if(logged) fprintf(ficlog,"GNU libc version: %s\n", gnu_get_libc_version());
1.177     brouard  6484: #endif
1.169     brouard  6485: #endif
1.172     brouard  6486: 
                   6487:    //   void main()
                   6488:    //   {
1.169     brouard  6489: #if defined(_MSC_VER)
1.174     brouard  6490:    if (IsWow64()){
1.191     brouard  6491:           printf("\nThe program (probably compiled for 32bit) is running under WOW64 (64bit) emulation.\n");
                   6492:           if (logged) fprintf(ficlog, "\nThe program (probably compiled for 32bit) is running under WOW64 (64bit) emulation.\n");
1.174     brouard  6493:    }
                   6494:    else{
1.191     brouard  6495:           printf("\nThe program is not running under WOW64 (i.e probably on a 64bit Windows).\n");
                   6496:           if (logged) fprintf(ficlog, "\nThe programm is not running under WOW64 (i.e probably on a 64bit Windows).\n");
1.174     brouard  6497:    }
1.172     brouard  6498:    //     printf("\nPress Enter to continue...");
                   6499:    //     getchar();
                   6500:    //   }
                   6501: 
1.169     brouard  6502: #endif
                   6503:    
1.167     brouard  6504: 
                   6505:  }
1.136     brouard  6506: 
1.203     brouard  6507:  int prevalence_limit(double *p, double **prlim, double ageminpar, double agemaxpar, double ftolpl, int *ncvyear){
1.180     brouard  6508:   /*--------------- Prevalence limit  (period or stable prevalence) --------------*/
                   6509:   int i, j, k, i1 ;
1.202     brouard  6510:   /* double ftolpl = 1.e-10; */
1.180     brouard  6511:   double age, agebase, agelim;
1.203     brouard  6512:   double tot;
1.180     brouard  6513: 
1.202     brouard  6514:   strcpy(filerespl,"PL_");
                   6515:   strcat(filerespl,fileresu);
                   6516:   if((ficrespl=fopen(filerespl,"w"))==NULL) {
                   6517:     printf("Problem with period (stable) prevalence resultfile: %s\n", filerespl);return 1;
                   6518:     fprintf(ficlog,"Problem with period (stable) prevalence resultfile: %s\n", filerespl);return 1;
                   6519:   }
                   6520:   printf("Computing period (stable) prevalence: result on file '%s' \n", filerespl);
                   6521:   fprintf(ficlog,"Computing period (stable) prevalence: result on file '%s' \n", filerespl);
                   6522:   pstamp(ficrespl);
1.203     brouard  6523:   fprintf(ficrespl,"# Period (stable) prevalence. Precision given by ftolpl=%g \n", ftolpl);
1.202     brouard  6524:   fprintf(ficrespl,"#Age ");
                   6525:   for(i=1; i<=nlstate;i++) fprintf(ficrespl,"%d-%d ",i,i);
                   6526:   fprintf(ficrespl,"\n");
1.180     brouard  6527:   
                   6528:     /* prlim=matrix(1,nlstate,1,nlstate);*/ /* back in main */
                   6529: 
                   6530:     agebase=ageminpar;
                   6531:     agelim=agemaxpar;
                   6532: 
                   6533:     i1=pow(2,cptcoveff);
                   6534:     if (cptcovn < 1){i1=1;}
                   6535: 
                   6536:     for(cptcov=1,k=0;cptcov<=i1;cptcov++){
                   6537:     /* for(cptcov=1,k=0;cptcov<=1;cptcov++){ */
                   6538:       //for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){
                   6539:        k=k+1;
                   6540:        /* to clean */
1.198     brouard  6541:        //printf("cptcov=%d cptcod=%d codtab=%d\n",cptcov, cptcod,codtabm(cptcod,cptcov));
1.200     brouard  6542:        fprintf(ficrespl,"#******");
                   6543:        printf("#******");
                   6544:        fprintf(ficlog,"#******");
1.180     brouard  6545:        for(j=1;j<=cptcoveff;j++) {
1.198     brouard  6546:          fprintf(ficrespl," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
                   6547:          printf(" V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
                   6548:          fprintf(ficlog," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
1.180     brouard  6549:        }
                   6550:        fprintf(ficrespl,"******\n");
                   6551:        printf("******\n");
                   6552:        fprintf(ficlog,"******\n");
                   6553: 
                   6554:        fprintf(ficrespl,"#Age ");
                   6555:        for(j=1;j<=cptcoveff;j++) {
1.200     brouard  6556:          fprintf(ficrespl,"V%d %d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
1.180     brouard  6557:        }
1.203     brouard  6558:        for(i=1; i<=nlstate;i++) fprintf(ficrespl,"  %d-%d   ",i,i);
                   6559:        fprintf(ficrespl,"Total Years_to_converge\n");
1.180     brouard  6560:        
                   6561:        for (age=agebase; age<=agelim; age++){
                   6562:        /* for (age=agebase; age<=agebase; age++){ */
1.203     brouard  6563:          prevalim(prlim, nlstate, p, age, oldm, savm, ftolpl, ncvyear, k);
1.180     brouard  6564:          fprintf(ficrespl,"%.0f ",age );
                   6565:          for(j=1;j<=cptcoveff;j++)
1.198     brouard  6566:            fprintf(ficrespl,"%d %d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
1.203     brouard  6567:          tot=0.;
                   6568:          for(i=1; i<=nlstate;i++){
                   6569:            tot +=  prlim[i][i];
1.180     brouard  6570:            fprintf(ficrespl," %.5f", prlim[i][i]);
1.203     brouard  6571:          }
                   6572:          fprintf(ficrespl," %.3f %d\n", tot, *ncvyear);
1.180     brouard  6573:        } /* Age */
                   6574:        /* was end of cptcod */
                   6575:     } /* cptcov */
1.184     brouard  6576:        return 0;
1.180     brouard  6577: }
                   6578: 
                   6579: int hPijx(double *p, int bage, int fage){
                   6580:     /*------------- h Pij x at various ages ------------*/
                   6581: 
                   6582:   int stepsize;
                   6583:   int agelim;
                   6584:   int hstepm;
                   6585:   int nhstepm;
                   6586:   int h, i, i1, j, k;
                   6587: 
                   6588:   double agedeb;
                   6589:   double ***p3mat;
                   6590: 
1.201     brouard  6591:     strcpy(filerespij,"PIJ_");  strcat(filerespij,fileresu);
1.180     brouard  6592:     if((ficrespij=fopen(filerespij,"w"))==NULL) {
                   6593:       printf("Problem with Pij resultfile: %s\n", filerespij); return 1;
                   6594:       fprintf(ficlog,"Problem with Pij resultfile: %s\n", filerespij); return 1;
                   6595:     }
                   6596:     printf("Computing pij: result on file '%s' \n", filerespij);
                   6597:     fprintf(ficlog,"Computing pij: result on file '%s' \n", filerespij);
                   6598:   
                   6599:     stepsize=(int) (stepm+YEARM-1)/YEARM;
                   6600:     /*if (stepm<=24) stepsize=2;*/
                   6601: 
                   6602:     agelim=AGESUP;
                   6603:     hstepm=stepsize*YEARM; /* Every year of age */
                   6604:     hstepm=hstepm/stepm; /* Typically 2 years, = 2/6 months = 4 */ 
                   6605: 
                   6606:     /* hstepm=1;   aff par mois*/
                   6607:     pstamp(ficrespij);
                   6608:     fprintf(ficrespij,"#****** h Pij x Probability to be in state j at age x+h being in i at x ");
                   6609:     i1= pow(2,cptcoveff);
1.183     brouard  6610:    /* for(cptcov=1,k=0;cptcov<=i1;cptcov++){ */
                   6611:    /*    /\*for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){*\/ */
                   6612:    /*          k=k+1;  */
                   6613:     for (k=1; k <= (int) pow(2,cptcoveff); k++){
                   6614:       fprintf(ficrespij,"\n#****** ");
                   6615:       for(j=1;j<=cptcoveff;j++) 
1.198     brouard  6616:        fprintf(ficrespij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
1.183     brouard  6617:       fprintf(ficrespij,"******\n");
                   6618:       
                   6619:       for (agedeb=fage; agedeb>=bage; agedeb--){ /* If stepm=6 months */
                   6620:        nhstepm=(int) rint((agelim-agedeb)*YEARM/stepm); /* Typically 20 years = 20*12/6=40 */ 
                   6621:        nhstepm = nhstepm/hstepm; /* Typically 40/4=10 */
                   6622:        
                   6623:        /*        nhstepm=nhstepm*YEARM; aff par mois*/
1.180     brouard  6624:        
1.183     brouard  6625:        p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   6626:        oldm=oldms;savm=savms;
                   6627:        hpxij(p3mat,nhstepm,agedeb,hstepm,p,nlstate,stepm,oldm,savm, k);  
                   6628:        fprintf(ficrespij,"# Cov Agex agex+h hpijx with i,j=");
                   6629:        for(i=1; i<=nlstate;i++)
                   6630:          for(j=1; j<=nlstate+ndeath;j++)
                   6631:            fprintf(ficrespij," %1d-%1d",i,j);
                   6632:        fprintf(ficrespij,"\n");
                   6633:        for (h=0; h<=nhstepm; h++){
                   6634:          /*agedebphstep = agedeb + h*hstepm/YEARM*stepm;*/
                   6635:          fprintf(ficrespij,"%d %3.f %3.f",k, agedeb, agedeb + h*hstepm/YEARM*stepm );
1.180     brouard  6636:          for(i=1; i<=nlstate;i++)
                   6637:            for(j=1; j<=nlstate+ndeath;j++)
1.183     brouard  6638:              fprintf(ficrespij," %.5f", p3mat[i][j][h]);
1.180     brouard  6639:          fprintf(ficrespij,"\n");
                   6640:        }
1.183     brouard  6641:        free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   6642:        fprintf(ficrespij,"\n");
                   6643:       }
1.180     brouard  6644:       /*}*/
                   6645:     }
1.184     brouard  6646:        return 0;
1.180     brouard  6647: }
                   6648: 
                   6649: 
1.136     brouard  6650: /***********************************************/
                   6651: /**************** Main Program *****************/
                   6652: /***********************************************/
                   6653: 
                   6654: int main(int argc, char *argv[])
                   6655: {
                   6656: #ifdef GSL
                   6657:   const gsl_multimin_fminimizer_type *T;
                   6658:   size_t iteri = 0, it;
                   6659:   int rval = GSL_CONTINUE;
                   6660:   int status = GSL_SUCCESS;
                   6661:   double ssval;
                   6662: #endif
                   6663:   int movingaverage(double ***probs, double bage,double fage, double ***mobaverage, int mobilav);
1.164     brouard  6664:   int i,j, k, n=MAXN,iter=0,m,size=100, cptcod;
1.203     brouard  6665:   int ncvyearnp=0;
                   6666:   int *ncvyear=&ncvyearnp; /* Number of years needed for the period prevalence to converge */
1.164     brouard  6667:   int jj, ll, li, lj, lk;
1.136     brouard  6668:   int numlinepar=0; /* Current linenumber of parameter file */
1.197     brouard  6669:   int num_filled;
1.136     brouard  6670:   int itimes;
                   6671:   int NDIM=2;
                   6672:   int vpopbased=0;
                   6673: 
1.164     brouard  6674:   char ca[32], cb[32];
1.136     brouard  6675:   /*  FILE *fichtm; *//* Html File */
                   6676:   /* FILE *ficgp;*/ /*Gnuplot File */
                   6677:   struct stat info;
1.191     brouard  6678:   double agedeb=0.;
1.194     brouard  6679: 
                   6680:   double ageminpar=AGEOVERFLOW,agemin=AGEOVERFLOW, agemaxpar=-AGEOVERFLOW, agemax=-AGEOVERFLOW;
1.136     brouard  6681: 
1.165     brouard  6682:   double fret;
1.191     brouard  6683:   double dum=0.; /* Dummy variable */
1.136     brouard  6684:   double ***p3mat;
                   6685:   double ***mobaverage;
1.164     brouard  6686: 
                   6687:   char line[MAXLINE];
1.197     brouard  6688:   char path[MAXLINE],pathc[MAXLINE],pathcd[MAXLINE],pathtot[MAXLINE];
                   6689: 
                   6690:   char model[MAXLINE], modeltemp[MAXLINE];
1.136     brouard  6691:   char pathr[MAXLINE], pathimach[MAXLINE]; 
1.164     brouard  6692:   char *tok, *val; /* pathtot */
1.136     brouard  6693:   int firstobs=1, lastobs=10;
1.195     brouard  6694:   int c,  h , cpt, c2;
1.191     brouard  6695:   int jl=0;
                   6696:   int i1, j1, jk, stepsize=0;
1.194     brouard  6697:   int count=0;
                   6698: 
1.164     brouard  6699:   int *tab; 
1.136     brouard  6700:   int mobilavproj=0 , prevfcast=0 ; /* moving average of prev, If prevfcast=1 prevalence projection */
                   6701:   int mobilav=0,popforecast=0;
1.191     brouard  6702:   int hstepm=0, nhstepm=0;
1.136     brouard  6703:   int agemortsup;
                   6704:   float  sumlpop=0.;
                   6705:   double jprev1=1, mprev1=1,anprev1=2000,jprev2=1, mprev2=1,anprev2=2000;
                   6706:   double jpyram=1, mpyram=1,anpyram=2000,jpyram1=1, mpyram1=1,anpyram1=2000;
                   6707: 
1.191     brouard  6708:   double bage=0, fage=110., age, agelim=0., agebase=0.;
1.136     brouard  6709:   double ftolpl=FTOL;
                   6710:   double **prlim;
                   6711:   double ***param; /* Matrix of parameters */
                   6712:   double  *p;
                   6713:   double **matcov; /* Matrix of covariance */
1.203     brouard  6714:   double **hess; /* Hessian matrix */
1.136     brouard  6715:   double ***delti3; /* Scale */
                   6716:   double *delti; /* Scale */
                   6717:   double ***eij, ***vareij;
                   6718:   double **varpl; /* Variances of prevalence limits by age */
                   6719:   double *epj, vepp;
1.164     brouard  6720: 
1.136     brouard  6721:   double dateprev1, dateprev2,jproj1=1,mproj1=1,anproj1=2000,jproj2=1,mproj2=1,anproj2=2000;
                   6722:   double **ximort;
1.145     brouard  6723:   char *alph[]={"a","a","b","c","d","e"}, str[4]="1234";
1.136     brouard  6724:   int *dcwave;
                   6725: 
1.164     brouard  6726:   char z[1]="c";
1.136     brouard  6727: 
                   6728:   /*char  *strt;*/
                   6729:   char strtend[80];
1.126     brouard  6730: 
1.164     brouard  6731: 
1.126     brouard  6732: /*   setlocale (LC_ALL, ""); */
                   6733: /*   bindtextdomain (PACKAGE, LOCALEDIR); */
                   6734: /*   textdomain (PACKAGE); */
                   6735: /*   setlocale (LC_CTYPE, ""); */
                   6736: /*   setlocale (LC_MESSAGES, ""); */
                   6737: 
                   6738:   /*   gettimeofday(&start_time, (struct timezone*)0); */ /* at first time */
1.157     brouard  6739:   rstart_time = time(NULL);  
                   6740:   /*  (void) gettimeofday(&start_time,&tzp);*/
                   6741:   start_time = *localtime(&rstart_time);
1.126     brouard  6742:   curr_time=start_time;
1.157     brouard  6743:   /*tml = *localtime(&start_time.tm_sec);*/
                   6744:   /* strcpy(strstart,asctime(&tml)); */
                   6745:   strcpy(strstart,asctime(&start_time));
1.126     brouard  6746: 
                   6747: /*  printf("Localtime (at start)=%s",strstart); */
1.157     brouard  6748: /*  tp.tm_sec = tp.tm_sec +86400; */
                   6749: /*  tm = *localtime(&start_time.tm_sec); */
1.126     brouard  6750: /*   tmg.tm_year=tmg.tm_year +dsign*dyear; */
                   6751: /*   tmg.tm_mon=tmg.tm_mon +dsign*dmonth; */
                   6752: /*   tmg.tm_hour=tmg.tm_hour + 1; */
1.157     brouard  6753: /*   tp.tm_sec = mktime(&tmg); */
1.126     brouard  6754: /*   strt=asctime(&tmg); */
                   6755: /*   printf("Time(after) =%s",strstart);  */
                   6756: /*  (void) time (&time_value);
                   6757: *  printf("time=%d,t-=%d\n",time_value,time_value-86400);
                   6758: *  tm = *localtime(&time_value);
                   6759: *  strstart=asctime(&tm);
                   6760: *  printf("tim_value=%d,asctime=%s\n",time_value,strstart); 
                   6761: */
                   6762: 
                   6763:   nberr=0; /* Number of errors and warnings */
                   6764:   nbwarn=0;
1.184     brouard  6765: #ifdef WIN32
                   6766:   _getcwd(pathcd, size);
                   6767: #else
1.126     brouard  6768:   getcwd(pathcd, size);
1.184     brouard  6769: #endif
1.191     brouard  6770:   syscompilerinfo(0);
1.196     brouard  6771:   printf("\nIMaCh version %s, %s\n%s",version, copyright, fullversion);
1.126     brouard  6772:   if(argc <=1){
                   6773:     printf("\nEnter the parameter file name: ");
1.205     brouard  6774:     if(!fgets(pathr,FILENAMELENGTH,stdin)){
                   6775:       printf("ERROR Empty parameter file name\n");
                   6776:       goto end;
                   6777:     }
1.126     brouard  6778:     i=strlen(pathr);
                   6779:     if(pathr[i-1]=='\n')
                   6780:       pathr[i-1]='\0';
1.156     brouard  6781:     i=strlen(pathr);
1.205     brouard  6782:     if(i >= 1 && pathr[i-1]==' ') {/* This may happen when dragging on oS/X! */
1.156     brouard  6783:       pathr[i-1]='\0';
1.205     brouard  6784:     }
                   6785:     i=strlen(pathr);
                   6786:     if( i==0 ){
                   6787:       printf("ERROR Empty parameter file name\n");
                   6788:       goto end;
                   6789:     }
                   6790:     for (tok = pathr; tok != NULL; ){
1.126     brouard  6791:       printf("Pathr |%s|\n",pathr);
                   6792:       while ((val = strsep(&tok, "\"" )) != NULL && *val == '\0');
                   6793:       printf("val= |%s| pathr=%s\n",val,pathr);
                   6794:       strcpy (pathtot, val);
                   6795:       if(pathr[0] == '\0') break; /* Dirty */
                   6796:     }
                   6797:   }
                   6798:   else{
                   6799:     strcpy(pathtot,argv[1]);
                   6800:   }
                   6801:   /*if(getcwd(pathcd, MAXLINE)!= NULL)printf ("Error pathcd\n");*/
                   6802:   /*cygwin_split_path(pathtot,path,optionfile);
                   6803:     printf("pathtot=%s, path=%s, optionfile=%s\n",pathtot,path,optionfile);*/
                   6804:   /* cutv(path,optionfile,pathtot,'\\');*/
                   6805: 
                   6806:   /* Split argv[0], imach program to get pathimach */
                   6807:   printf("\nargv[0]=%s argv[1]=%s, \n",argv[0],argv[1]);
                   6808:   split(argv[0],pathimach,optionfile,optionfilext,optionfilefiname);
                   6809:   printf("\nargv[0]=%s pathimach=%s, \noptionfile=%s \noptionfilext=%s \noptionfilefiname=%s\n",argv[0],pathimach,optionfile,optionfilext,optionfilefiname);
                   6810:  /*   strcpy(pathimach,argv[0]); */
                   6811:   /* Split argv[1]=pathtot, parameter file name to get path, optionfile, extension and name */
                   6812:   split(pathtot,path,optionfile,optionfilext,optionfilefiname);
                   6813:   printf("\npathtot=%s,\npath=%s,\noptionfile=%s \noptionfilext=%s \noptionfilefiname=%s\n",pathtot,path,optionfile,optionfilext,optionfilefiname);
1.184     brouard  6814: #ifdef WIN32
                   6815:   _chdir(path); /* Can be a relative path */
                   6816:   if(_getcwd(pathcd,MAXLINE) > 0) /* So pathcd is the full path */
                   6817: #else
1.126     brouard  6818:   chdir(path); /* Can be a relative path */
1.184     brouard  6819:   if (getcwd(pathcd, MAXLINE) > 0) /* So pathcd is the full path */
                   6820: #endif
                   6821:   printf("Current directory %s!\n",pathcd);
1.126     brouard  6822:   strcpy(command,"mkdir ");
                   6823:   strcat(command,optionfilefiname);
                   6824:   if((outcmd=system(command)) != 0){
1.169     brouard  6825:     printf("Directory already exists (or can't create it) %s%s, err=%d\n",path,optionfilefiname,outcmd);
1.126     brouard  6826:     /* fprintf(ficlog,"Problem creating directory %s%s\n",path,optionfilefiname); */
                   6827:     /* fclose(ficlog); */
                   6828: /*     exit(1); */
                   6829:   }
                   6830: /*   if((imk=mkdir(optionfilefiname))<0){ */
                   6831: /*     perror("mkdir"); */
                   6832: /*   } */
                   6833: 
                   6834:   /*-------- arguments in the command line --------*/
                   6835: 
1.186     brouard  6836:   /* Main Log file */
1.126     brouard  6837:   strcat(filelog, optionfilefiname);
                   6838:   strcat(filelog,".log");    /* */
                   6839:   if((ficlog=fopen(filelog,"w"))==NULL)    {
                   6840:     printf("Problem with logfile %s\n",filelog);
                   6841:     goto end;
                   6842:   }
                   6843:   fprintf(ficlog,"Log filename:%s\n",filelog);
1.197     brouard  6844:   fprintf(ficlog,"Version %s %s",version,fullversion);
1.126     brouard  6845:   fprintf(ficlog,"\nEnter the parameter file name: \n");
                   6846:   fprintf(ficlog,"pathimach=%s\npathtot=%s\n\
                   6847:  path=%s \n\
                   6848:  optionfile=%s\n\
                   6849:  optionfilext=%s\n\
1.156     brouard  6850:  optionfilefiname='%s'\n",pathimach,pathtot,path,optionfile,optionfilext,optionfilefiname);
1.126     brouard  6851: 
1.197     brouard  6852:   syscompilerinfo(1);
1.167     brouard  6853: 
1.126     brouard  6854:   printf("Local time (at start):%s",strstart);
                   6855:   fprintf(ficlog,"Local time (at start): %s",strstart);
                   6856:   fflush(ficlog);
                   6857: /*   (void) gettimeofday(&curr_time,&tzp); */
1.157     brouard  6858: /*   printf("Elapsed time %d\n", asc_diff_time(curr_time.tm_sec-start_time.tm_sec,tmpout)); */
1.126     brouard  6859: 
                   6860:   /* */
                   6861:   strcpy(fileres,"r");
                   6862:   strcat(fileres, optionfilefiname);
1.201     brouard  6863:   strcat(fileresu, optionfilefiname); /* Without r in front */
1.126     brouard  6864:   strcat(fileres,".txt");    /* Other files have txt extension */
1.201     brouard  6865:   strcat(fileresu,".txt");    /* Other files have txt extension */
1.126     brouard  6866: 
1.186     brouard  6867:   /* Main ---------arguments file --------*/
1.126     brouard  6868: 
                   6869:   if((ficpar=fopen(optionfile,"r"))==NULL)    {
1.155     brouard  6870:     printf("Problem with optionfile '%s' with errno='%s'\n",optionfile,strerror(errno));
                   6871:     fprintf(ficlog,"Problem with optionfile '%s' with errno='%s'\n",optionfile,strerror(errno));
1.126     brouard  6872:     fflush(ficlog);
1.149     brouard  6873:     /* goto end; */
                   6874:     exit(70); 
1.126     brouard  6875:   }
                   6876: 
                   6877: 
                   6878: 
                   6879:   strcpy(filereso,"o");
1.201     brouard  6880:   strcat(filereso,fileresu);
1.126     brouard  6881:   if((ficparo=fopen(filereso,"w"))==NULL) { /* opened on subdirectory */
                   6882:     printf("Problem with Output resultfile: %s\n", filereso);
                   6883:     fprintf(ficlog,"Problem with Output resultfile: %s\n", filereso);
                   6884:     fflush(ficlog);
                   6885:     goto end;
                   6886:   }
                   6887: 
                   6888:   /* Reads comments: lines beginning with '#' */
                   6889:   numlinepar=0;
1.197     brouard  6890: 
                   6891:     /* First parameter line */
                   6892:   while(fgets(line, MAXLINE, ficpar)) {
                   6893:     /* If line starts with a # it is a comment */
                   6894:     if (line[0] == '#') {
                   6895:       numlinepar++;
                   6896:       fputs(line,stdout);
                   6897:       fputs(line,ficparo);
                   6898:       fputs(line,ficlog);
                   6899:       continue;
                   6900:     }else
                   6901:       break;
                   6902:   }
                   6903:   if((num_filled=sscanf(line,"title=%s datafile=%s lastobs=%d firstpass=%d lastpass=%d\n", \
                   6904:                        title, datafile, &lastobs, &firstpass,&lastpass)) !=EOF){
                   6905:     if (num_filled != 5) {
                   6906:       printf("Should be 5 parameters\n");
                   6907:     }
1.126     brouard  6908:     numlinepar++;
1.197     brouard  6909:     printf("title=%s datafile=%s lastobs=%d firstpass=%d lastpass=%d\n", title, datafile, lastobs, firstpass,lastpass);
                   6910:   }
                   6911:   /* Second parameter line */
                   6912:   while(fgets(line, MAXLINE, ficpar)) {
                   6913:     /* If line starts with a # it is a comment */
                   6914:     if (line[0] == '#') {
                   6915:       numlinepar++;
                   6916:       fputs(line,stdout);
                   6917:       fputs(line,ficparo);
                   6918:       fputs(line,ficlog);
                   6919:       continue;
                   6920:     }else
                   6921:       break;
                   6922:   }
                   6923:   if((num_filled=sscanf(line,"ftol=%lf stepm=%d ncovcol=%d nlstate=%d ndeath=%d maxwav=%d mle=%d weight=%d\n", \
                   6924:                        &ftol, &stepm, &ncovcol, &nlstate, &ndeath, &maxwav, &mle, &weightopt)) !=EOF){
                   6925:     if (num_filled != 8) {
                   6926:       printf("Not 8\n");
                   6927:     }
                   6928:     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  6929:   }
1.203     brouard  6930:   /* ftolpl=6*ftol*1.e5; /\* 6.e-3 make convergences in less than 80 loops for the prevalence limit *\/ */
                   6931:   ftolpl=6.e-3; /* 6.e-3 make convergences in less than 80 loops for the prevalence limit */
1.197     brouard  6932:   /* Third parameter line */
                   6933:   while(fgets(line, MAXLINE, ficpar)) {
                   6934:     /* If line starts with a # it is a comment */
                   6935:     if (line[0] == '#') {
                   6936:       numlinepar++;
                   6937:       fputs(line,stdout);
                   6938:       fputs(line,ficparo);
                   6939:       fputs(line,ficlog);
                   6940:       continue;
                   6941:     }else
                   6942:       break;
                   6943:   }
1.201     brouard  6944:   if((num_filled=sscanf(line,"model=1+age%[^.\n]", model)) !=EOF){
                   6945:     if (num_filled == 0)
                   6946:             model[0]='\0';
                   6947:     else if (num_filled != 1){
1.197     brouard  6948:       printf("ERROR %d: Model should be at minimum 'model=1+age.' %s\n",num_filled, line);
                   6949:       fprintf(ficlog,"ERROR %d: Model should be at minimum 'model=1+age.' %s\n",num_filled, line);
                   6950:       model[0]='\0';
                   6951:       goto end;
                   6952:     }
                   6953:     else{
                   6954:       if (model[0]=='+'){
                   6955:        for(i=1; i<=strlen(model);i++)
                   6956:          modeltemp[i-1]=model[i];
1.201     brouard  6957:        strcpy(model,modeltemp); 
1.197     brouard  6958:       }
                   6959:     }
1.199     brouard  6960:     /* printf(" model=1+age%s modeltemp= %s, model=%s\n",model, modeltemp, model);fflush(stdout); */
1.203     brouard  6961:     printf("model=1+age+%s\n",model);fflush(stdout);
1.197     brouard  6962:   }
                   6963:   /* 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); */
                   6964:   /* numlinepar=numlinepar+3; /\* In general *\/ */
                   6965:   /* 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  6966:   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);
                   6967:   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  6968:   fflush(ficlog);
1.190     brouard  6969:   /* if(model[0]=='#'|| model[0]== '\0'){ */
                   6970:   if(model[0]=='#'){
1.187     brouard  6971:     printf("Error in 'model' line: model should start with 'model=1+age+' and end with '.' \n \
                   6972:  'model=1+age+.' or 'model=1+age+V1.' or 'model=1+age+age*age+V1+V1*age.' or \n \
                   6973:  'model=1+age+V1+V2.' or 'model=1+age+V1+V2+V1*V2.' etc. \n");         \
                   6974:     if(mle != -1){
                   6975:       printf("Fix the model line and run imach with mle=-1 to get a correct template of the parameter file.\n");
                   6976:       exit(1);
                   6977:     }
                   6978:   }
1.126     brouard  6979:   while((c=getc(ficpar))=='#' && c!= EOF){
                   6980:     ungetc(c,ficpar);
                   6981:     fgets(line, MAXLINE, ficpar);
                   6982:     numlinepar++;
1.195     brouard  6983:     if(line[1]=='q'){ /* This #q will quit imach (the answer is q) */
                   6984:       z[0]=line[1];
                   6985:     }
                   6986:     /* printf("****line [1] = %c \n",line[1]); */
1.141     brouard  6987:     fputs(line, stdout);
                   6988:     //puts(line);
1.126     brouard  6989:     fputs(line,ficparo);
                   6990:     fputs(line,ficlog);
                   6991:   }
                   6992:   ungetc(c,ficpar);
                   6993: 
                   6994:    
1.145     brouard  6995:   covar=matrix(0,NCOVMAX,1,n);  /**< used in readdata */
1.136     brouard  6996:   cptcovn=0; /*Number of covariates, i.e. number of '+' in model statement plus one, indepently of n in Vn*/
                   6997:   /* v1+v2+v3+v2*v4+v5*age makes cptcovn = 5
                   6998:      v1+v2*age+v2*v3 makes cptcovn = 3
                   6999:   */
                   7000:   if (strlen(model)>1) 
1.187     brouard  7001:     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  7002:   else
1.187     brouard  7003:     ncovmodel=2; /* Constant and age */
1.133     brouard  7004:   nforce= (nlstate+ndeath-1)*nlstate; /* Number of forces ij from state i to j */
                   7005:   npar= nforce*ncovmodel; /* Number of parameters like aij*/
1.131     brouard  7006:   if(npar >MAXPARM || nlstate >NLSTATEMAX || ndeath >NDEATHMAX || ncovmodel>NCOVMAX){
                   7007:     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);
                   7008:     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);
                   7009:     fflush(stdout);
                   7010:     fclose (ficlog);
                   7011:     goto end;
                   7012:   }
1.126     brouard  7013:   delti3= ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel);
                   7014:   delti=delti3[1][1];
                   7015:   /*delti=vector(1,npar); *//* Scale of each paramater (output from hesscov)*/
                   7016:   if(mle==-1){ /* Print a wizard for help writing covariance matrix */
                   7017:     prwizard(ncovmodel, nlstate, ndeath, model, ficparo);
1.191     brouard  7018:     printf(" You chose mle=-1, look at file %s for a template of covariance matrix \n",filereso);
                   7019:     fprintf(ficlog," You chose mle=-1, look at file %s for a template of covariance matrix \n",filereso);
1.126     brouard  7020:     free_ma3x(delti3,1,nlstate,1, nlstate+ndeath-1,1,ncovmodel); 
                   7021:     fclose (ficparo);
                   7022:     fclose (ficlog);
                   7023:     goto end;
                   7024:     exit(0);
                   7025:   }
1.186     brouard  7026:   else if(mle==-3) { /* Main Wizard */
1.126     brouard  7027:     prwizard(ncovmodel, nlstate, ndeath, model, ficparo);
1.192     brouard  7028:     printf(" You chose mle=-3, look at file %s for a template of covariance matrix \n",filereso);
                   7029:     fprintf(ficlog," You chose mle=-3, look at file %s for a template of covariance matrix \n",filereso);
1.126     brouard  7030:     param= ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel);
                   7031:     matcov=matrix(1,npar,1,npar);
1.203     brouard  7032:     hess=matrix(1,npar,1,npar);
1.126     brouard  7033:   }
                   7034:   else{
1.145     brouard  7035:     /* Read guessed parameters */
1.126     brouard  7036:     /* Reads comments: lines beginning with '#' */
                   7037:     while((c=getc(ficpar))=='#' && c!= EOF){
                   7038:       ungetc(c,ficpar);
                   7039:       fgets(line, MAXLINE, ficpar);
                   7040:       numlinepar++;
1.141     brouard  7041:       fputs(line,stdout);
1.126     brouard  7042:       fputs(line,ficparo);
                   7043:       fputs(line,ficlog);
                   7044:     }
                   7045:     ungetc(c,ficpar);
                   7046:     
                   7047:     param= ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel);
                   7048:     for(i=1; i <=nlstate; i++){
                   7049:       j=0;
                   7050:       for(jj=1; jj <=nlstate+ndeath; jj++){
                   7051:        if(jj==i) continue;
                   7052:        j++;
                   7053:        fscanf(ficpar,"%1d%1d",&i1,&j1);
1.193     brouard  7054:        if ((i1 != i) || (j1 != jj)){
1.126     brouard  7055:          printf("Error in line parameters number %d, %1d%1d instead of %1d%1d \n \
                   7056: It might be a problem of design; if ncovcol and the model are correct\n \
                   7057: run imach with mle=-1 to get a correct template of the parameter file.\n",numlinepar, i,j, i1, j1);
                   7058:          exit(1);
                   7059:        }
                   7060:        fprintf(ficparo,"%1d%1d",i1,j1);
                   7061:        if(mle==1)
1.193     brouard  7062:          printf("%1d%1d",i,jj);
                   7063:        fprintf(ficlog,"%1d%1d",i,jj);
1.126     brouard  7064:        for(k=1; k<=ncovmodel;k++){
                   7065:          fscanf(ficpar," %lf",&param[i][j][k]);
                   7066:          if(mle==1){
                   7067:            printf(" %lf",param[i][j][k]);
                   7068:            fprintf(ficlog," %lf",param[i][j][k]);
                   7069:          }
                   7070:          else
                   7071:            fprintf(ficlog," %lf",param[i][j][k]);
                   7072:          fprintf(ficparo," %lf",param[i][j][k]);
                   7073:        }
                   7074:        fscanf(ficpar,"\n");
                   7075:        numlinepar++;
                   7076:        if(mle==1)
                   7077:          printf("\n");
                   7078:        fprintf(ficlog,"\n");
                   7079:        fprintf(ficparo,"\n");
                   7080:       }
                   7081:     }  
                   7082:     fflush(ficlog);
                   7083: 
1.145     brouard  7084:     /* Reads scales values */
1.126     brouard  7085:     p=param[1][1];
                   7086:     
                   7087:     /* Reads comments: lines beginning with '#' */
                   7088:     while((c=getc(ficpar))=='#' && c!= EOF){
                   7089:       ungetc(c,ficpar);
                   7090:       fgets(line, MAXLINE, ficpar);
                   7091:       numlinepar++;
1.141     brouard  7092:       fputs(line,stdout);
1.126     brouard  7093:       fputs(line,ficparo);
                   7094:       fputs(line,ficlog);
                   7095:     }
                   7096:     ungetc(c,ficpar);
                   7097: 
                   7098:     for(i=1; i <=nlstate; i++){
                   7099:       for(j=1; j <=nlstate+ndeath-1; j++){
                   7100:        fscanf(ficpar,"%1d%1d",&i1,&j1);
1.164     brouard  7101:        if ( (i1-i) * (j1-j) != 0){
1.126     brouard  7102:          printf("Error in line parameters number %d, %1d%1d instead of %1d%1d \n",numlinepar, i,j, i1, j1);
                   7103:          exit(1);
                   7104:        }
                   7105:        printf("%1d%1d",i,j);
                   7106:        fprintf(ficparo,"%1d%1d",i1,j1);
                   7107:        fprintf(ficlog,"%1d%1d",i1,j1);
                   7108:        for(k=1; k<=ncovmodel;k++){
                   7109:          fscanf(ficpar,"%le",&delti3[i][j][k]);
                   7110:          printf(" %le",delti3[i][j][k]);
                   7111:          fprintf(ficparo," %le",delti3[i][j][k]);
                   7112:          fprintf(ficlog," %le",delti3[i][j][k]);
                   7113:        }
                   7114:        fscanf(ficpar,"\n");
                   7115:        numlinepar++;
                   7116:        printf("\n");
                   7117:        fprintf(ficparo,"\n");
                   7118:        fprintf(ficlog,"\n");
                   7119:       }
                   7120:     }
                   7121:     fflush(ficlog);
                   7122: 
1.145     brouard  7123:     /* Reads covariance matrix */
1.126     brouard  7124:     delti=delti3[1][1];
                   7125: 
                   7126: 
                   7127:     /* free_ma3x(delti3,1,nlstate,1,nlstate+ndeath-1,1,ncovmodel); */ /* Hasn't to to freed here otherwise delti is no more allocated */
                   7128:   
                   7129:     /* Reads comments: lines beginning with '#' */
                   7130:     while((c=getc(ficpar))=='#' && c!= EOF){
                   7131:       ungetc(c,ficpar);
                   7132:       fgets(line, MAXLINE, ficpar);
                   7133:       numlinepar++;
1.141     brouard  7134:       fputs(line,stdout);
1.126     brouard  7135:       fputs(line,ficparo);
                   7136:       fputs(line,ficlog);
                   7137:     }
                   7138:     ungetc(c,ficpar);
                   7139:   
                   7140:     matcov=matrix(1,npar,1,npar);
1.203     brouard  7141:     hess=matrix(1,npar,1,npar);
1.131     brouard  7142:     for(i=1; i <=npar; i++)
                   7143:       for(j=1; j <=npar; j++) matcov[i][j]=0.;
                   7144:       
1.194     brouard  7145:     /* Scans npar lines */
1.126     brouard  7146:     for(i=1; i <=npar; i++){
1.194     brouard  7147:       count=fscanf(ficpar,"%1d%1d%1d",&i1,&j1,&jk);
                   7148:       if(count != 3){
                   7149:        printf("Error! Error in parameter file %s at line %d after line starting with %1d%1d%1d\n\
                   7150: This is probably because your covariance matrix doesn't \n  contain exactly %d lines corresponding to your model line '1+age+%s'.\n\
                   7151: Please run with mle=-1 to get a correct covariance matrix.\n",optionfile,numlinepar, i1,j1,jk, npar, model);
                   7152:        fprintf(ficlog,"Error! Error in parameter file %s at line %d after line starting with %1d%1d%1d\n\
                   7153: This is probably because your covariance matrix doesn't \n  contain exactly %d lines corresponding to your model line '1+age+%s'.\n\
                   7154: Please run with mle=-1 to get a correct covariance matrix.\n",optionfile,numlinepar, i1,j1,jk, npar, model);
                   7155:        exit(1);
                   7156:       }else
1.126     brouard  7157:       if(mle==1)
1.194     brouard  7158:        printf("%1d%1d%1d",i1,j1,jk);
                   7159:       fprintf(ficlog,"%1d%1d%1d",i1,j1,jk);
                   7160:       fprintf(ficparo,"%1d%1d%1d",i1,j1,jk);
1.126     brouard  7161:       for(j=1; j <=i; j++){
                   7162:        fscanf(ficpar," %le",&matcov[i][j]);
                   7163:        if(mle==1){
                   7164:          printf(" %.5le",matcov[i][j]);
                   7165:        }
                   7166:        fprintf(ficlog," %.5le",matcov[i][j]);
                   7167:        fprintf(ficparo," %.5le",matcov[i][j]);
                   7168:       }
                   7169:       fscanf(ficpar,"\n");
                   7170:       numlinepar++;
                   7171:       if(mle==1)
                   7172:        printf("\n");
                   7173:       fprintf(ficlog,"\n");
                   7174:       fprintf(ficparo,"\n");
                   7175:     }
1.194     brouard  7176:     /* End of read covariance matrix npar lines */
1.126     brouard  7177:     for(i=1; i <=npar; i++)
                   7178:       for(j=i+1;j<=npar;j++)
                   7179:        matcov[i][j]=matcov[j][i];
                   7180:     
                   7181:     if(mle==1)
                   7182:       printf("\n");
                   7183:     fprintf(ficlog,"\n");
                   7184:     
                   7185:     fflush(ficlog);
                   7186:     
                   7187:     /*-------- Rewriting parameter file ----------*/
                   7188:     strcpy(rfileres,"r");    /* "Rparameterfile */
                   7189:     strcat(rfileres,optionfilefiname);    /* Parameter file first name*/
                   7190:     strcat(rfileres,".");    /* */
                   7191:     strcat(rfileres,optionfilext);    /* Other files have txt extension */
                   7192:     if((ficres =fopen(rfileres,"w"))==NULL) {
1.201     brouard  7193:       printf("Problem writing new parameter file: %s\n", rfileres);goto end;
                   7194:       fprintf(ficlog,"Problem writing new parameter file: %s\n", rfileres);goto end;
1.126     brouard  7195:     }
                   7196:     fprintf(ficres,"#%s\n",version);
                   7197:   }    /* End of mle != -3 */
                   7198: 
1.186     brouard  7199:   /*  Main data
                   7200:    */
1.126     brouard  7201:   n= lastobs;
                   7202:   num=lvector(1,n);
                   7203:   moisnais=vector(1,n);
                   7204:   annais=vector(1,n);
                   7205:   moisdc=vector(1,n);
                   7206:   andc=vector(1,n);
                   7207:   agedc=vector(1,n);
                   7208:   cod=ivector(1,n);
                   7209:   weight=vector(1,n);
                   7210:   for(i=1;i<=n;i++) weight[i]=1.0; /* Equal weights, 1 by default */
                   7211:   mint=matrix(1,maxwav,1,n);
                   7212:   anint=matrix(1,maxwav,1,n);
1.131     brouard  7213:   s=imatrix(1,maxwav+1,1,n); /* s[i][j] health state for wave i and individual j */ 
1.126     brouard  7214:   tab=ivector(1,NCOVMAX);
1.144     brouard  7215:   ncodemax=ivector(1,NCOVMAX); /* Number of code per covariate; if O and 1 only, 2**ncov; V1+V2+V3+V4=>16 */
1.192     brouard  7216:   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  7217: 
1.136     brouard  7218:   /* Reads data from file datafile */
                   7219:   if (readdata(datafile, firstobs, lastobs, &imx)==1)
                   7220:     goto end;
                   7221: 
                   7222:   /* Calculation of the number of parameters from char model */
1.137     brouard  7223:     /*    modelsav=V2+V1+V4+age*V3 strb=age*V3 stra=V2+V1+V4 
                   7224:        k=4 (age*V3) Tvar[k=4]= 3 (from V3) Tag[cptcovage=1]=4
                   7225:        k=3 V4 Tvar[k=3]= 4 (from V4)
                   7226:        k=2 V1 Tvar[k=2]= 1 (from V1)
                   7227:        k=1 Tvar[1]=2 (from V2)
                   7228:     */
                   7229:   Tvar=ivector(1,NCOVMAX); /* Was 15 changed to NCOVMAX. */
                   7230:   /*  V2+V1+V4+age*V3 is a model with 4 covariates (3 plus signs). 
                   7231:       For each model-covariate stores the data-covariate id. Tvar[1]=2, Tvar[2]=1, Tvar[3]=4, 
                   7232:       Tvar[4=age*V3] is 3 and 'age' is recorded in Tage.
                   7233:   */
                   7234:   /* For model-covariate k tells which data-covariate to use but
                   7235:     because this model-covariate is a construction we invent a new column
                   7236:     ncovcol + k1
                   7237:     If already ncovcol=4 and model=V2+V1+V1*V4+age*V3
                   7238:     Tvar[3=V1*V4]=4+1 etc */
1.145     brouard  7239:   Tprod=ivector(1,NCOVMAX); /* Gives the position of a product */
1.137     brouard  7240:   /* Tprod[k1=1]=3(=V1*V4) for V2+V1+V1*V4+age*V3
                   7241:      if  V2+V1+V1*V4+age*V3+V3*V2   TProd[k1=2]=5 (V3*V2)
                   7242:   */
1.145     brouard  7243:   Tvaraff=ivector(1,NCOVMAX); /* Unclear */
                   7244:   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  7245:                            * For V3*V2 (in V2+V1+V1*V4+age*V3+V3*V2), V3*V2 position is 2nd. 
                   7246:                            * Tvard[k1=2][1]=3 (V3) Tvard[k1=2][2]=2(V2) */
1.145     brouard  7247:   Tage=ivector(1,NCOVMAX); /* Gives the covariate id of covariates associated with age: V2 + V1 + age*V4 + V3*age
1.137     brouard  7248:                         4 covariates (3 plus signs)
                   7249:                         Tage[1=V3*age]= 4; Tage[2=age*V4] = 3
                   7250:                      */  
1.136     brouard  7251: 
1.186     brouard  7252: /* Main decodemodel */
                   7253: 
1.187     brouard  7254: 
1.136     brouard  7255:   if(decodemodel(model, lastobs) == 1)
                   7256:     goto end;
                   7257: 
1.137     brouard  7258:   if((double)(lastobs-imx)/(double)imx > 1.10){
                   7259:     nbwarn++;
                   7260:     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); 
                   7261:     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); 
                   7262:   }
1.136     brouard  7263:     /*  if(mle==1){*/
1.137     brouard  7264:   if (weightopt != 1) { /* Maximisation without weights. We can have weights different from 1 but want no weight*/
                   7265:     for(i=1;i<=imx;i++) weight[i]=1.0; /* changed to imx */
1.136     brouard  7266:   }
                   7267: 
                   7268:     /*-calculation of age at interview from date of interview and age at death -*/
                   7269:   agev=matrix(1,maxwav,1,imx);
                   7270: 
                   7271:   if(calandcheckages(imx, maxwav, &agemin, &agemax, &nberr, &nbwarn) == 1)
                   7272:     goto end;
                   7273: 
1.126     brouard  7274: 
1.136     brouard  7275:   agegomp=(int)agemin;
                   7276:   free_vector(moisnais,1,n);
                   7277:   free_vector(annais,1,n);
1.126     brouard  7278:   /* free_matrix(mint,1,maxwav,1,n);
                   7279:      free_matrix(anint,1,maxwav,1,n);*/
                   7280:   free_vector(moisdc,1,n);
                   7281:   free_vector(andc,1,n);
1.145     brouard  7282:   /* */
                   7283:   
1.126     brouard  7284:   wav=ivector(1,imx);
                   7285:   dh=imatrix(1,lastpass-firstpass+1,1,imx);
                   7286:   bh=imatrix(1,lastpass-firstpass+1,1,imx);
                   7287:   mw=imatrix(1,lastpass-firstpass+1,1,imx);
                   7288:    
                   7289:   /* Concatenates waves */
                   7290:   concatwav(wav, dh, bh, mw, s, agedc, agev,  firstpass, lastpass, imx, nlstate, stepm);
1.145     brouard  7291:   /* */
                   7292:  
1.126     brouard  7293:   /* Routine tricode is to calculate cptcoveff (real number of unique covariates) and to associate covariable number and modality */
                   7294: 
                   7295:   nbcode=imatrix(0,NCOVMAX,0,NCOVMAX); 
                   7296:   ncodemax[1]=1;
1.145     brouard  7297:   Ndum =ivector(-1,NCOVMAX);  
1.187     brouard  7298:   if (ncovmodel-nagesqr > 2 ) /* That is if covariate other than cst, age and age*age */
1.145     brouard  7299:     tricode(Tvar,nbcode,imx, Ndum); /**< Fills nbcode[Tvar[j]][l]; */
1.186     brouard  7300:   /* Nbcode gives the value of the lth modality of jth covariate, in
                   7301:      V2+V1*age, there are 3 covariates Tvar[2]=1 (V1).*/
                   7302:   /* 1 to ncodemax[j] is the maximum value of this jth covariate */
1.145     brouard  7303: 
1.200     brouard  7304:   /*  codtab=imatrix(1,100,1,10);*/ /* codtab[h,k]=( (h-1) - mod(k-1,2**(k-1) )/2**(k-1) */
1.198     brouard  7305:   /*printf(" codtab[1,1],codtab[100,10]=%d,%d\n", codtab[1][1],codtabm(100,10));*/
1.186     brouard  7306:   /* codtab gives the value 1 or 2 of the hth combination of k covariates (1 or 2).*/
1.145     brouard  7307:   h=0;
                   7308: 
                   7309: 
                   7310:   /*if (cptcovn > 0) */
1.126     brouard  7311:       
1.145     brouard  7312:  
1.126     brouard  7313:   m=pow(2,cptcoveff);
                   7314:  
1.144     brouard  7315:          /**< codtab(h,k)  k   = codtab[h,k]=( (h-1) - mod(k-1,2**(k-1) )/2**(k-1) + 1
1.186     brouard  7316:           * For k=4 covariates, h goes from 1 to 2**k
                   7317:           * codtabm(h,k)=  1 & (h-1) >> (k-1) ;
                   7318:           *     h\k   1     2     3     4
1.143     brouard  7319:           *______________________________  
                   7320:           *     1 i=1 1 i=1 1 i=1 1 i=1 1
                   7321:           *     2     2     1     1     1
                   7322:           *     3 i=2 1     2     1     1
                   7323:           *     4     2     2     1     1
                   7324:           *     5 i=3 1 i=2 1     2     1
                   7325:           *     6     2     1     2     1
                   7326:           *     7 i=4 1     2     2     1
                   7327:           *     8     2     2     2     1
1.197     brouard  7328:           *     9 i=5 1 i=3 1 i=2 1     2
                   7329:           *    10     2     1     1     2
                   7330:           *    11 i=6 1     2     1     2
                   7331:           *    12     2     2     1     2
                   7332:           *    13 i=7 1 i=4 1     2     2    
                   7333:           *    14     2     1     2     2
                   7334:           *    15 i=8 1     2     2     2
                   7335:           *    16     2     2     2     2
1.143     brouard  7336:           */
1.202     brouard  7337:   /* /\* for(h=1; h <=100 ;h++){  *\/ */
                   7338:   /*   /\* printf("h=%2d ", h); *\/ */
                   7339:   /*    /\* for(k=1; k <=10; k++){ *\/ */
                   7340:   /*      /\* printf("k=%d %d ",k,codtabm(h,k)); *\/ */
                   7341:   /*    /\*   codtab[h][k]=codtabm(h,k); *\/ */
                   7342:   /*    /\* } *\/ */
                   7343:   /*    /\* printf("\n"); *\/ */
                   7344:   /* } */
1.197     brouard  7345:   /* for(k=1;k<=cptcoveff; k++){ /\* scans any effective covariate *\/ */
                   7346:   /*   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 *\/  */
                   7347:   /*     for(j=1; j <= ncodemax[k]; j++){ /\* For each modality of this covariate ncodemax=2*\/ */
                   7348:   /*   for(cpt=1; cpt <=pow(2,k-1); cpt++){  /\* cpt=1 to 8/2**(3+1-1 or 3+1-3) =1 or 4 *\/  */
                   7349:   /*     h++; */
                   7350:   /*     if (h>m)  */
                   7351:   /*       h=1; */
                   7352:   /*     codtab[h][k]=j; */
                   7353:   /*     /\* codtab[12][3]=1; *\/ */
                   7354:   /*     /\*codtab[h][Tvar[k]]=j;*\/ */
                   7355:   /*     /\* 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]]); *\/ */
                   7356:   /*   }  */
                   7357:   /*     } */
                   7358:   /*   } */
                   7359:   /* }  */
1.126     brouard  7360:   /* printf("codtab[1][2]=%d codtab[2][2]=%d",codtab[1][2],codtab[2][2]); 
                   7361:      codtab[1][2]=1;codtab[2][2]=2; */
1.197     brouard  7362:   /* for(i=1; i <=m ;i++){  */
                   7363:   /*    for(k=1; k <=cptcovn; k++){ */
                   7364:   /*      printf("i=%d k=%d %d %d ",i,k,codtab[i][k], cptcoveff); */
                   7365:   /*    } */
                   7366:   /*    printf("\n"); */
                   7367:   /* } */
                   7368:   /*   scanf("%d",i);*/
1.145     brouard  7369: 
                   7370:  free_ivector(Ndum,-1,NCOVMAX);
                   7371: 
                   7372: 
1.126     brouard  7373:     
1.186     brouard  7374:   /* Initialisation of ----------- gnuplot -------------*/
1.126     brouard  7375:   strcpy(optionfilegnuplot,optionfilefiname);
                   7376:   if(mle==-3)
1.201     brouard  7377:     strcat(optionfilegnuplot,"-MORT_");
1.126     brouard  7378:   strcat(optionfilegnuplot,".gp");
                   7379: 
                   7380:   if((ficgp=fopen(optionfilegnuplot,"w"))==NULL) {
                   7381:     printf("Problem with file %s",optionfilegnuplot);
                   7382:   }
                   7383:   else{
1.204     brouard  7384:     fprintf(ficgp,"\n# IMaCh-%s\n", version); 
1.126     brouard  7385:     fprintf(ficgp,"# %s\n", optionfilegnuplot); 
1.141     brouard  7386:     //fprintf(ficgp,"set missing 'NaNq'\n");
                   7387:     fprintf(ficgp,"set datafile missing 'NaNq'\n");
1.126     brouard  7388:   }
                   7389:   /*  fclose(ficgp);*/
1.186     brouard  7390: 
                   7391: 
                   7392:   /* Initialisation of --------- index.htm --------*/
1.126     brouard  7393: 
                   7394:   strcpy(optionfilehtm,optionfilefiname); /* Main html file */
                   7395:   if(mle==-3)
1.201     brouard  7396:     strcat(optionfilehtm,"-MORT_");
1.126     brouard  7397:   strcat(optionfilehtm,".htm");
                   7398:   if((fichtm=fopen(optionfilehtm,"w"))==NULL)    {
1.131     brouard  7399:     printf("Problem with %s \n",optionfilehtm);
                   7400:     exit(0);
1.126     brouard  7401:   }
                   7402: 
                   7403:   strcpy(optionfilehtmcov,optionfilefiname); /* Only for matrix of covariance */
                   7404:   strcat(optionfilehtmcov,"-cov.htm");
                   7405:   if((fichtmcov=fopen(optionfilehtmcov,"w"))==NULL)    {
                   7406:     printf("Problem with %s \n",optionfilehtmcov), exit(0);
                   7407:   }
                   7408:   else{
                   7409:   fprintf(fichtmcov,"<html><head>\n<title>IMaCh Cov %s</title></head>\n <body><font size=\"2\">%s <br> %s</font> \
                   7410: <hr size=\"2\" color=\"#EC5E5E\"> \n\
1.204     brouard  7411: Title=%s <br>Datafile=%s Firstpass=%d Lastpass=%d Stepm=%d Weight=%d Model=1+age+%s<br>\n",\
1.126     brouard  7412:          optionfilehtmcov,version,fullversion,title,datafile,firstpass,lastpass,stepm, weightopt, model);
                   7413:   }
                   7414: 
1.204     brouard  7415:   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é-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</a></font><br>  \
                   7416: <hr size=\"2\" color=\"#EC5E5E\"> \n\
                   7417: <font size=\"2\">IMaCh-%s <br> %s</font> \
1.126     brouard  7418: <hr size=\"2\" color=\"#EC5E5E\"> \n\
1.204     brouard  7419: Title=%s <br>Datafile=%s Firstpass=%d Lastpass=%d Stepm=%d Weight=%d Model=1+age+%s<br>\n\
1.126     brouard  7420: \n\
                   7421: <hr  size=\"2\" color=\"#EC5E5E\">\
                   7422:  <ul><li><h4>Parameter files</h4>\n\
                   7423:  - Parameter file: <a href=\"%s.%s\">%s.%s</a><br>\n\
                   7424:  - Copy of the parameter file: <a href=\"o%s\">o%s</a><br>\n\
                   7425:  - Log file of the run: <a href=\"%s\">%s</a><br>\n\
                   7426:  - Gnuplot file name: <a href=\"%s\">%s</a><br>\n\
                   7427:  - Date and time at start: %s</ul>\n",\
                   7428:          optionfilehtm,version,fullversion,title,datafile,firstpass,lastpass,stepm, weightopt, model,\
                   7429:          optionfilefiname,optionfilext,optionfilefiname,optionfilext,\
                   7430:          fileres,fileres,\
                   7431:          filelog,filelog,optionfilegnuplot,optionfilegnuplot,strstart);
                   7432:   fflush(fichtm);
                   7433: 
                   7434:   strcpy(pathr,path);
                   7435:   strcat(pathr,optionfilefiname);
1.184     brouard  7436: #ifdef WIN32
                   7437:   _chdir(optionfilefiname); /* Move to directory named optionfile */
                   7438: #else
1.126     brouard  7439:   chdir(optionfilefiname); /* Move to directory named optionfile */
1.184     brouard  7440: #endif
                   7441:          
1.126     brouard  7442:   
                   7443:   /* Calculates basic frequencies. Computes observed prevalence at single age
                   7444:      and prints on file fileres'p'. */
                   7445:   freqsummary(fileres, agemin, agemax, s, agev, nlstate, imx,Tvaraff,nbcode, ncodemax,mint,anint,strstart);
                   7446: 
                   7447:   fprintf(fichtm,"\n");
                   7448:   fprintf(fichtm,"<br>Total number of observations=%d <br>\n\
                   7449: Youngest age at first (selected) pass %.2f, oldest age %.2f<br>\n\
                   7450: Interval (in months) between two waves: Min=%d Max=%d Mean=%.2lf<br>\n",\
                   7451:          imx,agemin,agemax,jmin,jmax,jmean);
                   7452:   pmmij= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
                   7453:     oldms= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
                   7454:     newms= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
                   7455:     savms= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
                   7456:     oldm=oldms; newm=newms; savm=savms; /* Keeps fixed addresses to free */
                   7457:     
                   7458:    
                   7459:   /* For Powell, parameters are in a vector p[] starting at p[1]
                   7460:      so we point p on param[1][1] so that p[1] maps on param[1][1][1] */
                   7461:   p=param[1][1]; /* *(*(*(param +1)+1)+0) */
                   7462: 
                   7463:   globpr=0; /* To get the number ipmx of contributions and the sum of weights*/
1.186     brouard  7464:   /* For mortality only */
1.126     brouard  7465:   if (mle==-3){
1.136     brouard  7466:     ximort=matrix(1,NDIM,1,NDIM); 
1.186     brouard  7467:     /*     ximort=gsl_matrix_alloc(1,NDIM,1,NDIM); */
1.126     brouard  7468:     cens=ivector(1,n);
                   7469:     ageexmed=vector(1,n);
                   7470:     agecens=vector(1,n);
                   7471:     dcwave=ivector(1,n);
                   7472:  
                   7473:     for (i=1; i<=imx; i++){
                   7474:       dcwave[i]=-1;
                   7475:       for (m=firstpass; m<=lastpass; m++)
                   7476:        if (s[m][i]>nlstate) {
                   7477:          dcwave[i]=m;
                   7478:          /*    printf("i=%d j=%d s=%d dcwave=%d\n",i,j, s[j][i],dcwave[i]);*/
                   7479:          break;
                   7480:        }
                   7481:     }
                   7482: 
                   7483:     for (i=1; i<=imx; i++) {
                   7484:       if (wav[i]>0){
                   7485:        ageexmed[i]=agev[mw[1][i]][i];
                   7486:        j=wav[i];
                   7487:        agecens[i]=1.; 
                   7488: 
                   7489:        if (ageexmed[i]> 1 && wav[i] > 0){
                   7490:          agecens[i]=agev[mw[j][i]][i];
                   7491:          cens[i]= 1;
                   7492:        }else if (ageexmed[i]< 1) 
                   7493:          cens[i]= -1;
                   7494:        if (agedc[i]< AGESUP && agedc[i]>1 && dcwave[i]>firstpass && dcwave[i]<=lastpass)
                   7495:          cens[i]=0 ;
                   7496:       }
                   7497:       else cens[i]=-1;
                   7498:     }
                   7499:     
                   7500:     for (i=1;i<=NDIM;i++) {
                   7501:       for (j=1;j<=NDIM;j++)
                   7502:        ximort[i][j]=(i == j ? 1.0 : 0.0);
                   7503:     }
                   7504:     
1.145     brouard  7505:     /*p[1]=0.0268; p[NDIM]=0.083;*/
1.126     brouard  7506:     /*printf("%lf %lf", p[1], p[2]);*/
                   7507:     
                   7508:     
1.136     brouard  7509: #ifdef GSL
                   7510:     printf("GSL optimization\n");  fprintf(ficlog,"Powell\n");
1.162     brouard  7511: #else
1.126     brouard  7512:     printf("Powell\n");  fprintf(ficlog,"Powell\n");
1.136     brouard  7513: #endif
1.201     brouard  7514:     strcpy(filerespow,"POW-MORT_"); 
                   7515:     strcat(filerespow,fileresu);
1.126     brouard  7516:     if((ficrespow=fopen(filerespow,"w"))==NULL) {
                   7517:       printf("Problem with resultfile: %s\n", filerespow);
                   7518:       fprintf(ficlog,"Problem with resultfile: %s\n", filerespow);
                   7519:     }
1.136     brouard  7520: #ifdef GSL
                   7521:     fprintf(ficrespow,"# GSL optimization\n# iter -2*LL");
1.162     brouard  7522: #else
1.126     brouard  7523:     fprintf(ficrespow,"# Powell\n# iter -2*LL");
1.136     brouard  7524: #endif
1.126     brouard  7525:     /*  for (i=1;i<=nlstate;i++)
                   7526:        for(j=1;j<=nlstate+ndeath;j++)
                   7527:        if(j!=i)fprintf(ficrespow," p%1d%1d",i,j);
                   7528:     */
                   7529:     fprintf(ficrespow,"\n");
1.136     brouard  7530: #ifdef GSL
                   7531:     /* gsl starts here */ 
                   7532:     T = gsl_multimin_fminimizer_nmsimplex;
                   7533:     gsl_multimin_fminimizer *sfm = NULL;
                   7534:     gsl_vector *ss, *x;
                   7535:     gsl_multimin_function minex_func;
                   7536: 
                   7537:     /* Initial vertex size vector */
                   7538:     ss = gsl_vector_alloc (NDIM);
                   7539:     
                   7540:     if (ss == NULL){
                   7541:       GSL_ERROR_VAL ("failed to allocate space for ss", GSL_ENOMEM, 0);
                   7542:     }
                   7543:     /* Set all step sizes to 1 */
                   7544:     gsl_vector_set_all (ss, 0.001);
                   7545: 
                   7546:     /* Starting point */
1.126     brouard  7547:     
1.136     brouard  7548:     x = gsl_vector_alloc (NDIM);
                   7549:     
                   7550:     if (x == NULL){
                   7551:       gsl_vector_free(ss);
                   7552:       GSL_ERROR_VAL ("failed to allocate space for x", GSL_ENOMEM, 0);
                   7553:     }
                   7554:   
                   7555:     /* Initialize method and iterate */
                   7556:     /*     p[1]=0.0268; p[NDIM]=0.083; */
1.186     brouard  7557:     /*     gsl_vector_set(x, 0, 0.0268); */
                   7558:     /*     gsl_vector_set(x, 1, 0.083); */
1.136     brouard  7559:     gsl_vector_set(x, 0, p[1]);
                   7560:     gsl_vector_set(x, 1, p[2]);
                   7561: 
                   7562:     minex_func.f = &gompertz_f;
                   7563:     minex_func.n = NDIM;
                   7564:     minex_func.params = (void *)&p; /* ??? */
                   7565:     
                   7566:     sfm = gsl_multimin_fminimizer_alloc (T, NDIM);
                   7567:     gsl_multimin_fminimizer_set (sfm, &minex_func, x, ss);
                   7568:     
                   7569:     printf("Iterations beginning .....\n\n");
                   7570:     printf("Iter. #    Intercept       Slope     -Log Likelihood     Simplex size\n");
                   7571: 
                   7572:     iteri=0;
                   7573:     while (rval == GSL_CONTINUE){
                   7574:       iteri++;
                   7575:       status = gsl_multimin_fminimizer_iterate(sfm);
                   7576:       
                   7577:       if (status) printf("error: %s\n", gsl_strerror (status));
                   7578:       fflush(0);
                   7579:       
                   7580:       if (status) 
                   7581:         break;
                   7582:       
                   7583:       rval = gsl_multimin_test_size (gsl_multimin_fminimizer_size (sfm), 1e-6);
                   7584:       ssval = gsl_multimin_fminimizer_size (sfm);
                   7585:       
                   7586:       if (rval == GSL_SUCCESS)
                   7587:         printf ("converged to a local maximum at\n");
                   7588:       
                   7589:       printf("%5d ", iteri);
                   7590:       for (it = 0; it < NDIM; it++){
                   7591:        printf ("%10.5f ", gsl_vector_get (sfm->x, it));
                   7592:       }
                   7593:       printf("f() = %-10.5f ssize = %.7f\n", sfm->fval, ssval);
                   7594:     }
                   7595:     
                   7596:     printf("\n\n Please note: Program should be run many times with varying starting points to detemine global maximum\n\n");
                   7597:     
                   7598:     gsl_vector_free(x); /* initial values */
                   7599:     gsl_vector_free(ss); /* inital step size */
                   7600:     for (it=0; it<NDIM; it++){
                   7601:       p[it+1]=gsl_vector_get(sfm->x,it);
                   7602:       fprintf(ficrespow," %.12lf", p[it]);
                   7603:     }
                   7604:     gsl_multimin_fminimizer_free (sfm); /* p *(sfm.x.data) et p *(sfm.x.data+1)  */
                   7605: #endif
                   7606: #ifdef POWELL
                   7607:      powell(p,ximort,NDIM,ftol,&iter,&fret,gompertz);
                   7608: #endif  
1.126     brouard  7609:     fclose(ficrespow);
                   7610:     
1.203     brouard  7611:     hesscov(matcov, hess, p, NDIM, delti, 1e-4, gompertz); 
1.126     brouard  7612: 
                   7613:     for(i=1; i <=NDIM; i++)
                   7614:       for(j=i+1;j<=NDIM;j++)
                   7615:        matcov[i][j]=matcov[j][i];
                   7616:     
                   7617:     printf("\nCovariance matrix\n ");
1.203     brouard  7618:     fprintf(ficlog,"\nCovariance matrix\n ");
1.126     brouard  7619:     for(i=1; i <=NDIM; i++) {
                   7620:       for(j=1;j<=NDIM;j++){ 
                   7621:        printf("%f ",matcov[i][j]);
1.203     brouard  7622:        fprintf(ficlog,"%f ",matcov[i][j]);
1.126     brouard  7623:       }
1.203     brouard  7624:       printf("\n ");  fprintf(ficlog,"\n ");
1.126     brouard  7625:     }
                   7626:     
                   7627:     printf("iter=%d MLE=%f Eq=%lf*exp(%lf*(age-%d))\n",iter,-gompertz(p),p[1],p[2],agegomp);
1.193     brouard  7628:     for (i=1;i<=NDIM;i++) {
1.126     brouard  7629:       printf("%f [%f ; %f]\n",p[i],p[i]-2*sqrt(matcov[i][i]),p[i]+2*sqrt(matcov[i][i]));
1.193     brouard  7630:       fprintf(ficlog,"%f [%f ; %f]\n",p[i],p[i]-2*sqrt(matcov[i][i]),p[i]+2*sqrt(matcov[i][i]));
                   7631:     }
1.126     brouard  7632:     lsurv=vector(1,AGESUP);
                   7633:     lpop=vector(1,AGESUP);
                   7634:     tpop=vector(1,AGESUP);
                   7635:     lsurv[agegomp]=100000;
                   7636:     
                   7637:     for (k=agegomp;k<=AGESUP;k++) {
                   7638:       agemortsup=k;
                   7639:       if (p[1]*exp(p[2]*(k-agegomp))>1) break;
                   7640:     }
                   7641:     
                   7642:     for (k=agegomp;k<agemortsup;k++)
                   7643:       lsurv[k+1]=lsurv[k]-lsurv[k]*(p[1]*exp(p[2]*(k-agegomp)));
                   7644:     
                   7645:     for (k=agegomp;k<agemortsup;k++){
                   7646:       lpop[k]=(lsurv[k]+lsurv[k+1])/2.;
                   7647:       sumlpop=sumlpop+lpop[k];
                   7648:     }
                   7649:     
                   7650:     tpop[agegomp]=sumlpop;
                   7651:     for (k=agegomp;k<(agemortsup-3);k++){
                   7652:       /*  tpop[k+1]=2;*/
                   7653:       tpop[k+1]=tpop[k]-lpop[k];
                   7654:     }
                   7655:     
                   7656:     
                   7657:     printf("\nAge   lx     qx    dx    Lx     Tx     e(x)\n");
                   7658:     for (k=agegomp;k<(agemortsup-2);k++) 
                   7659:       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]);
                   7660:     
                   7661:     
                   7662:     replace_back_to_slash(pathc,pathcd); /* Even gnuplot wants a / */
1.194     brouard  7663:     if(ageminpar == AGEOVERFLOW ||agemaxpar == AGEOVERFLOW){
                   7664:        printf("Warning! Error in gnuplot file with ageminpar %f or agemaxpar %f overflow\n\
                   7665: This is probably because your parameter file doesn't \n  contain the exact number of lines (or columns) corresponding to your model line.\n\
                   7666: Please run with mle=-1 to get a correct covariance matrix.\n",ageminpar,agemaxpar);
                   7667:        fprintf(ficlog,"Warning! Error in gnuplot file with ageminpar %f or agemaxpar %f overflow\n\
                   7668: This is probably because your parameter file doesn't \n  contain the exact number of lines (or columns) corresponding to your model line.\n\
                   7669: Please run with mle=-1 to get a correct covariance matrix.\n",ageminpar,agemaxpar);
                   7670:     }else
1.201     brouard  7671:       printinggnuplotmort(fileresu, optionfilefiname,ageminpar,agemaxpar,fage, pathc,p);
                   7672:     printinghtmlmort(fileresu,title,datafile, firstpass, lastpass, \
1.126     brouard  7673:                     stepm, weightopt,\
                   7674:                     model,imx,p,matcov,agemortsup);
                   7675:     
                   7676:     free_vector(lsurv,1,AGESUP);
                   7677:     free_vector(lpop,1,AGESUP);
                   7678:     free_vector(tpop,1,AGESUP);
1.136     brouard  7679: #ifdef GSL
                   7680:     free_ivector(cens,1,n);
                   7681:     free_vector(agecens,1,n);
                   7682:     free_ivector(dcwave,1,n);
                   7683:     free_matrix(ximort,1,NDIM,1,NDIM);
                   7684: #endif
1.186     brouard  7685:   } /* Endof if mle==-3 mortality only */
1.205     brouard  7686:   /* Standard  */
                   7687:   else{ /* For mle !=- 3, could be 0 or 1 or 4 etc. */
                   7688:     globpr=0;/* Computes sum of likelihood for globpr=1 and funcone */
                   7689:     /* Computes likelihood for initial parameters, uses funcone to compute gpimx and gsw */
1.132     brouard  7690:     likelione(ficres, p, npar, nlstate, &globpr, &ipmx, &sw, &fretone, funcone); /* Prints the contributions to the likelihood */
1.126     brouard  7691:     printf("First Likeli=%12.6f ipmx=%ld sw=%12.6f",fretone,ipmx,sw);
                   7692:     for (k=1; k<=npar;k++)
                   7693:       printf(" %d %8.5f",k,p[k]);
                   7694:     printf("\n");
1.205     brouard  7695:     if(mle>=1){ /* Could be 1 or 2, Real Maximization */
                   7696:       /* mlikeli uses func not funcone */
                   7697:       mlikeli(ficres,p, npar, ncovmodel, nlstate, ftol, func);
                   7698:     }
                   7699:     if(mle==0) {/* No optimization, will print the likelihoods for the datafile */
                   7700:       globpr=0;/* Computes sum of likelihood for globpr=1 and funcone */
                   7701:       /* Computes likelihood for initial parameters, uses funcone to compute gpimx and gsw */
                   7702:       likelione(ficres, p, npar, nlstate, &globpr, &ipmx, &sw, &fretone, funcone); /* Prints the contributions to the likelihood */
                   7703:     }
                   7704:     globpr=1; /* again, to print the individual contributions using computed gpimx and gsw */
1.126     brouard  7705:     likelione(ficres, p, npar, nlstate, &globpr, &ipmx, &sw, &fretone, funcone); /* Prints the contributions to the likelihood */
                   7706:     printf("Second Likeli=%12.6f ipmx=%ld sw=%12.6f",fretone,ipmx,sw);
                   7707:     for (k=1; k<=npar;k++)
                   7708:       printf(" %d %8.5f",k,p[k]);
                   7709:     printf("\n");
                   7710:     
                   7711:     /*--------- results files --------------*/
1.192     brouard  7712:     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  7713:     
                   7714:     
                   7715:     fprintf(ficres,"# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
                   7716:     printf("# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
                   7717:     fprintf(ficlog,"# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
                   7718:     for(i=1,jk=1; i <=nlstate; i++){
                   7719:       for(k=1; k <=(nlstate+ndeath); k++){
                   7720:        if (k != i) {
                   7721:          printf("%d%d ",i,k);
                   7722:          fprintf(ficlog,"%d%d ",i,k);
                   7723:          fprintf(ficres,"%1d%1d ",i,k);
                   7724:          for(j=1; j <=ncovmodel; j++){
1.190     brouard  7725:            printf("%12.7f ",p[jk]);
                   7726:            fprintf(ficlog,"%12.7f ",p[jk]);
                   7727:            fprintf(ficres,"%12.7f ",p[jk]);
1.126     brouard  7728:            jk++; 
                   7729:          }
                   7730:          printf("\n");
                   7731:          fprintf(ficlog,"\n");
                   7732:          fprintf(ficres,"\n");
                   7733:        }
                   7734:       }
                   7735:     }
1.203     brouard  7736:     if(mle != 0){
                   7737:       /* Computing hessian and covariance matrix only at a peak of the Likelihood, that is after optimization */
1.126     brouard  7738:       ftolhess=ftol; /* Usually correct */
1.203     brouard  7739:       hesscov(matcov, hess, p, npar, delti, ftolhess, func);
                   7740:       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");
                   7741:       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");
                   7742:       for(i=1,jk=1; i <=nlstate; i++){
                   7743:        for(k=1; k <=(nlstate+ndeath); k++){
                   7744:          if (k != i) {
                   7745:            printf("%d%d ",i,k);
                   7746:            fprintf(ficlog,"%d%d ",i,k);
                   7747:            for(j=1; j <=ncovmodel; j++){
                   7748:              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]));
                   7749:              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]));
                   7750:              jk++; 
                   7751:            }
                   7752:            printf("\n");
                   7753:            fprintf(ficlog,"\n");
1.193     brouard  7754:          }
                   7755:        }
                   7756:       }
1.203     brouard  7757:     } /* end of hesscov and Wald tests */
1.193     brouard  7758: 
1.203     brouard  7759:     /*  */
1.126     brouard  7760:     fprintf(ficres,"# Scales (for hessian or gradient estimation)\n");
                   7761:     printf("# Scales (for hessian or gradient estimation)\n");
                   7762:     fprintf(ficlog,"# Scales (for hessian or gradient estimation)\n");
                   7763:     for(i=1,jk=1; i <=nlstate; i++){
                   7764:       for(j=1; j <=nlstate+ndeath; j++){
                   7765:        if (j!=i) {
                   7766:          fprintf(ficres,"%1d%1d",i,j);
                   7767:          printf("%1d%1d",i,j);
                   7768:          fprintf(ficlog,"%1d%1d",i,j);
                   7769:          for(k=1; k<=ncovmodel;k++){
                   7770:            printf(" %.5e",delti[jk]);
                   7771:            fprintf(ficlog," %.5e",delti[jk]);
                   7772:            fprintf(ficres," %.5e",delti[jk]);
                   7773:            jk++;
                   7774:          }
                   7775:          printf("\n");
                   7776:          fprintf(ficlog,"\n");
                   7777:          fprintf(ficres,"\n");
                   7778:        }
                   7779:       }
                   7780:     }
                   7781:     
                   7782:     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  7783:     if(mle >= 1) /* To big for the screen */
1.126     brouard  7784:       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");
                   7785:     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");
                   7786:     /* # 121 Var(a12)\n\ */
                   7787:     /* # 122 Cov(b12,a12) Var(b12)\n\ */
                   7788:     /* # 131 Cov(a13,a12) Cov(a13,b12, Var(a13)\n\ */
                   7789:     /* # 132 Cov(b13,a12) Cov(b13,b12, Cov(b13,a13) Var(b13)\n\ */
                   7790:     /* # 212 Cov(a21,a12) Cov(a21,b12, Cov(a21,a13) Cov(a21,b13) Var(a21)\n\ */
                   7791:     /* # 212 Cov(b21,a12) Cov(b21,b12, Cov(b21,a13) Cov(b21,b13) Cov(b21,a21) Var(b21)\n\ */
                   7792:     /* # 232 Cov(a23,a12) Cov(a23,b12, Cov(a23,a13) Cov(a23,b13) Cov(a23,a21) Cov(a23,b21) Var(a23)\n\ */
                   7793:     /* # 232 Cov(b23,a12) Cov(b23,b12) ... Var (b23)\n" */
                   7794:     
                   7795:     
                   7796:     /* Just to have a covariance matrix which will be more understandable
                   7797:        even is we still don't want to manage dictionary of variables
                   7798:     */
                   7799:     for(itimes=1;itimes<=2;itimes++){
                   7800:       jj=0;
                   7801:       for(i=1; i <=nlstate; i++){
                   7802:        for(j=1; j <=nlstate+ndeath; j++){
                   7803:          if(j==i) continue;
                   7804:          for(k=1; k<=ncovmodel;k++){
                   7805:            jj++;
                   7806:            ca[0]= k+'a'-1;ca[1]='\0';
                   7807:            if(itimes==1){
                   7808:              if(mle>=1)
                   7809:                printf("#%1d%1d%d",i,j,k);
                   7810:              fprintf(ficlog,"#%1d%1d%d",i,j,k);
                   7811:              fprintf(ficres,"#%1d%1d%d",i,j,k);
                   7812:            }else{
                   7813:              if(mle>=1)
                   7814:                printf("%1d%1d%d",i,j,k);
                   7815:              fprintf(ficlog,"%1d%1d%d",i,j,k);
                   7816:              fprintf(ficres,"%1d%1d%d",i,j,k);
                   7817:            }
                   7818:            ll=0;
                   7819:            for(li=1;li <=nlstate; li++){
                   7820:              for(lj=1;lj <=nlstate+ndeath; lj++){
                   7821:                if(lj==li) continue;
                   7822:                for(lk=1;lk<=ncovmodel;lk++){
                   7823:                  ll++;
                   7824:                  if(ll<=jj){
                   7825:                    cb[0]= lk +'a'-1;cb[1]='\0';
                   7826:                    if(ll<jj){
                   7827:                      if(itimes==1){
                   7828:                        if(mle>=1)
                   7829:                          printf(" Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
                   7830:                        fprintf(ficlog," Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
                   7831:                        fprintf(ficres," Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
                   7832:                      }else{
                   7833:                        if(mle>=1)
                   7834:                          printf(" %.5e",matcov[jj][ll]); 
                   7835:                        fprintf(ficlog," %.5e",matcov[jj][ll]); 
                   7836:                        fprintf(ficres," %.5e",matcov[jj][ll]); 
                   7837:                      }
                   7838:                    }else{
                   7839:                      if(itimes==1){
                   7840:                        if(mle>=1)
                   7841:                          printf(" Var(%s%1d%1d)",ca,i,j);
                   7842:                        fprintf(ficlog," Var(%s%1d%1d)",ca,i,j);
                   7843:                        fprintf(ficres," Var(%s%1d%1d)",ca,i,j);
                   7844:                      }else{
                   7845:                        if(mle>=1)
1.203     brouard  7846:                          printf(" %.7e",matcov[jj][ll]); 
                   7847:                        fprintf(ficlog," %.7e",matcov[jj][ll]); 
                   7848:                        fprintf(ficres," %.7e",matcov[jj][ll]); 
1.126     brouard  7849:                      }
                   7850:                    }
                   7851:                  }
                   7852:                } /* end lk */
                   7853:              } /* end lj */
                   7854:            } /* end li */
                   7855:            if(mle>=1)
                   7856:              printf("\n");
                   7857:            fprintf(ficlog,"\n");
                   7858:            fprintf(ficres,"\n");
                   7859:            numlinepar++;
                   7860:          } /* end k*/
                   7861:        } /*end j */
                   7862:       } /* end i */
                   7863:     } /* end itimes */
                   7864:     
                   7865:     fflush(ficlog);
                   7866:     fflush(ficres);
                   7867:     
                   7868:     while((c=getc(ficpar))=='#' && c!= EOF){
                   7869:       ungetc(c,ficpar);
                   7870:       fgets(line, MAXLINE, ficpar);
1.141     brouard  7871:       fputs(line,stdout);
1.126     brouard  7872:       fputs(line,ficparo);
                   7873:     }
                   7874:     ungetc(c,ficpar);
                   7875:     
                   7876:     estepm=0;
                   7877:     fscanf(ficpar,"agemin=%lf agemax=%lf bage=%lf fage=%lf estepm=%d\n",&ageminpar,&agemaxpar, &bage, &fage, &estepm);
                   7878:     if (estepm==0 || estepm < stepm) estepm=stepm;
                   7879:     if (fage <= 2) {
                   7880:       bage = ageminpar;
                   7881:       fage = agemaxpar;
                   7882:     }
                   7883:     
                   7884:     fprintf(ficres,"# agemin agemax for life expectancy, bage fage (if mle==0 ie no data nor Max likelihood).\n");
                   7885:     fprintf(ficres,"agemin=%.0f agemax=%.0f bage=%.0f fage=%.0f estepm=%d\n",ageminpar,agemaxpar,bage,fage, estepm);
                   7886:     fprintf(ficparo,"agemin=%.0f agemax=%.0f bage=%.0f fage=%.0f estepm=%d\n",ageminpar,agemaxpar,bage,fage, estepm);
1.186     brouard  7887: 
                   7888:     /* Other stuffs, more or less useful */    
1.126     brouard  7889:     while((c=getc(ficpar))=='#' && c!= EOF){
                   7890:       ungetc(c,ficpar);
                   7891:       fgets(line, MAXLINE, ficpar);
1.141     brouard  7892:       fputs(line,stdout);
1.126     brouard  7893:       fputs(line,ficparo);
                   7894:     }
                   7895:     ungetc(c,ficpar);
                   7896:     
                   7897:     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);
                   7898:     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);
                   7899:     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);
                   7900:     printf("begin-prev-date=%.lf/%.lf/%.lf end-prev-date=%.lf/%.lf/%.lf mov_average=%d\n",jprev1, mprev1,anprev1,jprev2, mprev2,anprev2,mobilav);
                   7901:     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);
                   7902:     
                   7903:     while((c=getc(ficpar))=='#' && c!= EOF){
                   7904:       ungetc(c,ficpar);
                   7905:       fgets(line, MAXLINE, ficpar);
1.141     brouard  7906:       fputs(line,stdout);
1.126     brouard  7907:       fputs(line,ficparo);
                   7908:     }
                   7909:     ungetc(c,ficpar);
                   7910:     
                   7911:     
                   7912:     dateprev1=anprev1+(mprev1-1)/12.+(jprev1-1)/365.;
                   7913:     dateprev2=anprev2+(mprev2-1)/12.+(jprev2-1)/365.;
                   7914:     
                   7915:     fscanf(ficpar,"pop_based=%d\n",&popbased);
1.193     brouard  7916:     fprintf(ficlog,"pop_based=%d\n",popbased);
1.126     brouard  7917:     fprintf(ficparo,"pop_based=%d\n",popbased);   
                   7918:     fprintf(ficres,"pop_based=%d\n",popbased);   
                   7919:     
                   7920:     while((c=getc(ficpar))=='#' && c!= EOF){
                   7921:       ungetc(c,ficpar);
                   7922:       fgets(line, MAXLINE, ficpar);
1.141     brouard  7923:       fputs(line,stdout);
1.126     brouard  7924:       fputs(line,ficparo);
                   7925:     }
                   7926:     ungetc(c,ficpar);
                   7927:     
                   7928:     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);
                   7929:     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);
                   7930:     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);
                   7931:     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);
                   7932:     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);
                   7933:     /* day and month of proj2 are not used but only year anproj2.*/
                   7934:     
                   7935:     
                   7936:     
1.145     brouard  7937:      /* freqsummary(fileres, agemin, agemax, s, agev, nlstate, imx,Tvaraff,nbcode, ncodemax,mint,anint); */
                   7938:     /* ,dateprev1,dateprev2,jprev1, mprev1,anprev1,jprev2, mprev2,anprev2); */
1.126     brouard  7939:     
                   7940:     replace_back_to_slash(pathc,pathcd); /* Even gnuplot wants a / */
1.194     brouard  7941:     if(ageminpar == AGEOVERFLOW ||agemaxpar == -AGEOVERFLOW){
                   7942:        printf("Warning! Error in gnuplot file with ageminpar %f or agemaxpar %f overflow\n\
                   7943: This is probably because your parameter file doesn't \n  contain the exact number of lines (or columns) corresponding to your model line.\n\
                   7944: Please run with mle=-1 to get a correct covariance matrix.\n",ageminpar,agemaxpar);
                   7945:        fprintf(ficlog,"Warning! Error in gnuplot file with ageminpar %f or agemaxpar %f overflow\n\
                   7946: This is probably because your parameter file doesn't \n  contain the exact number of lines (or columns) corresponding to your model line.\n\
                   7947: Please run with mle=-1 to get a correct covariance matrix.\n",ageminpar,agemaxpar);
                   7948:     }else
1.201     brouard  7949:       printinggnuplot(fileresu, optionfilefiname,ageminpar,agemaxpar,fage, pathc,p);
1.126     brouard  7950:     
1.201     brouard  7951:     printinghtml(fileresu,title,datafile, firstpass, lastpass, stepm, weightopt,\
1.126     brouard  7952:                 model,imx,jmin,jmax,jmean,rfileres,popforecast,estepm,\
                   7953:                 jprev1,mprev1,anprev1,jprev2,mprev2,anprev2);
                   7954:       
                   7955:    /*------------ free_vector  -------------*/
                   7956:    /*  chdir(path); */
                   7957:  
                   7958:     free_ivector(wav,1,imx);
                   7959:     free_imatrix(dh,1,lastpass-firstpass+1,1,imx);
                   7960:     free_imatrix(bh,1,lastpass-firstpass+1,1,imx);
                   7961:     free_imatrix(mw,1,lastpass-firstpass+1,1,imx);   
                   7962:     free_lvector(num,1,n);
                   7963:     free_vector(agedc,1,n);
                   7964:     /*free_matrix(covar,0,NCOVMAX,1,n);*/
                   7965:     /*free_matrix(covar,1,NCOVMAX,1,n);*/
                   7966:     fclose(ficparo);
                   7967:     fclose(ficres);
                   7968: 
                   7969: 
1.186     brouard  7970:     /* Other results (useful)*/
                   7971: 
                   7972: 
1.126     brouard  7973:     /*--------------- Prevalence limit  (period or stable prevalence) --------------*/
1.180     brouard  7974:     /*#include "prevlim.h"*/  /* Use ficrespl, ficlog */
                   7975:     prlim=matrix(1,nlstate,1,nlstate);
1.203     brouard  7976:     prevalence_limit(p, prlim,  ageminpar, agemaxpar, ftolpl, ncvyear);
1.126     brouard  7977:     fclose(ficrespl);
                   7978: 
1.145     brouard  7979: #ifdef FREEEXIT2
                   7980: #include "freeexit2.h"
                   7981: #endif
                   7982: 
1.126     brouard  7983:     /*------------- h Pij x at various ages ------------*/
1.180     brouard  7984:     /*#include "hpijx.h"*/
                   7985:     hPijx(p, bage, fage);
1.145     brouard  7986:     fclose(ficrespij);
1.126     brouard  7987: 
1.145     brouard  7988:   /*-------------- Variance of one-step probabilities---*/
                   7989:     k=1;
1.126     brouard  7990:     varprob(optionfilefiname, matcov, p, delti, nlstate, bage, fage,k,Tvar,nbcode, ncodemax,strstart);
                   7991: 
                   7992: 
                   7993:     probs= ma3x(1,AGESUP,1,NCOVMAX, 1,NCOVMAX);
                   7994:     for(i=1;i<=AGESUP;i++)
                   7995:       for(j=1;j<=NCOVMAX;j++)
                   7996:        for(k=1;k<=NCOVMAX;k++)
                   7997:          probs[i][j][k]=0.;
                   7998: 
                   7999:     /*---------- Forecasting ------------------*/
                   8000:     /*if((stepm == 1) && (strcmp(model,".")==0)){*/
                   8001:     if(prevfcast==1){
                   8002:       /*    if(stepm ==1){*/
1.201     brouard  8003:       prevforecast(fileresu, anproj1, mproj1, jproj1, agemin, agemax, dateprev1, dateprev2, mobilavproj, bage, fage, firstpass, lastpass, anproj2, p, cptcoveff);
1.126     brouard  8004:       /* (popforecast==1) populforecast(fileres, anpyram,mpyram,jpyram, agemin,agemax, dateprev1, dateprev2,mobilav, agedeb, fage, popforecast, popfile, anpyram1,p, i1);*/
                   8005:       /*      }  */
                   8006:       /*      else{ */
                   8007:       /*        erreur=108; */
                   8008:       /*        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); */
                   8009:       /*        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); */
                   8010:       /*      } */
                   8011:     }
1.186     brouard  8012:  
                   8013:     /* ------ Other prevalence ratios------------ */
1.126     brouard  8014: 
1.127     brouard  8015:     /* Computes prevalence between agemin (i.e minimal age computed) and no more ageminpar */
                   8016: 
                   8017:     prevalence(probs, agemin, agemax, s, agev, nlstate, imx, Tvar, nbcode, ncodemax, mint, anint, dateprev1, dateprev2, firstpass, lastpass);
                   8018:     /*  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",\
                   8019:        ageminpar, agemax, s[lastpass][imx], agev[lastpass][imx], nlstate, imx, mint[lastpass][imx],anint[lastpass][imx], dateprev1, dateprev2, firstpass, lastpass);
                   8020:     */
1.126     brouard  8021: 
1.127     brouard  8022:     if (mobilav!=0) {
                   8023:       mobaverage= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
                   8024:       if (movingaverage(probs, bage, fage, mobaverage,mobilav)!=0){
                   8025:        fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav);
                   8026:        printf(" Error in movingaverage mobilav=%d\n",mobilav);
                   8027:       }
1.126     brouard  8028:     }
                   8029: 
                   8030: 
1.127     brouard  8031:     /*---------- Health expectancies, no variances ------------*/
                   8032: 
1.201     brouard  8033:     strcpy(filerese,"E_");
                   8034:     strcat(filerese,fileresu);
1.126     brouard  8035:     if((ficreseij=fopen(filerese,"w"))==NULL) {
                   8036:       printf("Problem with Health Exp. resultfile: %s\n", filerese); exit(0);
                   8037:       fprintf(ficlog,"Problem with Health Exp. resultfile: %s\n", filerese); exit(0);
                   8038:     }
                   8039:     printf("Computing Health Expectancies: result on file '%s' \n", filerese);
                   8040:     fprintf(ficlog,"Computing Health Expectancies: result on file '%s' \n", filerese);
1.145     brouard  8041:     /*for(cptcov=1,k=0;cptcov<=i1;cptcov++){
                   8042:       for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){*/
                   8043:           
                   8044:     for (k=1; k <= (int) pow(2,cptcoveff); k++){
1.127     brouard  8045:        fprintf(ficreseij,"\n#****** ");
                   8046:        for(j=1;j<=cptcoveff;j++) {
1.200     brouard  8047:          fprintf(ficreseij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
1.127     brouard  8048:        }
                   8049:        fprintf(ficreseij,"******\n");
                   8050: 
                   8051:        eij=ma3x(1,nlstate,1,nlstate,(int) bage, (int) fage);
                   8052:        oldm=oldms;savm=savms;
                   8053:        evsij(eij, p, nlstate, stepm, (int) bage, (int)fage, oldm, savm, k, estepm, strstart);  
                   8054:       
                   8055:        free_ma3x(eij,1,nlstate,1,nlstate,(int) bage, (int)fage);
1.145     brouard  8056:       /*}*/
1.127     brouard  8057:     }
                   8058:     fclose(ficreseij);
                   8059: 
                   8060: 
                   8061:     /*---------- Health expectancies and variances ------------*/
                   8062: 
                   8063: 
1.201     brouard  8064:     strcpy(filerest,"T_");
                   8065:     strcat(filerest,fileresu);
1.127     brouard  8066:     if((ficrest=fopen(filerest,"w"))==NULL) {
                   8067:       printf("Problem with total LE resultfile: %s\n", filerest);goto end;
                   8068:       fprintf(ficlog,"Problem with total LE resultfile: %s\n", filerest);goto end;
                   8069:     }
                   8070:     printf("Computing Total Life expectancies with their standard errors: file '%s' \n", filerest); 
                   8071:     fprintf(ficlog,"Computing Total Life expectancies with their standard errors: file '%s' \n", filerest); 
                   8072: 
1.126     brouard  8073: 
1.201     brouard  8074:     strcpy(fileresstde,"STDE_");
                   8075:     strcat(fileresstde,fileresu);
1.126     brouard  8076:     if((ficresstdeij=fopen(fileresstde,"w"))==NULL) {
                   8077:       printf("Problem with Health Exp. and std errors resultfile: %s\n", fileresstde); exit(0);
                   8078:       fprintf(ficlog,"Problem with Health Exp. and std errors resultfile: %s\n", fileresstde); exit(0);
                   8079:     }
                   8080:     printf("Computing Health Expectancies and standard errors: result on file '%s' \n", fileresstde);
                   8081:     fprintf(ficlog,"Computing Health Expectancies and standard errors: result on file '%s' \n", fileresstde);
                   8082: 
1.201     brouard  8083:     strcpy(filerescve,"CVE_");
                   8084:     strcat(filerescve,fileresu);
1.126     brouard  8085:     if((ficrescveij=fopen(filerescve,"w"))==NULL) {
                   8086:       printf("Problem with Covar. Health Exp. resultfile: %s\n", filerescve); exit(0);
                   8087:       fprintf(ficlog,"Problem with Covar. Health Exp. resultfile: %s\n", filerescve); exit(0);
                   8088:     }
                   8089:     printf("Computing Covar. of Health Expectancies: result on file '%s' \n", filerescve);
                   8090:     fprintf(ficlog,"Computing Covar. of Health Expectancies: result on file '%s' \n", filerescve);
                   8091: 
1.201     brouard  8092:     strcpy(fileresv,"V_");
                   8093:     strcat(fileresv,fileresu);
1.126     brouard  8094:     if((ficresvij=fopen(fileresv,"w"))==NULL) {
                   8095:       printf("Problem with variance resultfile: %s\n", fileresv);exit(0);
                   8096:       fprintf(ficlog,"Problem with variance resultfile: %s\n", fileresv);exit(0);
                   8097:     }
                   8098:     printf("Computing Variance-covariance of DFLEs: file '%s' \n", fileresv);
                   8099:     fprintf(ficlog,"Computing Variance-covariance of DFLEs: file '%s' \n", fileresv);
                   8100: 
1.145     brouard  8101:     /*for(cptcov=1,k=0;cptcov<=i1;cptcov++){
                   8102:       for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){*/
                   8103:           
                   8104:     for (k=1; k <= (int) pow(2,cptcoveff); k++){
                   8105:        fprintf(ficrest,"\n#****** ");
1.126     brouard  8106:        for(j=1;j<=cptcoveff;j++) 
1.200     brouard  8107:          fprintf(ficrest,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
1.126     brouard  8108:        fprintf(ficrest,"******\n");
                   8109: 
                   8110:        fprintf(ficresstdeij,"\n#****** ");
                   8111:        fprintf(ficrescveij,"\n#****** ");
                   8112:        for(j=1;j<=cptcoveff;j++) {
1.200     brouard  8113:          fprintf(ficresstdeij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
                   8114:          fprintf(ficrescveij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
1.126     brouard  8115:        }
                   8116:        fprintf(ficresstdeij,"******\n");
                   8117:        fprintf(ficrescveij,"******\n");
                   8118: 
                   8119:        fprintf(ficresvij,"\n#****** ");
                   8120:        for(j=1;j<=cptcoveff;j++) 
1.200     brouard  8121:          fprintf(ficresvij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
1.126     brouard  8122:        fprintf(ficresvij,"******\n");
                   8123: 
                   8124:        eij=ma3x(1,nlstate,1,nlstate,(int) bage, (int) fage);
                   8125:        oldm=oldms;savm=savms;
1.127     brouard  8126:        cvevsij(eij, p, nlstate, stepm, (int) bage, (int)fage, oldm, savm, k, estepm, delti, matcov, strstart);  
1.145     brouard  8127:        /*
                   8128:         */
                   8129:        /* goto endfree; */
1.126     brouard  8130:  
                   8131:        vareij=ma3x(1,nlstate,1,nlstate,(int) bage, (int) fage);
                   8132:        pstamp(ficrest);
1.145     brouard  8133: 
                   8134: 
1.128     brouard  8135:        for(vpopbased=0; vpopbased <= popbased; vpopbased++){ /* Done for vpopbased=0 and vpopbased=1 if popbased==1*/
1.199     brouard  8136:          oldm=oldms;savm=savms; /* ZZ Segmentation fault */
1.161     brouard  8137:          cptcod= 0; /* To be deleted */
1.203     brouard  8138:          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.145     brouard  8139:          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 ");
1.128     brouard  8140:          if(vpopbased==1)
                   8141:            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);
                   8142:          else
                   8143:            fprintf(ficrest,"the age specific period (stable) prevalences in each health state \n");
1.201     brouard  8144:          fprintf(ficrest,"# Age popbased mobilav e.. (std) ");
1.128     brouard  8145:          for (i=1;i<=nlstate;i++) fprintf(ficrest,"e.%d (std) ",i);
                   8146:          fprintf(ficrest,"\n");
1.199     brouard  8147:          /* printf("Which p?\n"); for(i=1;i<=npar;i++)printf("p[i=%d]=%lf,",i,p[i]);printf("\n"); */
1.128     brouard  8148:          epj=vector(1,nlstate+1);
                   8149:          for(age=bage; age <=fage ;age++){
1.203     brouard  8150:            prevalim(prlim, nlstate, p, age, oldm, savm, ftolpl, ncvyear, k); /*ZZ Is it the correct prevalim */
1.128     brouard  8151:            if (vpopbased==1) {
                   8152:              if(mobilav ==0){
                   8153:                for(i=1; i<=nlstate;i++)
                   8154:                  prlim[i][i]=probs[(int)age][i][k];
                   8155:              }else{ /* mobilav */ 
                   8156:                for(i=1; i<=nlstate;i++)
                   8157:                  prlim[i][i]=mobaverage[(int)age][i][k];
                   8158:              }
1.126     brouard  8159:            }
                   8160:        
1.201     brouard  8161:            fprintf(ficrest," %4.0f %d %d",age, vpopbased, mobilav);
1.205     brouard  8162:            /* fprintf(ficrest," %4.0f %d %d %d %d",age, vpopbased, mobilav,Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]); */ /* to be done */
1.199     brouard  8163:            /* printf(" age %4.0f ",age); */
1.128     brouard  8164:            for(j=1, epj[nlstate+1]=0.;j <=nlstate;j++){
                   8165:              for(i=1, epj[j]=0.;i <=nlstate;i++) {
                   8166:                epj[j] += prlim[i][i]*eij[i][j][(int)age];
1.199     brouard  8167:                /*ZZZ  printf("%lf %lf ", prlim[i][i] ,eij[i][j][(int)age]);*/
                   8168:                /* printf("%lf %lf ", prlim[i][i] ,eij[i][j][(int)age]); */
1.128     brouard  8169:              }
                   8170:              epj[nlstate+1] +=epj[j];
1.126     brouard  8171:            }
1.199     brouard  8172:            /* printf(" age %4.0f \n",age); */
1.126     brouard  8173: 
1.128     brouard  8174:            for(i=1, vepp=0.;i <=nlstate;i++)
                   8175:              for(j=1;j <=nlstate;j++)
                   8176:                vepp += vareij[i][j][(int)age];
                   8177:            fprintf(ficrest," %7.3f (%7.3f)", epj[nlstate+1],sqrt(vepp));
                   8178:            for(j=1;j <=nlstate;j++){
                   8179:              fprintf(ficrest," %7.3f (%7.3f)", epj[j],sqrt(vareij[j][j][(int)age]));
                   8180:            }
                   8181:            fprintf(ficrest,"\n");
1.126     brouard  8182:          }
                   8183:        }
                   8184:        free_ma3x(eij,1,nlstate,1,nlstate,(int) bage, (int)fage);
                   8185:        free_ma3x(vareij,1,nlstate,1,nlstate,(int) bage, (int)fage);
                   8186:        free_vector(epj,1,nlstate+1);
1.145     brouard  8187:       /*}*/
1.126     brouard  8188:     }
                   8189:     free_vector(weight,1,n);
1.145     brouard  8190:     free_imatrix(Tvard,1,NCOVMAX,1,2);
1.126     brouard  8191:     free_imatrix(s,1,maxwav+1,1,n);
                   8192:     free_matrix(anint,1,maxwav,1,n); 
                   8193:     free_matrix(mint,1,maxwav,1,n);
                   8194:     free_ivector(cod,1,n);
                   8195:     free_ivector(tab,1,NCOVMAX);
                   8196:     fclose(ficresstdeij);
                   8197:     fclose(ficrescveij);
                   8198:     fclose(ficresvij);
                   8199:     fclose(ficrest);
                   8200:     fclose(ficpar);
                   8201:   
                   8202:     /*------- Variance of period (stable) prevalence------*/   
                   8203: 
1.201     brouard  8204:     strcpy(fileresvpl,"VPL_");
                   8205:     strcat(fileresvpl,fileresu);
1.126     brouard  8206:     if((ficresvpl=fopen(fileresvpl,"w"))==NULL) {
                   8207:       printf("Problem with variance of period (stable) prevalence  resultfile: %s\n", fileresvpl);
                   8208:       exit(0);
                   8209:     }
                   8210:     printf("Computing Variance-covariance of period (stable) prevalence: file '%s' \n", fileresvpl);
                   8211: 
1.145     brouard  8212:     /*for(cptcov=1,k=0;cptcov<=i1;cptcov++){
                   8213:       for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){*/
                   8214:           
                   8215:     for (k=1; k <= (int) pow(2,cptcoveff); k++){
                   8216:        fprintf(ficresvpl,"\n#****** ");
1.126     brouard  8217:        for(j=1;j<=cptcoveff;j++) 
1.200     brouard  8218:          fprintf(ficresvpl,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
1.126     brouard  8219:        fprintf(ficresvpl,"******\n");
                   8220:       
                   8221:        varpl=matrix(1,nlstate,(int) bage, (int) fage);
                   8222:        oldm=oldms;savm=savms;
1.203     brouard  8223:        varprevlim(fileres, varpl, matcov, p, delti, nlstate, stepm, (int) bage, (int) fage, oldm, savm, prlim, ftolpl, ncvyear, k, strstart);
1.126     brouard  8224:        free_matrix(varpl,1,nlstate,(int) bage, (int)fage);
1.145     brouard  8225:       /*}*/
1.126     brouard  8226:     }
                   8227: 
                   8228:     fclose(ficresvpl);
                   8229: 
                   8230:     /*---------- End : free ----------------*/
                   8231:     if (mobilav!=0) free_ma3x(mobaverage,1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
                   8232:     free_ma3x(probs,1,AGESUP,1,NCOVMAX, 1,NCOVMAX);
                   8233:   }  /* mle==-3 arrives here for freeing */
1.164     brouard  8234:  /* endfree:*/
1.141     brouard  8235:     free_matrix(prlim,1,nlstate,1,nlstate); /*here or after loop ? */
1.126     brouard  8236:     free_matrix(pmmij,1,nlstate+ndeath,1,nlstate+ndeath);
                   8237:     free_matrix(oldms, 1,nlstate+ndeath,1,nlstate+ndeath);
                   8238:     free_matrix(newms, 1,nlstate+ndeath,1,nlstate+ndeath);
                   8239:     free_matrix(savms, 1,nlstate+ndeath,1,nlstate+ndeath);
                   8240:     free_matrix(covar,0,NCOVMAX,1,n);
                   8241:     free_matrix(matcov,1,npar,1,npar);
1.203     brouard  8242:     free_matrix(hess,1,npar,1,npar);
1.126     brouard  8243:     /*free_vector(delti,1,npar);*/
                   8244:     free_ma3x(delti3,1,nlstate,1, nlstate+ndeath-1,1,ncovmodel); 
                   8245:     free_matrix(agev,1,maxwav,1,imx);
                   8246:     free_ma3x(param,1,nlstate,1, nlstate+ndeath-1,1,ncovmodel);
                   8247: 
1.145     brouard  8248:     free_ivector(ncodemax,1,NCOVMAX);
1.192     brouard  8249:     free_ivector(ncodemaxwundef,1,NCOVMAX);
1.145     brouard  8250:     free_ivector(Tvar,1,NCOVMAX);
                   8251:     free_ivector(Tprod,1,NCOVMAX);
                   8252:     free_ivector(Tvaraff,1,NCOVMAX);
                   8253:     free_ivector(Tage,1,NCOVMAX);
1.126     brouard  8254: 
                   8255:     free_imatrix(nbcode,0,NCOVMAX,0,NCOVMAX);
1.200     brouard  8256:     /* free_imatrix(codtab,1,100,1,10); */
1.126     brouard  8257:   fflush(fichtm);
                   8258:   fflush(ficgp);
                   8259:   
                   8260: 
                   8261:   if((nberr >0) || (nbwarn>0)){
                   8262:     printf("End of Imach with %d errors and/or %d warnings\n",nberr,nbwarn);
                   8263:     fprintf(ficlog,"End of Imach with %d errors and/or warnings %d\n",nberr,nbwarn);
                   8264:   }else{
                   8265:     printf("End of Imach\n");
                   8266:     fprintf(ficlog,"End of Imach\n");
                   8267:   }
                   8268:   printf("See log file on %s\n",filelog);
                   8269:   /*  gettimeofday(&end_time, (struct timezone*)0);*/  /* after time */
1.157     brouard  8270:   /*(void) gettimeofday(&end_time,&tzp);*/
                   8271:   rend_time = time(NULL);  
                   8272:   end_time = *localtime(&rend_time);
                   8273:   /* tml = *localtime(&end_time.tm_sec); */
                   8274:   strcpy(strtend,asctime(&end_time));
1.126     brouard  8275:   printf("Local time at start %s\nLocal time at end   %s",strstart, strtend); 
                   8276:   fprintf(ficlog,"Local time at start %s\nLocal time at end   %s\n",strstart, strtend); 
1.157     brouard  8277:   printf("Total time used %s\n", asc_diff_time(rend_time -rstart_time,tmpout));
1.126     brouard  8278: 
1.157     brouard  8279:   printf("Total time was %.0lf Sec.\n", difftime(rend_time,rstart_time));
                   8280:   fprintf(ficlog,"Total time used %s\n", asc_diff_time(rend_time -rstart_time,tmpout));
                   8281:   fprintf(ficlog,"Total time was %.0lf Sec.\n", difftime(rend_time,rstart_time));
1.126     brouard  8282:   /*  printf("Total time was %d uSec.\n", total_usecs);*/
                   8283: /*   if(fileappend(fichtm,optionfilehtm)){ */
                   8284:   fprintf(fichtm,"<br>Local time at start %s<br>Local time at end   %s<br>\n</body></html>",strstart, strtend);
                   8285:   fclose(fichtm);
                   8286:   fprintf(fichtmcov,"<br>Local time at start %s<br>Local time at end   %s<br>\n</body></html>",strstart, strtend);
                   8287:   fclose(fichtmcov);
                   8288:   fclose(ficgp);
                   8289:   fclose(ficlog);
                   8290:   /*------ End -----------*/
                   8291: 
                   8292: 
                   8293:    printf("Before Current directory %s!\n",pathcd);
1.184     brouard  8294: #ifdef WIN32
                   8295:    if (_chdir(pathcd) != 0)
                   8296:           printf("Can't move to directory %s!\n",path);
                   8297:    if(_getcwd(pathcd,MAXLINE) > 0)
                   8298: #else
1.126     brouard  8299:    if(chdir(pathcd) != 0)
1.184     brouard  8300:           printf("Can't move to directory %s!\n", path);
                   8301:    if (getcwd(pathcd, MAXLINE) > 0)
                   8302: #endif 
1.126     brouard  8303:     printf("Current directory %s!\n",pathcd);
                   8304:   /*strcat(plotcmd,CHARSEPARATOR);*/
                   8305:   sprintf(plotcmd,"gnuplot");
1.157     brouard  8306: #ifdef _WIN32
1.126     brouard  8307:   sprintf(plotcmd,"\"%sgnuplot.exe\"",pathimach);
                   8308: #endif
                   8309:   if(!stat(plotcmd,&info)){
1.158     brouard  8310:     printf("Error or gnuplot program not found: '%s'\n",plotcmd);fflush(stdout);
1.126     brouard  8311:     if(!stat(getenv("GNUPLOTBIN"),&info)){
1.158     brouard  8312:       printf("Error or gnuplot program not found: '%s' Environment GNUPLOTBIN not set.\n",plotcmd);fflush(stdout);
1.126     brouard  8313:     }else
                   8314:       strcpy(pplotcmd,plotcmd);
1.157     brouard  8315: #ifdef __unix
1.126     brouard  8316:     strcpy(plotcmd,GNUPLOTPROGRAM);
                   8317:     if(!stat(plotcmd,&info)){
1.158     brouard  8318:       printf("Error gnuplot program not found: '%s'\n",plotcmd);fflush(stdout);
1.126     brouard  8319:     }else
                   8320:       strcpy(pplotcmd,plotcmd);
                   8321: #endif
                   8322:   }else
                   8323:     strcpy(pplotcmd,plotcmd);
                   8324:   
                   8325:   sprintf(plotcmd,"%s %s",pplotcmd, optionfilegnuplot);
1.158     brouard  8326:   printf("Starting graphs with: '%s'\n",plotcmd);fflush(stdout);
1.126     brouard  8327: 
                   8328:   if((outcmd=system(plotcmd)) != 0){
1.158     brouard  8329:     printf("gnuplot command might not be in your path: '%s', err=%d\n", plotcmd, outcmd);
1.154     brouard  8330:     printf("\n Trying if gnuplot resides on the same directory that IMaCh\n");
1.152     brouard  8331:     sprintf(plotcmd,"%sgnuplot %s", pathimach, optionfilegnuplot);
1.150     brouard  8332:     if((outcmd=system(plotcmd)) != 0)
1.153     brouard  8333:       printf("\n Still a problem with gnuplot command %s, err=%d\n", plotcmd, outcmd);
1.126     brouard  8334:   }
1.158     brouard  8335:   printf(" Successful, please wait...");
1.126     brouard  8336:   while (z[0] != 'q') {
                   8337:     /* chdir(path); */
1.154     brouard  8338:     printf("\nType e to edit results with your browser, g to graph again and q for exit: ");
1.126     brouard  8339:     scanf("%s",z);
                   8340: /*     if (z[0] == 'c') system("./imach"); */
                   8341:     if (z[0] == 'e') {
1.158     brouard  8342: #ifdef __APPLE__
1.152     brouard  8343:       sprintf(pplotcmd, "open %s", optionfilehtm);
1.157     brouard  8344: #elif __linux
                   8345:       sprintf(pplotcmd, "xdg-open %s", optionfilehtm);
1.153     brouard  8346: #else
1.152     brouard  8347:       sprintf(pplotcmd, "%s", optionfilehtm);
1.153     brouard  8348: #endif
                   8349:       printf("Starting browser with: %s",pplotcmd);fflush(stdout);
                   8350:       system(pplotcmd);
1.126     brouard  8351:     }
                   8352:     else if (z[0] == 'g') system(plotcmd);
                   8353:     else if (z[0] == 'q') exit(0);
                   8354:   }
                   8355:   end:
                   8356:   while (z[0] != 'q') {
1.195     brouard  8357:     printf("\nType  q for exiting: "); fflush(stdout);
1.126     brouard  8358:     scanf("%s",z);
                   8359:   }
                   8360: }

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