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

1.197   ! brouard     1: /* $Id: imach.c,v 1.196 2015/08/18 23:17:52 brouard Exp $
1.126     brouard     2:   $State: Exp $
1.163     brouard     3:   $Log: imach.c,v $
1.197   ! brouard     4:   Revision 1.196  2015/08/18 23:17:52  brouard
        !             5:   Summary: 0.98q5
        !             6: 
1.196     brouard     7:   Revision 1.195  2015/08/18 16:28:39  brouard
                      8:   Summary: Adding a hack for testing purpose
                      9: 
                     10:   After reading the title, ftol and model lines, if the comment line has
                     11:   a q, starting with #q, the answer at the end of the run is quit. It
                     12:   permits to run test files in batch with ctest. The former workaround was
                     13:   $ echo q | imach foo.imach
                     14: 
1.195     brouard    15:   Revision 1.194  2015/08/18 13:32:00  brouard
                     16:   Summary:  Adding error when the covariance matrix doesn't contain the exact number of lines required by the model line.
                     17: 
1.194     brouard    18:   Revision 1.193  2015/08/04 07:17:42  brouard
                     19:   Summary: 0.98q4
                     20: 
1.193     brouard    21:   Revision 1.192  2015/07/16 16:49:02  brouard
                     22:   Summary: Fixing some outputs
                     23: 
1.192     brouard    24:   Revision 1.191  2015/07/14 10:00:33  brouard
                     25:   Summary: Some fixes
                     26: 
1.191     brouard    27:   Revision 1.190  2015/05/05 08:51:13  brouard
                     28:   Summary: Adding digits in output parameters (7 digits instead of 6)
                     29: 
                     30:   Fix 1+age+.
                     31: 
1.190     brouard    32:   Revision 1.189  2015/04/30 14:45:16  brouard
                     33:   Summary: 0.98q2
                     34: 
1.189     brouard    35:   Revision 1.188  2015/04/30 08:27:53  brouard
                     36:   *** empty log message ***
                     37: 
1.188     brouard    38:   Revision 1.187  2015/04/29 09:11:15  brouard
                     39:   *** empty log message ***
                     40: 
1.187     brouard    41:   Revision 1.186  2015/04/23 12:01:52  brouard
                     42:   Summary: V1*age is working now, version 0.98q1
                     43: 
                     44:   Some codes had been disabled in order to simplify and Vn*age was
                     45:   working in the optimization phase, ie, giving correct MLE parameters,
                     46:   but, as usual, outputs were not correct and program core dumped.
                     47: 
1.186     brouard    48:   Revision 1.185  2015/03/11 13:26:42  brouard
                     49:   Summary: Inclusion of compile and links command line for Intel Compiler
                     50: 
1.185     brouard    51:   Revision 1.184  2015/03/11 11:52:39  brouard
                     52:   Summary: Back from Windows 8. Intel Compiler
                     53: 
1.184     brouard    54:   Revision 1.183  2015/03/10 20:34:32  brouard
                     55:   Summary: 0.98q0, trying with directest, mnbrak fixed
                     56: 
                     57:   We use directest instead of original Powell test; probably no
                     58:   incidence on the results, but better justifications;
                     59:   We fixed Numerical Recipes mnbrak routine which was wrong and gave
                     60:   wrong results.
                     61: 
1.183     brouard    62:   Revision 1.182  2015/02/12 08:19:57  brouard
                     63:   Summary: Trying to keep directest which seems simpler and more general
                     64:   Author: Nicolas Brouard
                     65: 
1.182     brouard    66:   Revision 1.181  2015/02/11 23:22:24  brouard
                     67:   Summary: Comments on Powell added
                     68: 
                     69:   Author:
                     70: 
1.181     brouard    71:   Revision 1.180  2015/02/11 17:33:45  brouard
                     72:   Summary: Finishing move from main to function (hpijx and prevalence_limit)
                     73: 
1.180     brouard    74:   Revision 1.179  2015/01/04 09:57:06  brouard
                     75:   Summary: back to OS/X
                     76: 
1.179     brouard    77:   Revision 1.178  2015/01/04 09:35:48  brouard
                     78:   *** empty log message ***
                     79: 
1.178     brouard    80:   Revision 1.177  2015/01/03 18:40:56  brouard
                     81:   Summary: Still testing ilc32 on OSX
                     82: 
1.177     brouard    83:   Revision 1.176  2015/01/03 16:45:04  brouard
                     84:   *** empty log message ***
                     85: 
1.176     brouard    86:   Revision 1.175  2015/01/03 16:33:42  brouard
                     87:   *** empty log message ***
                     88: 
1.175     brouard    89:   Revision 1.174  2015/01/03 16:15:49  brouard
                     90:   Summary: Still in cross-compilation
                     91: 
1.174     brouard    92:   Revision 1.173  2015/01/03 12:06:26  brouard
                     93:   Summary: trying to detect cross-compilation
                     94: 
1.173     brouard    95:   Revision 1.172  2014/12/27 12:07:47  brouard
                     96:   Summary: Back from Visual Studio and Intel, options for compiling for Windows XP
                     97: 
1.172     brouard    98:   Revision 1.171  2014/12/23 13:26:59  brouard
                     99:   Summary: Back from Visual C
                    100: 
                    101:   Still problem with utsname.h on Windows
                    102: 
1.171     brouard   103:   Revision 1.170  2014/12/23 11:17:12  brouard
                    104:   Summary: Cleaning some \%% back to %%
                    105: 
                    106:   The escape was mandatory for a specific compiler (which one?), but too many warnings.
                    107: 
1.170     brouard   108:   Revision 1.169  2014/12/22 23:08:31  brouard
                    109:   Summary: 0.98p
                    110: 
                    111:   Outputs some informations on compiler used, OS etc. Testing on different platforms.
                    112: 
1.169     brouard   113:   Revision 1.168  2014/12/22 15:17:42  brouard
1.170     brouard   114:   Summary: update
1.169     brouard   115: 
1.168     brouard   116:   Revision 1.167  2014/12/22 13:50:56  brouard
                    117:   Summary: Testing uname and compiler version and if compiled 32 or 64
                    118: 
                    119:   Testing on Linux 64
                    120: 
1.167     brouard   121:   Revision 1.166  2014/12/22 11:40:47  brouard
                    122:   *** empty log message ***
                    123: 
1.166     brouard   124:   Revision 1.165  2014/12/16 11:20:36  brouard
                    125:   Summary: After compiling on Visual C
                    126: 
                    127:   * imach.c (Module): Merging 1.61 to 1.162
                    128: 
1.165     brouard   129:   Revision 1.164  2014/12/16 10:52:11  brouard
                    130:   Summary: Merging with Visual C after suppressing some warnings for unused variables. Also fixing Saito's bug 0.98Xn
                    131: 
                    132:   * imach.c (Module): Merging 1.61 to 1.162
                    133: 
1.164     brouard   134:   Revision 1.163  2014/12/16 10:30:11  brouard
                    135:   * imach.c (Module): Merging 1.61 to 1.162
                    136: 
1.163     brouard   137:   Revision 1.162  2014/09/25 11:43:39  brouard
                    138:   Summary: temporary backup 0.99!
                    139: 
1.162     brouard   140:   Revision 1.1  2014/09/16 11:06:58  brouard
                    141:   Summary: With some code (wrong) for nlopt
                    142: 
                    143:   Author:
                    144: 
                    145:   Revision 1.161  2014/09/15 20:41:41  brouard
                    146:   Summary: Problem with macro SQR on Intel compiler
                    147: 
1.161     brouard   148:   Revision 1.160  2014/09/02 09:24:05  brouard
                    149:   *** empty log message ***
                    150: 
1.160     brouard   151:   Revision 1.159  2014/09/01 10:34:10  brouard
                    152:   Summary: WIN32
                    153:   Author: Brouard
                    154: 
1.159     brouard   155:   Revision 1.158  2014/08/27 17:11:51  brouard
                    156:   *** empty log message ***
                    157: 
1.158     brouard   158:   Revision 1.157  2014/08/27 16:26:55  brouard
                    159:   Summary: Preparing windows Visual studio version
                    160:   Author: Brouard
                    161: 
                    162:   In order to compile on Visual studio, time.h is now correct and time_t
                    163:   and tm struct should be used. difftime should be used but sometimes I
                    164:   just make the differences in raw time format (time(&now).
                    165:   Trying to suppress #ifdef LINUX
                    166:   Add xdg-open for __linux in order to open default browser.
                    167: 
1.157     brouard   168:   Revision 1.156  2014/08/25 20:10:10  brouard
                    169:   *** empty log message ***
                    170: 
1.156     brouard   171:   Revision 1.155  2014/08/25 18:32:34  brouard
                    172:   Summary: New compile, minor changes
                    173:   Author: Brouard
                    174: 
1.155     brouard   175:   Revision 1.154  2014/06/20 17:32:08  brouard
                    176:   Summary: Outputs now all graphs of convergence to period prevalence
                    177: 
1.154     brouard   178:   Revision 1.153  2014/06/20 16:45:46  brouard
                    179:   Summary: If 3 live state, convergence to period prevalence on same graph
                    180:   Author: Brouard
                    181: 
1.153     brouard   182:   Revision 1.152  2014/06/18 17:54:09  brouard
                    183:   Summary: open browser, use gnuplot on same dir than imach if not found in the path
                    184: 
1.152     brouard   185:   Revision 1.151  2014/06/18 16:43:30  brouard
                    186:   *** empty log message ***
                    187: 
1.151     brouard   188:   Revision 1.150  2014/06/18 16:42:35  brouard
                    189:   Summary: If gnuplot is not in the path try on same directory than imach binary (OSX)
                    190:   Author: brouard
                    191: 
1.150     brouard   192:   Revision 1.149  2014/06/18 15:51:14  brouard
                    193:   Summary: Some fixes in parameter files errors
                    194:   Author: Nicolas Brouard
                    195: 
1.149     brouard   196:   Revision 1.148  2014/06/17 17:38:48  brouard
                    197:   Summary: Nothing new
                    198:   Author: Brouard
                    199: 
                    200:   Just a new packaging for OS/X version 0.98nS
                    201: 
1.148     brouard   202:   Revision 1.147  2014/06/16 10:33:11  brouard
                    203:   *** empty log message ***
                    204: 
1.147     brouard   205:   Revision 1.146  2014/06/16 10:20:28  brouard
                    206:   Summary: Merge
                    207:   Author: Brouard
                    208: 
                    209:   Merge, before building revised version.
                    210: 
1.146     brouard   211:   Revision 1.145  2014/06/10 21:23:15  brouard
                    212:   Summary: Debugging with valgrind
                    213:   Author: Nicolas Brouard
                    214: 
                    215:   Lot of changes in order to output the results with some covariates
                    216:   After the Edimburgh REVES conference 2014, it seems mandatory to
                    217:   improve the code.
                    218:   No more memory valgrind error but a lot has to be done in order to
                    219:   continue the work of splitting the code into subroutines.
                    220:   Also, decodemodel has been improved. Tricode is still not
                    221:   optimal. nbcode should be improved. Documentation has been added in
                    222:   the source code.
                    223: 
1.144     brouard   224:   Revision 1.143  2014/01/26 09:45:38  brouard
                    225:   Summary: Version 0.98nR (to be improved, but gives same optimization results as 0.98k. Nice, promising
                    226: 
                    227:   * imach.c (Module): Trying to merge old staffs together while being at Tokyo. Not tested...
                    228:   (Module): Version 0.98nR Running ok, but output format still only works for three covariates.
                    229: 
1.143     brouard   230:   Revision 1.142  2014/01/26 03:57:36  brouard
                    231:   Summary: gnuplot changed plot w l 1 has to be changed to plot w l lt 2
                    232: 
                    233:   * imach.c (Module): Trying to merge old staffs together while being at Tokyo. Not tested...
                    234: 
1.142     brouard   235:   Revision 1.141  2014/01/26 02:42:01  brouard
                    236:   * imach.c (Module): Trying to merge old staffs together while being at Tokyo. Not tested...
                    237: 
1.141     brouard   238:   Revision 1.140  2011/09/02 10:37:54  brouard
                    239:   Summary: times.h is ok with mingw32 now.
                    240: 
1.140     brouard   241:   Revision 1.139  2010/06/14 07:50:17  brouard
                    242:   After the theft of my laptop, I probably lost some lines of codes which were not uploaded to the CVS tree.
                    243:   I remember having already fixed agemin agemax which are pointers now but not cvs saved.
                    244: 
1.139     brouard   245:   Revision 1.138  2010/04/30 18:19:40  brouard
                    246:   *** empty log message ***
                    247: 
1.138     brouard   248:   Revision 1.137  2010/04/29 18:11:38  brouard
                    249:   (Module): Checking covariates for more complex models
                    250:   than V1+V2. A lot of change to be done. Unstable.
                    251: 
1.137     brouard   252:   Revision 1.136  2010/04/26 20:30:53  brouard
                    253:   (Module): merging some libgsl code. Fixing computation
                    254:   of likelione (using inter/intrapolation if mle = 0) in order to
                    255:   get same likelihood as if mle=1.
                    256:   Some cleaning of code and comments added.
                    257: 
1.136     brouard   258:   Revision 1.135  2009/10/29 15:33:14  brouard
                    259:   (Module): Now imach stops if date of birth, at least year of birth, is not given. Some cleaning of the code.
                    260: 
1.135     brouard   261:   Revision 1.134  2009/10/29 13:18:53  brouard
                    262:   (Module): Now imach stops if date of birth, at least year of birth, is not given. Some cleaning of the code.
                    263: 
1.134     brouard   264:   Revision 1.133  2009/07/06 10:21:25  brouard
                    265:   just nforces
                    266: 
1.133     brouard   267:   Revision 1.132  2009/07/06 08:22:05  brouard
                    268:   Many tings
                    269: 
1.132     brouard   270:   Revision 1.131  2009/06/20 16:22:47  brouard
                    271:   Some dimensions resccaled
                    272: 
1.131     brouard   273:   Revision 1.130  2009/05/26 06:44:34  brouard
                    274:   (Module): Max Covariate is now set to 20 instead of 8. A
                    275:   lot of cleaning with variables initialized to 0. Trying to make
                    276:   V2+V3*age+V1+V4 strb=V3*age+V1+V4 working better.
                    277: 
1.130     brouard   278:   Revision 1.129  2007/08/31 13:49:27  lievre
                    279:   Modification of the way of exiting when the covariate is not binary in order to see on the window the error message before exiting
                    280: 
1.129     lievre    281:   Revision 1.128  2006/06/30 13:02:05  brouard
                    282:   (Module): Clarifications on computing e.j
                    283: 
1.128     brouard   284:   Revision 1.127  2006/04/28 18:11:50  brouard
                    285:   (Module): Yes the sum of survivors was wrong since
                    286:   imach-114 because nhstepm was no more computed in the age
                    287:   loop. Now we define nhstepma in the age loop.
                    288:   (Module): In order to speed up (in case of numerous covariates) we
                    289:   compute health expectancies (without variances) in a first step
                    290:   and then all the health expectancies with variances or standard
                    291:   deviation (needs data from the Hessian matrices) which slows the
                    292:   computation.
                    293:   In the future we should be able to stop the program is only health
                    294:   expectancies and graph are needed without standard deviations.
                    295: 
1.127     brouard   296:   Revision 1.126  2006/04/28 17:23:28  brouard
                    297:   (Module): Yes the sum of survivors was wrong since
                    298:   imach-114 because nhstepm was no more computed in the age
                    299:   loop. Now we define nhstepma in the age loop.
                    300:   Version 0.98h
                    301: 
1.126     brouard   302:   Revision 1.125  2006/04/04 15:20:31  lievre
                    303:   Errors in calculation of health expectancies. Age was not initialized.
                    304:   Forecasting file added.
                    305: 
                    306:   Revision 1.124  2006/03/22 17:13:53  lievre
                    307:   Parameters are printed with %lf instead of %f (more numbers after the comma).
                    308:   The log-likelihood is printed in the log file
                    309: 
                    310:   Revision 1.123  2006/03/20 10:52:43  brouard
                    311:   * imach.c (Module): <title> changed, corresponds to .htm file
                    312:   name. <head> headers where missing.
                    313: 
                    314:   * imach.c (Module): Weights can have a decimal point as for
                    315:   English (a comma might work with a correct LC_NUMERIC environment,
                    316:   otherwise the weight is truncated).
                    317:   Modification of warning when the covariates values are not 0 or
                    318:   1.
                    319:   Version 0.98g
                    320: 
                    321:   Revision 1.122  2006/03/20 09:45:41  brouard
                    322:   (Module): Weights can have a decimal point as for
                    323:   English (a comma might work with a correct LC_NUMERIC environment,
                    324:   otherwise the weight is truncated).
                    325:   Modification of warning when the covariates values are not 0 or
                    326:   1.
                    327:   Version 0.98g
                    328: 
                    329:   Revision 1.121  2006/03/16 17:45:01  lievre
                    330:   * imach.c (Module): Comments concerning covariates added
                    331: 
                    332:   * imach.c (Module): refinements in the computation of lli if
                    333:   status=-2 in order to have more reliable computation if stepm is
                    334:   not 1 month. Version 0.98f
                    335: 
                    336:   Revision 1.120  2006/03/16 15:10:38  lievre
                    337:   (Module): refinements in the computation of lli if
                    338:   status=-2 in order to have more reliable computation if stepm is
                    339:   not 1 month. Version 0.98f
                    340: 
                    341:   Revision 1.119  2006/03/15 17:42:26  brouard
                    342:   (Module): Bug if status = -2, the loglikelihood was
                    343:   computed as likelihood omitting the logarithm. Version O.98e
                    344: 
                    345:   Revision 1.118  2006/03/14 18:20:07  brouard
                    346:   (Module): varevsij Comments added explaining the second
                    347:   table of variances if popbased=1 .
                    348:   (Module): Covariances of eij, ekl added, graphs fixed, new html link.
                    349:   (Module): Function pstamp added
                    350:   (Module): Version 0.98d
                    351: 
                    352:   Revision 1.117  2006/03/14 17:16:22  brouard
                    353:   (Module): varevsij Comments added explaining the second
                    354:   table of variances if popbased=1 .
                    355:   (Module): Covariances of eij, ekl added, graphs fixed, new html link.
                    356:   (Module): Function pstamp added
                    357:   (Module): Version 0.98d
                    358: 
                    359:   Revision 1.116  2006/03/06 10:29:27  brouard
                    360:   (Module): Variance-covariance wrong links and
                    361:   varian-covariance of ej. is needed (Saito).
                    362: 
                    363:   Revision 1.115  2006/02/27 12:17:45  brouard
                    364:   (Module): One freematrix added in mlikeli! 0.98c
                    365: 
                    366:   Revision 1.114  2006/02/26 12:57:58  brouard
                    367:   (Module): Some improvements in processing parameter
                    368:   filename with strsep.
                    369: 
                    370:   Revision 1.113  2006/02/24 14:20:24  brouard
                    371:   (Module): Memory leaks checks with valgrind and:
                    372:   datafile was not closed, some imatrix were not freed and on matrix
                    373:   allocation too.
                    374: 
                    375:   Revision 1.112  2006/01/30 09:55:26  brouard
                    376:   (Module): Back to gnuplot.exe instead of wgnuplot.exe
                    377: 
                    378:   Revision 1.111  2006/01/25 20:38:18  brouard
                    379:   (Module): Lots of cleaning and bugs added (Gompertz)
                    380:   (Module): Comments can be added in data file. Missing date values
                    381:   can be a simple dot '.'.
                    382: 
                    383:   Revision 1.110  2006/01/25 00:51:50  brouard
                    384:   (Module): Lots of cleaning and bugs added (Gompertz)
                    385: 
                    386:   Revision 1.109  2006/01/24 19:37:15  brouard
                    387:   (Module): Comments (lines starting with a #) are allowed in data.
                    388: 
                    389:   Revision 1.108  2006/01/19 18:05:42  lievre
                    390:   Gnuplot problem appeared...
                    391:   To be fixed
                    392: 
                    393:   Revision 1.107  2006/01/19 16:20:37  brouard
                    394:   Test existence of gnuplot in imach path
                    395: 
                    396:   Revision 1.106  2006/01/19 13:24:36  brouard
                    397:   Some cleaning and links added in html output
                    398: 
                    399:   Revision 1.105  2006/01/05 20:23:19  lievre
                    400:   *** empty log message ***
                    401: 
                    402:   Revision 1.104  2005/09/30 16:11:43  lievre
                    403:   (Module): sump fixed, loop imx fixed, and simplifications.
                    404:   (Module): If the status is missing at the last wave but we know
                    405:   that the person is alive, then we can code his/her status as -2
                    406:   (instead of missing=-1 in earlier versions) and his/her
                    407:   contributions to the likelihood is 1 - Prob of dying from last
                    408:   health status (= 1-p13= p11+p12 in the easiest case of somebody in
                    409:   the healthy state at last known wave). Version is 0.98
                    410: 
                    411:   Revision 1.103  2005/09/30 15:54:49  lievre
                    412:   (Module): sump fixed, loop imx fixed, and simplifications.
                    413: 
                    414:   Revision 1.102  2004/09/15 17:31:30  brouard
                    415:   Add the possibility to read data file including tab characters.
                    416: 
                    417:   Revision 1.101  2004/09/15 10:38:38  brouard
                    418:   Fix on curr_time
                    419: 
                    420:   Revision 1.100  2004/07/12 18:29:06  brouard
                    421:   Add version for Mac OS X. Just define UNIX in Makefile
                    422: 
                    423:   Revision 1.99  2004/06/05 08:57:40  brouard
                    424:   *** empty log message ***
                    425: 
                    426:   Revision 1.98  2004/05/16 15:05:56  brouard
                    427:   New version 0.97 . First attempt to estimate force of mortality
                    428:   directly from the data i.e. without the need of knowing the health
                    429:   state at each age, but using a Gompertz model: log u =a + b*age .
                    430:   This is the basic analysis of mortality and should be done before any
                    431:   other analysis, in order to test if the mortality estimated from the
                    432:   cross-longitudinal survey is different from the mortality estimated
                    433:   from other sources like vital statistic data.
                    434: 
                    435:   The same imach parameter file can be used but the option for mle should be -3.
                    436: 
1.133     brouard   437:   Agnès, who wrote this part of the code, tried to keep most of the
1.126     brouard   438:   former routines in order to include the new code within the former code.
                    439: 
                    440:   The output is very simple: only an estimate of the intercept and of
                    441:   the slope with 95% confident intervals.
                    442: 
                    443:   Current limitations:
                    444:   A) Even if you enter covariates, i.e. with the
                    445:   model= V1+V2 equation for example, the programm does only estimate a unique global model without covariates.
                    446:   B) There is no computation of Life Expectancy nor Life Table.
                    447: 
                    448:   Revision 1.97  2004/02/20 13:25:42  lievre
                    449:   Version 0.96d. Population forecasting command line is (temporarily)
                    450:   suppressed.
                    451: 
                    452:   Revision 1.96  2003/07/15 15:38:55  brouard
                    453:   * imach.c (Repository): Errors in subdirf, 2, 3 while printing tmpout is
                    454:   rewritten within the same printf. Workaround: many printfs.
                    455: 
                    456:   Revision 1.95  2003/07/08 07:54:34  brouard
                    457:   * imach.c (Repository):
                    458:   (Repository): Using imachwizard code to output a more meaningful covariance
                    459:   matrix (cov(a12,c31) instead of numbers.
                    460: 
                    461:   Revision 1.94  2003/06/27 13:00:02  brouard
                    462:   Just cleaning
                    463: 
                    464:   Revision 1.93  2003/06/25 16:33:55  brouard
                    465:   (Module): On windows (cygwin) function asctime_r doesn't
                    466:   exist so I changed back to asctime which exists.
                    467:   (Module): Version 0.96b
                    468: 
                    469:   Revision 1.92  2003/06/25 16:30:45  brouard
                    470:   (Module): On windows (cygwin) function asctime_r doesn't
                    471:   exist so I changed back to asctime which exists.
                    472: 
                    473:   Revision 1.91  2003/06/25 15:30:29  brouard
                    474:   * imach.c (Repository): Duplicated warning errors corrected.
                    475:   (Repository): Elapsed time after each iteration is now output. It
                    476:   helps to forecast when convergence will be reached. Elapsed time
                    477:   is stamped in powell.  We created a new html file for the graphs
                    478:   concerning matrix of covariance. It has extension -cov.htm.
                    479: 
                    480:   Revision 1.90  2003/06/24 12:34:15  brouard
                    481:   (Module): Some bugs corrected for windows. Also, when
                    482:   mle=-1 a template is output in file "or"mypar.txt with the design
                    483:   of the covariance matrix to be input.
                    484: 
                    485:   Revision 1.89  2003/06/24 12:30:52  brouard
                    486:   (Module): Some bugs corrected for windows. Also, when
                    487:   mle=-1 a template is output in file "or"mypar.txt with the design
                    488:   of the covariance matrix to be input.
                    489: 
                    490:   Revision 1.88  2003/06/23 17:54:56  brouard
                    491:   * 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.
                    492: 
                    493:   Revision 1.87  2003/06/18 12:26:01  brouard
                    494:   Version 0.96
                    495: 
                    496:   Revision 1.86  2003/06/17 20:04:08  brouard
                    497:   (Module): Change position of html and gnuplot routines and added
                    498:   routine fileappend.
                    499: 
                    500:   Revision 1.85  2003/06/17 13:12:43  brouard
                    501:   * imach.c (Repository): Check when date of death was earlier that
                    502:   current date of interview. It may happen when the death was just
                    503:   prior to the death. In this case, dh was negative and likelihood
                    504:   was wrong (infinity). We still send an "Error" but patch by
                    505:   assuming that the date of death was just one stepm after the
                    506:   interview.
                    507:   (Repository): Because some people have very long ID (first column)
                    508:   we changed int to long in num[] and we added a new lvector for
                    509:   memory allocation. But we also truncated to 8 characters (left
                    510:   truncation)
                    511:   (Repository): No more line truncation errors.
                    512: 
                    513:   Revision 1.84  2003/06/13 21:44:43  brouard
                    514:   * imach.c (Repository): Replace "freqsummary" at a correct
                    515:   place. It differs from routine "prevalence" which may be called
                    516:   many times. Probs is memory consuming and must be used with
                    517:   parcimony.
                    518:   Version 0.95a3 (should output exactly the same maximization than 0.8a2)
                    519: 
                    520:   Revision 1.83  2003/06/10 13:39:11  lievre
                    521:   *** empty log message ***
                    522: 
                    523:   Revision 1.82  2003/06/05 15:57:20  brouard
                    524:   Add log in  imach.c and  fullversion number is now printed.
                    525: 
                    526: */
                    527: /*
                    528:    Interpolated Markov Chain
                    529: 
                    530:   Short summary of the programme:
                    531:   
                    532:   This program computes Healthy Life Expectancies from
                    533:   cross-longitudinal data. Cross-longitudinal data consist in: -1- a
                    534:   first survey ("cross") where individuals from different ages are
                    535:   interviewed on their health status or degree of disability (in the
                    536:   case of a health survey which is our main interest) -2- at least a
                    537:   second wave of interviews ("longitudinal") which measure each change
                    538:   (if any) in individual health status.  Health expectancies are
                    539:   computed from the time spent in each health state according to a
                    540:   model. More health states you consider, more time is necessary to reach the
                    541:   Maximum Likelihood of the parameters involved in the model.  The
                    542:   simplest model is the multinomial logistic model where pij is the
                    543:   probability to be observed in state j at the second wave
                    544:   conditional to be observed in state i at the first wave. Therefore
                    545:   the model is: log(pij/pii)= aij + bij*age+ cij*sex + etc , where
                    546:   'age' is age and 'sex' is a covariate. If you want to have a more
                    547:   complex model than "constant and age", you should modify the program
                    548:   where the markup *Covariates have to be included here again* invites
                    549:   you to do it.  More covariates you add, slower the
                    550:   convergence.
                    551: 
                    552:   The advantage of this computer programme, compared to a simple
                    553:   multinomial logistic model, is clear when the delay between waves is not
                    554:   identical for each individual. Also, if a individual missed an
                    555:   intermediate interview, the information is lost, but taken into
                    556:   account using an interpolation or extrapolation.  
                    557: 
                    558:   hPijx is the probability to be observed in state i at age x+h
                    559:   conditional to the observed state i at age x. The delay 'h' can be
                    560:   split into an exact number (nh*stepm) of unobserved intermediate
                    561:   states. This elementary transition (by month, quarter,
                    562:   semester or year) is modelled as a multinomial logistic.  The hPx
                    563:   matrix is simply the matrix product of nh*stepm elementary matrices
                    564:   and the contribution of each individual to the likelihood is simply
                    565:   hPijx.
                    566: 
                    567:   Also this programme outputs the covariance matrix of the parameters but also
                    568:   of the life expectancies. It also computes the period (stable) prevalence. 
                    569:   
1.133     brouard   570:   Authors: Nicolas Brouard (brouard@ined.fr) and Agnès Lièvre (lievre@ined.fr).
                    571:            Institut national d'études démographiques, Paris.
1.126     brouard   572:   This software have been partly granted by Euro-REVES, a concerted action
                    573:   from the European Union.
                    574:   It is copyrighted identically to a GNU software product, ie programme and
                    575:   software can be distributed freely for non commercial use. Latest version
                    576:   can be accessed at http://euroreves.ined.fr/imach .
                    577: 
                    578:   Help to debug: LD_PRELOAD=/usr/local/lib/libnjamd.so ./imach foo.imach
                    579:   or better on gdb : set env LD_PRELOAD=/usr/local/lib/libnjamd.so
                    580:   
                    581:   **********************************************************************/
                    582: /*
                    583:   main
                    584:   read parameterfile
                    585:   read datafile
                    586:   concatwav
                    587:   freqsummary
                    588:   if (mle >= 1)
                    589:     mlikeli
                    590:   print results files
                    591:   if mle==1 
                    592:      computes hessian
                    593:   read end of parameter file: agemin, agemax, bage, fage, estepm
                    594:       begin-prev-date,...
                    595:   open gnuplot file
                    596:   open html file
1.145     brouard   597:   period (stable) prevalence      | pl_nom    1-1 2-2 etc by covariate
                    598:    for age prevalim()             | #****** V1=0  V2=1  V3=1  V4=0 ******
                    599:                                   | 65 1 0 2 1 3 1 4 0  0.96326 0.03674
                    600:     freexexit2 possible for memory heap.
                    601: 
                    602:   h Pij x                         | pij_nom  ficrestpij
                    603:    # Cov Agex agex+h hpijx with i,j= 1-1 1-2     1-3     2-1     2-2     2-3
                    604:        1  85   85    1.00000             0.00000 0.00000 0.00000 1.00000 0.00000
                    605:        1  85   86    0.68299             0.22291 0.09410 0.71093 0.00000 0.28907
                    606: 
                    607:        1  65   99    0.00364             0.00322 0.99314 0.00350 0.00310 0.99340
                    608:        1  65  100    0.00214             0.00204 0.99581 0.00206 0.00196 0.99597
                    609:   variance of p one-step probabilities varprob  | prob_nom   ficresprob #One-step probabilities and stand. devi in ()
                    610:    Standard deviation of one-step probabilities | probcor_nom   ficresprobcor #One-step probabilities and correlation matrix
                    611:    Matrix of variance covariance of one-step probabilities |  probcov_nom ficresprobcov #One-step probabilities and covariance matrix
                    612: 
1.126     brouard   613:   forecasting if prevfcast==1 prevforecast call prevalence()
                    614:   health expectancies
                    615:   Variance-covariance of DFLE
                    616:   prevalence()
                    617:    movingaverage()
                    618:   varevsij() 
                    619:   if popbased==1 varevsij(,popbased)
                    620:   total life expectancies
                    621:   Variance of period (stable) prevalence
                    622:  end
                    623: */
                    624: 
1.187     brouard   625: /* #define DEBUG */
                    626: /* #define DEBUGBRENT */
1.165     brouard   627: #define POWELL /* Instead of NLOPT */
1.192     brouard   628: #define POWELLF1F3 /* Skip test */
1.186     brouard   629: /* #define POWELLORIGINAL /\* Don't use Directest to decide new direction but original Powell test *\/ */
                    630: /* #define MNBRAKORIGINAL /\* Don't use mnbrak fix *\/ */
1.126     brouard   631: 
                    632: #include <math.h>
                    633: #include <stdio.h>
                    634: #include <stdlib.h>
                    635: #include <string.h>
1.159     brouard   636: 
                    637: #ifdef _WIN32
                    638: #include <io.h>
1.172     brouard   639: #include <windows.h>
                    640: #include <tchar.h>
1.159     brouard   641: #else
1.126     brouard   642: #include <unistd.h>
1.159     brouard   643: #endif
1.126     brouard   644: 
                    645: #include <limits.h>
                    646: #include <sys/types.h>
1.171     brouard   647: 
                    648: #if defined(__GNUC__)
                    649: #include <sys/utsname.h> /* Doesn't work on Windows */
                    650: #endif
                    651: 
1.126     brouard   652: #include <sys/stat.h>
                    653: #include <errno.h>
1.159     brouard   654: /* extern int errno; */
1.126     brouard   655: 
1.157     brouard   656: /* #ifdef LINUX */
                    657: /* #include <time.h> */
                    658: /* #include "timeval.h" */
                    659: /* #else */
                    660: /* #include <sys/time.h> */
                    661: /* #endif */
                    662: 
1.126     brouard   663: #include <time.h>
                    664: 
1.136     brouard   665: #ifdef GSL
                    666: #include <gsl/gsl_errno.h>
                    667: #include <gsl/gsl_multimin.h>
                    668: #endif
                    669: 
1.167     brouard   670: 
1.162     brouard   671: #ifdef NLOPT
                    672: #include <nlopt.h>
                    673: typedef struct {
                    674:   double (* function)(double [] );
                    675: } myfunc_data ;
                    676: #endif
                    677: 
1.126     brouard   678: /* #include <libintl.h> */
                    679: /* #define _(String) gettext (String) */
                    680: 
1.141     brouard   681: #define MAXLINE 1024 /* Was 256. Overflow with 312 with 2 states and 4 covariates. Should be ok */
1.126     brouard   682: 
                    683: #define GNUPLOTPROGRAM "gnuplot"
                    684: /*#define GNUPLOTPROGRAM "..\\gp37mgw\\wgnuplot"*/
                    685: #define FILENAMELENGTH 132
                    686: 
                    687: #define        GLOCK_ERROR_NOPATH              -1      /* empty path */
                    688: #define        GLOCK_ERROR_GETCWD              -2      /* cannot get cwd */
                    689: 
1.144     brouard   690: #define MAXPARM 128 /**< Maximum number of parameters for the optimization */
                    691: #define NPARMAX 64 /**< (nlstate+ndeath-1)*nlstate*ncovmodel */
1.126     brouard   692: 
                    693: #define NINTERVMAX 8
1.144     brouard   694: #define NLSTATEMAX 8 /**< Maximum number of live states (for func) */
                    695: #define NDEATHMAX 8 /**< Maximum number of dead states (for func) */
                    696: #define NCOVMAX 20 /**< Maximum number of covariates, including generated covariates V1*V2 */
1.197   ! brouard   697: #define codtabm(h,k)  (1 & (h-1) >> (k-1))+1
1.126     brouard   698: #define MAXN 20000
1.144     brouard   699: #define YEARM 12. /**< Number of months per year */
1.126     brouard   700: #define AGESUP 130
                    701: #define AGEBASE 40
1.194     brouard   702: #define AGEOVERFLOW 1.e20
1.164     brouard   703: #define AGEGOMP 10 /**< Minimal age for Gompertz adjustment */
1.157     brouard   704: #ifdef _WIN32
                    705: #define DIRSEPARATOR '\\'
                    706: #define CHARSEPARATOR "\\"
                    707: #define ODIRSEPARATOR '/'
                    708: #else
1.126     brouard   709: #define DIRSEPARATOR '/'
                    710: #define CHARSEPARATOR "/"
                    711: #define ODIRSEPARATOR '\\'
                    712: #endif
                    713: 
1.197   ! brouard   714: /* $Id: imach.c,v 1.196 2015/08/18 23:17:52 brouard Exp $ */
1.126     brouard   715: /* $State: Exp $ */
1.196     brouard   716: #include "version.h"
                    717: char version[]=__IMACH_VERSION__;
1.197   ! brouard   718: char copyright[]="September 2015,INED-EUROREVES-Institut de longevite-Japan Society for the Promotion of Science (Grant-in-Aid for Scientific Research 25293121), Intel Software 2015";
        !           719: char fullversion[]="$Revision: 1.196 $ $Date: 2015/08/18 23:17:52 $"; 
1.126     brouard   720: char strstart[80];
                    721: char optionfilext[10], optionfilefiname[FILENAMELENGTH];
1.130     brouard   722: int erreur=0, nberr=0, nbwarn=0; /* Error number, number of errors number of warnings  */
1.187     brouard   723: int nagesqr=0, nforce=0; /* nagesqr=1 if model is including age*age, number of forces */
1.145     brouard   724: /* Number of covariates model=V2+V1+ V3*age+V2*V4 */
                    725: int cptcovn=0; /**< cptcovn number of covariates added in the model (excepting constant and age and age*product) */
                    726: int cptcovt=0; /**< cptcovt number of covariates added in the model (excepting constant and age) */
                    727: int cptcovs=0; /**< cptcovs number of simple covariates V2+V1 =2 */
                    728: int cptcovage=0; /**< Number of covariates with age: V3*age only =1 */
                    729: int cptcovprodnoage=0; /**< Number of covariate products without age */   
                    730: int cptcoveff=0; /* Total number of covariates to vary for printing results */
                    731: int cptcov=0; /* Working variable */
1.126     brouard   732: int npar=NPARMAX;
                    733: int nlstate=2; /* Number of live states */
                    734: int ndeath=1; /* Number of dead states */
1.130     brouard   735: int ncovmodel=0, ncovcol=0;     /* Total number of covariables including constant a12*1 +b12*x ncovmodel=2 */
1.126     brouard   736: int popbased=0;
                    737: 
                    738: int *wav; /* Number of waves for this individuual 0 is possible */
1.130     brouard   739: int maxwav=0; /* Maxim number of waves */
                    740: int jmin=0, jmax=0; /* min, max spacing between 2 waves */
                    741: int ijmin=0, ijmax=0; /* Individuals having jmin and jmax */ 
                    742: int gipmx=0, gsw=0; /* Global variables on the number of contributions 
1.126     brouard   743:                   to the likelihood and the sum of weights (done by funcone)*/
1.130     brouard   744: int mle=1, weightopt=0;
1.126     brouard   745: int **mw; /* mw[mi][i] is number of the mi wave for this individual */
                    746: int **dh; /* dh[mi][i] is number of steps between mi,mi+1 for this individual */
                    747: int **bh; /* bh[mi][i] is the bias (+ or -) for this individual if the delay between
                    748:           * wave mi and wave mi+1 is not an exact multiple of stepm. */
1.162     brouard   749: int countcallfunc=0;  /* Count the number of calls to func */
1.130     brouard   750: double jmean=1; /* Mean space between 2 waves */
1.145     brouard   751: double **matprod2(); /* test */
1.126     brouard   752: double **oldm, **newm, **savm; /* Working pointers to matrices */
                    753: double **oldms, **newms, **savms; /* Fixed working pointers to matrices */
1.136     brouard   754: /*FILE *fic ; */ /* Used in readdata only */
                    755: FILE *ficpar, *ficparo,*ficres, *ficresp, *ficrespl, *ficrespij, *ficrest,*ficresf,*ficrespop;
1.126     brouard   756: FILE *ficlog, *ficrespow;
1.130     brouard   757: int globpr=0; /* Global variable for printing or not */
1.126     brouard   758: double fretone; /* Only one call to likelihood */
1.130     brouard   759: long ipmx=0; /* Number of contributions */
1.126     brouard   760: double sw; /* Sum of weights */
                    761: char filerespow[FILENAMELENGTH];
                    762: char fileresilk[FILENAMELENGTH]; /* File of individual contributions to the likelihood */
                    763: FILE *ficresilk;
                    764: FILE *ficgp,*ficresprob,*ficpop, *ficresprobcov, *ficresprobcor;
                    765: FILE *ficresprobmorprev;
                    766: FILE *fichtm, *fichtmcov; /* Html File */
                    767: FILE *ficreseij;
                    768: char filerese[FILENAMELENGTH];
                    769: FILE *ficresstdeij;
                    770: char fileresstde[FILENAMELENGTH];
                    771: FILE *ficrescveij;
                    772: char filerescve[FILENAMELENGTH];
                    773: FILE  *ficresvij;
                    774: char fileresv[FILENAMELENGTH];
                    775: FILE  *ficresvpl;
                    776: char fileresvpl[FILENAMELENGTH];
                    777: char title[MAXLINE];
                    778: char optionfile[FILENAMELENGTH], datafile[FILENAMELENGTH],  filerespl[FILENAMELENGTH];
                    779: char plotcmd[FILENAMELENGTH], pplotcmd[FILENAMELENGTH];
                    780: char tmpout[FILENAMELENGTH],  tmpout2[FILENAMELENGTH]; 
                    781: char command[FILENAMELENGTH];
                    782: int  outcmd=0;
                    783: 
                    784: char fileres[FILENAMELENGTH], filerespij[FILENAMELENGTH], filereso[FILENAMELENGTH], rfileres[FILENAMELENGTH];
                    785: 
                    786: char filelog[FILENAMELENGTH]; /* Log file */
                    787: char filerest[FILENAMELENGTH];
                    788: char fileregp[FILENAMELENGTH];
                    789: char popfile[FILENAMELENGTH];
                    790: 
                    791: char optionfilegnuplot[FILENAMELENGTH], optionfilehtm[FILENAMELENGTH], optionfilehtmcov[FILENAMELENGTH] ;
                    792: 
1.157     brouard   793: /* struct timeval start_time, end_time, curr_time, last_time, forecast_time; */
                    794: /* struct timezone tzp; */
                    795: /* extern int gettimeofday(); */
                    796: struct tm tml, *gmtime(), *localtime();
                    797: 
                    798: extern time_t time();
                    799: 
                    800: struct tm start_time, end_time, curr_time, last_time, forecast_time;
                    801: time_t  rstart_time, rend_time, rcurr_time, rlast_time, rforecast_time; /* raw time */
                    802: struct tm tm;
                    803: 
1.126     brouard   804: char strcurr[80], strfor[80];
                    805: 
                    806: char *endptr;
                    807: long lval;
                    808: double dval;
                    809: 
                    810: #define NR_END 1
                    811: #define FREE_ARG char*
                    812: #define FTOL 1.0e-10
                    813: 
                    814: #define NRANSI 
                    815: #define ITMAX 200 
                    816: 
                    817: #define TOL 2.0e-4 
                    818: 
                    819: #define CGOLD 0.3819660 
                    820: #define ZEPS 1.0e-10 
                    821: #define SHFT(a,b,c,d) (a)=(b);(b)=(c);(c)=(d); 
                    822: 
                    823: #define GOLD 1.618034 
                    824: #define GLIMIT 100.0 
                    825: #define TINY 1.0e-20 
                    826: 
                    827: static double maxarg1,maxarg2;
                    828: #define FMAX(a,b) (maxarg1=(a),maxarg2=(b),(maxarg1)>(maxarg2)? (maxarg1):(maxarg2))
                    829: #define FMIN(a,b) (maxarg1=(a),maxarg2=(b),(maxarg1)<(maxarg2)? (maxarg1):(maxarg2))
                    830:   
                    831: #define SIGN(a,b) ((b)>0.0 ? fabs(a) : -fabs(a))
                    832: #define rint(a) floor(a+0.5)
1.166     brouard   833: /* http://www.thphys.uni-heidelberg.de/~robbers/cmbeasy/doc/html/myutils_8h-source.html */
1.183     brouard   834: #define mytinydouble 1.0e-16
1.166     brouard   835: /* #define DEQUAL(a,b) (fabs((a)-(b))<mytinydouble) */
                    836: /* http://www.thphys.uni-heidelberg.de/~robbers/cmbeasy/doc/html/mynrutils_8h-source.html */
                    837: /* static double dsqrarg; */
                    838: /* #define DSQR(a) (DEQUAL((dsqrarg=(a)),0.0) ? 0.0 : dsqrarg*dsqrarg) */
1.126     brouard   839: static double sqrarg;
                    840: #define SQR(a) ((sqrarg=(a)) == 0.0 ? 0.0 :sqrarg*sqrarg)
                    841: #define SWAP(a,b) {temp=(a);(a)=(b);(b)=temp;} 
                    842: int agegomp= AGEGOMP;
                    843: 
                    844: int imx; 
                    845: int stepm=1;
                    846: /* Stepm, step in month: minimum step interpolation*/
                    847: 
                    848: int estepm;
                    849: /* Estepm, step in month to interpolate survival function in order to approximate Life Expectancy*/
                    850: 
                    851: int m,nb;
                    852: long *num;
1.197   ! brouard   853: int firstpass=0, lastpass=4,*cod, *cens;
1.192     brouard   854: int *ncodemax;  /* ncodemax[j]= Number of modalities of the j th
                    855:                   covariate for which somebody answered excluding 
                    856:                   undefined. Usually 2: 0 and 1. */
                    857: int *ncodemaxwundef;  /* ncodemax[j]= Number of modalities of the j th
                    858:                             covariate for which somebody answered including 
                    859:                             undefined. Usually 3: -1, 0 and 1. */
1.126     brouard   860: double **agev,*moisnais, *annais, *moisdc, *andc,**mint, **anint;
                    861: double **pmmij, ***probs;
                    862: double *ageexmed,*agecens;
                    863: double dateintmean=0;
                    864: 
                    865: double *weight;
                    866: int **s; /* Status */
1.141     brouard   867: double *agedc;
1.145     brouard   868: double  **covar; /**< covar[j,i], value of jth covariate for individual i,
1.141     brouard   869:                  * covar=matrix(0,NCOVMAX,1,n); 
1.187     brouard   870:                  * cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*age; */
1.141     brouard   871: double  idx; 
                    872: int **nbcode, *Tvar; /**< model=V2 => Tvar[1]= 2 */
1.197   ! brouard   873: int *Tage;
1.145     brouard   874: int *Ndum; /** Freq of modality (tricode */
1.141     brouard   875: int **codtab; /**< codtab=imatrix(1,100,1,10); */
                    876: int **Tvard, *Tprod, cptcovprod, *Tvaraff;
1.126     brouard   877: double *lsurv, *lpop, *tpop;
                    878: 
1.143     brouard   879: double ftol=FTOL; /**< Tolerance for computing Max Likelihood */
                    880: double ftolhess; /**< Tolerance for computing hessian */
1.126     brouard   881: 
                    882: /**************** split *************************/
                    883: static int split( char *path, char *dirc, char *name, char *ext, char *finame )
                    884: {
                    885:   /* From a file name with (full) path (either Unix or Windows) we extract the directory (dirc)
                    886:      the name of the file (name), its extension only (ext) and its first part of the name (finame)
                    887:   */ 
                    888:   char *ss;                            /* pointer */
1.186     brouard   889:   int  l1=0, l2=0;                             /* length counters */
1.126     brouard   890: 
                    891:   l1 = strlen(path );                  /* length of path */
                    892:   if ( l1 == 0 ) return( GLOCK_ERROR_NOPATH );
                    893:   ss= strrchr( path, DIRSEPARATOR );           /* find last / */
                    894:   if ( ss == NULL ) {                  /* no directory, so determine current directory */
                    895:     strcpy( name, path );              /* we got the fullname name because no directory */
                    896:     /*if(strrchr(path, ODIRSEPARATOR )==NULL)
                    897:       printf("Warning you should use %s as a separator\n",DIRSEPARATOR);*/
                    898:     /* get current working directory */
                    899:     /*    extern  char* getcwd ( char *buf , int len);*/
1.184     brouard   900: #ifdef WIN32
                    901:     if (_getcwd( dirc, FILENAME_MAX ) == NULL ) {
                    902: #else
                    903:        if (getcwd(dirc, FILENAME_MAX) == NULL) {
                    904: #endif
1.126     brouard   905:       return( GLOCK_ERROR_GETCWD );
                    906:     }
                    907:     /* got dirc from getcwd*/
                    908:     printf(" DIRC = %s \n",dirc);
                    909:   } else {                             /* strip direcotry from path */
                    910:     ss++;                              /* after this, the filename */
                    911:     l2 = strlen( ss );                 /* length of filename */
                    912:     if ( l2 == 0 ) return( GLOCK_ERROR_NOPATH );
                    913:     strcpy( name, ss );                /* save file name */
                    914:     strncpy( dirc, path, l1 - l2 );    /* now the directory */
1.186     brouard   915:     dirc[l1-l2] = '\0';                        /* add zero */
1.126     brouard   916:     printf(" DIRC2 = %s \n",dirc);
                    917:   }
                    918:   /* We add a separator at the end of dirc if not exists */
                    919:   l1 = strlen( dirc );                 /* length of directory */
                    920:   if( dirc[l1-1] != DIRSEPARATOR ){
                    921:     dirc[l1] =  DIRSEPARATOR;
                    922:     dirc[l1+1] = 0; 
                    923:     printf(" DIRC3 = %s \n",dirc);
                    924:   }
                    925:   ss = strrchr( name, '.' );           /* find last / */
                    926:   if (ss >0){
                    927:     ss++;
                    928:     strcpy(ext,ss);                    /* save extension */
                    929:     l1= strlen( name);
                    930:     l2= strlen(ss)+1;
                    931:     strncpy( finame, name, l1-l2);
                    932:     finame[l1-l2]= 0;
                    933:   }
                    934: 
                    935:   return( 0 );                         /* we're done */
                    936: }
                    937: 
                    938: 
                    939: /******************************************/
                    940: 
                    941: void replace_back_to_slash(char *s, char*t)
                    942: {
                    943:   int i;
                    944:   int lg=0;
                    945:   i=0;
                    946:   lg=strlen(t);
                    947:   for(i=0; i<= lg; i++) {
                    948:     (s[i] = t[i]);
                    949:     if (t[i]== '\\') s[i]='/';
                    950:   }
                    951: }
                    952: 
1.132     brouard   953: char *trimbb(char *out, char *in)
1.137     brouard   954: { /* Trim multiple blanks in line but keeps first blanks if line starts with blanks */
1.132     brouard   955:   char *s;
                    956:   s=out;
                    957:   while (*in != '\0'){
1.137     brouard   958:     while( *in == ' ' && *(in+1) == ' '){ /* && *(in+1) != '\0'){*/
1.132     brouard   959:       in++;
                    960:     }
                    961:     *out++ = *in++;
                    962:   }
                    963:   *out='\0';
                    964:   return s;
                    965: }
                    966: 
1.187     brouard   967: /* char *substrchaine(char *out, char *in, char *chain) */
                    968: /* { */
                    969: /*   /\* Substract chain 'chain' from 'in', return and output 'out' *\/ */
                    970: /*   char *s, *t; */
                    971: /*   t=in;s=out; */
                    972: /*   while ((*in != *chain) && (*in != '\0')){ */
                    973: /*     *out++ = *in++; */
                    974: /*   } */
                    975: 
                    976: /*   /\* *in matches *chain *\/ */
                    977: /*   while ((*in++ == *chain++) && (*in != '\0')){ */
                    978: /*     printf("*in = %c, *out= %c *chain= %c \n", *in, *out, *chain);  */
                    979: /*   } */
                    980: /*   in--; chain--; */
                    981: /*   while ( (*in != '\0')){ */
                    982: /*     printf("Bef *in = %c, *out= %c *chain= %c \n", *in, *out, *chain);  */
                    983: /*     *out++ = *in++; */
                    984: /*     printf("Aft *in = %c, *out= %c *chain= %c \n", *in, *out, *chain);  */
                    985: /*   } */
                    986: /*   *out='\0'; */
                    987: /*   out=s; */
                    988: /*   return out; */
                    989: /* } */
                    990: char *substrchaine(char *out, char *in, char *chain)
                    991: {
                    992:   /* Substract chain 'chain' from 'in', return and output 'out' */
                    993:   /* in="V1+V1*age+age*age+V2", chain="age*age" */
                    994: 
                    995:   char *strloc;
                    996: 
                    997:   strcpy (out, in); 
                    998:   strloc = strstr(out, chain); /* strloc points to out at age*age+V2 */
                    999:   printf("Bef strloc=%s chain=%s out=%s \n", strloc, chain, out);
                   1000:   if(strloc != NULL){ 
                   1001:     /* will affect out */ /* strloc+strlenc(chain)=+V2 */ /* Will also work in Unicode */
                   1002:     memmove(strloc,strloc+strlen(chain), strlen(strloc+strlen(chain))+1);
                   1003:     /* strcpy (strloc, strloc +strlen(chain));*/
                   1004:   }
                   1005:   printf("Aft strloc=%s chain=%s in=%s out=%s \n", strloc, chain, in, out);
                   1006:   return out;
                   1007: }
                   1008: 
                   1009: 
1.145     brouard  1010: char *cutl(char *blocc, char *alocc, char *in, char occ)
                   1011: {
1.187     brouard  1012:   /* cuts string in into blocc and alocc where blocc ends before FIRST occurence of char 'occ' 
1.145     brouard  1013:      and alocc starts after first occurence of char 'occ' : ex cutv(blocc,alocc,"abcdef2ghi2j",'2')
1.187     brouard  1014:      gives blocc="abcdef" and alocc="ghi2j".
1.145     brouard  1015:      If occ is not found blocc is null and alocc is equal to in. Returns blocc
                   1016:   */
1.160     brouard  1017:   char *s, *t;
1.145     brouard  1018:   t=in;s=in;
                   1019:   while ((*in != occ) && (*in != '\0')){
                   1020:     *alocc++ = *in++;
                   1021:   }
                   1022:   if( *in == occ){
                   1023:     *(alocc)='\0';
                   1024:     s=++in;
                   1025:   }
                   1026:  
                   1027:   if (s == t) {/* occ not found */
                   1028:     *(alocc-(in-s))='\0';
                   1029:     in=s;
                   1030:   }
                   1031:   while ( *in != '\0'){
                   1032:     *blocc++ = *in++;
                   1033:   }
                   1034: 
                   1035:   *blocc='\0';
                   1036:   return t;
                   1037: }
1.137     brouard  1038: char *cutv(char *blocc, char *alocc, char *in, char occ)
                   1039: {
1.187     brouard  1040:   /* cuts string in into blocc and alocc where blocc ends before LAST occurence of char 'occ' 
1.137     brouard  1041:      and alocc starts after last occurence of char 'occ' : ex cutv(blocc,alocc,"abcdef2ghi2j",'2')
                   1042:      gives blocc="abcdef2ghi" and alocc="j".
                   1043:      If occ is not found blocc is null and alocc is equal to in. Returns alocc
                   1044:   */
                   1045:   char *s, *t;
                   1046:   t=in;s=in;
                   1047:   while (*in != '\0'){
                   1048:     while( *in == occ){
                   1049:       *blocc++ = *in++;
                   1050:       s=in;
                   1051:     }
                   1052:     *blocc++ = *in++;
                   1053:   }
                   1054:   if (s == t) /* occ not found */
                   1055:     *(blocc-(in-s))='\0';
                   1056:   else
                   1057:     *(blocc-(in-s)-1)='\0';
                   1058:   in=s;
                   1059:   while ( *in != '\0'){
                   1060:     *alocc++ = *in++;
                   1061:   }
                   1062: 
                   1063:   *alocc='\0';
                   1064:   return s;
                   1065: }
                   1066: 
1.126     brouard  1067: int nbocc(char *s, char occ)
                   1068: {
                   1069:   int i,j=0;
                   1070:   int lg=20;
                   1071:   i=0;
                   1072:   lg=strlen(s);
                   1073:   for(i=0; i<= lg; i++) {
                   1074:   if  (s[i] == occ ) j++;
                   1075:   }
                   1076:   return j;
                   1077: }
                   1078: 
1.137     brouard  1079: /* void cutv(char *u,char *v, char*t, char occ) */
                   1080: /* { */
                   1081: /*   /\* cuts string t into u and v where u ends before last occurence of char 'occ'  */
                   1082: /*      and v starts after last occurence of char 'occ' : ex cutv(u,v,"abcdef2ghi2j",'2') */
                   1083: /*      gives u="abcdef2ghi" and v="j" *\/ */
                   1084: /*   int i,lg,j,p=0; */
                   1085: /*   i=0; */
                   1086: /*   lg=strlen(t); */
                   1087: /*   for(j=0; j<=lg-1; j++) { */
                   1088: /*     if((t[j]!= occ) && (t[j+1]== occ)) p=j+1; */
                   1089: /*   } */
1.126     brouard  1090: 
1.137     brouard  1091: /*   for(j=0; j<p; j++) { */
                   1092: /*     (u[j] = t[j]); */
                   1093: /*   } */
                   1094: /*      u[p]='\0'; */
1.126     brouard  1095: 
1.137     brouard  1096: /*    for(j=0; j<= lg; j++) { */
                   1097: /*     if (j>=(p+1))(v[j-p-1] = t[j]); */
                   1098: /*   } */
                   1099: /* } */
1.126     brouard  1100: 
1.160     brouard  1101: #ifdef _WIN32
                   1102: char * strsep(char **pp, const char *delim)
                   1103: {
                   1104:   char *p, *q;
                   1105:          
                   1106:   if ((p = *pp) == NULL)
                   1107:     return 0;
                   1108:   if ((q = strpbrk (p, delim)) != NULL)
                   1109:   {
                   1110:     *pp = q + 1;
                   1111:     *q = '\0';
                   1112:   }
                   1113:   else
                   1114:     *pp = 0;
                   1115:   return p;
                   1116: }
                   1117: #endif
                   1118: 
1.126     brouard  1119: /********************** nrerror ********************/
                   1120: 
                   1121: void nrerror(char error_text[])
                   1122: {
                   1123:   fprintf(stderr,"ERREUR ...\n");
                   1124:   fprintf(stderr,"%s\n",error_text);
                   1125:   exit(EXIT_FAILURE);
                   1126: }
                   1127: /*********************** vector *******************/
                   1128: double *vector(int nl, int nh)
                   1129: {
                   1130:   double *v;
                   1131:   v=(double *) malloc((size_t)((nh-nl+1+NR_END)*sizeof(double)));
                   1132:   if (!v) nrerror("allocation failure in vector");
                   1133:   return v-nl+NR_END;
                   1134: }
                   1135: 
                   1136: /************************ free vector ******************/
                   1137: void free_vector(double*v, int nl, int nh)
                   1138: {
                   1139:   free((FREE_ARG)(v+nl-NR_END));
                   1140: }
                   1141: 
                   1142: /************************ivector *******************************/
                   1143: int *ivector(long nl,long nh)
                   1144: {
                   1145:   int *v;
                   1146:   v=(int *) malloc((size_t)((nh-nl+1+NR_END)*sizeof(int)));
                   1147:   if (!v) nrerror("allocation failure in ivector");
                   1148:   return v-nl+NR_END;
                   1149: }
                   1150: 
                   1151: /******************free ivector **************************/
                   1152: void free_ivector(int *v, long nl, long nh)
                   1153: {
                   1154:   free((FREE_ARG)(v+nl-NR_END));
                   1155: }
                   1156: 
                   1157: /************************lvector *******************************/
                   1158: long *lvector(long nl,long nh)
                   1159: {
                   1160:   long *v;
                   1161:   v=(long *) malloc((size_t)((nh-nl+1+NR_END)*sizeof(long)));
                   1162:   if (!v) nrerror("allocation failure in ivector");
                   1163:   return v-nl+NR_END;
                   1164: }
                   1165: 
                   1166: /******************free lvector **************************/
                   1167: void free_lvector(long *v, long nl, long nh)
                   1168: {
                   1169:   free((FREE_ARG)(v+nl-NR_END));
                   1170: }
                   1171: 
                   1172: /******************* imatrix *******************************/
                   1173: int **imatrix(long nrl, long nrh, long ncl, long nch) 
                   1174:      /* allocate a int matrix with subscript range m[nrl..nrh][ncl..nch] */ 
                   1175: { 
                   1176:   long i, nrow=nrh-nrl+1,ncol=nch-ncl+1; 
                   1177:   int **m; 
                   1178:   
                   1179:   /* allocate pointers to rows */ 
                   1180:   m=(int **) malloc((size_t)((nrow+NR_END)*sizeof(int*))); 
                   1181:   if (!m) nrerror("allocation failure 1 in matrix()"); 
                   1182:   m += NR_END; 
                   1183:   m -= nrl; 
                   1184:   
                   1185:   
                   1186:   /* allocate rows and set pointers to them */ 
                   1187:   m[nrl]=(int *) malloc((size_t)((nrow*ncol+NR_END)*sizeof(int))); 
                   1188:   if (!m[nrl]) nrerror("allocation failure 2 in matrix()"); 
                   1189:   m[nrl] += NR_END; 
                   1190:   m[nrl] -= ncl; 
                   1191:   
                   1192:   for(i=nrl+1;i<=nrh;i++) m[i]=m[i-1]+ncol; 
                   1193:   
                   1194:   /* return pointer to array of pointers to rows */ 
                   1195:   return m; 
                   1196: } 
                   1197: 
                   1198: /****************** free_imatrix *************************/
                   1199: void free_imatrix(m,nrl,nrh,ncl,nch)
                   1200:       int **m;
                   1201:       long nch,ncl,nrh,nrl; 
                   1202:      /* free an int matrix allocated by imatrix() */ 
                   1203: { 
                   1204:   free((FREE_ARG) (m[nrl]+ncl-NR_END)); 
                   1205:   free((FREE_ARG) (m+nrl-NR_END)); 
                   1206: } 
                   1207: 
                   1208: /******************* matrix *******************************/
                   1209: double **matrix(long nrl, long nrh, long ncl, long nch)
                   1210: {
                   1211:   long i, nrow=nrh-nrl+1, ncol=nch-ncl+1;
                   1212:   double **m;
                   1213: 
                   1214:   m=(double **) malloc((size_t)((nrow+NR_END)*sizeof(double*)));
                   1215:   if (!m) nrerror("allocation failure 1 in matrix()");
                   1216:   m += NR_END;
                   1217:   m -= nrl;
                   1218: 
                   1219:   m[nrl]=(double *) malloc((size_t)((nrow*ncol+NR_END)*sizeof(double)));
                   1220:   if (!m[nrl]) nrerror("allocation failure 2 in matrix()");
                   1221:   m[nrl] += NR_END;
                   1222:   m[nrl] -= ncl;
                   1223: 
                   1224:   for (i=nrl+1; i<=nrh; i++) m[i]=m[i-1]+ncol;
                   1225:   return m;
1.145     brouard  1226:   /* print *(*(m+1)+70) or print m[1][70]; print m+1 or print &(m[1]) or &(m[1][0])
                   1227: m[i] = address of ith row of the table. &(m[i]) is its value which is another adress
                   1228: that of m[i][0]. In order to get the value p m[i][0] but it is unitialized.
1.126     brouard  1229:    */
                   1230: }
                   1231: 
                   1232: /*************************free matrix ************************/
                   1233: void free_matrix(double **m, long nrl, long nrh, long ncl, long nch)
                   1234: {
                   1235:   free((FREE_ARG)(m[nrl]+ncl-NR_END));
                   1236:   free((FREE_ARG)(m+nrl-NR_END));
                   1237: }
                   1238: 
                   1239: /******************* ma3x *******************************/
                   1240: double ***ma3x(long nrl, long nrh, long ncl, long nch, long nll, long nlh)
                   1241: {
                   1242:   long i, j, nrow=nrh-nrl+1, ncol=nch-ncl+1, nlay=nlh-nll+1;
                   1243:   double ***m;
                   1244: 
                   1245:   m=(double ***) malloc((size_t)((nrow+NR_END)*sizeof(double*)));
                   1246:   if (!m) nrerror("allocation failure 1 in matrix()");
                   1247:   m += NR_END;
                   1248:   m -= nrl;
                   1249: 
                   1250:   m[nrl]=(double **) malloc((size_t)((nrow*ncol+NR_END)*sizeof(double)));
                   1251:   if (!m[nrl]) nrerror("allocation failure 2 in matrix()");
                   1252:   m[nrl] += NR_END;
                   1253:   m[nrl] -= ncl;
                   1254: 
                   1255:   for (i=nrl+1; i<=nrh; i++) m[i]=m[i-1]+ncol;
                   1256: 
                   1257:   m[nrl][ncl]=(double *) malloc((size_t)((nrow*ncol*nlay+NR_END)*sizeof(double)));
                   1258:   if (!m[nrl][ncl]) nrerror("allocation failure 3 in matrix()");
                   1259:   m[nrl][ncl] += NR_END;
                   1260:   m[nrl][ncl] -= nll;
                   1261:   for (j=ncl+1; j<=nch; j++) 
                   1262:     m[nrl][j]=m[nrl][j-1]+nlay;
                   1263:   
                   1264:   for (i=nrl+1; i<=nrh; i++) {
                   1265:     m[i][ncl]=m[i-1l][ncl]+ncol*nlay;
                   1266:     for (j=ncl+1; j<=nch; j++) 
                   1267:       m[i][j]=m[i][j-1]+nlay;
                   1268:   }
                   1269:   return m; 
                   1270:   /*  gdb: p *(m+1) <=> p m[1] and p (m+1) <=> p (m+1) <=> p &(m[1])
                   1271:            &(m[i][j][k]) <=> *((*(m+i) + j)+k)
                   1272:   */
                   1273: }
                   1274: 
                   1275: /*************************free ma3x ************************/
                   1276: void free_ma3x(double ***m, long nrl, long nrh, long ncl, long nch,long nll, long nlh)
                   1277: {
                   1278:   free((FREE_ARG)(m[nrl][ncl]+ nll-NR_END));
                   1279:   free((FREE_ARG)(m[nrl]+ncl-NR_END));
                   1280:   free((FREE_ARG)(m+nrl-NR_END));
                   1281: }
                   1282: 
                   1283: /*************** function subdirf ***********/
                   1284: char *subdirf(char fileres[])
                   1285: {
                   1286:   /* Caution optionfilefiname is hidden */
                   1287:   strcpy(tmpout,optionfilefiname);
                   1288:   strcat(tmpout,"/"); /* Add to the right */
                   1289:   strcat(tmpout,fileres);
                   1290:   return tmpout;
                   1291: }
                   1292: 
                   1293: /*************** function subdirf2 ***********/
                   1294: char *subdirf2(char fileres[], char *preop)
                   1295: {
                   1296:   
                   1297:   /* Caution optionfilefiname is hidden */
                   1298:   strcpy(tmpout,optionfilefiname);
                   1299:   strcat(tmpout,"/");
                   1300:   strcat(tmpout,preop);
                   1301:   strcat(tmpout,fileres);
                   1302:   return tmpout;
                   1303: }
                   1304: 
                   1305: /*************** function subdirf3 ***********/
                   1306: char *subdirf3(char fileres[], char *preop, char *preop2)
                   1307: {
                   1308:   
                   1309:   /* Caution optionfilefiname is hidden */
                   1310:   strcpy(tmpout,optionfilefiname);
                   1311:   strcat(tmpout,"/");
                   1312:   strcat(tmpout,preop);
                   1313:   strcat(tmpout,preop2);
                   1314:   strcat(tmpout,fileres);
                   1315:   return tmpout;
                   1316: }
                   1317: 
1.162     brouard  1318: char *asc_diff_time(long time_sec, char ascdiff[])
                   1319: {
                   1320:   long sec_left, days, hours, minutes;
                   1321:   days = (time_sec) / (60*60*24);
                   1322:   sec_left = (time_sec) % (60*60*24);
                   1323:   hours = (sec_left) / (60*60) ;
                   1324:   sec_left = (sec_left) %(60*60);
                   1325:   minutes = (sec_left) /60;
                   1326:   sec_left = (sec_left) % (60);
                   1327:   sprintf(ascdiff,"%ld day(s) %ld hour(s) %ld minute(s) %ld second(s)",days, hours, minutes, sec_left);  
                   1328:   return ascdiff;
                   1329: }
                   1330: 
1.126     brouard  1331: /***************** f1dim *************************/
                   1332: extern int ncom; 
                   1333: extern double *pcom,*xicom;
                   1334: extern double (*nrfunc)(double []); 
                   1335:  
                   1336: double f1dim(double x) 
                   1337: { 
                   1338:   int j; 
                   1339:   double f;
                   1340:   double *xt; 
                   1341:  
                   1342:   xt=vector(1,ncom); 
                   1343:   for (j=1;j<=ncom;j++) xt[j]=pcom[j]+x*xicom[j]; 
                   1344:   f=(*nrfunc)(xt); 
                   1345:   free_vector(xt,1,ncom); 
                   1346:   return f; 
                   1347: } 
                   1348: 
                   1349: /*****************brent *************************/
                   1350: double brent(double ax, double bx, double cx, double (*f)(double), double tol,         double *xmin) 
1.187     brouard  1351: {
                   1352:   /* Given a function f, and given a bracketing triplet of abscissas ax, bx, cx (such that bx is
                   1353:    * between ax and cx, and f(bx) is less than both f(ax) and f(cx) ), this routine isolates
                   1354:    * the minimum to a fractional precision of about tol using Brent’s method. The abscissa of
                   1355:    * the minimum is returned as xmin, and the minimum function value is returned as brent , the
                   1356:    * returned function value. 
                   1357:   */
1.126     brouard  1358:   int iter; 
                   1359:   double a,b,d,etemp;
1.159     brouard  1360:   double fu=0,fv,fw,fx;
1.164     brouard  1361:   double ftemp=0.;
1.126     brouard  1362:   double p,q,r,tol1,tol2,u,v,w,x,xm; 
                   1363:   double e=0.0; 
                   1364:  
                   1365:   a=(ax < cx ? ax : cx); 
                   1366:   b=(ax > cx ? ax : cx); 
                   1367:   x=w=v=bx; 
                   1368:   fw=fv=fx=(*f)(x); 
                   1369:   for (iter=1;iter<=ITMAX;iter++) { 
                   1370:     xm=0.5*(a+b); 
                   1371:     tol2=2.0*(tol1=tol*fabs(x)+ZEPS); 
                   1372:     /*         if (2.0*fabs(fp-(*fret)) <= ftol*(fabs(fp)+fabs(*fret)))*/
                   1373:     printf(".");fflush(stdout);
                   1374:     fprintf(ficlog,".");fflush(ficlog);
1.162     brouard  1375: #ifdef DEBUGBRENT
1.126     brouard  1376:     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);
                   1377:     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);
                   1378:     /*         if ((fabs(x-xm) <= (tol2-0.5*(b-a)))||(2.0*fabs(fu-ftemp) <= ftol*1.e-2*(fabs(fu)+fabs(ftemp)))) { */
                   1379: #endif
                   1380:     if (fabs(x-xm) <= (tol2-0.5*(b-a))){ 
                   1381:       *xmin=x; 
                   1382:       return fx; 
                   1383:     } 
                   1384:     ftemp=fu;
                   1385:     if (fabs(e) > tol1) { 
                   1386:       r=(x-w)*(fx-fv); 
                   1387:       q=(x-v)*(fx-fw); 
                   1388:       p=(x-v)*q-(x-w)*r; 
                   1389:       q=2.0*(q-r); 
                   1390:       if (q > 0.0) p = -p; 
                   1391:       q=fabs(q); 
                   1392:       etemp=e; 
                   1393:       e=d; 
                   1394:       if (fabs(p) >= fabs(0.5*q*etemp) || p <= q*(a-x) || p >= q*(b-x)) 
                   1395:        d=CGOLD*(e=(x >= xm ? a-x : b-x)); 
                   1396:       else { 
                   1397:        d=p/q; 
                   1398:        u=x+d; 
                   1399:        if (u-a < tol2 || b-u < tol2) 
                   1400:          d=SIGN(tol1,xm-x); 
                   1401:       } 
                   1402:     } else { 
                   1403:       d=CGOLD*(e=(x >= xm ? a-x : b-x)); 
                   1404:     } 
                   1405:     u=(fabs(d) >= tol1 ? x+d : x+SIGN(tol1,d)); 
                   1406:     fu=(*f)(u); 
                   1407:     if (fu <= fx) { 
                   1408:       if (u >= x) a=x; else b=x; 
                   1409:       SHFT(v,w,x,u) 
1.183     brouard  1410:       SHFT(fv,fw,fx,fu) 
                   1411:     } else { 
                   1412:       if (u < x) a=u; else b=u; 
                   1413:       if (fu <= fw || w == x) { 
                   1414:        v=w; 
                   1415:        w=u; 
                   1416:        fv=fw; 
                   1417:        fw=fu; 
                   1418:       } else if (fu <= fv || v == x || v == w) { 
                   1419:        v=u; 
                   1420:        fv=fu; 
                   1421:       } 
                   1422:     } 
1.126     brouard  1423:   } 
                   1424:   nrerror("Too many iterations in brent"); 
                   1425:   *xmin=x; 
                   1426:   return fx; 
                   1427: } 
                   1428: 
                   1429: /****************** mnbrak ***********************/
                   1430: 
                   1431: void mnbrak(double *ax, double *bx, double *cx, double *fa, double *fb, double *fc, 
                   1432:            double (*func)(double)) 
1.183     brouard  1433: { /* Given a function func , and given distinct initial points ax and bx , this routine searches in
                   1434: the downhill direction (defined by the function as evaluated at the initial points) and returns
                   1435: new points ax , bx , cx that bracket a minimum of the function. Also returned are the function
                   1436: values at the three points, fa, fb , and fc such that fa > fb and fb < fc.
                   1437:    */
1.126     brouard  1438:   double ulim,u,r,q, dum;
                   1439:   double fu; 
1.187     brouard  1440: 
                   1441:   double scale=10.;
                   1442:   int iterscale=0;
                   1443: 
                   1444:   *fa=(*func)(*ax); /*  xta[j]=pcom[j]+(*ax)*xicom[j]; fa=f(xta[j])*/
                   1445:   *fb=(*func)(*bx); /*  xtb[j]=pcom[j]+(*bx)*xicom[j]; fb=f(xtb[j]) */
                   1446: 
                   1447: 
                   1448:   /* while(*fb != *fb){ /\* *ax should be ok, reducing distance to *ax *\/ */
                   1449:   /*   printf("Warning mnbrak *fb = %lf, *bx=%lf *ax=%lf *fa==%lf iter=%d\n",*fb, *bx, *ax, *fa, iterscale++); */
                   1450:   /*   *bx = *ax - (*ax - *bx)/scale; */
                   1451:   /*   *fb=(*func)(*bx);  /\*  xtb[j]=pcom[j]+(*bx)*xicom[j]; fb=f(xtb[j]) *\/ */
                   1452:   /* } */
                   1453: 
1.126     brouard  1454:   if (*fb > *fa) { 
                   1455:     SHFT(dum,*ax,*bx,dum) 
1.183     brouard  1456:     SHFT(dum,*fb,*fa,dum) 
                   1457:   } 
1.126     brouard  1458:   *cx=(*bx)+GOLD*(*bx-*ax); 
                   1459:   *fc=(*func)(*cx); 
1.183     brouard  1460: #ifdef DEBUG
                   1461:   printf("mnbrak0 *fb=%.12e *fc=%.12e\n",*fb,*fc);
                   1462:   fprintf(ficlog,"mnbrak0 *fb=%.12e *fc=%.12e\n",*fb,*fc);
                   1463: #endif
                   1464:   while (*fb > *fc) { /* Declining a,b,c with fa> fb > fc */
1.126     brouard  1465:     r=(*bx-*ax)*(*fb-*fc); 
                   1466:     q=(*bx-*cx)*(*fb-*fa); 
                   1467:     u=(*bx)-((*bx-*cx)*q-(*bx-*ax)*r)/ 
1.183     brouard  1468:       (2.0*SIGN(FMAX(fabs(q-r),TINY),q-r)); /* Minimum abscissa of a parabolic estimated from (a,fa), (b,fb) and (c,fc). */
                   1469:     ulim=(*bx)+GLIMIT*(*cx-*bx); /* Maximum abscissa where function should be evaluated */
                   1470:     if ((*bx-u)*(u-*cx) > 0.0) { /* if u_p is between b and c */
1.126     brouard  1471:       fu=(*func)(u); 
1.163     brouard  1472: #ifdef DEBUG
                   1473:       /* f(x)=A(x-u)**2+f(u) */
                   1474:       double A, fparabu; 
                   1475:       A= (*fb - *fa)/(*bx-*ax)/(*bx+*ax-2*u);
                   1476:       fparabu= *fa - A*(*ax-u)*(*ax-u);
                   1477:       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);
                   1478:       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  1479:       /* And thus,it can be that fu > *fc even if fparabu < *fc */
                   1480:       /* mnbrak (*ax=7.666299858533, *fa=299039.693133272231), (*bx=8.595447774979, *fb=298976.598289369489),
                   1481:         (*cx=10.098840694817, *fc=298946.631474258087),  (*u=9.852501168332, fu=298948.773013752128, fparabu=298945.434711494134) */
                   1482:       /* In that case, there is no bracket in the output! Routine is wrong with many consequences.*/
1.163     brouard  1483: #endif 
1.184     brouard  1484: #ifdef MNBRAKORIGINAL
1.183     brouard  1485: #else
1.191     brouard  1486: /*       if (fu > *fc) { */
                   1487: /* #ifdef DEBUG */
                   1488: /*       printf("mnbrak4  fu > fc \n"); */
                   1489: /*       fprintf(ficlog, "mnbrak4 fu > fc\n"); */
                   1490: /* #endif */
                   1491: /*     /\* 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 *\\/  *\/ */
                   1492: /*     /\* SHFT(*fa,*fc,fu,*fc) /\\* (b, u, c) is a bracket while test fb > fc will be fu > fc  will exit *\\/ *\/ */
                   1493: /*     dum=u; /\* Shifting c and u *\/ */
                   1494: /*     u = *cx; */
                   1495: /*     *cx = dum; */
                   1496: /*     dum = fu; */
                   1497: /*     fu = *fc; */
                   1498: /*     *fc =dum; */
                   1499: /*       } else { /\* end *\/ */
                   1500: /* #ifdef DEBUG */
                   1501: /*       printf("mnbrak3  fu < fc \n"); */
                   1502: /*       fprintf(ficlog, "mnbrak3 fu < fc\n"); */
                   1503: /* #endif */
                   1504: /*     dum=u; /\* Shifting c and u *\/ */
                   1505: /*     u = *cx; */
                   1506: /*     *cx = dum; */
                   1507: /*     dum = fu; */
                   1508: /*     fu = *fc; */
                   1509: /*     *fc =dum; */
                   1510: /*       } */
1.183     brouard  1511: #ifdef DEBUG
1.191     brouard  1512:       printf("mnbrak34  fu < or >= fc \n");
                   1513:       fprintf(ficlog, "mnbrak34 fu < fc\n");
1.183     brouard  1514: #endif
1.191     brouard  1515:       dum=u; /* Shifting c and u */
                   1516:       u = *cx;
                   1517:       *cx = dum;
                   1518:       dum = fu;
                   1519:       fu = *fc;
                   1520:       *fc =dum;
1.183     brouard  1521: #endif
1.162     brouard  1522:     } else if ((*cx-u)*(u-ulim) > 0.0) { /* u is after c but before ulim */
1.183     brouard  1523: #ifdef DEBUG
                   1524:       printf("mnbrak2  u after c but before ulim\n");
                   1525:       fprintf(ficlog, "mnbrak2 u after c but before ulim\n");
                   1526: #endif
1.126     brouard  1527:       fu=(*func)(u); 
                   1528:       if (fu < *fc) { 
1.183     brouard  1529: #ifdef DEBUG
                   1530:       printf("mnbrak2  u after c but before ulim AND fu < fc\n");
                   1531:       fprintf(ficlog, "mnbrak2 u after c but before ulim AND fu <fc \n");
                   1532: #endif
1.126     brouard  1533:        SHFT(*bx,*cx,u,*cx+GOLD*(*cx-*bx)) 
1.183     brouard  1534:        SHFT(*fb,*fc,fu,(*func)(u)) 
                   1535:       } 
1.162     brouard  1536:     } else if ((u-ulim)*(ulim-*cx) >= 0.0) { /* u outside ulim (verifying that ulim is beyond c) */
1.183     brouard  1537: #ifdef DEBUG
                   1538:       printf("mnbrak2  u outside ulim (verifying that ulim is beyond c)\n");
                   1539:       fprintf(ficlog, "mnbrak2 u outside ulim (verifying that ulim is beyond c)\n");
                   1540: #endif
1.126     brouard  1541:       u=ulim; 
                   1542:       fu=(*func)(u); 
1.183     brouard  1543:     } else { /* u could be left to b (if r > q parabola has a maximum) */
                   1544: #ifdef DEBUG
                   1545:       printf("mnbrak2  u could be left to b (if r > q parabola has a maximum)\n");
                   1546:       fprintf(ficlog, "mnbrak2  u could be left to b (if r > q parabola has a maximum)\n");
                   1547: #endif
1.126     brouard  1548:       u=(*cx)+GOLD*(*cx-*bx); 
                   1549:       fu=(*func)(u); 
1.183     brouard  1550:     } /* end tests */
1.126     brouard  1551:     SHFT(*ax,*bx,*cx,u) 
1.183     brouard  1552:     SHFT(*fa,*fb,*fc,fu) 
                   1553: #ifdef DEBUG
                   1554:       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);
                   1555:       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);
                   1556: #endif
                   1557:   } /* 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  1558: } 
                   1559: 
                   1560: /*************** linmin ************************/
1.162     brouard  1561: /* Given an n -dimensional point p[1..n] and an n -dimensional direction xi[1..n] , moves and
                   1562: resets p to where the function func(p) takes on a minimum along the direction xi from p ,
                   1563: and replaces xi by the actual vector displacement that p was moved. Also returns as fret
                   1564: the value of func at the returned location p . This is actually all accomplished by calling the
                   1565: routines mnbrak and brent .*/
1.126     brouard  1566: int ncom; 
                   1567: double *pcom,*xicom;
                   1568: double (*nrfunc)(double []); 
                   1569:  
                   1570: void linmin(double p[], double xi[], int n, double *fret,double (*func)(double [])) 
                   1571: { 
                   1572:   double brent(double ax, double bx, double cx, 
                   1573:               double (*f)(double), double tol, double *xmin); 
                   1574:   double f1dim(double x); 
                   1575:   void mnbrak(double *ax, double *bx, double *cx, double *fa, double *fb, 
                   1576:              double *fc, double (*func)(double)); 
                   1577:   int j; 
                   1578:   double xx,xmin,bx,ax; 
                   1579:   double fx,fb,fa;
1.187     brouard  1580: 
                   1581:   double scale=10., axs, xxs, xxss; /* Scale added for infinity */
1.126     brouard  1582:  
                   1583:   ncom=n; 
                   1584:   pcom=vector(1,n); 
                   1585:   xicom=vector(1,n); 
                   1586:   nrfunc=func; 
                   1587:   for (j=1;j<=n;j++) { 
                   1588:     pcom[j]=p[j]; 
                   1589:     xicom[j]=xi[j]; 
                   1590:   } 
1.187     brouard  1591: 
1.192     brouard  1592:   /* axs=0.0; */
                   1593:   /* xxss=1; /\* 1 and using scale *\/ */
1.187     brouard  1594:   xxs=1;
1.192     brouard  1595:   /* do{ */
1.187     brouard  1596:     ax=0.;
                   1597:     xx= xxs;
                   1598:     mnbrak(&ax,&xx,&bx,&fa,&fx,&fb,f1dim);  /* Outputs: xtx[j]=pcom[j]+(*xx)*xicom[j]; fx=f(xtx[j]) */
                   1599:     /* brackets with inputs ax=0 and xx=1, but points, pcom=p, and directions values, xicom=xi, are sent via f1dim(x) */
                   1600:     /* 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))   */
                   1601:     /* Outputs: fa=f(p(j)) and fx=f(p(j) + xxs * xi(j) ) and f(bx)= f(p(j)+ bx* xi(j)) */
                   1602:     /* Given input ax=axs and xx=xxs, xx might be too far from ax to get a finite f(xx) */
                   1603:     /* Searches on line, outputs (ax, xx, bx) such that fx < min(fa and fb) */
                   1604:     /* 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.192     brouard  1605:   /*   if (fx != fx){ */
                   1606:   /*   xxs=xxs/scale; /\* Trying a smaller xx, closer to initial ax=0 *\/ */
                   1607:   /*   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); */
                   1608:   /*   } */
                   1609:   /* }while(fx != fx); */
1.187     brouard  1610: 
1.191     brouard  1611: #ifdef DEBUGLINMIN
                   1612:   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);
                   1613: #endif
1.187     brouard  1614:   *fret=brent(ax,xx,bx,f1dim,TOL,&xmin); /* Giving a bracketting triplet (ax, xx, bx), find a minimum, xmin, according to f1dim, *fret(xmin),*/
                   1615:   /* fa = f(p[j] + ax * xi[j]), fx = f(p[j] + xx * xi[j]), fb = f(p[j] + bx * xi[j]) */
                   1616:   /* fmin = f(p[j] + xmin * xi[j]) */
                   1617:   /* P+lambda n in that direction (lambdamin), with TOL between abscisses */
                   1618:   /* f1dim(xmin): for (j=1;j<=ncom;j++) xt[j]=pcom[j]+xmin*xicom[j]; */
1.126     brouard  1619: #ifdef DEBUG
                   1620:   printf("retour brent fret=%.12e xmin=%.12e\n",*fret,xmin);
                   1621:   fprintf(ficlog,"retour brent fret=%.12e xmin=%.12e\n",*fret,xmin);
                   1622: #endif
1.191     brouard  1623: #ifdef DEBUGLINMIN
                   1624:   printf("linmin end ");
                   1625: #endif
1.126     brouard  1626:   for (j=1;j<=n;j++) { 
1.188     brouard  1627:     /* printf(" before xi[%d]=%12.8f", j,xi[j]); */
1.187     brouard  1628:     xi[j] *= xmin; /* xi rescaled by xmin: if xmin=-1.237 and xi=(1,0,...,0) xi=(-1.237,0,...,0) */
1.189     brouard  1629:     /* if(xxs <1.0) */
                   1630:     /*   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 ); */
1.187     brouard  1631:     p[j] += xi[j]; /* Parameters values are updated accordingly */
1.126     brouard  1632:   } 
1.189     brouard  1633:   /* printf("\n"); */
1.191     brouard  1634: #ifdef DEBUGLINMIN
                   1635:   printf("Comparing last *frec(xmin=%12.8f)=%12.8f from Brent and frec(0.)=%12.8f \n", xmin, *fret, (*func)(p));
                   1636:   for (j=1;j<=n;j++) { 
                   1637:     printf(" xi[%d]= %12.7f p[%d]= %12.7f",j,xi[j],j,p[j]);
                   1638:     if(j % ncovmodel == 0)
                   1639:       printf("\n");
                   1640:   }
                   1641: #endif
1.126     brouard  1642:   free_vector(xicom,1,n); 
                   1643:   free_vector(pcom,1,n); 
                   1644: } 
                   1645: 
                   1646: 
                   1647: /*************** powell ************************/
1.162     brouard  1648: /*
                   1649: Minimization of a function func of n variables. Input consists of an initial starting point
                   1650: p[1..n] ; an initial matrix xi[1..n][1..n] , whose columns contain the initial set of di-
                   1651: rections (usually the n unit vectors); and ftol , the fractional tolerance in the function value
                   1652: such that failure to decrease by more than this amount on one iteration signals doneness. On
                   1653: output, p is set to the best point found, xi is the then-current direction set, fret is the returned
                   1654: function value at p , and iter is the number of iterations taken. The routine linmin is used.
                   1655:  */
1.126     brouard  1656: void powell(double p[], double **xi, int n, double ftol, int *iter, double *fret, 
                   1657:            double (*func)(double [])) 
                   1658: { 
                   1659:   void linmin(double p[], double xi[], int n, double *fret, 
                   1660:              double (*func)(double [])); 
                   1661:   int i,ibig,j; 
                   1662:   double del,t,*pt,*ptt,*xit;
1.181     brouard  1663:   double directest;
1.126     brouard  1664:   double fp,fptt;
                   1665:   double *xits;
                   1666:   int niterf, itmp;
                   1667: 
                   1668:   pt=vector(1,n); 
                   1669:   ptt=vector(1,n); 
                   1670:   xit=vector(1,n); 
                   1671:   xits=vector(1,n); 
                   1672:   *fret=(*func)(p); 
                   1673:   for (j=1;j<=n;j++) pt[j]=p[j]; 
1.157     brouard  1674:     rcurr_time = time(NULL);  
1.126     brouard  1675:   for (*iter=1;;++(*iter)) { 
1.187     brouard  1676:     fp=(*fret); /* From former iteration or initial value */
1.126     brouard  1677:     ibig=0; 
                   1678:     del=0.0; 
1.157     brouard  1679:     rlast_time=rcurr_time;
                   1680:     /* (void) gettimeofday(&curr_time,&tzp); */
                   1681:     rcurr_time = time(NULL);  
                   1682:     curr_time = *localtime(&rcurr_time);
                   1683:     printf("\nPowell iter=%d -2*LL=%.12f %ld sec. %ld sec.",*iter,*fret, rcurr_time-rlast_time, rcurr_time-rstart_time);fflush(stdout);
                   1684:     fprintf(ficlog,"\nPowell iter=%d -2*LL=%.12f %ld sec. %ld sec.",*iter,*fret,rcurr_time-rlast_time, rcurr_time-rstart_time); fflush(ficlog);
                   1685: /*     fprintf(ficrespow,"%d %.12f %ld",*iter,*fret,curr_time.tm_sec-start_time.tm_sec); */
1.192     brouard  1686:     for (i=1;i<=n;i++) {
1.126     brouard  1687:       printf(" %d %.12f",i, p[i]);
                   1688:       fprintf(ficlog," %d %.12lf",i, p[i]);
                   1689:       fprintf(ficrespow," %.12lf", p[i]);
                   1690:     }
                   1691:     printf("\n");
                   1692:     fprintf(ficlog,"\n");
                   1693:     fprintf(ficrespow,"\n");fflush(ficrespow);
                   1694:     if(*iter <=3){
1.157     brouard  1695:       tml = *localtime(&rcurr_time);
                   1696:       strcpy(strcurr,asctime(&tml));
                   1697:       rforecast_time=rcurr_time; 
1.126     brouard  1698:       itmp = strlen(strcurr);
                   1699:       if(strcurr[itmp-1]=='\n')  /* Windows outputs with a new line */
                   1700:        strcurr[itmp-1]='\0';
1.162     brouard  1701:       printf("\nConsidering the time needed for the last iteration #%d: %ld seconds,\n",*iter,rcurr_time-rlast_time);
1.157     brouard  1702:       fprintf(ficlog,"\nConsidering the time needed for this last iteration #%d: %ld seconds,\n",*iter,rcurr_time-rlast_time);
1.126     brouard  1703:       for(niterf=10;niterf<=30;niterf+=10){
1.157     brouard  1704:        rforecast_time=rcurr_time+(niterf-*iter)*(rcurr_time-rlast_time);
                   1705:        forecast_time = *localtime(&rforecast_time);
                   1706:        strcpy(strfor,asctime(&forecast_time));
1.126     brouard  1707:        itmp = strlen(strfor);
                   1708:        if(strfor[itmp-1]=='\n')
                   1709:        strfor[itmp-1]='\0';
1.157     brouard  1710:        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);
                   1711:        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  1712:       }
                   1713:     }
1.187     brouard  1714:     for (i=1;i<=n;i++) { /* For each direction i */
                   1715:       for (j=1;j<=n;j++) xit[j]=xi[j][i]; /* Directions stored from previous iteration with previous scales */
1.126     brouard  1716:       fptt=(*fret); 
                   1717: #ifdef DEBUG
1.164     brouard  1718:          printf("fret=%lf, %lf, %lf \n", *fret, *fret, *fret);
                   1719:          fprintf(ficlog, "fret=%lf, %lf, %lf \n", *fret, *fret, *fret);
1.126     brouard  1720: #endif
1.187     brouard  1721:          printf("%d",i);fflush(stdout); /* print direction (parameter) i */
1.126     brouard  1722:       fprintf(ficlog,"%d",i);fflush(ficlog);
1.188     brouard  1723:       linmin(p,xit,n,fret,func); /* Point p[n]. xit[n] has been loaded for direction i as input.*/
                   1724:                                    /* Outputs are fret(new point p) p is updated and xit rescaled */
                   1725:       if (fabs(fptt-(*fret)) > del) { /* We are keeping the max gain on each of the n directions */
                   1726:        /* because that direction will be replaced unless the gain del is small */
                   1727:        /* in comparison with the 'probable' gain, mu^2, with the last average direction. */
                   1728:        /* Unless the n directions are conjugate some gain in the determinant may be obtained */
                   1729:        /* with the new direction. */
1.126     brouard  1730:        del=fabs(fptt-(*fret)); 
                   1731:        ibig=i; 
                   1732:       } 
                   1733: #ifdef DEBUG
                   1734:       printf("%d %.12e",i,(*fret));
                   1735:       fprintf(ficlog,"%d %.12e",i,(*fret));
                   1736:       for (j=1;j<=n;j++) {
                   1737:        xits[j]=FMAX(fabs(p[j]-pt[j]),1.e-5);
                   1738:        printf(" x(%d)=%.12e",j,xit[j]);
                   1739:        fprintf(ficlog," x(%d)=%.12e",j,xit[j]);
                   1740:       }
                   1741:       for(j=1;j<=n;j++) {
1.162     brouard  1742:        printf(" p(%d)=%.12e",j,p[j]);
                   1743:        fprintf(ficlog," p(%d)=%.12e",j,p[j]);
1.126     brouard  1744:       }
                   1745:       printf("\n");
                   1746:       fprintf(ficlog,"\n");
                   1747: #endif
1.187     brouard  1748:     } /* end loop on each direction i */
                   1749:     /* Convergence test will use last linmin estimation (fret) and compare former iteration (fp) */ 
1.188     brouard  1750:     /* But p and xit have been updated at the end of linmin, *fret corresponds to new p, xit  */
1.187     brouard  1751:     /* New value of last point Pn is not computed, P(n-1) */
1.182     brouard  1752:     if (2.0*fabs(fp-(*fret)) <= ftol*(fabs(fp)+fabs(*fret))) { /* Did we reach enough precision? */
1.188     brouard  1753:       /* We could compare with a chi^2. chisquare(0.95,ddl=1)=3.84 */
                   1754:       /* By adding age*age in a model, the new -2LL should be lower and the difference follows a */
                   1755:       /* a chisquare statistics with 1 degree. To be significant at the 95% level, it should have */
                   1756:       /* decreased of more than 3.84  */
                   1757:       /* By adding age*age and V1*age the gain (-2LL) should be more than 5.99 (ddl=2) */
                   1758:       /* By using V1+V2+V3, the gain should be  7.82, compared with basic 1+age. */
                   1759:       /* By adding 10 parameters more the gain should be 18.31 */
                   1760: 
                   1761:       /* Starting the program with initial values given by a former maximization will simply change */
                   1762:       /* the scales of the directions and the directions, because the are reset to canonical directions */
                   1763:       /* Thus the first calls to linmin will give new points and better maximizations until fp-(*fret) is */
                   1764:       /* under the tolerance value. If the tolerance is very small 1.e-9, it could last long.  */
1.126     brouard  1765: #ifdef DEBUG
                   1766:       int k[2],l;
                   1767:       k[0]=1;
                   1768:       k[1]=-1;
                   1769:       printf("Max: %.12e",(*func)(p));
                   1770:       fprintf(ficlog,"Max: %.12e",(*func)(p));
                   1771:       for (j=1;j<=n;j++) {
                   1772:        printf(" %.12e",p[j]);
                   1773:        fprintf(ficlog," %.12e",p[j]);
                   1774:       }
                   1775:       printf("\n");
                   1776:       fprintf(ficlog,"\n");
                   1777:       for(l=0;l<=1;l++) {
                   1778:        for (j=1;j<=n;j++) {
                   1779:          ptt[j]=p[j]+(p[j]-pt[j])*k[l];
                   1780:          printf("l=%d j=%d ptt=%.12e, xits=%.12e, p=%.12e, xit=%.12e", l,j,ptt[j],xits[j],p[j],xit[j]);
                   1781:          fprintf(ficlog,"l=%d j=%d ptt=%.12e, xits=%.12e, p=%.12e, xit=%.12e", l,j,ptt[j],xits[j],p[j],xit[j]);
                   1782:        }
                   1783:        printf("func(ptt)=%.12e, deriv=%.12e\n",(*func)(ptt),(ptt[j]-p[j])/((*func)(ptt)-(*func)(p)));
                   1784:        fprintf(ficlog,"func(ptt)=%.12e, deriv=%.12e\n",(*func)(ptt),(ptt[j]-p[j])/((*func)(ptt)-(*func)(p)));
                   1785:       }
                   1786: #endif
                   1787: 
                   1788: 
                   1789:       free_vector(xit,1,n); 
                   1790:       free_vector(xits,1,n); 
                   1791:       free_vector(ptt,1,n); 
                   1792:       free_vector(pt,1,n); 
                   1793:       return; 
1.192     brouard  1794:     } /* enough precision */ 
1.126     brouard  1795:     if (*iter == ITMAX) nrerror("powell exceeding maximum iterations."); 
1.181     brouard  1796:     for (j=1;j<=n;j++) { /* Computes the extrapolated point P_0 + 2 (P_n-P_0) */
1.126     brouard  1797:       ptt[j]=2.0*p[j]-pt[j]; 
                   1798:       xit[j]=p[j]-pt[j]; 
                   1799:       pt[j]=p[j]; 
                   1800:     } 
1.181     brouard  1801:     fptt=(*func)(ptt); /* f_3 */
1.192     brouard  1802: #ifdef POWELLF1F3
                   1803: #else
1.161     brouard  1804:     if (fptt < fp) { /* If extrapolated point is better, decide if we keep that new direction or not */
1.192     brouard  1805: #endif
1.162     brouard  1806:       /* (x1 f1=fp), (x2 f2=*fret), (x3 f3=fptt), (xm fm) */
1.161     brouard  1807:       /* From x1 (P0) distance of x2 is at h and x3 is 2h */
1.162     brouard  1808:       /* Let f"(x2) be the 2nd derivative equal everywhere.  */
                   1809:       /* Then the parabolic through (x1,f1), (x2,f2) and (x3,f3) */
                   1810:       /* will reach at f3 = fm + h^2/2 f"m  ; f" = (f1 -2f2 +f3 ) / h**2 */
1.181     brouard  1811:       /* Conditional for using this new direction is that mu^2 = (f1-2f2+f3)^2 /2 < del */
1.161     brouard  1812:       /* t=2.0*(fp-2.0*(*fret)+fptt)*SQR(fp-(*fret)-del)-del*SQR(fp-fptt); */
1.183     brouard  1813: #ifdef NRCORIGINAL
                   1814:       t=2.0*(fp-2.0*(*fret)+fptt)*SQR(fp-(*fret)-del)- del*SQR(fp-fptt); /* Original Numerical Recipes in C*/
                   1815: #else
                   1816:       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  1817:       t= t- del*SQR(fp-fptt);
1.183     brouard  1818: #endif
1.182     brouard  1819:       directest = fp-2.0*(*fret)+fptt - 2.0 * del; /* If del was big enough we change it for a new direction */
1.161     brouard  1820: #ifdef DEBUG
1.181     brouard  1821:       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);
                   1822:       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  1823:       printf("t3= %.12lf, t4= %.12lf, t3*= %.12lf, t4*= %.12lf\n",SQR(fp-(*fret)-del),SQR(fp-fptt),
                   1824:             (fp-(*fret)-del)*(fp-(*fret)-del),(fp-fptt)*(fp-fptt));
                   1825:       fprintf(ficlog,"t3= %.12lf, t4= %.12lf, t3*= %.12lf, t4*= %.12lf\n",SQR(fp-(*fret)-del),SQR(fp-fptt),
                   1826:             (fp-(*fret)-del)*(fp-(*fret)-del),(fp-fptt)*(fp-fptt));
                   1827:       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);
                   1828:       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);
                   1829: #endif
1.183     brouard  1830: #ifdef POWELLORIGINAL
                   1831:       if (t < 0.0) { /* Then we use it for new direction */
                   1832: #else
1.182     brouard  1833:       if (directest*t < 0.0) { /* Contradiction between both tests */
1.192     brouard  1834:        printf("directest= %.12lf, t= %.12lf, f1= %.12lf,f2= %.12lf,f3= %.12lf, del= %.12lf\n",directest, t, fp,(*fret),fptt,del);
                   1835:         printf("f1-2f2+f3= %.12lf, f1-f2-del= %.12lf, f1-f3= %.12lf\n",fp-2.0*(*fret)+fptt, fp -(*fret) -del, fp-fptt);
                   1836:         fprintf(ficlog,"directest= %.12lf, t= %.12lf, f1= %.12lf,f2= %.12lf,f3= %.12lf, del= %.12lf\n",directest, t, fp,(*fret),fptt, del);
                   1837:         fprintf(ficlog,"f1-2f2+f3= %.12lf, f1-f2-del= %.12lf, f1-f3= %.12lf\n",fp-2.0*(*fret)+fptt, fp -(*fret) -del, fp-fptt);
                   1838:       } 
1.181     brouard  1839:       if (directest < 0.0) { /* Then we use it for new direction */
                   1840: #endif
1.191     brouard  1841: #ifdef DEBUGLINMIN
                   1842:        printf("Before linmin in direction P%d-P0\n",n);
                   1843:        for (j=1;j<=n;j++) { 
                   1844:          printf("Before xit[%d]= %12.7f p[%d]= %12.7f",j,xit[j],j,p[j]);
                   1845:          if(j % ncovmodel == 0)
                   1846:            printf("\n");
                   1847:        }
                   1848: #endif
1.187     brouard  1849:        linmin(p,xit,n,fret,func); /* computes minimum on the extrapolated direction: changes p and rescales xit.*/
1.191     brouard  1850: #ifdef DEBUGLINMIN
                   1851:        for (j=1;j<=n;j++) { 
                   1852:          printf("After xit[%d]= %12.7f p[%d]= %12.7f",j,xit[j],j,p[j]);
                   1853:          if(j % ncovmodel == 0)
                   1854:            printf("\n");
                   1855:        }
                   1856: #endif
1.126     brouard  1857:        for (j=1;j<=n;j++) { 
1.181     brouard  1858:          xi[j][ibig]=xi[j][n]; /* Replace direction with biggest decrease by last direction n */
                   1859:          xi[j][n]=xit[j];      /* and this nth direction by the by the average p_0 p_n */
1.126     brouard  1860:        }
1.181     brouard  1861:        printf("Gaining to use new average direction of P0 P%d instead of biggest increase direction %d :\n",n,ibig);
                   1862:        fprintf(ficlog,"Gaining to use new average direction of P0 P%d instead of biggest increase direction %d :\n",n,ibig);
1.161     brouard  1863: 
1.126     brouard  1864: #ifdef DEBUG
1.164     brouard  1865:        printf("Direction changed  last moved %d in place of ibig=%d, new last is the average:\n",n,ibig);
                   1866:        fprintf(ficlog,"Direction changed  last moved %d in place of ibig=%d, new last is the average:\n",n,ibig);
1.126     brouard  1867:        for(j=1;j<=n;j++){
                   1868:          printf(" %.12e",xit[j]);
                   1869:          fprintf(ficlog," %.12e",xit[j]);
                   1870:        }
                   1871:        printf("\n");
                   1872:        fprintf(ficlog,"\n");
                   1873: #endif
1.192     brouard  1874:       } /* end of t or directest negative */
                   1875: #ifdef POWELLF1F3
                   1876: #else
1.162     brouard  1877:     } /* end if (fptt < fp)  */
1.192     brouard  1878: #endif
                   1879:   } /* loop iteration */ 
1.126     brouard  1880: } 
                   1881: 
                   1882: /**** Prevalence limit (stable or period prevalence)  ****************/
                   1883: 
                   1884: double **prevalim(double **prlim, int nlstate, double x[], double age, double **oldm, double **savm, double ftolpl, int ij)
                   1885: {
                   1886:   /* Computes the prevalence limit in each live state at age x by left multiplying the unit
                   1887:      matrix by transitions matrix until convergence is reached */
1.169     brouard  1888:   
1.126     brouard  1889:   int i, ii,j,k;
                   1890:   double min, max, maxmin, maxmax,sumnew=0.;
1.145     brouard  1891:   /* double **matprod2(); */ /* test */
1.131     brouard  1892:   double **out, cov[NCOVMAX+1], **pmij();
1.126     brouard  1893:   double **newm;
                   1894:   double agefin, delaymax=50 ; /* Max number of years to converge */
1.169     brouard  1895:   
1.126     brouard  1896:   for (ii=1;ii<=nlstate+ndeath;ii++)
                   1897:     for (j=1;j<=nlstate+ndeath;j++){
                   1898:       oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   1899:     }
1.169     brouard  1900:   
                   1901:   cov[1]=1.;
                   1902:   
                   1903:   /* Even if hstepm = 1, at least one multiplication by the unit matrix */
1.126     brouard  1904:   for(agefin=age-stepm/YEARM; agefin>=age-delaymax; agefin=agefin-stepm/YEARM){
                   1905:     newm=savm;
                   1906:     /* Covariates have to be included here again */
1.138     brouard  1907:     cov[2]=agefin;
1.187     brouard  1908:     if(nagesqr==1)
                   1909:       cov[3]= agefin*agefin;;
1.138     brouard  1910:     for (k=1; k<=cptcovn;k++) {
1.187     brouard  1911:       cov[2+nagesqr+k]=nbcode[Tvar[k]][codtab[ij][Tvar[k]]];
1.197   ! brouard  1912:       /*      printf("prevalim ij=%d k=%d Tvar[%d]=%d nbcode=%d cov=%lf codtab[%d][Tvar[%d]]=%d \n",ij,k, k, Tvar[k],nbcode[Tvar[k]][codtab[ij][Tvar[k]]],cov[2+k], ij, k, codtab[ij][Tvar[k]]);*/
1.138     brouard  1913:     }
1.186     brouard  1914:     /*wrong? for (k=1; k<=cptcovage;k++) cov[2+Tage[k]]=cov[2+Tage[k]]*cov[2]; */
1.187     brouard  1915:     for (k=1; k<=cptcovage;k++) cov[2+nagesqr+Tage[k]]=nbcode[Tvar[k]][codtab[ij][Tvar[k]]]*cov[2];
1.186     brouard  1916:     for (k=1; k<=cptcovprod;k++) /* Useless */
1.187     brouard  1917:       cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtab[ij][Tvard[k][1]]] * nbcode[Tvard[k][2]][codtab[ij][Tvard[k][2]]];
1.138     brouard  1918:     
                   1919:     /*printf("ij=%d cptcovprod=%d tvar=%d ", ij, cptcovprod, Tvar[1]);*/
                   1920:     /*printf("ij=%d cov[3]=%lf cov[4]=%lf \n",ij, cov[3],cov[4]);*/
                   1921:     /*printf("ij=%d cov[3]=%lf \n",ij, cov[3]);*/
1.145     brouard  1922:     /* savm=pmij(pmmij,cov,ncovmodel,x,nlstate); */
                   1923:     /* out=matprod2(newm, pmij(pmmij,cov,ncovmodel,x,nlstate),1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, oldm); /\* Bug Valgrind *\/ */
1.142     brouard  1924:     out=matprod2(newm, pmij(pmmij,cov,ncovmodel,x,nlstate),1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, oldm); /* Bug Valgrind */
1.138     brouard  1925:     
1.126     brouard  1926:     savm=oldm;
                   1927:     oldm=newm;
                   1928:     maxmax=0.;
                   1929:     for(j=1;j<=nlstate;j++){
                   1930:       min=1.;
                   1931:       max=0.;
                   1932:       for(i=1; i<=nlstate; i++) {
                   1933:        sumnew=0;
                   1934:        for(k=1; k<=ndeath; k++) sumnew+=newm[i][nlstate+k];
                   1935:        prlim[i][j]= newm[i][j]/(1-sumnew);
1.145     brouard  1936:         /*printf(" prevalim i=%d, j=%d, prmlim[%d][%d]=%f, agefin=%d \n", i, j, i, j, prlim[i][j],(int)agefin);*/
1.126     brouard  1937:        max=FMAX(max,prlim[i][j]);
                   1938:        min=FMIN(min,prlim[i][j]);
                   1939:       }
                   1940:       maxmin=max-min;
                   1941:       maxmax=FMAX(maxmax,maxmin);
1.169     brouard  1942:     } /* j loop */
1.126     brouard  1943:     if(maxmax < ftolpl){
                   1944:       return prlim;
                   1945:     }
1.169     brouard  1946:   } /* age loop */
                   1947:   return prlim; /* should not reach here */
1.126     brouard  1948: }
                   1949: 
                   1950: /*************** transition probabilities ***************/ 
                   1951: 
                   1952: double **pmij(double **ps, double *cov, int ncovmodel, double *x, int nlstate )
                   1953: {
1.138     brouard  1954:   /* According to parameters values stored in x and the covariate's values stored in cov,
                   1955:      computes the probability to be observed in state j being in state i by appying the
                   1956:      model to the ncovmodel covariates (including constant and age).
                   1957:      lnpijopii=ln(pij/pii)= aij+bij*age+cij*v1+dij*v2+... = sum_nc=1^ncovmodel xij(nc)*cov[nc]
                   1958:      and, according on how parameters are entered, the position of the coefficient xij(nc) of the
                   1959:      ncth covariate in the global vector x is given by the formula:
                   1960:      j<i nc+((i-1)*(nlstate+ndeath-1)+j-1)*ncovmodel
                   1961:      j>=i nc + ((i-1)*(nlstate+ndeath-1)+(j-2))*ncovmodel
                   1962:      Computes ln(pij/pii) (lnpijopii), deduces pij/pii by exponentiation,
                   1963:      sums on j different of i to get 1-pii/pii, deduces pii, and then all pij.
                   1964:      Outputs ps[i][j] the probability to be observed in j being in j according to
                   1965:      the values of the covariates cov[nc] and corresponding parameter values x[nc+shiftij]
                   1966:   */
                   1967:   double s1, lnpijopii;
1.126     brouard  1968:   /*double t34;*/
1.164     brouard  1969:   int i,j, nc, ii, jj;
1.126     brouard  1970: 
                   1971:     for(i=1; i<= nlstate; i++){
                   1972:       for(j=1; j<i;j++){
1.138     brouard  1973:        for (nc=1, lnpijopii=0.;nc <=ncovmodel; nc++){
                   1974:          /*lnpijopii += param[i][j][nc]*cov[nc];*/
                   1975:          lnpijopii += x[nc+((i-1)*(nlstate+ndeath-1)+j-1)*ncovmodel]*cov[nc];
                   1976: /*      printf("Int j<i s1=%.17e, lnpijopii=%.17e\n",s1,lnpijopii); */
1.126     brouard  1977:        }
1.138     brouard  1978:        ps[i][j]=lnpijopii; /* In fact ln(pij/pii) */
                   1979: /*     printf("s1=%.17e, lnpijopii=%.17e\n",s1,lnpijopii); */
1.126     brouard  1980:       }
                   1981:       for(j=i+1; j<=nlstate+ndeath;j++){
1.138     brouard  1982:        for (nc=1, lnpijopii=0.;nc <=ncovmodel; nc++){
                   1983:          /*lnpijopii += x[(i-1)*nlstate*ncovmodel+(j-2)*ncovmodel+nc+(i-1)*(ndeath-1)*ncovmodel]*cov[nc];*/
                   1984:          lnpijopii += x[nc + ((i-1)*(nlstate+ndeath-1)+(j-2))*ncovmodel]*cov[nc];
                   1985: /*       printf("Int j>i s1=%.17e, lnpijopii=%.17e %lx %lx\n",s1,lnpijopii,s1,lnpijopii); */
1.126     brouard  1986:        }
1.138     brouard  1987:        ps[i][j]=lnpijopii; /* In fact ln(pij/pii) */
1.126     brouard  1988:       }
                   1989:     }
                   1990:     
                   1991:     for(i=1; i<= nlstate; i++){
                   1992:       s1=0;
1.131     brouard  1993:       for(j=1; j<i; j++){
1.138     brouard  1994:        s1+=exp(ps[i][j]); /* In fact sums pij/pii */
1.131     brouard  1995:        /*printf("debug1 %d %d ps=%lf exp(ps)=%lf s1+=%lf\n",i,j,ps[i][j],exp(ps[i][j]),s1); */
                   1996:       }
                   1997:       for(j=i+1; j<=nlstate+ndeath; j++){
1.138     brouard  1998:        s1+=exp(ps[i][j]); /* In fact sums pij/pii */
1.131     brouard  1999:        /*printf("debug2 %d %d ps=%lf exp(ps)=%lf s1+=%lf\n",i,j,ps[i][j],exp(ps[i][j]),s1); */
                   2000:       }
1.138     brouard  2001:       /* s1= sum_{j<>i} pij/pii=(1-pii)/pii and thus pii is known from s1 */
1.126     brouard  2002:       ps[i][i]=1./(s1+1.);
1.138     brouard  2003:       /* Computing other pijs */
1.126     brouard  2004:       for(j=1; j<i; j++)
                   2005:        ps[i][j]= exp(ps[i][j])*ps[i][i];
                   2006:       for(j=i+1; j<=nlstate+ndeath; j++)
                   2007:        ps[i][j]= exp(ps[i][j])*ps[i][i];
                   2008:       /* ps[i][nlstate+1]=1.-s1- ps[i][i];*/ /* Sum should be 1 */
                   2009:     } /* end i */
                   2010:     
                   2011:     for(ii=nlstate+1; ii<= nlstate+ndeath; ii++){
                   2012:       for(jj=1; jj<= nlstate+ndeath; jj++){
                   2013:        ps[ii][jj]=0;
                   2014:        ps[ii][ii]=1;
                   2015:       }
                   2016:     }
                   2017:     
1.145     brouard  2018:     
                   2019:     /* for(ii=1; ii<= nlstate+ndeath; ii++){ */
                   2020:     /*   for(jj=1; jj<= nlstate+ndeath; jj++){ */
                   2021:     /*         printf(" pmij  ps[%d][%d]=%lf ",ii,jj,ps[ii][jj]); */
                   2022:     /*   } */
                   2023:     /*   printf("\n "); */
                   2024:     /* } */
                   2025:     /* printf("\n ");printf("%lf ",cov[2]);*/
                   2026:     /*
1.126     brouard  2027:       for(i=1; i<= npar; i++) printf("%f ",x[i]);
                   2028:       goto end;*/
                   2029:     return ps;
                   2030: }
                   2031: 
                   2032: /**************** Product of 2 matrices ******************/
                   2033: 
1.145     brouard  2034: double **matprod2(double **out, double **in,int nrl, int nrh, int ncl, int nch, int ncolol, int ncoloh, double **b)
1.126     brouard  2035: {
                   2036:   /* Computes the matrix product of in(1,nrh-nrl+1)(1,nch-ncl+1) times
                   2037:      b(1,nch-ncl+1)(1,ncoloh-ncolol+1) into out(...) */
                   2038:   /* in, b, out are matrice of pointers which should have been initialized 
                   2039:      before: only the contents of out is modified. The function returns
                   2040:      a pointer to pointers identical to out */
1.145     brouard  2041:   int i, j, k;
1.126     brouard  2042:   for(i=nrl; i<= nrh; i++)
1.145     brouard  2043:     for(k=ncolol; k<=ncoloh; k++){
                   2044:       out[i][k]=0.;
                   2045:       for(j=ncl; j<=nch; j++)
                   2046:        out[i][k] +=in[i][j]*b[j][k];
                   2047:     }
1.126     brouard  2048:   return out;
                   2049: }
                   2050: 
                   2051: 
                   2052: /************* Higher Matrix Product ***************/
                   2053: 
                   2054: double ***hpxij(double ***po, int nhstepm, double age, int hstepm, double *x, int nlstate, int stepm, double **oldm, double **savm, int ij )
                   2055: {
                   2056:   /* Computes the transition matrix starting at age 'age' over 
                   2057:      'nhstepm*hstepm*stepm' months (i.e. until
                   2058:      age (in years)  age+nhstepm*hstepm*stepm/12) by multiplying 
                   2059:      nhstepm*hstepm matrices. 
                   2060:      Output is stored in matrix po[i][j][h] for h every 'hstepm' step 
                   2061:      (typically every 2 years instead of every month which is too big 
                   2062:      for the memory).
                   2063:      Model is determined by parameters x and covariates have to be 
                   2064:      included manually here. 
                   2065: 
                   2066:      */
                   2067: 
                   2068:   int i, j, d, h, k;
1.131     brouard  2069:   double **out, cov[NCOVMAX+1];
1.126     brouard  2070:   double **newm;
1.187     brouard  2071:   double agexact;
1.126     brouard  2072: 
                   2073:   /* Hstepm could be zero and should return the unit matrix */
                   2074:   for (i=1;i<=nlstate+ndeath;i++)
                   2075:     for (j=1;j<=nlstate+ndeath;j++){
                   2076:       oldm[i][j]=(i==j ? 1.0 : 0.0);
                   2077:       po[i][j][0]=(i==j ? 1.0 : 0.0);
                   2078:     }
                   2079:   /* Even if hstepm = 1, at least one multiplication by the unit matrix */
                   2080:   for(h=1; h <=nhstepm; h++){
                   2081:     for(d=1; d <=hstepm; d++){
                   2082:       newm=savm;
                   2083:       /* Covariates have to be included here again */
                   2084:       cov[1]=1.;
1.187     brouard  2085:       agexact=age+((h-1)*hstepm + (d-1))*stepm/YEARM;
                   2086:       cov[2]=agexact;
                   2087:       if(nagesqr==1)
                   2088:        cov[3]= agexact*agexact;
1.131     brouard  2089:       for (k=1; k<=cptcovn;k++) 
1.187     brouard  2090:        cov[2+nagesqr+k]=nbcode[Tvar[k]][codtab[ij][Tvar[k]]];
1.186     brouard  2091:       for (k=1; k<=cptcovage;k++) /* Should start at cptcovn+1 */
                   2092:        /* cov[2+Tage[k]]=cov[2+Tage[k]]*cov[2]; */
1.187     brouard  2093:        cov[2+nagesqr+Tage[k]]=nbcode[Tvar[Tage[k]]][codtab[ij][Tvar[Tage[k]]]]*cov[2];
1.145     brouard  2094:       for (k=1; k<=cptcovprod;k++) /* Useless because included in cptcovn */
1.187     brouard  2095:        cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtab[ij][Tvard[k][1]]]*nbcode[Tvard[k][2]][codtab[ij][Tvard[k][2]]];
1.126     brouard  2096: 
                   2097: 
                   2098:       /*printf("hxi cptcov=%d cptcode=%d\n",cptcov,cptcode);*/
                   2099:       /*printf("h=%d d=%d age=%f cov=%f\n",h,d,age,cov[2]);*/
                   2100:       out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, 
                   2101:                   pmij(pmmij,cov,ncovmodel,x,nlstate));
                   2102:       savm=oldm;
                   2103:       oldm=newm;
                   2104:     }
                   2105:     for(i=1; i<=nlstate+ndeath; i++)
                   2106:       for(j=1;j<=nlstate+ndeath;j++) {
                   2107:        po[i][j][h]=newm[i][j];
1.128     brouard  2108:        /*if(h==nhstepm) printf("po[%d][%d][%d]=%f ",i,j,h,po[i][j][h]);*/
1.126     brouard  2109:       }
1.128     brouard  2110:     /*printf("h=%d ",h);*/
1.126     brouard  2111:   } /* end h */
1.128     brouard  2112: /*     printf("\n H=%d \n",h); */
1.126     brouard  2113:   return po;
                   2114: }
                   2115: 
1.162     brouard  2116: #ifdef NLOPT
                   2117:   double  myfunc(unsigned n, const double *p1, double *grad, void *pd){
                   2118:   double fret;
                   2119:   double *xt;
                   2120:   int j;
                   2121:   myfunc_data *d2 = (myfunc_data *) pd;
                   2122: /* xt = (p1-1); */
                   2123:   xt=vector(1,n); 
                   2124:   for (j=1;j<=n;j++)   xt[j]=p1[j-1]; /* xt[1]=p1[0] */
                   2125: 
                   2126:   fret=(d2->function)(xt); /*  p xt[1]@8 is fine */
                   2127:   /* fret=(*func)(xt); /\*  p xt[1]@8 is fine *\/ */
                   2128:   printf("Function = %.12lf ",fret);
                   2129:   for (j=1;j<=n;j++) printf(" %d %.8lf", j, xt[j]); 
                   2130:   printf("\n");
                   2131:  free_vector(xt,1,n);
                   2132:   return fret;
                   2133: }
                   2134: #endif
1.126     brouard  2135: 
                   2136: /*************** log-likelihood *************/
                   2137: double func( double *x)
                   2138: {
                   2139:   int i, ii, j, k, mi, d, kk;
1.131     brouard  2140:   double l, ll[NLSTATEMAX+1], cov[NCOVMAX+1];
1.126     brouard  2141:   double **out;
                   2142:   double sw; /* Sum of weights */
                   2143:   double lli; /* Individual log likelihood */
                   2144:   int s1, s2;
                   2145:   double bbh, survp;
                   2146:   long ipmx;
1.187     brouard  2147:   double agexact;
1.126     brouard  2148:   /*extern weight */
                   2149:   /* We are differentiating ll according to initial status */
                   2150:   /*  for (i=1;i<=npar;i++) printf("%f ", x[i]);*/
                   2151:   /*for(i=1;i<imx;i++) 
                   2152:     printf(" %d\n",s[4][i]);
                   2153:   */
1.162     brouard  2154: 
                   2155:   ++countcallfunc;
                   2156: 
1.126     brouard  2157:   cov[1]=1.;
                   2158: 
                   2159:   for(k=1; k<=nlstate; k++) ll[k]=0.;
                   2160: 
                   2161:   if(mle==1){
                   2162:     for (i=1,ipmx=0, sw=0.; i<=imx; i++){
1.138     brouard  2163:       /* Computes the values of the ncovmodel covariates of the model
                   2164:         depending if the covariates are fixed or variying (age dependent) and stores them in cov[]
                   2165:         Then computes with function pmij which return a matrix p[i][j] giving the elementary probability
                   2166:         to be observed in j being in i according to the model.
                   2167:        */
1.145     brouard  2168:       for (k=1; k<=cptcovn;k++){ /* Simple and product covariates without age* products */
1.187     brouard  2169:          cov[2+nagesqr+k]=covar[Tvar[k]][i];
1.145     brouard  2170:       }
1.137     brouard  2171:       /* In model V2+V1*V4+age*V3+V3*V2 Tvar[1] is V2, Tvar[2=V1*V4] 
1.138     brouard  2172:         is 6, Tvar[3=age*V3] should not be computed because of age Tvar[4=V3*V2] 
1.137     brouard  2173:         has been calculated etc */
1.126     brouard  2174:       for(mi=1; mi<= wav[i]-1; mi++){
                   2175:        for (ii=1;ii<=nlstate+ndeath;ii++)
                   2176:          for (j=1;j<=nlstate+ndeath;j++){
                   2177:            oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   2178:            savm[ii][j]=(ii==j ? 1.0 : 0.0);
                   2179:          }
                   2180:        for(d=0; d<dh[mi][i]; d++){
                   2181:          newm=savm;
1.187     brouard  2182:          agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;
                   2183:          cov[2]=agexact;
                   2184:          if(nagesqr==1)
                   2185:            cov[3]= agexact*agexact;
1.126     brouard  2186:          for (kk=1; kk<=cptcovage;kk++) {
1.187     brouard  2187:            cov[Tage[kk]+2+nagesqr]=covar[Tvar[Tage[kk]]][i]*agexact; /* Tage[kk] gives the data-covariate associated with age */
1.126     brouard  2188:          }
                   2189:          out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
                   2190:                       1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
                   2191:          savm=oldm;
                   2192:          oldm=newm;
                   2193:        } /* end mult */
                   2194:       
                   2195:        /*lli=log(out[s[mw[mi][i]][i]][s[mw[mi+1][i]][i]]);*/ /* Original formula */
                   2196:        /* But now since version 0.9 we anticipate for bias at large stepm.
                   2197:         * If stepm is larger than one month (smallest stepm) and if the exact delay 
                   2198:         * (in months) between two waves is not a multiple of stepm, we rounded to 
                   2199:         * the nearest (and in case of equal distance, to the lowest) interval but now
                   2200:         * we keep into memory the bias bh[mi][i] and also the previous matrix product
                   2201:         * (i.e to dh[mi][i]-1) saved in 'savm'. Then we inter(extra)polate the
                   2202:         * probability in order to take into account the bias as a fraction of the way
                   2203:         * from savm to out if bh is negative or even beyond if bh is positive. bh varies
                   2204:         * -stepm/2 to stepm/2 .
                   2205:         * For stepm=1 the results are the same as for previous versions of Imach.
                   2206:         * For stepm > 1 the results are less biased than in previous versions. 
                   2207:         */
                   2208:        s1=s[mw[mi][i]][i];
                   2209:        s2=s[mw[mi+1][i]][i];
                   2210:        bbh=(double)bh[mi][i]/(double)stepm; 
                   2211:        /* bias bh is positive if real duration
                   2212:         * is higher than the multiple of stepm and negative otherwise.
                   2213:         */
                   2214:        /* lli= (savm[s1][s2]>1.e-8 ?(1.+bbh)*log(out[s1][s2])- bbh*log(savm[s1][s2]):log((1.+bbh)*out[s1][s2]));*/
                   2215:        if( s2 > nlstate){ 
                   2216:          /* i.e. if s2 is a death state and if the date of death is known 
                   2217:             then the contribution to the likelihood is the probability to 
                   2218:             die between last step unit time and current  step unit time, 
                   2219:             which is also equal to probability to die before dh 
                   2220:             minus probability to die before dh-stepm . 
                   2221:             In version up to 0.92 likelihood was computed
                   2222:        as if date of death was unknown. Death was treated as any other
                   2223:        health state: the date of the interview describes the actual state
                   2224:        and not the date of a change in health state. The former idea was
                   2225:        to consider that at each interview the state was recorded
                   2226:        (healthy, disable or death) and IMaCh was corrected; but when we
                   2227:        introduced the exact date of death then we should have modified
                   2228:        the contribution of an exact death to the likelihood. This new
                   2229:        contribution is smaller and very dependent of the step unit
                   2230:        stepm. It is no more the probability to die between last interview
                   2231:        and month of death but the probability to survive from last
                   2232:        interview up to one month before death multiplied by the
                   2233:        probability to die within a month. Thanks to Chris
                   2234:        Jackson for correcting this bug.  Former versions increased
                   2235:        mortality artificially. The bad side is that we add another loop
                   2236:        which slows down the processing. The difference can be up to 10%
                   2237:        lower mortality.
                   2238:          */
1.183     brouard  2239:        /* If, at the beginning of the maximization mostly, the
                   2240:           cumulative probability or probability to be dead is
                   2241:           constant (ie = 1) over time d, the difference is equal to
                   2242:           0.  out[s1][3] = savm[s1][3]: probability, being at state
                   2243:           s1 at precedent wave, to be dead a month before current
                   2244:           wave is equal to probability, being at state s1 at
                   2245:           precedent wave, to be dead at mont of the current
                   2246:           wave. Then the observed probability (that this person died)
                   2247:           is null according to current estimated parameter. In fact,
                   2248:           it should be very low but not zero otherwise the log go to
                   2249:           infinity.
                   2250:        */
                   2251: /* #ifdef INFINITYORIGINAL */
                   2252: /*         lli=log(out[s1][s2] - savm[s1][s2]); */
                   2253: /* #else */
                   2254: /*       if ((out[s1][s2] - savm[s1][s2]) < mytinydouble)  */
                   2255: /*         lli=log(mytinydouble); */
                   2256: /*       else */
                   2257: /*         lli=log(out[s1][s2] - savm[s1][s2]); */
                   2258: /* #endif */
                   2259:            lli=log(out[s1][s2] - savm[s1][s2]);
1.126     brouard  2260: 
                   2261:        } else if  (s2==-2) {
                   2262:          for (j=1,survp=0. ; j<=nlstate; j++) 
                   2263:            survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j];
                   2264:          /*survp += out[s1][j]; */
                   2265:          lli= log(survp);
                   2266:        }
                   2267:        
                   2268:        else if  (s2==-4) { 
                   2269:          for (j=3,survp=0. ; j<=nlstate; j++)  
                   2270:            survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j];
                   2271:          lli= log(survp); 
                   2272:        } 
                   2273: 
                   2274:        else if  (s2==-5) { 
                   2275:          for (j=1,survp=0. ; j<=2; j++)  
                   2276:            survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j];
                   2277:          lli= log(survp); 
                   2278:        } 
                   2279:        
                   2280:        else{
                   2281:          lli= log((1.+bbh)*out[s1][s2]- bbh*savm[s1][s2]); /* linear interpolation */
                   2282:          /*  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 */
                   2283:        } 
                   2284:        /*lli=(1.+bbh)*log(out[s1][s2])- bbh*log(savm[s1][s2]);*/
                   2285:        /*if(lli ==000.0)*/
                   2286:        /*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); */
                   2287:        ipmx +=1;
                   2288:        sw += weight[i];
                   2289:        ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
1.183     brouard  2290:        /* if (lli < log(mytinydouble)){ */
                   2291:        /*   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); */
                   2292:        /*   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]); */
                   2293:        /* } */
1.126     brouard  2294:       } /* end of wave */
                   2295:     } /* end of individual */
                   2296:   }  else if(mle==2){
                   2297:     for (i=1,ipmx=0, sw=0.; i<=imx; i++){
1.187     brouard  2298:       for (k=1; k<=cptcovn;k++) cov[2+nagesqr+k]=covar[Tvar[k]][i];
1.126     brouard  2299:       for(mi=1; mi<= wav[i]-1; mi++){
                   2300:        for (ii=1;ii<=nlstate+ndeath;ii++)
                   2301:          for (j=1;j<=nlstate+ndeath;j++){
                   2302:            oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   2303:            savm[ii][j]=(ii==j ? 1.0 : 0.0);
                   2304:          }
                   2305:        for(d=0; d<=dh[mi][i]; d++){
                   2306:          newm=savm;
1.187     brouard  2307:          agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;
                   2308:          cov[2]=agexact;
                   2309:          if(nagesqr==1)
                   2310:            cov[3]= agexact*agexact;
1.126     brouard  2311:          for (kk=1; kk<=cptcovage;kk++) {
1.187     brouard  2312:            cov[Tage[kk]+2+nagesqr]=covar[Tvar[Tage[kk]]][i]*agexact;
1.126     brouard  2313:          }
                   2314:          out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
                   2315:                       1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
                   2316:          savm=oldm;
                   2317:          oldm=newm;
                   2318:        } /* end mult */
                   2319:       
                   2320:        s1=s[mw[mi][i]][i];
                   2321:        s2=s[mw[mi+1][i]][i];
                   2322:        bbh=(double)bh[mi][i]/(double)stepm; 
                   2323:        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 */
                   2324:        ipmx +=1;
                   2325:        sw += weight[i];
                   2326:        ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
                   2327:       } /* end of wave */
                   2328:     } /* end of individual */
                   2329:   }  else if(mle==3){  /* exponential inter-extrapolation */
                   2330:     for (i=1,ipmx=0, sw=0.; i<=imx; i++){
1.187     brouard  2331:       for (k=1; k<=cptcovn;k++) cov[2+nagesqr+k]=covar[Tvar[k]][i];
1.126     brouard  2332:       for(mi=1; mi<= wav[i]-1; mi++){
                   2333:        for (ii=1;ii<=nlstate+ndeath;ii++)
                   2334:          for (j=1;j<=nlstate+ndeath;j++){
                   2335:            oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   2336:            savm[ii][j]=(ii==j ? 1.0 : 0.0);
                   2337:          }
                   2338:        for(d=0; d<dh[mi][i]; d++){
                   2339:          newm=savm;
1.187     brouard  2340:          agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;
                   2341:          cov[2]=agexact;
                   2342:          if(nagesqr==1)
                   2343:            cov[3]= agexact*agexact;
1.126     brouard  2344:          for (kk=1; kk<=cptcovage;kk++) {
1.187     brouard  2345:            cov[Tage[kk]+2+nagesqr]=covar[Tvar[Tage[kk]]][i]*agexact;
1.126     brouard  2346:          }
                   2347:          out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
                   2348:                       1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
                   2349:          savm=oldm;
                   2350:          oldm=newm;
                   2351:        } /* end mult */
                   2352:       
                   2353:        s1=s[mw[mi][i]][i];
                   2354:        s2=s[mw[mi+1][i]][i];
                   2355:        bbh=(double)bh[mi][i]/(double)stepm; 
                   2356:        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 */
                   2357:        ipmx +=1;
                   2358:        sw += weight[i];
                   2359:        ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
                   2360:       } /* end of wave */
                   2361:     } /* end of individual */
                   2362:   }else if (mle==4){  /* ml=4 no inter-extrapolation */
                   2363:     for (i=1,ipmx=0, sw=0.; i<=imx; i++){
1.187     brouard  2364:       for (k=1; k<=cptcovn;k++) cov[2+nagesqr+k]=covar[Tvar[k]][i];
1.126     brouard  2365:       for(mi=1; mi<= wav[i]-1; mi++){
                   2366:        for (ii=1;ii<=nlstate+ndeath;ii++)
                   2367:          for (j=1;j<=nlstate+ndeath;j++){
                   2368:            oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   2369:            savm[ii][j]=(ii==j ? 1.0 : 0.0);
                   2370:          }
                   2371:        for(d=0; d<dh[mi][i]; d++){
                   2372:          newm=savm;
1.187     brouard  2373:          agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;
                   2374:          cov[2]=agexact;
                   2375:          if(nagesqr==1)
                   2376:            cov[3]= agexact*agexact;
1.126     brouard  2377:          for (kk=1; kk<=cptcovage;kk++) {
1.187     brouard  2378:            cov[Tage[kk]+2+nagesqr]=covar[Tvar[Tage[kk]]][i]*agexact;
1.126     brouard  2379:          }
                   2380:        
                   2381:          out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
                   2382:                       1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
                   2383:          savm=oldm;
                   2384:          oldm=newm;
                   2385:        } /* end mult */
                   2386:       
                   2387:        s1=s[mw[mi][i]][i];
                   2388:        s2=s[mw[mi+1][i]][i];
                   2389:        if( s2 > nlstate){ 
                   2390:          lli=log(out[s1][s2] - savm[s1][s2]);
                   2391:        }else{
                   2392:          lli=log(out[s[mw[mi][i]][i]][s[mw[mi+1][i]][i]]); /* Original formula */
                   2393:        }
                   2394:        ipmx +=1;
                   2395:        sw += weight[i];
                   2396:        ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
                   2397: /*     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]); */
                   2398:       } /* end of wave */
                   2399:     } /* end of individual */
                   2400:   }else{  /* ml=5 no inter-extrapolation no jackson =0.8a */
                   2401:     for (i=1,ipmx=0, sw=0.; i<=imx; i++){
1.187     brouard  2402:       for (k=1; k<=cptcovn;k++) cov[2+nagesqr+k]=covar[Tvar[k]][i];
1.126     brouard  2403:       for(mi=1; mi<= wav[i]-1; mi++){
                   2404:        for (ii=1;ii<=nlstate+ndeath;ii++)
                   2405:          for (j=1;j<=nlstate+ndeath;j++){
                   2406:            oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   2407:            savm[ii][j]=(ii==j ? 1.0 : 0.0);
                   2408:          }
                   2409:        for(d=0; d<dh[mi][i]; d++){
                   2410:          newm=savm;
1.187     brouard  2411:          agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;
                   2412:          cov[2]=agexact;
                   2413:          if(nagesqr==1)
                   2414:            cov[3]= agexact*agexact;
1.126     brouard  2415:          for (kk=1; kk<=cptcovage;kk++) {
1.187     brouard  2416:            cov[Tage[kk]+2+nagesqr]=covar[Tvar[Tage[kk]]][i]*agexact;
1.126     brouard  2417:          }
                   2418:        
                   2419:          out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
                   2420:                       1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
                   2421:          savm=oldm;
                   2422:          oldm=newm;
                   2423:        } /* end mult */
                   2424:       
                   2425:        s1=s[mw[mi][i]][i];
                   2426:        s2=s[mw[mi+1][i]][i];
                   2427:        lli=log(out[s[mw[mi][i]][i]][s[mw[mi+1][i]][i]]); /* Original formula */
                   2428:        ipmx +=1;
                   2429:        sw += weight[i];
                   2430:        ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
                   2431:        /*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]);*/
                   2432:       } /* end of wave */
                   2433:     } /* end of individual */
                   2434:   } /* End of if */
                   2435:   for(k=1,l=0.; k<=nlstate; k++) l += ll[k];
                   2436:   /* printf("l1=%f l2=%f ",ll[1],ll[2]); */
                   2437:   l= l*ipmx/sw; /* To get the same order of magnitude as if weight=1 for every body */
                   2438:   return -l;
                   2439: }
                   2440: 
                   2441: /*************** log-likelihood *************/
                   2442: double funcone( double *x)
                   2443: {
                   2444:   /* Same as likeli but slower because of a lot of printf and if */
                   2445:   int i, ii, j, k, mi, d, kk;
1.131     brouard  2446:   double l, ll[NLSTATEMAX+1], cov[NCOVMAX+1];
1.126     brouard  2447:   double **out;
                   2448:   double lli; /* Individual log likelihood */
                   2449:   double llt;
                   2450:   int s1, s2;
                   2451:   double bbh, survp;
1.187     brouard  2452:   double agexact;
1.126     brouard  2453:   /*extern weight */
                   2454:   /* We are differentiating ll according to initial status */
                   2455:   /*  for (i=1;i<=npar;i++) printf("%f ", x[i]);*/
                   2456:   /*for(i=1;i<imx;i++) 
                   2457:     printf(" %d\n",s[4][i]);
                   2458:   */
                   2459:   cov[1]=1.;
                   2460: 
                   2461:   for(k=1; k<=nlstate; k++) ll[k]=0.;
                   2462: 
                   2463:   for (i=1,ipmx=0, sw=0.; i<=imx; i++){
1.187     brouard  2464:     for (k=1; k<=cptcovn;k++) cov[2+nagesqr+k]=covar[Tvar[k]][i];
1.126     brouard  2465:     for(mi=1; mi<= wav[i]-1; mi++){
                   2466:       for (ii=1;ii<=nlstate+ndeath;ii++)
                   2467:        for (j=1;j<=nlstate+ndeath;j++){
                   2468:          oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   2469:          savm[ii][j]=(ii==j ? 1.0 : 0.0);
                   2470:        }
                   2471:       for(d=0; d<dh[mi][i]; d++){
                   2472:        newm=savm;
1.187     brouard  2473:        agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;
                   2474:        cov[2]=agexact;
                   2475:        if(nagesqr==1)
                   2476:          cov[3]= agexact*agexact;
1.126     brouard  2477:        for (kk=1; kk<=cptcovage;kk++) {
1.187     brouard  2478:          cov[Tage[kk]+2+nagesqr]=covar[Tvar[Tage[kk]]][i]*agexact;
1.126     brouard  2479:        }
1.187     brouard  2480: 
1.145     brouard  2481:        /* savm=pmij(pmmij,cov,ncovmodel,x,nlstate); */
1.126     brouard  2482:        out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
                   2483:                     1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
1.145     brouard  2484:        /* out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath, */
                   2485:        /*           1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate)); */
1.126     brouard  2486:        savm=oldm;
                   2487:        oldm=newm;
                   2488:       } /* end mult */
                   2489:       
                   2490:       s1=s[mw[mi][i]][i];
                   2491:       s2=s[mw[mi+1][i]][i];
                   2492:       bbh=(double)bh[mi][i]/(double)stepm; 
                   2493:       /* bias is positive if real duration
                   2494:        * is higher than the multiple of stepm and negative otherwise.
                   2495:        */
                   2496:       if( s2 > nlstate && (mle <5) ){  /* Jackson */
                   2497:        lli=log(out[s1][s2] - savm[s1][s2]);
                   2498:       } else if  (s2==-2) {
                   2499:        for (j=1,survp=0. ; j<=nlstate; j++) 
                   2500:          survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j];
                   2501:        lli= log(survp);
                   2502:       }else if (mle==1){
                   2503:        lli= log((1.+bbh)*out[s1][s2]- bbh*savm[s1][s2]); /* linear interpolation */
                   2504:       } else if(mle==2){
                   2505:        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 */
                   2506:       } else if(mle==3){  /* exponential inter-extrapolation */
                   2507:        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 */
                   2508:       } else if (mle==4){  /* mle=4 no inter-extrapolation */
                   2509:        lli=log(out[s1][s2]); /* Original formula */
1.136     brouard  2510:       } else{  /* mle=0 back to 1 */
                   2511:        lli= log((1.+bbh)*out[s1][s2]- bbh*savm[s1][s2]); /* linear interpolation */
                   2512:        /*lli=log(out[s1][s2]); */ /* Original formula */
1.126     brouard  2513:       } /* End of if */
                   2514:       ipmx +=1;
                   2515:       sw += weight[i];
                   2516:       ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
1.132     brouard  2517:       /*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  2518:       if(globpr){
1.141     brouard  2519:        fprintf(ficresilk,"%9ld %6d %2d %2d %1d %1d %3d %11.6f %8.4f\
1.126     brouard  2520:  %11.6f %11.6f %11.6f ", \
                   2521:                num[i],i,s1,s2,mi,mw[mi][i],dh[mi][i],exp(lli),weight[i],
                   2522:                2*weight[i]*lli,out[s1][s2],savm[s1][s2]);
                   2523:        for(k=1,llt=0.,l=0.; k<=nlstate; k++){
                   2524:          llt +=ll[k]*gipmx/gsw;
                   2525:          fprintf(ficresilk," %10.6f",-ll[k]*gipmx/gsw);
                   2526:        }
                   2527:        fprintf(ficresilk," %10.6f\n", -llt);
                   2528:       }
                   2529:     } /* end of wave */
                   2530:   } /* end of individual */
                   2531:   for(k=1,l=0.; k<=nlstate; k++) l += ll[k];
                   2532:   /* printf("l1=%f l2=%f ",ll[1],ll[2]); */
                   2533:   l= l*ipmx/sw; /* To get the same order of magnitude as if weight=1 for every body */
                   2534:   if(globpr==0){ /* First time we count the contributions and weights */
                   2535:     gipmx=ipmx;
                   2536:     gsw=sw;
                   2537:   }
                   2538:   return -l;
                   2539: }
                   2540: 
                   2541: 
                   2542: /*************** function likelione ***********/
                   2543: void likelione(FILE *ficres,double p[], int npar, int nlstate, int *globpri, long *ipmx, double *sw, double *fretone, double (*funcone)(double []))
                   2544: {
                   2545:   /* This routine should help understanding what is done with 
                   2546:      the selection of individuals/waves and
                   2547:      to check the exact contribution to the likelihood.
                   2548:      Plotting could be done.
                   2549:    */
                   2550:   int k;
                   2551: 
                   2552:   if(*globpri !=0){ /* Just counts and sums, no printings */
                   2553:     strcpy(fileresilk,"ilk"); 
                   2554:     strcat(fileresilk,fileres);
                   2555:     if((ficresilk=fopen(fileresilk,"w"))==NULL) {
                   2556:       printf("Problem with resultfile: %s\n", fileresilk);
                   2557:       fprintf(ficlog,"Problem with resultfile: %s\n", fileresilk);
                   2558:     }
                   2559:     fprintf(ficresilk, "#individual(line's_record) s1 s2 wave# effective_wave# number_of_matrices_product pij weight -2ln(pij)*weight 0pij_x 0pij_(x-stepm) cumulating_loglikeli_by_health_state(reweighted=-2ll*weightXnumber_of_contribs/sum_of_weights) and_total\n");
                   2560:     fprintf(ficresilk, "#num_i i s1 s2 mi mw dh likeli weight 2wlli out sav ");
                   2561:     /*         i,s1,s2,mi,mw[mi][i],dh[mi][i],exp(lli),weight[i],2*weight[i]*lli,out[s1][s2],savm[s1][s2]); */
                   2562:     for(k=1; k<=nlstate; k++) 
                   2563:       fprintf(ficresilk," -2*gipw/gsw*weight*ll[%d]++",k);
                   2564:     fprintf(ficresilk," -2*gipw/gsw*weight*ll(total)\n");
                   2565:   }
                   2566: 
                   2567:   *fretone=(*funcone)(p);
                   2568:   if(*globpri !=0){
                   2569:     fclose(ficresilk);
                   2570:     fprintf(fichtm,"\n<br>File of contributions to the likelihood: <a href=\"%s\">%s</a><br>\n",subdirf(fileresilk),subdirf(fileresilk));
                   2571:     fflush(fichtm); 
                   2572:   } 
                   2573:   return;
                   2574: }
                   2575: 
                   2576: 
                   2577: /*********** Maximum Likelihood Estimation ***************/
                   2578: 
                   2579: void mlikeli(FILE *ficres,double p[], int npar, int ncovmodel, int nlstate, double ftol, double (*func)(double []))
                   2580: {
1.165     brouard  2581:   int i,j, iter=0;
1.126     brouard  2582:   double **xi;
                   2583:   double fret;
                   2584:   double fretone; /* Only one call to likelihood */
                   2585:   /*  char filerespow[FILENAMELENGTH];*/
1.162     brouard  2586: 
                   2587: #ifdef NLOPT
                   2588:   int creturn;
                   2589:   nlopt_opt opt;
                   2590:   /* double lb[9] = { -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL }; /\* lower bounds *\/ */
                   2591:   double *lb;
                   2592:   double minf; /* the minimum objective value, upon return */
                   2593:   double * p1; /* Shifted parameters from 0 instead of 1 */
                   2594:   myfunc_data dinst, *d = &dinst;
                   2595: #endif
                   2596: 
                   2597: 
1.126     brouard  2598:   xi=matrix(1,npar,1,npar);
                   2599:   for (i=1;i<=npar;i++)
                   2600:     for (j=1;j<=npar;j++)
                   2601:       xi[i][j]=(i==j ? 1.0 : 0.0);
                   2602:   printf("Powell\n");  fprintf(ficlog,"Powell\n");
                   2603:   strcpy(filerespow,"pow"); 
                   2604:   strcat(filerespow,fileres);
                   2605:   if((ficrespow=fopen(filerespow,"w"))==NULL) {
                   2606:     printf("Problem with resultfile: %s\n", filerespow);
                   2607:     fprintf(ficlog,"Problem with resultfile: %s\n", filerespow);
                   2608:   }
                   2609:   fprintf(ficrespow,"# Powell\n# iter -2*LL");
                   2610:   for (i=1;i<=nlstate;i++)
                   2611:     for(j=1;j<=nlstate+ndeath;j++)
                   2612:       if(j!=i)fprintf(ficrespow," p%1d%1d",i,j);
                   2613:   fprintf(ficrespow,"\n");
1.162     brouard  2614: #ifdef POWELL
1.126     brouard  2615:   powell(p,xi,npar,ftol,&iter,&fret,func);
1.162     brouard  2616: #endif
1.126     brouard  2617: 
1.162     brouard  2618: #ifdef NLOPT
                   2619: #ifdef NEWUOA
                   2620:   opt = nlopt_create(NLOPT_LN_NEWUOA,npar);
                   2621: #else
                   2622:   opt = nlopt_create(NLOPT_LN_BOBYQA,npar);
                   2623: #endif
                   2624:   lb=vector(0,npar-1);
                   2625:   for (i=0;i<npar;i++) lb[i]= -HUGE_VAL;
                   2626:   nlopt_set_lower_bounds(opt, lb);
                   2627:   nlopt_set_initial_step1(opt, 0.1);
                   2628:   
                   2629:   p1= (p+1); /*  p *(p+1)@8 and p *(p1)@8 are equal p1[0]=p[1] */
                   2630:   d->function = func;
                   2631:   printf(" Func %.12lf \n",myfunc(npar,p1,NULL,d));
                   2632:   nlopt_set_min_objective(opt, myfunc, d);
                   2633:   nlopt_set_xtol_rel(opt, ftol);
                   2634:   if ((creturn=nlopt_optimize(opt, p1, &minf)) < 0) {
                   2635:     printf("nlopt failed! %d\n",creturn); 
                   2636:   }
                   2637:   else {
                   2638:     printf("found minimum after %d evaluations (NLOPT=%d)\n", countcallfunc ,NLOPT);
                   2639:     printf("found minimum at f(%g,%g) = %0.10g\n", p[0], p[1], minf);
                   2640:     iter=1; /* not equal */
                   2641:   }
                   2642:   nlopt_destroy(opt);
                   2643: #endif
1.126     brouard  2644:   free_matrix(xi,1,npar,1,npar);
                   2645:   fclose(ficrespow);
1.180     brouard  2646:   printf("#Number of iterations & function calls = %d & %d, -2 Log likelihood = %.12f\n",iter, countcallfunc,func(p));
                   2647:   fprintf(ficlog,"#Number of iterations & function calls = %d & %d, -2 Log likelihood = %.12f\n",iter, countcallfunc,func(p));
                   2648:   fprintf(ficres,"#Number of iterations & function calls = %d & %d, -2 Log likelihood = %.12f\n",iter, countcallfunc,func(p));
1.126     brouard  2649: 
                   2650: }
                   2651: 
                   2652: /**** Computes Hessian and covariance matrix ***/
                   2653: void hesscov(double **matcov, double p[], int npar, double delti[], double ftolhess, double (*func)(double []))
                   2654: {
                   2655:   double  **a,**y,*x,pd;
                   2656:   double **hess;
1.164     brouard  2657:   int i, j;
1.126     brouard  2658:   int *indx;
                   2659: 
                   2660:   double hessii(double p[], double delta, int theta, double delti[],double (*func)(double []),int npar);
                   2661:   double hessij(double p[], double delti[], int i, int j,double (*func)(double []),int npar);
                   2662:   void lubksb(double **a, int npar, int *indx, double b[]) ;
                   2663:   void ludcmp(double **a, int npar, int *indx, double *d) ;
                   2664:   double gompertz(double p[]);
                   2665:   hess=matrix(1,npar,1,npar);
                   2666: 
                   2667:   printf("\nCalculation of the hessian matrix. Wait...\n");
                   2668:   fprintf(ficlog,"\nCalculation of the hessian matrix. Wait...\n");
                   2669:   for (i=1;i<=npar;i++){
                   2670:     printf("%d",i);fflush(stdout);
                   2671:     fprintf(ficlog,"%d",i);fflush(ficlog);
                   2672:    
                   2673:      hess[i][i]=hessii(p,ftolhess,i,delti,func,npar);
                   2674:     
                   2675:     /*  printf(" %f ",p[i]);
                   2676:        printf(" %lf %lf %lf",hess[i][i],ftolhess,delti[i]);*/
                   2677:   }
                   2678:   
                   2679:   for (i=1;i<=npar;i++) {
                   2680:     for (j=1;j<=npar;j++)  {
                   2681:       if (j>i) { 
                   2682:        printf(".%d%d",i,j);fflush(stdout);
                   2683:        fprintf(ficlog,".%d%d",i,j);fflush(ficlog);
                   2684:        hess[i][j]=hessij(p,delti,i,j,func,npar);
                   2685:        
                   2686:        hess[j][i]=hess[i][j];    
                   2687:        /*printf(" %lf ",hess[i][j]);*/
                   2688:       }
                   2689:     }
                   2690:   }
                   2691:   printf("\n");
                   2692:   fprintf(ficlog,"\n");
                   2693: 
                   2694:   printf("\nInverting the hessian to get the covariance matrix. Wait...\n");
                   2695:   fprintf(ficlog,"\nInverting the hessian to get the covariance matrix. Wait...\n");
                   2696:   
                   2697:   a=matrix(1,npar,1,npar);
                   2698:   y=matrix(1,npar,1,npar);
                   2699:   x=vector(1,npar);
                   2700:   indx=ivector(1,npar);
                   2701:   for (i=1;i<=npar;i++)
                   2702:     for (j=1;j<=npar;j++) a[i][j]=hess[i][j];
                   2703:   ludcmp(a,npar,indx,&pd);
                   2704: 
                   2705:   for (j=1;j<=npar;j++) {
                   2706:     for (i=1;i<=npar;i++) x[i]=0;
                   2707:     x[j]=1;
                   2708:     lubksb(a,npar,indx,x);
                   2709:     for (i=1;i<=npar;i++){ 
                   2710:       matcov[i][j]=x[i];
                   2711:     }
                   2712:   }
                   2713: 
                   2714:   printf("\n#Hessian matrix#\n");
                   2715:   fprintf(ficlog,"\n#Hessian matrix#\n");
                   2716:   for (i=1;i<=npar;i++) { 
                   2717:     for (j=1;j<=npar;j++) { 
                   2718:       printf("%.3e ",hess[i][j]);
                   2719:       fprintf(ficlog,"%.3e ",hess[i][j]);
                   2720:     }
                   2721:     printf("\n");
                   2722:     fprintf(ficlog,"\n");
                   2723:   }
                   2724: 
                   2725:   /* Recompute Inverse */
                   2726:   for (i=1;i<=npar;i++)
                   2727:     for (j=1;j<=npar;j++) a[i][j]=matcov[i][j];
                   2728:   ludcmp(a,npar,indx,&pd);
                   2729: 
                   2730:   /*  printf("\n#Hessian matrix recomputed#\n");
                   2731: 
                   2732:   for (j=1;j<=npar;j++) {
                   2733:     for (i=1;i<=npar;i++) x[i]=0;
                   2734:     x[j]=1;
                   2735:     lubksb(a,npar,indx,x);
                   2736:     for (i=1;i<=npar;i++){ 
                   2737:       y[i][j]=x[i];
                   2738:       printf("%.3e ",y[i][j]);
                   2739:       fprintf(ficlog,"%.3e ",y[i][j]);
                   2740:     }
                   2741:     printf("\n");
                   2742:     fprintf(ficlog,"\n");
                   2743:   }
                   2744:   */
                   2745: 
                   2746:   free_matrix(a,1,npar,1,npar);
                   2747:   free_matrix(y,1,npar,1,npar);
                   2748:   free_vector(x,1,npar);
                   2749:   free_ivector(indx,1,npar);
                   2750:   free_matrix(hess,1,npar,1,npar);
                   2751: 
                   2752: 
                   2753: }
                   2754: 
                   2755: /*************** hessian matrix ****************/
                   2756: double hessii(double x[], double delta, int theta, double delti[], double (*func)(double []), int npar)
                   2757: {
                   2758:   int i;
                   2759:   int l=1, lmax=20;
                   2760:   double k1,k2;
1.132     brouard  2761:   double p2[MAXPARM+1]; /* identical to x */
1.126     brouard  2762:   double res;
                   2763:   double delt=0.0001, delts, nkhi=10.,nkhif=1., khi=1.e-4;
                   2764:   double fx;
                   2765:   int k=0,kmax=10;
                   2766:   double l1;
                   2767: 
                   2768:   fx=func(x);
                   2769:   for (i=1;i<=npar;i++) p2[i]=x[i];
1.145     brouard  2770:   for(l=0 ; l <=lmax; l++){  /* Enlarging the zone around the Maximum */
1.126     brouard  2771:     l1=pow(10,l);
                   2772:     delts=delt;
                   2773:     for(k=1 ; k <kmax; k=k+1){
                   2774:       delt = delta*(l1*k);
                   2775:       p2[theta]=x[theta] +delt;
1.145     brouard  2776:       k1=func(p2)-fx;   /* Might be negative if too close to the theoretical maximum */
1.126     brouard  2777:       p2[theta]=x[theta]-delt;
                   2778:       k2=func(p2)-fx;
                   2779:       /*res= (k1-2.0*fx+k2)/delt/delt; */
                   2780:       res= (k1+k2)/delt/delt/2.; /* Divided by because L and not 2*L */
                   2781:       
1.132     brouard  2782: #ifdef DEBUGHESS
1.126     brouard  2783:       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);
                   2784:       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);
                   2785: #endif
                   2786:       /*if(fabs(k1-2.0*fx+k2) <1.e-13){ */
                   2787:       if((k1 <khi/nkhi/2.) || (k2 <khi/nkhi/2.)){
                   2788:        k=kmax;
                   2789:       }
                   2790:       else if((k1 >khi/nkhif) || (k2 >khi/nkhif)){ /* Keeps lastvalue before 3.84/2 KHI2 5% 1d.f. */
1.164     brouard  2791:        k=kmax; l=lmax*10;
1.126     brouard  2792:       }
                   2793:       else if((k1 >khi/nkhi) || (k2 >khi/nkhi)){ 
                   2794:        delts=delt;
                   2795:       }
                   2796:     }
                   2797:   }
                   2798:   delti[theta]=delts;
                   2799:   return res; 
                   2800:   
                   2801: }
                   2802: 
                   2803: double hessij( double x[], double delti[], int thetai,int thetaj,double (*func)(double []),int npar)
                   2804: {
                   2805:   int i;
1.164     brouard  2806:   int l=1, lmax=20;
1.126     brouard  2807:   double k1,k2,k3,k4,res,fx;
1.132     brouard  2808:   double p2[MAXPARM+1];
1.126     brouard  2809:   int k;
                   2810: 
                   2811:   fx=func(x);
                   2812:   for (k=1; k<=2; k++) {
                   2813:     for (i=1;i<=npar;i++) p2[i]=x[i];
                   2814:     p2[thetai]=x[thetai]+delti[thetai]/k;
                   2815:     p2[thetaj]=x[thetaj]+delti[thetaj]/k;
                   2816:     k1=func(p2)-fx;
                   2817:   
                   2818:     p2[thetai]=x[thetai]+delti[thetai]/k;
                   2819:     p2[thetaj]=x[thetaj]-delti[thetaj]/k;
                   2820:     k2=func(p2)-fx;
                   2821:   
                   2822:     p2[thetai]=x[thetai]-delti[thetai]/k;
                   2823:     p2[thetaj]=x[thetaj]+delti[thetaj]/k;
                   2824:     k3=func(p2)-fx;
                   2825:   
                   2826:     p2[thetai]=x[thetai]-delti[thetai]/k;
                   2827:     p2[thetaj]=x[thetaj]-delti[thetaj]/k;
                   2828:     k4=func(p2)-fx;
                   2829:     res=(k1-k2-k3+k4)/4.0/delti[thetai]*k/delti[thetaj]*k/2.; /* Because of L not 2*L */
                   2830: #ifdef DEBUG
                   2831:     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);
                   2832:     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);
                   2833: #endif
                   2834:   }
                   2835:   return res;
                   2836: }
                   2837: 
                   2838: /************** Inverse of matrix **************/
                   2839: void ludcmp(double **a, int n, int *indx, double *d) 
                   2840: { 
                   2841:   int i,imax,j,k; 
                   2842:   double big,dum,sum,temp; 
                   2843:   double *vv; 
                   2844:  
                   2845:   vv=vector(1,n); 
                   2846:   *d=1.0; 
                   2847:   for (i=1;i<=n;i++) { 
                   2848:     big=0.0; 
                   2849:     for (j=1;j<=n;j++) 
                   2850:       if ((temp=fabs(a[i][j])) > big) big=temp; 
                   2851:     if (big == 0.0) nrerror("Singular matrix in routine ludcmp"); 
                   2852:     vv[i]=1.0/big; 
                   2853:   } 
                   2854:   for (j=1;j<=n;j++) { 
                   2855:     for (i=1;i<j;i++) { 
                   2856:       sum=a[i][j]; 
                   2857:       for (k=1;k<i;k++) sum -= a[i][k]*a[k][j]; 
                   2858:       a[i][j]=sum; 
                   2859:     } 
                   2860:     big=0.0; 
                   2861:     for (i=j;i<=n;i++) { 
                   2862:       sum=a[i][j]; 
                   2863:       for (k=1;k<j;k++) 
                   2864:        sum -= a[i][k]*a[k][j]; 
                   2865:       a[i][j]=sum; 
                   2866:       if ( (dum=vv[i]*fabs(sum)) >= big) { 
                   2867:        big=dum; 
                   2868:        imax=i; 
                   2869:       } 
                   2870:     } 
                   2871:     if (j != imax) { 
                   2872:       for (k=1;k<=n;k++) { 
                   2873:        dum=a[imax][k]; 
                   2874:        a[imax][k]=a[j][k]; 
                   2875:        a[j][k]=dum; 
                   2876:       } 
                   2877:       *d = -(*d); 
                   2878:       vv[imax]=vv[j]; 
                   2879:     } 
                   2880:     indx[j]=imax; 
                   2881:     if (a[j][j] == 0.0) a[j][j]=TINY; 
                   2882:     if (j != n) { 
                   2883:       dum=1.0/(a[j][j]); 
                   2884:       for (i=j+1;i<=n;i++) a[i][j] *= dum; 
                   2885:     } 
                   2886:   } 
                   2887:   free_vector(vv,1,n);  /* Doesn't work */
                   2888: ;
                   2889: } 
                   2890: 
                   2891: void lubksb(double **a, int n, int *indx, double b[]) 
                   2892: { 
                   2893:   int i,ii=0,ip,j; 
                   2894:   double sum; 
                   2895:  
                   2896:   for (i=1;i<=n;i++) { 
                   2897:     ip=indx[i]; 
                   2898:     sum=b[ip]; 
                   2899:     b[ip]=b[i]; 
                   2900:     if (ii) 
                   2901:       for (j=ii;j<=i-1;j++) sum -= a[i][j]*b[j]; 
                   2902:     else if (sum) ii=i; 
                   2903:     b[i]=sum; 
                   2904:   } 
                   2905:   for (i=n;i>=1;i--) { 
                   2906:     sum=b[i]; 
                   2907:     for (j=i+1;j<=n;j++) sum -= a[i][j]*b[j]; 
                   2908:     b[i]=sum/a[i][i]; 
                   2909:   } 
                   2910: } 
                   2911: 
                   2912: void pstamp(FILE *fichier)
                   2913: {
1.196     brouard  2914:   fprintf(fichier,"# %s.%s\n#IMaCh version %s, %s\n#%s\n# %s", optionfilefiname,optionfilext,version,copyright, fullversion, strstart);
1.126     brouard  2915: }
                   2916: 
                   2917: /************ Frequencies ********************/
                   2918: 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[])
                   2919: {  /* Some frequencies */
                   2920:   
1.164     brouard  2921:   int i, m, jk, j1, bool, z1,j;
1.126     brouard  2922:   int first;
                   2923:   double ***freq; /* Frequencies */
                   2924:   double *pp, **prop;
                   2925:   double pos,posprop, k2, dateintsum=0,k2cpt=0;
                   2926:   char fileresp[FILENAMELENGTH];
                   2927:   
                   2928:   pp=vector(1,nlstate);
                   2929:   prop=matrix(1,nlstate,iagemin,iagemax+3);
                   2930:   strcpy(fileresp,"p");
                   2931:   strcat(fileresp,fileres);
                   2932:   if((ficresp=fopen(fileresp,"w"))==NULL) {
                   2933:     printf("Problem with prevalence resultfile: %s\n", fileresp);
                   2934:     fprintf(ficlog,"Problem with prevalence resultfile: %s\n", fileresp);
                   2935:     exit(0);
                   2936:   }
                   2937:   freq= ma3x(-5,nlstate+ndeath,-5,nlstate+ndeath,iagemin,iagemax+3);
                   2938:   j1=0;
                   2939:   
                   2940:   j=cptcoveff;
                   2941:   if (cptcovn<1) {j=1;ncodemax[1]=1;}
                   2942: 
                   2943:   first=1;
                   2944: 
1.169     brouard  2945:   /* for(k1=1; k1<=j ; k1++){ */  /* Loop on covariates */
                   2946:   /*  for(i1=1; i1<=ncodemax[k1];i1++){ */ /* Now it is 2 */
                   2947:   /*    j1++; */
1.145     brouard  2948:   for (j1 = 1; j1 <= (int) pow(2,cptcoveff); j1++){
1.126     brouard  2949:       /*printf("cptcoveff=%d Tvaraff=%d", cptcoveff,Tvaraff[1]);
                   2950:        scanf("%d", i);*/
                   2951:       for (i=-5; i<=nlstate+ndeath; i++)  
                   2952:        for (jk=-5; jk<=nlstate+ndeath; jk++)  
                   2953:          for(m=iagemin; m <= iagemax+3; m++)
                   2954:            freq[i][jk][m]=0;
1.143     brouard  2955:       
                   2956:       for (i=1; i<=nlstate; i++)  
                   2957:        for(m=iagemin; m <= iagemax+3; m++)
                   2958:          prop[i][m]=0;
1.126     brouard  2959:       
                   2960:       dateintsum=0;
                   2961:       k2cpt=0;
                   2962:       for (i=1; i<=imx; i++) {
                   2963:        bool=1;
1.144     brouard  2964:        if  (cptcovn>0) { /* Filter is here: Must be looked at for model=V1+V2+V3+V4 */
                   2965:          for (z1=1; z1<=cptcoveff; z1++)       
                   2966:             if (covar[Tvaraff[z1]][i]!= nbcode[Tvaraff[z1]][codtab[j1][z1]]){
1.145     brouard  2967:                 /* Tests if the value of each of the covariates of i is equal to filter j1 */
1.144     brouard  2968:               bool=0;
1.145     brouard  2969:               /* printf("bool=%d i=%d, z1=%d, Tvaraff[%d]=%d, covar[Tvarff][%d]=%2f, codtab[%d][%d]=%d, nbcode[Tvaraff][codtab[%d][%d]=%d, j1=%d\n", 
                   2970:                 bool,i,z1, z1, Tvaraff[z1],i,covar[Tvaraff[z1]][i],j1,z1,codtab[j1][z1],
                   2971:                 j1,z1,nbcode[Tvaraff[z1]][codtab[j1][z1]],j1);*/
1.144     brouard  2972:               /* For j1=7 in V1+V2+V3+V4 = 0 1 1 0 and codtab[7][3]=1 and nbcde[3][?]=1*/
                   2973:             } 
1.126     brouard  2974:        }
1.144     brouard  2975:  
1.126     brouard  2976:        if (bool==1){
                   2977:          for(m=firstpass; m<=lastpass; m++){
                   2978:            k2=anint[m][i]+(mint[m][i]/12.);
                   2979:            /*if ((k2>=dateprev1) && (k2<=dateprev2)) {*/
                   2980:              if(agev[m][i]==0) agev[m][i]=iagemax+1;
                   2981:              if(agev[m][i]==1) agev[m][i]=iagemax+2;
                   2982:              if (s[m][i]>0 && s[m][i]<=nlstate) prop[s[m][i]][(int)agev[m][i]] += weight[i];
                   2983:              if (m<lastpass) {
                   2984:                freq[s[m][i]][s[m+1][i]][(int)agev[m][i]] += weight[i];
                   2985:                freq[s[m][i]][s[m+1][i]][iagemax+3] += weight[i];
                   2986:              }
                   2987:              
                   2988:              if ((agev[m][i]>1) && (agev[m][i]< (iagemax+3))) {
                   2989:                dateintsum=dateintsum+k2;
                   2990:                k2cpt++;
                   2991:              }
                   2992:              /*}*/
                   2993:          }
                   2994:        }
1.145     brouard  2995:       } /* end i */
1.126     brouard  2996:        
                   2997:       /*      fprintf(ficresp, "#Count between %.lf/%.lf/%.lf and %.lf/%.lf/%.lf\n",jprev1, mprev1,anprev1,jprev2, mprev2,anprev2);*/
                   2998:       pstamp(ficresp);
                   2999:       if  (cptcovn>0) {
                   3000:        fprintf(ficresp, "\n#********** Variable "); 
                   3001:        for (z1=1; z1<=cptcoveff; z1++) fprintf(ficresp, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtab[j1][z1]]);
                   3002:        fprintf(ficresp, "**********\n#");
1.143     brouard  3003:        fprintf(ficlog, "\n#********** Variable "); 
                   3004:        for (z1=1; z1<=cptcoveff; z1++) fprintf(ficlog, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtab[j1][z1]]);
                   3005:        fprintf(ficlog, "**********\n#");
1.126     brouard  3006:       }
                   3007:       for(i=1; i<=nlstate;i++) 
                   3008:        fprintf(ficresp, " Age Prev(%d) N(%d) N",i,i);
                   3009:       fprintf(ficresp, "\n");
                   3010:       
                   3011:       for(i=iagemin; i <= iagemax+3; i++){
                   3012:        if(i==iagemax+3){
                   3013:          fprintf(ficlog,"Total");
                   3014:        }else{
                   3015:          if(first==1){
                   3016:            first=0;
                   3017:            printf("See log file for details...\n");
                   3018:          }
                   3019:          fprintf(ficlog,"Age %d", i);
                   3020:        }
                   3021:        for(jk=1; jk <=nlstate ; jk++){
                   3022:          for(m=-1, pp[jk]=0; m <=nlstate+ndeath ; m++)
                   3023:            pp[jk] += freq[jk][m][i]; 
                   3024:        }
                   3025:        for(jk=1; jk <=nlstate ; jk++){
                   3026:          for(m=-1, pos=0; m <=0 ; m++)
                   3027:            pos += freq[jk][m][i];
                   3028:          if(pp[jk]>=1.e-10){
                   3029:            if(first==1){
1.132     brouard  3030:              printf(" %d.=%.0f loss[%d]=%.1f%%",jk,pp[jk],jk,100*pos/pp[jk]);
1.126     brouard  3031:            }
                   3032:            fprintf(ficlog," %d.=%.0f loss[%d]=%.1f%%",jk,pp[jk],jk,100*pos/pp[jk]);
                   3033:          }else{
                   3034:            if(first==1)
                   3035:              printf(" %d.=%.0f loss[%d]=NaNQ%%",jk,pp[jk],jk);
                   3036:            fprintf(ficlog," %d.=%.0f loss[%d]=NaNQ%%",jk,pp[jk],jk);
                   3037:          }
                   3038:        }
                   3039: 
                   3040:        for(jk=1; jk <=nlstate ; jk++){
                   3041:          for(m=0, pp[jk]=0; m <=nlstate+ndeath; m++)
                   3042:            pp[jk] += freq[jk][m][i];
                   3043:        }       
                   3044:        for(jk=1,pos=0,posprop=0; jk <=nlstate ; jk++){
                   3045:          pos += pp[jk];
                   3046:          posprop += prop[jk][i];
                   3047:        }
                   3048:        for(jk=1; jk <=nlstate ; jk++){
                   3049:          if(pos>=1.e-5){
                   3050:            if(first==1)
                   3051:              printf(" %d.=%.0f prev[%d]=%.1f%%",jk,pp[jk],jk,100*pp[jk]/pos);
                   3052:            fprintf(ficlog," %d.=%.0f prev[%d]=%.1f%%",jk,pp[jk],jk,100*pp[jk]/pos);
                   3053:          }else{
                   3054:            if(first==1)
                   3055:              printf(" %d.=%.0f prev[%d]=NaNQ%%",jk,pp[jk],jk);
                   3056:            fprintf(ficlog," %d.=%.0f prev[%d]=NaNQ%%",jk,pp[jk],jk);
                   3057:          }
                   3058:          if( i <= iagemax){
                   3059:            if(pos>=1.e-5){
                   3060:              fprintf(ficresp," %d %.5f %.0f %.0f",i,prop[jk][i]/posprop, prop[jk][i],posprop);
                   3061:              /*probs[i][jk][j1]= pp[jk]/pos;*/
                   3062:              /*printf("\ni=%d jk=%d j1=%d %.5f %.0f %.0f %f",i,jk,j1,pp[jk]/pos, pp[jk],pos,probs[i][jk][j1]);*/
                   3063:            }
                   3064:            else
                   3065:              fprintf(ficresp," %d NaNq %.0f %.0f",i,prop[jk][i],posprop);
                   3066:          }
                   3067:        }
                   3068:        
                   3069:        for(jk=-1; jk <=nlstate+ndeath; jk++)
                   3070:          for(m=-1; m <=nlstate+ndeath; m++)
                   3071:            if(freq[jk][m][i] !=0 ) {
                   3072:            if(first==1)
                   3073:              printf(" %d%d=%.0f",jk,m,freq[jk][m][i]);
                   3074:              fprintf(ficlog," %d%d=%.0f",jk,m,freq[jk][m][i]);
                   3075:            }
                   3076:        if(i <= iagemax)
                   3077:          fprintf(ficresp,"\n");
                   3078:        if(first==1)
                   3079:          printf("Others in log...\n");
                   3080:        fprintf(ficlog,"\n");
                   3081:       }
1.145     brouard  3082:       /*}*/
1.126     brouard  3083:   }
                   3084:   dateintmean=dateintsum/k2cpt; 
                   3085:  
                   3086:   fclose(ficresp);
                   3087:   free_ma3x(freq,-5,nlstate+ndeath,-5,nlstate+ndeath, iagemin, iagemax+3);
                   3088:   free_vector(pp,1,nlstate);
                   3089:   free_matrix(prop,1,nlstate,iagemin, iagemax+3);
                   3090:   /* End of Freq */
                   3091: }
                   3092: 
                   3093: /************ Prevalence ********************/
                   3094: 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)
                   3095: {  
                   3096:   /* Compute observed prevalence between dateprev1 and dateprev2 by counting the number of people
                   3097:      in each health status at the date of interview (if between dateprev1 and dateprev2).
                   3098:      We still use firstpass and lastpass as another selection.
                   3099:   */
                   3100:  
1.164     brouard  3101:   int i, m, jk, j1, bool, z1,j;
                   3102: 
                   3103:   double **prop;
                   3104:   double posprop; 
1.126     brouard  3105:   double  y2; /* in fractional years */
                   3106:   int iagemin, iagemax;
1.145     brouard  3107:   int first; /** to stop verbosity which is redirected to log file */
1.126     brouard  3108: 
                   3109:   iagemin= (int) agemin;
                   3110:   iagemax= (int) agemax;
                   3111:   /*pp=vector(1,nlstate);*/
                   3112:   prop=matrix(1,nlstate,iagemin,iagemax+3); 
                   3113:   /*  freq=ma3x(-1,nlstate+ndeath,-1,nlstate+ndeath,iagemin,iagemax+3);*/
                   3114:   j1=0;
                   3115:   
1.145     brouard  3116:   /*j=cptcoveff;*/
1.126     brouard  3117:   if (cptcovn<1) {j=1;ncodemax[1]=1;}
                   3118:   
1.145     brouard  3119:   first=1;
                   3120:   for(j1=1; j1<= (int) pow(2,cptcoveff);j1++){
                   3121:     /*for(i1=1; i1<=ncodemax[k1];i1++){
                   3122:       j1++;*/
1.126     brouard  3123:       
                   3124:       for (i=1; i<=nlstate; i++)  
                   3125:        for(m=iagemin; m <= iagemax+3; m++)
                   3126:          prop[i][m]=0.0;
                   3127:      
                   3128:       for (i=1; i<=imx; i++) { /* Each individual */
                   3129:        bool=1;
                   3130:        if  (cptcovn>0) {
                   3131:          for (z1=1; z1<=cptcoveff; z1++) 
                   3132:            if (covar[Tvaraff[z1]][i]!= nbcode[Tvaraff[z1]][codtab[j1][z1]]) 
                   3133:              bool=0;
                   3134:        } 
                   3135:        if (bool==1) { 
                   3136:          for(m=firstpass; m<=lastpass; m++){/* Other selection (we can limit to certain interviews*/
                   3137:            y2=anint[m][i]+(mint[m][i]/12.); /* Fractional date in year */
                   3138:            if ((y2>=dateprev1) && (y2<=dateprev2)) { /* Here is the main selection (fractional years) */
                   3139:              if(agev[m][i]==0) agev[m][i]=iagemax+1;
                   3140:              if(agev[m][i]==1) agev[m][i]=iagemax+2;
                   3141:              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); 
                   3142:              if (s[m][i]>0 && s[m][i]<=nlstate) { 
                   3143:                /*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]]);*/
                   3144:                prop[s[m][i]][(int)agev[m][i]] += weight[i];
                   3145:                prop[s[m][i]][iagemax+3] += weight[i]; 
                   3146:              } 
                   3147:            }
                   3148:          } /* end selection of waves */
                   3149:        }
                   3150:       }
                   3151:       for(i=iagemin; i <= iagemax+3; i++){  
                   3152:        for(jk=1,posprop=0; jk <=nlstate ; jk++) { 
                   3153:          posprop += prop[jk][i]; 
                   3154:        } 
1.145     brouard  3155:        
1.126     brouard  3156:        for(jk=1; jk <=nlstate ; jk++){     
                   3157:          if( i <=  iagemax){ 
                   3158:            if(posprop>=1.e-5){ 
                   3159:              probs[i][jk][j1]= prop[jk][i]/posprop;
1.145     brouard  3160:            } else{
                   3161:              if(first==1){
                   3162:                first=0;
                   3163:                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]);
                   3164:              }
                   3165:            }
1.126     brouard  3166:          } 
                   3167:        }/* end jk */ 
                   3168:       }/* end i */ 
1.145     brouard  3169:     /*} *//* end i1 */
                   3170:   } /* end j1 */
1.126     brouard  3171:   
                   3172:   /*  free_ma3x(freq,-1,nlstate+ndeath,-1,nlstate+ndeath, iagemin, iagemax+3);*/
                   3173:   /*free_vector(pp,1,nlstate);*/
                   3174:   free_matrix(prop,1,nlstate, iagemin,iagemax+3);
                   3175: }  /* End of prevalence */
                   3176: 
                   3177: /************* Waves Concatenation ***************/
                   3178: 
                   3179: 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)
                   3180: {
                   3181:   /* Concatenates waves: wav[i] is the number of effective (useful waves) of individual i.
                   3182:      Death is a valid wave (if date is known).
                   3183:      mw[mi][i] is the mi (mi=1 to wav[i])  effective wave of individual i
                   3184:      dh[m][i] or dh[mw[mi][i]][i] is the delay between two effective waves m=mw[mi][i]
                   3185:      and mw[mi+1][i]. dh depends on stepm.
                   3186:      */
                   3187: 
                   3188:   int i, mi, m;
                   3189:   /* int j, k=0,jk, ju, jl,jmin=1e+5, jmax=-1;
                   3190:      double sum=0., jmean=0.;*/
                   3191:   int first;
                   3192:   int j, k=0,jk, ju, jl;
                   3193:   double sum=0.;
                   3194:   first=0;
1.164     brouard  3195:   jmin=100000;
1.126     brouard  3196:   jmax=-1;
                   3197:   jmean=0.;
                   3198:   for(i=1; i<=imx; i++){
                   3199:     mi=0;
                   3200:     m=firstpass;
                   3201:     while(s[m][i] <= nlstate){
                   3202:       if(s[m][i]>=1 || s[m][i]==-2 || s[m][i]==-4 || s[m][i]==-5)
                   3203:        mw[++mi][i]=m;
                   3204:       if(m >=lastpass)
                   3205:        break;
                   3206:       else
                   3207:        m++;
                   3208:     }/* end while */
                   3209:     if (s[m][i] > nlstate){
                   3210:       mi++;    /* Death is another wave */
                   3211:       /* if(mi==0)  never been interviewed correctly before death */
                   3212:         /* Only death is a correct wave */
                   3213:       mw[mi][i]=m;
                   3214:     }
                   3215: 
                   3216:     wav[i]=mi;
                   3217:     if(mi==0){
                   3218:       nbwarn++;
                   3219:       if(first==0){
                   3220:        printf("Warning! No valid information for individual %ld line=%d (skipped) and may be others, see log file\n",num[i],i);
                   3221:        first=1;
                   3222:       }
                   3223:       if(first==1){
                   3224:        fprintf(ficlog,"Warning! No valid information for individual %ld line=%d (skipped)\n",num[i],i);
                   3225:       }
                   3226:     } /* end mi==0 */
                   3227:   } /* End individuals */
                   3228: 
                   3229:   for(i=1; i<=imx; i++){
                   3230:     for(mi=1; mi<wav[i];mi++){
                   3231:       if (stepm <=0)
                   3232:        dh[mi][i]=1;
                   3233:       else{
                   3234:        if (s[mw[mi+1][i]][i] > nlstate) { /* A death */
                   3235:          if (agedc[i] < 2*AGESUP) {
                   3236:            j= rint(agedc[i]*12-agev[mw[mi][i]][i]*12); 
                   3237:            if(j==0) j=1;  /* Survives at least one month after exam */
                   3238:            else if(j<0){
                   3239:              nberr++;
                   3240:              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]);
                   3241:              j=1; /* Temporary Dangerous patch */
                   3242:              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);
                   3243:              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]);
                   3244:              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);
                   3245:            }
                   3246:            k=k+1;
                   3247:            if (j >= jmax){
                   3248:              jmax=j;
                   3249:              ijmax=i;
                   3250:            }
                   3251:            if (j <= jmin){
                   3252:              jmin=j;
                   3253:              ijmin=i;
                   3254:            }
                   3255:            sum=sum+j;
                   3256:            /*if (j<0) printf("j=%d num=%d \n",j,i);*/
                   3257:            /*    printf("%d %d %d %d\n", s[mw[mi][i]][i] ,s[mw[mi+1][i]][i],j,i);*/
                   3258:          }
                   3259:        }
                   3260:        else{
                   3261:          j= rint( (agev[mw[mi+1][i]][i]*12 - agev[mw[mi][i]][i]*12));
                   3262: /*       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]); */
                   3263: 
                   3264:          k=k+1;
                   3265:          if (j >= jmax) {
                   3266:            jmax=j;
                   3267:            ijmax=i;
                   3268:          }
                   3269:          else if (j <= jmin){
                   3270:            jmin=j;
                   3271:            ijmin=i;
                   3272:          }
                   3273:          /*        if (j<10) printf("j=%d jmin=%d num=%d ",j,jmin,i); */
                   3274:          /*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]);*/
                   3275:          if(j<0){
                   3276:            nberr++;
                   3277:            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]);
                   3278:            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]);
                   3279:          }
                   3280:          sum=sum+j;
                   3281:        }
                   3282:        jk= j/stepm;
                   3283:        jl= j -jk*stepm;
                   3284:        ju= j -(jk+1)*stepm;
                   3285:        if(mle <=1){ /* only if we use a the linear-interpoloation pseudo-likelihood */
                   3286:          if(jl==0){
                   3287:            dh[mi][i]=jk;
                   3288:            bh[mi][i]=0;
                   3289:          }else{ /* We want a negative bias in order to only have interpolation ie
1.136     brouard  3290:                  * to avoid the price of an extra matrix product in likelihood */
1.126     brouard  3291:            dh[mi][i]=jk+1;
                   3292:            bh[mi][i]=ju;
                   3293:          }
                   3294:        }else{
                   3295:          if(jl <= -ju){
                   3296:            dh[mi][i]=jk;
                   3297:            bh[mi][i]=jl;       /* bias is positive if real duration
                   3298:                                 * is higher than the multiple of stepm and negative otherwise.
                   3299:                                 */
                   3300:          }
                   3301:          else{
                   3302:            dh[mi][i]=jk+1;
                   3303:            bh[mi][i]=ju;
                   3304:          }
                   3305:          if(dh[mi][i]==0){
                   3306:            dh[mi][i]=1; /* At least one step */
                   3307:            bh[mi][i]=ju; /* At least one step */
                   3308:            /*  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);*/
                   3309:          }
                   3310:        } /* end if mle */
                   3311:       }
                   3312:     } /* end wave */
                   3313:   }
                   3314:   jmean=sum/k;
                   3315:   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  3316:   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  3317:  }
                   3318: 
                   3319: /*********** Tricode ****************************/
1.145     brouard  3320: void tricode(int *Tvar, int **nbcode, int imx, int *Ndum)
1.126     brouard  3321: {
1.144     brouard  3322:   /**< Uses cptcovn+2*cptcovprod as the number of covariates */
                   3323:   /*     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  3324:    * Boring subroutine which should only output nbcode[Tvar[j]][k]
1.145     brouard  3325:    * Tvar[5] in V2+V1+V3*age+V2*V4 is 2 (V2)
1.169     brouard  3326:    * nbcode[Tvar[j]][1]= 
1.144     brouard  3327:   */
1.130     brouard  3328: 
1.145     brouard  3329:   int ij=1, k=0, j=0, i=0, maxncov=NCOVMAX;
1.136     brouard  3330:   int modmaxcovj=0; /* Modality max of covariates j */
1.145     brouard  3331:   int cptcode=0; /* Modality max of covariates j */
                   3332:   int modmincovj=0; /* Modality min of covariates j */
                   3333: 
                   3334: 
1.126     brouard  3335:   cptcoveff=0; 
                   3336:  
1.144     brouard  3337:   for (k=1; k <= maxncov; k++) ncodemax[k]=0; /* Horrible constant again replaced by NCOVMAX */
1.126     brouard  3338: 
1.145     brouard  3339:   /* Loop on covariates without age and products */
1.186     brouard  3340:   for (j=1; j<=(cptcovs); j++) { /* From model V1 + V2*age+ V3 + V3*V4 keeps V1 + V3 = 2 only */
1.192     brouard  3341:     for (k=-1; k < maxncov; k++) Ndum[k]=0;
1.186     brouard  3342:     for (i=1; i<=imx; i++) { /* Loop on individuals: reads the data file to get the maximum value of the 
1.136     brouard  3343:                               modality of this covariate Vj*/ 
1.145     brouard  3344:       ij=(int)(covar[Tvar[j]][i]); /* ij=0 or 1 or -1. Value of the covariate Tvar[j] for individual i
                   3345:                                    * If product of Vn*Vm, still boolean *:
                   3346:                                    * If it was coded 1, 2, 3, 4 should be splitted into 3 boolean variables
                   3347:                                    * 1 => 0 0 0, 2 => 0 0 1, 3 => 0 1 1, 4=1 0 0   */
                   3348:       /* Finds for covariate j, n=Tvar[j] of Vn . ij is the
1.136     brouard  3349:                                      modality of the nth covariate of individual i. */
1.145     brouard  3350:       if (ij > modmaxcovj)
                   3351:         modmaxcovj=ij; 
                   3352:       else if (ij < modmincovj) 
                   3353:        modmincovj=ij; 
                   3354:       if ((ij < -1) && (ij > NCOVMAX)){
                   3355:        printf( "Error: minimal is less than -1 or maximal is bigger than %d. Exiting. \n", NCOVMAX );
                   3356:        exit(1);
                   3357:       }else
1.136     brouard  3358:       Ndum[ij]++; /*counts and stores the occurence of this modality 0, 1, -1*/
1.145     brouard  3359:       /*  If coded 1, 2, 3 , counts the number of 1 Ndum[1], number of 2, Ndum[2], etc */
1.126     brouard  3360:       /*printf("i=%d ij=%d Ndum[ij]=%d imx=%d",i,ij,Ndum[ij],imx);*/
1.136     brouard  3361:       /* getting the maximum value of the modality of the covariate
                   3362:         (should be 0 or 1 now) Tvar[j]. If V=sex and male is coded 0 and
                   3363:         female is 1, then modmaxcovj=1.*/
1.192     brouard  3364:     } /* end for loop on individuals i */
1.145     brouard  3365:     printf(" Minimal and maximal values of %d th covariate V%d: min=%d max=%d \n", j, Tvar[j], modmincovj, modmaxcovj);
1.192     brouard  3366:     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  3367:     cptcode=modmaxcovj;
1.137     brouard  3368:     /* Ndum[0] = frequency of 0 for model-covariate j, Ndum[1] frequency of 1 etc. */
1.145     brouard  3369:    /*for (i=0; i<=cptcode; i++) {*/
1.192     brouard  3370:     for (k=modmincovj;  k<=modmaxcovj; k++) { /* k=-1 ? 0 and 1*//* For each value k of the modality of model-cov j */
                   3371:       printf("Frequencies of covariates %d ie V%d with value %d: %d\n", j, Tvar[j], k, Ndum[k]);
                   3372:       fprintf(ficlog, "Frequencies of covariates %d ie V%d with value %d: %d\n", j, Tvar[j], k, Ndum[k]);
                   3373:       if( Ndum[k] != 0 ){ /* Counts if nobody answered modality k ie empty modality, we skip it and reorder */
                   3374:        if( k != -1){
                   3375:          ncodemax[j]++;  /* ncodemax[j]= Number of modalities of the j th
                   3376:                             covariate for which somebody answered excluding 
                   3377:                             undefined. Usually 2: 0 and 1. */
                   3378:        }
                   3379:        ncodemaxwundef[j]++; /* ncodemax[j]= Number of modalities of the j th
                   3380:                             covariate for which somebody answered including 
                   3381:                             undefined. Usually 3: -1, 0 and 1. */
1.145     brouard  3382:       }
                   3383:       /* In fact  ncodemax[j]=2 (dichotom. variables only) but it could be more for
                   3384:         historical reasons: 3 if coded 1, 2, 3 and 4 and Ndum[2]=0 */
1.131     brouard  3385:     } /* Ndum[-1] number of undefined modalities */
1.126     brouard  3386: 
1.136     brouard  3387:     /* j is a covariate, n=Tvar[j] of Vn; Fills nbcode */
1.186     brouard  3388:     /* For covariate j, modalities could be 1, 2, 3, 4, 5, 6, 7. 
                   3389:        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  3390:        modmincovj=3; modmaxcovj = 7;
1.186     brouard  3391:        There are only 3 modalities non empty 3, 6, 7 (or 2 if 27 is too few) : ncodemax[j]=3;
                   3392:        which will be coded 0, 1, 2 which in binary on 2=3-1 digits are 0=00 1=01, 2=10;
                   3393:        defining two dummy variables: variables V1_1 and V1_2.
1.145     brouard  3394:        nbcode[Tvar[j]][ij]=k;
                   3395:        nbcode[Tvar[j]][1]=0;
                   3396:        nbcode[Tvar[j]][2]=1;
                   3397:        nbcode[Tvar[j]][3]=2;
1.197   ! brouard  3398:        To be continued (not working yet).
1.145     brouard  3399:     */
1.197   ! brouard  3400:     ij=0; /* ij is similar to i but can jump over null modalities */
        !          3401:     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*/
        !          3402:        if (Ndum[i] == 0) { /* If nobody responded to this modality k */
1.192     brouard  3403:          break;
                   3404:        }
                   3405:        ij++;
1.197   ! brouard  3406:        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  3407:        cptcode = ij; /* New max modality for covar j */
                   3408:     } /* end of loop on modality i=-1 to 1 or more */
                   3409:       
                   3410:     /*   for (k=0; k<= cptcode; k++) { /\* k=-1 ? k=0 to 1 *\//\* Could be 1 to 4 *\//\* cptcode=modmaxcovj *\/ */
                   3411:     /*         /\*recode from 0 *\/ */
                   3412:     /*                                      k is a modality. If we have model=V1+V1*sex  */
                   3413:     /*                                      then: nbcode[1][1]=0 ; nbcode[1][2]=1; nbcode[2][1]=0 ; nbcode[2][2]=1; */
                   3414:     /*                                   But if some modality were not used, it is recoded from 0 to a newer modmaxcovj=cptcode *\/ */
                   3415:     /*         } */
                   3416:     /*         /\* cptcode = ij; *\/ /\* New max modality for covar j *\/ */
                   3417:     /*         if (ij > ncodemax[j]) { */
                   3418:     /*           printf( " Error ij=%d > ncodemax[%d]=%d\n", ij, j, ncodemax[j]);  */
                   3419:     /*           fprintf(ficlog, " Error ij=%d > ncodemax[%d]=%d\n", ij, j, ncodemax[j]); */
                   3420:     /*           break; */
                   3421:     /*         } */
                   3422:     /*   }  /\* end of loop on modality k *\/ */
1.137     brouard  3423:   } /* end of loop on model-covariate j. nbcode[Tvarj][1]=0 and nbcode[Tvarj][2]=1 sets the value of covariate j*/  
                   3424:   
1.145     brouard  3425:  for (k=-1; k< maxncov; k++) Ndum[k]=0; 
1.137     brouard  3426:   
1.187     brouard  3427:   for (i=1; i<=ncovmodel-2-nagesqr; i++) { /* -2, cste and age and eventually age*age */ 
1.145     brouard  3428:    /* Listing of all covariables in statement model to see if some covariates appear twice. For example, V1 appears twice in V1+V1*V2.*/ 
                   3429:    ij=Tvar[i]; /* Tvar might be -1 if status was unknown */ 
1.187     brouard  3430:    Ndum[ij]++; /* Might be supersed V1 + V1*age */
1.145     brouard  3431:  } 
1.126     brouard  3432: 
1.192     brouard  3433:  ij=0;
1.145     brouard  3434:  for (i=0; i<=  maxncov-1; i++) { /* modmaxcovj is unknown here. Only Ndum[2(V2),3(age*V3), 5(V3*V2) 6(V1*V4) */
                   3435:    /*printf("Ndum[%d]=%d\n",i, Ndum[i]);*/
1.126     brouard  3436:    if((Ndum[i]!=0) && (i<=ncovcol)){
1.192     brouard  3437:      ij++;
1.145     brouard  3438:      /*printf("diff Ndum[%d]=%d\n",i, Ndum[i]);*/
                   3439:      Tvaraff[ij]=i; /*For printing (unclear) */
1.192     brouard  3440:    }else{
                   3441:        /* Tvaraff[ij]=0; */
                   3442:    }
1.126     brouard  3443:  }
1.192     brouard  3444:  /* ij--; */
1.144     brouard  3445:  cptcoveff=ij; /*Number of total covariates*/
1.145     brouard  3446: 
1.126     brouard  3447: }
                   3448: 
1.145     brouard  3449: 
1.126     brouard  3450: /*********** Health Expectancies ****************/
                   3451: 
1.127     brouard  3452: 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  3453: 
                   3454: {
                   3455:   /* Health expectancies, no variances */
1.164     brouard  3456:   int i, j, nhstepm, hstepm, h, nstepm;
1.126     brouard  3457:   int nhstepma, nstepma; /* Decreasing with age */
                   3458:   double age, agelim, hf;
                   3459:   double ***p3mat;
                   3460:   double eip;
                   3461: 
                   3462:   pstamp(ficreseij);
                   3463:   fprintf(ficreseij,"# (a) Life expectancies by health status at initial age and (b) health expectancies by health status at initial age\n");
                   3464:   fprintf(ficreseij,"# Age");
                   3465:   for(i=1; i<=nlstate;i++){
                   3466:     for(j=1; j<=nlstate;j++){
                   3467:       fprintf(ficreseij," e%1d%1d ",i,j);
                   3468:     }
                   3469:     fprintf(ficreseij," e%1d. ",i);
                   3470:   }
                   3471:   fprintf(ficreseij,"\n");
                   3472: 
                   3473:   
                   3474:   if(estepm < stepm){
                   3475:     printf ("Problem %d lower than %d\n",estepm, stepm);
                   3476:   }
                   3477:   else  hstepm=estepm;   
                   3478:   /* We compute the life expectancy from trapezoids spaced every estepm months
                   3479:    * This is mainly to measure the difference between two models: for example
                   3480:    * if stepm=24 months pijx are given only every 2 years and by summing them
                   3481:    * we are calculating an estimate of the Life Expectancy assuming a linear 
                   3482:    * progression in between and thus overestimating or underestimating according
                   3483:    * to the curvature of the survival function. If, for the same date, we 
                   3484:    * estimate the model with stepm=1 month, we can keep estepm to 24 months
                   3485:    * to compare the new estimate of Life expectancy with the same linear 
                   3486:    * hypothesis. A more precise result, taking into account a more precise
                   3487:    * curvature will be obtained if estepm is as small as stepm. */
                   3488: 
                   3489:   /* For example we decided to compute the life expectancy with the smallest unit */
                   3490:   /* hstepm beeing the number of stepms, if hstepm=1 the length of hstepm is stepm. 
                   3491:      nhstepm is the number of hstepm from age to agelim 
                   3492:      nstepm is the number of stepm from age to agelin. 
                   3493:      Look at hpijx to understand the reason of that which relies in memory size
                   3494:      and note for a fixed period like estepm months */
                   3495:   /* We decided (b) to get a life expectancy respecting the most precise curvature of the
                   3496:      survival function given by stepm (the optimization length). Unfortunately it
                   3497:      means that if the survival funtion is printed only each two years of age and if
                   3498:      you sum them up and add 1 year (area under the trapezoids) you won't get the same 
                   3499:      results. So we changed our mind and took the option of the best precision.
                   3500:   */
                   3501:   hstepm=hstepm/stepm; /* Typically in stepm units, if stepm=6 & estepm=24 , = 24/6 months = 4 */ 
                   3502: 
                   3503:   agelim=AGESUP;
                   3504:   /* If stepm=6 months */
                   3505:     /* Computed by stepm unit matrices, product of hstepm matrices, stored
                   3506:        in an array of nhstepm length: nhstepm=10, hstepm=4, stepm=6 months */
                   3507:     
                   3508: /* nhstepm age range expressed in number of stepm */
                   3509:   nstepm=(int) rint((agelim-bage)*YEARM/stepm); /* Biggest nstepm */
                   3510:   /* Typically if 20 years nstepm = 20*12/6=40 stepm */ 
                   3511:   /* if (stepm >= YEARM) hstepm=1;*/
                   3512:   nhstepm = nstepm/hstepm;/* Expressed in hstepm, typically nhstepm=40/4=10 */
                   3513:   p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   3514: 
                   3515:   for (age=bage; age<=fage; age ++){ 
                   3516:     nstepma=(int) rint((agelim-bage)*YEARM/stepm); /* Biggest nstepm */
                   3517:     /* Typically if 20 years nstepm = 20*12/6=40 stepm */ 
                   3518:     /* if (stepm >= YEARM) hstepm=1;*/
                   3519:     nhstepma = nstepma/hstepm;/* Expressed in hstepm, typically nhstepma=40/4=10 */
                   3520: 
                   3521:     /* If stepm=6 months */
                   3522:     /* Computed by stepm unit matrices, product of hstepma matrices, stored
                   3523:        in an array of nhstepma length: nhstepma=10, hstepm=4, stepm=6 months */
                   3524:     
                   3525:     hpxij(p3mat,nhstepma,age,hstepm,x,nlstate,stepm,oldm, savm, cij);  
                   3526:     
                   3527:     hf=hstepm*stepm/YEARM;  /* Duration of hstepm expressed in year unit. */
                   3528:     
                   3529:     printf("%d|",(int)age);fflush(stdout);
                   3530:     fprintf(ficlog,"%d|",(int)age);fflush(ficlog);
                   3531:     
                   3532:     /* Computing expectancies */
                   3533:     for(i=1; i<=nlstate;i++)
                   3534:       for(j=1; j<=nlstate;j++)
                   3535:        for (h=0, eij[i][j][(int)age]=0; h<=nhstepm-1; h++){
                   3536:          eij[i][j][(int)age] += (p3mat[i][j][h]+p3mat[i][j][h+1])/2.0*hf;
                   3537:          
                   3538:          /* 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]);*/
                   3539: 
                   3540:        }
                   3541: 
                   3542:     fprintf(ficreseij,"%3.0f",age );
                   3543:     for(i=1; i<=nlstate;i++){
                   3544:       eip=0;
                   3545:       for(j=1; j<=nlstate;j++){
                   3546:        eip +=eij[i][j][(int)age];
                   3547:        fprintf(ficreseij,"%9.4f", eij[i][j][(int)age] );
                   3548:       }
                   3549:       fprintf(ficreseij,"%9.4f", eip );
                   3550:     }
                   3551:     fprintf(ficreseij,"\n");
                   3552:     
                   3553:   }
                   3554:   free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   3555:   printf("\n");
                   3556:   fprintf(ficlog,"\n");
                   3557:   
                   3558: }
                   3559: 
1.127     brouard  3560: 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  3561: 
                   3562: {
                   3563:   /* Covariances of health expectancies eij and of total life expectancies according
                   3564:    to initial status i, ei. .
                   3565:   */
                   3566:   int i, j, nhstepm, hstepm, h, nstepm, k, cptj, cptj2, i2, j2, ij, ji;
                   3567:   int nhstepma, nstepma; /* Decreasing with age */
                   3568:   double age, agelim, hf;
                   3569:   double ***p3matp, ***p3matm, ***varhe;
                   3570:   double **dnewm,**doldm;
                   3571:   double *xp, *xm;
                   3572:   double **gp, **gm;
                   3573:   double ***gradg, ***trgradg;
                   3574:   int theta;
                   3575: 
                   3576:   double eip, vip;
                   3577: 
                   3578:   varhe=ma3x(1,nlstate*nlstate,1,nlstate*nlstate,(int) bage, (int) fage);
                   3579:   xp=vector(1,npar);
                   3580:   xm=vector(1,npar);
                   3581:   dnewm=matrix(1,nlstate*nlstate,1,npar);
                   3582:   doldm=matrix(1,nlstate*nlstate,1,nlstate*nlstate);
                   3583:   
                   3584:   pstamp(ficresstdeij);
                   3585:   fprintf(ficresstdeij,"# Health expectancies with standard errors\n");
                   3586:   fprintf(ficresstdeij,"# Age");
                   3587:   for(i=1; i<=nlstate;i++){
                   3588:     for(j=1; j<=nlstate;j++)
                   3589:       fprintf(ficresstdeij," e%1d%1d (SE)",i,j);
                   3590:     fprintf(ficresstdeij," e%1d. ",i);
                   3591:   }
                   3592:   fprintf(ficresstdeij,"\n");
                   3593: 
                   3594:   pstamp(ficrescveij);
                   3595:   fprintf(ficrescveij,"# Subdiagonal matrix of covariances of health expectancies by age: cov(eij,ekl)\n");
                   3596:   fprintf(ficrescveij,"# Age");
                   3597:   for(i=1; i<=nlstate;i++)
                   3598:     for(j=1; j<=nlstate;j++){
                   3599:       cptj= (j-1)*nlstate+i;
                   3600:       for(i2=1; i2<=nlstate;i2++)
                   3601:        for(j2=1; j2<=nlstate;j2++){
                   3602:          cptj2= (j2-1)*nlstate+i2;
                   3603:          if(cptj2 <= cptj)
                   3604:            fprintf(ficrescveij,"  %1d%1d,%1d%1d",i,j,i2,j2);
                   3605:        }
                   3606:     }
                   3607:   fprintf(ficrescveij,"\n");
                   3608:   
                   3609:   if(estepm < stepm){
                   3610:     printf ("Problem %d lower than %d\n",estepm, stepm);
                   3611:   }
                   3612:   else  hstepm=estepm;   
                   3613:   /* We compute the life expectancy from trapezoids spaced every estepm months
                   3614:    * This is mainly to measure the difference between two models: for example
                   3615:    * if stepm=24 months pijx are given only every 2 years and by summing them
                   3616:    * we are calculating an estimate of the Life Expectancy assuming a linear 
                   3617:    * progression in between and thus overestimating or underestimating according
                   3618:    * to the curvature of the survival function. If, for the same date, we 
                   3619:    * estimate the model with stepm=1 month, we can keep estepm to 24 months
                   3620:    * to compare the new estimate of Life expectancy with the same linear 
                   3621:    * hypothesis. A more precise result, taking into account a more precise
                   3622:    * curvature will be obtained if estepm is as small as stepm. */
                   3623: 
                   3624:   /* For example we decided to compute the life expectancy with the smallest unit */
                   3625:   /* hstepm beeing the number of stepms, if hstepm=1 the length of hstepm is stepm. 
                   3626:      nhstepm is the number of hstepm from age to agelim 
                   3627:      nstepm is the number of stepm from age to agelin. 
                   3628:      Look at hpijx to understand the reason of that which relies in memory size
                   3629:      and note for a fixed period like estepm months */
                   3630:   /* We decided (b) to get a life expectancy respecting the most precise curvature of the
                   3631:      survival function given by stepm (the optimization length). Unfortunately it
                   3632:      means that if the survival funtion is printed only each two years of age and if
                   3633:      you sum them up and add 1 year (area under the trapezoids) you won't get the same 
                   3634:      results. So we changed our mind and took the option of the best precision.
                   3635:   */
                   3636:   hstepm=hstepm/stepm; /* Typically in stepm units, if stepm=6 & estepm=24 , = 24/6 months = 4 */ 
                   3637: 
                   3638:   /* If stepm=6 months */
                   3639:   /* nhstepm age range expressed in number of stepm */
                   3640:   agelim=AGESUP;
                   3641:   nstepm=(int) rint((agelim-bage)*YEARM/stepm); 
                   3642:   /* Typically if 20 years nstepm = 20*12/6=40 stepm */ 
                   3643:   /* if (stepm >= YEARM) hstepm=1;*/
                   3644:   nhstepm = nstepm/hstepm;/* Expressed in hstepm, typically nhstepm=40/4=10 */
                   3645:   
                   3646:   p3matp=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   3647:   p3matm=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   3648:   gradg=ma3x(0,nhstepm,1,npar,1,nlstate*nlstate);
                   3649:   trgradg =ma3x(0,nhstepm,1,nlstate*nlstate,1,npar);
                   3650:   gp=matrix(0,nhstepm,1,nlstate*nlstate);
                   3651:   gm=matrix(0,nhstepm,1,nlstate*nlstate);
                   3652: 
                   3653:   for (age=bage; age<=fage; age ++){ 
                   3654:     nstepma=(int) rint((agelim-bage)*YEARM/stepm); /* Biggest nstepm */
                   3655:     /* Typically if 20 years nstepm = 20*12/6=40 stepm */ 
                   3656:     /* if (stepm >= YEARM) hstepm=1;*/
                   3657:     nhstepma = nstepma/hstepm;/* Expressed in hstepm, typically nhstepma=40/4=10 */
                   3658: 
                   3659:     /* If stepm=6 months */
                   3660:     /* Computed by stepm unit matrices, product of hstepma matrices, stored
                   3661:        in an array of nhstepma length: nhstepma=10, hstepm=4, stepm=6 months */
                   3662:     
                   3663:     hf=hstepm*stepm/YEARM;  /* Duration of hstepm expressed in year unit. */
                   3664: 
                   3665:     /* Computing  Variances of health expectancies */
                   3666:     /* Gradient is computed with plus gp and minus gm. Code is duplicated in order to
                   3667:        decrease memory allocation */
                   3668:     for(theta=1; theta <=npar; theta++){
                   3669:       for(i=1; i<=npar; i++){ 
                   3670:        xp[i] = x[i] + (i==theta ?delti[theta]:0);
                   3671:        xm[i] = x[i] - (i==theta ?delti[theta]:0);
                   3672:       }
                   3673:       hpxij(p3matp,nhstepm,age,hstepm,xp,nlstate,stepm,oldm,savm, cij);  
                   3674:       hpxij(p3matm,nhstepm,age,hstepm,xm,nlstate,stepm,oldm,savm, cij);  
                   3675:   
                   3676:       for(j=1; j<= nlstate; j++){
                   3677:        for(i=1; i<=nlstate; i++){
                   3678:          for(h=0; h<=nhstepm-1; h++){
                   3679:            gp[h][(j-1)*nlstate + i] = (p3matp[i][j][h]+p3matp[i][j][h+1])/2.;
                   3680:            gm[h][(j-1)*nlstate + i] = (p3matm[i][j][h]+p3matm[i][j][h+1])/2.;
                   3681:          }
                   3682:        }
                   3683:       }
                   3684:      
                   3685:       for(ij=1; ij<= nlstate*nlstate; ij++)
                   3686:        for(h=0; h<=nhstepm-1; h++){
                   3687:          gradg[h][theta][ij]= (gp[h][ij]-gm[h][ij])/2./delti[theta];
                   3688:        }
                   3689:     }/* End theta */
                   3690:     
                   3691:     
                   3692:     for(h=0; h<=nhstepm-1; h++)
                   3693:       for(j=1; j<=nlstate*nlstate;j++)
                   3694:        for(theta=1; theta <=npar; theta++)
                   3695:          trgradg[h][j][theta]=gradg[h][theta][j];
                   3696:     
                   3697: 
                   3698:      for(ij=1;ij<=nlstate*nlstate;ij++)
                   3699:       for(ji=1;ji<=nlstate*nlstate;ji++)
                   3700:        varhe[ij][ji][(int)age] =0.;
                   3701: 
                   3702:      printf("%d|",(int)age);fflush(stdout);
                   3703:      fprintf(ficlog,"%d|",(int)age);fflush(ficlog);
                   3704:      for(h=0;h<=nhstepm-1;h++){
                   3705:       for(k=0;k<=nhstepm-1;k++){
                   3706:        matprod2(dnewm,trgradg[h],1,nlstate*nlstate,1,npar,1,npar,matcov);
                   3707:        matprod2(doldm,dnewm,1,nlstate*nlstate,1,npar,1,nlstate*nlstate,gradg[k]);
                   3708:        for(ij=1;ij<=nlstate*nlstate;ij++)
                   3709:          for(ji=1;ji<=nlstate*nlstate;ji++)
                   3710:            varhe[ij][ji][(int)age] += doldm[ij][ji]*hf*hf;
                   3711:       }
                   3712:     }
                   3713: 
                   3714:     /* Computing expectancies */
                   3715:     hpxij(p3matm,nhstepm,age,hstepm,x,nlstate,stepm,oldm, savm, cij);  
                   3716:     for(i=1; i<=nlstate;i++)
                   3717:       for(j=1; j<=nlstate;j++)
                   3718:        for (h=0, eij[i][j][(int)age]=0; h<=nhstepm-1; h++){
                   3719:          eij[i][j][(int)age] += (p3matm[i][j][h]+p3matm[i][j][h+1])/2.0*hf;
                   3720:          
                   3721:          /* 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]);*/
                   3722: 
                   3723:        }
                   3724: 
                   3725:     fprintf(ficresstdeij,"%3.0f",age );
                   3726:     for(i=1; i<=nlstate;i++){
                   3727:       eip=0.;
                   3728:       vip=0.;
                   3729:       for(j=1; j<=nlstate;j++){
                   3730:        eip += eij[i][j][(int)age];
                   3731:        for(k=1; k<=nlstate;k++) /* Sum on j and k of cov(eij,eik) */
                   3732:          vip += varhe[(j-1)*nlstate+i][(k-1)*nlstate+i][(int)age];
                   3733:        fprintf(ficresstdeij," %9.4f (%.4f)", eij[i][j][(int)age], sqrt(varhe[(j-1)*nlstate+i][(j-1)*nlstate+i][(int)age]) );
                   3734:       }
                   3735:       fprintf(ficresstdeij," %9.4f (%.4f)", eip, sqrt(vip));
                   3736:     }
                   3737:     fprintf(ficresstdeij,"\n");
                   3738: 
                   3739:     fprintf(ficrescveij,"%3.0f",age );
                   3740:     for(i=1; i<=nlstate;i++)
                   3741:       for(j=1; j<=nlstate;j++){
                   3742:        cptj= (j-1)*nlstate+i;
                   3743:        for(i2=1; i2<=nlstate;i2++)
                   3744:          for(j2=1; j2<=nlstate;j2++){
                   3745:            cptj2= (j2-1)*nlstate+i2;
                   3746:            if(cptj2 <= cptj)
                   3747:              fprintf(ficrescveij," %.4f", varhe[cptj][cptj2][(int)age]);
                   3748:          }
                   3749:       }
                   3750:     fprintf(ficrescveij,"\n");
                   3751:    
                   3752:   }
                   3753:   free_matrix(gm,0,nhstepm,1,nlstate*nlstate);
                   3754:   free_matrix(gp,0,nhstepm,1,nlstate*nlstate);
                   3755:   free_ma3x(gradg,0,nhstepm,1,npar,1,nlstate*nlstate);
                   3756:   free_ma3x(trgradg,0,nhstepm,1,nlstate*nlstate,1,npar);
                   3757:   free_ma3x(p3matm,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   3758:   free_ma3x(p3matp,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   3759:   printf("\n");
                   3760:   fprintf(ficlog,"\n");
                   3761: 
                   3762:   free_vector(xm,1,npar);
                   3763:   free_vector(xp,1,npar);
                   3764:   free_matrix(dnewm,1,nlstate*nlstate,1,npar);
                   3765:   free_matrix(doldm,1,nlstate*nlstate,1,nlstate*nlstate);
                   3766:   free_ma3x(varhe,1,nlstate*nlstate,1,nlstate*nlstate,(int) bage, (int)fage);
                   3767: }
                   3768: 
                   3769: /************ Variance ******************/
                   3770: 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 ij, int estepm, int cptcov, int cptcod, int popbased, int mobilav, char strstart[])
                   3771: {
                   3772:   /* Variance of health expectancies */
                   3773:   /*  double **prevalim(double **prlim, int nlstate, double *xp, double age, double **oldm, double ** savm,double ftolpl);*/
                   3774:   /* double **newm;*/
1.169     brouard  3775:   /* int movingaverage(double ***probs, double bage,double fage, double ***mobaverage, int mobilav)*/
                   3776:   
                   3777:   int movingaverage();
1.126     brouard  3778:   double **dnewm,**doldm;
                   3779:   double **dnewmp,**doldmp;
                   3780:   int i, j, nhstepm, hstepm, h, nstepm ;
1.164     brouard  3781:   int k;
1.126     brouard  3782:   double *xp;
                   3783:   double **gp, **gm;  /* for var eij */
                   3784:   double ***gradg, ***trgradg; /*for var eij */
                   3785:   double **gradgp, **trgradgp; /* for var p point j */
                   3786:   double *gpp, *gmp; /* for var p point j */
                   3787:   double **varppt; /* for var p point j nlstate to nlstate+ndeath */
                   3788:   double ***p3mat;
                   3789:   double age,agelim, hf;
                   3790:   double ***mobaverage;
                   3791:   int theta;
                   3792:   char digit[4];
                   3793:   char digitp[25];
                   3794: 
                   3795:   char fileresprobmorprev[FILENAMELENGTH];
                   3796: 
                   3797:   if(popbased==1){
                   3798:     if(mobilav!=0)
                   3799:       strcpy(digitp,"-populbased-mobilav-");
                   3800:     else strcpy(digitp,"-populbased-nomobil-");
                   3801:   }
                   3802:   else 
                   3803:     strcpy(digitp,"-stablbased-");
                   3804: 
                   3805:   if (mobilav!=0) {
                   3806:     mobaverage= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
                   3807:     if (movingaverage(probs, bage, fage, mobaverage,mobilav)!=0){
                   3808:       fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav);
                   3809:       printf(" Error in movingaverage mobilav=%d\n",mobilav);
                   3810:     }
                   3811:   }
                   3812: 
                   3813:   strcpy(fileresprobmorprev,"prmorprev"); 
                   3814:   sprintf(digit,"%-d",ij);
                   3815:   /*printf("DIGIT=%s, ij=%d ijr=%-d|\n",digit, ij,ij);*/
                   3816:   strcat(fileresprobmorprev,digit); /* Tvar to be done */
                   3817:   strcat(fileresprobmorprev,digitp); /* Popbased or not, mobilav or not */
                   3818:   strcat(fileresprobmorprev,fileres);
                   3819:   if((ficresprobmorprev=fopen(fileresprobmorprev,"w"))==NULL) {
                   3820:     printf("Problem with resultfile: %s\n", fileresprobmorprev);
                   3821:     fprintf(ficlog,"Problem with resultfile: %s\n", fileresprobmorprev);
                   3822:   }
                   3823:   printf("Computing total mortality p.j=w1*p1j+w2*p2j+..: result on file '%s' \n",fileresprobmorprev);
                   3824:  
                   3825:   fprintf(ficlog,"Computing total mortality p.j=w1*p1j+w2*p2j+..: result on file '%s' \n",fileresprobmorprev);
                   3826:   pstamp(ficresprobmorprev);
                   3827:   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);
                   3828:   fprintf(ficresprobmorprev,"# Age cov=%-d",ij);
                   3829:   for(j=nlstate+1; j<=(nlstate+ndeath);j++){
                   3830:     fprintf(ficresprobmorprev," p.%-d SE",j);
                   3831:     for(i=1; i<=nlstate;i++)
                   3832:       fprintf(ficresprobmorprev," w%1d p%-d%-d",i,i,j);
                   3833:   }  
                   3834:   fprintf(ficresprobmorprev,"\n");
                   3835:   fprintf(ficgp,"\n# Routine varevsij");
                   3836:   /* fprintf(fichtm, "#Local time at start: %s", strstart);*/
                   3837:   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");
                   3838:   fprintf(fichtm,"\n<br>%s  <br>\n",digitp);
                   3839: /*   } */
                   3840:   varppt = matrix(nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);
                   3841:   pstamp(ficresvij);
                   3842:   fprintf(ficresvij,"# Variance and covariance of health expectancies e.j \n#  (weighted average of eij where weights are ");
                   3843:   if(popbased==1)
1.128     brouard  3844:     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  3845:   else
                   3846:     fprintf(ficresvij,"the age specific period (stable) prevalences in each health state \n");
                   3847:   fprintf(ficresvij,"# Age");
                   3848:   for(i=1; i<=nlstate;i++)
                   3849:     for(j=1; j<=nlstate;j++)
                   3850:       fprintf(ficresvij," Cov(e.%1d, e.%1d)",i,j);
                   3851:   fprintf(ficresvij,"\n");
                   3852: 
                   3853:   xp=vector(1,npar);
                   3854:   dnewm=matrix(1,nlstate,1,npar);
                   3855:   doldm=matrix(1,nlstate,1,nlstate);
                   3856:   dnewmp= matrix(nlstate+1,nlstate+ndeath,1,npar);
                   3857:   doldmp= matrix(nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);
                   3858: 
                   3859:   gradgp=matrix(1,npar,nlstate+1,nlstate+ndeath);
                   3860:   gpp=vector(nlstate+1,nlstate+ndeath);
                   3861:   gmp=vector(nlstate+1,nlstate+ndeath);
                   3862:   trgradgp =matrix(nlstate+1,nlstate+ndeath,1,npar); /* mu or p point j*/
                   3863:   
                   3864:   if(estepm < stepm){
                   3865:     printf ("Problem %d lower than %d\n",estepm, stepm);
                   3866:   }
                   3867:   else  hstepm=estepm;   
                   3868:   /* For example we decided to compute the life expectancy with the smallest unit */
                   3869:   /* hstepm beeing the number of stepms, if hstepm=1 the length of hstepm is stepm. 
                   3870:      nhstepm is the number of hstepm from age to agelim 
                   3871:      nstepm is the number of stepm from age to agelin. 
1.128     brouard  3872:      Look at function hpijx to understand why (it is linked to memory size questions) */
1.126     brouard  3873:   /* We decided (b) to get a life expectancy respecting the most precise curvature of the
                   3874:      survival function given by stepm (the optimization length). Unfortunately it
                   3875:      means that if the survival funtion is printed every two years of age and if
                   3876:      you sum them up and add 1 year (area under the trapezoids) you won't get the same 
                   3877:      results. So we changed our mind and took the option of the best precision.
                   3878:   */
                   3879:   hstepm=hstepm/stepm; /* Typically in stepm units, if stepm=6 & estepm=24 , = 24/6 months = 4 */ 
                   3880:   agelim = AGESUP;
                   3881:   for (age=bage; age<=fage; age ++){ /* If stepm=6 months */
                   3882:     nstepm=(int) rint((agelim-age)*YEARM/stepm); /* Typically 20 years = 20*12/6=40 */ 
                   3883:     nhstepm = nstepm/hstepm;/* Expressed in hstepm, typically nhstepm=40/4=10 */
                   3884:     p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   3885:     gradg=ma3x(0,nhstepm,1,npar,1,nlstate);
                   3886:     gp=matrix(0,nhstepm,1,nlstate);
                   3887:     gm=matrix(0,nhstepm,1,nlstate);
                   3888: 
                   3889: 
                   3890:     for(theta=1; theta <=npar; theta++){
                   3891:       for(i=1; i<=npar; i++){ /* Computes gradient x + delta*/
                   3892:        xp[i] = x[i] + (i==theta ?delti[theta]:0);
                   3893:       }
                   3894:       hpxij(p3mat,nhstepm,age,hstepm,xp,nlstate,stepm,oldm,savm, ij);  
                   3895:       prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ij);
                   3896: 
                   3897:       if (popbased==1) {
                   3898:        if(mobilav ==0){
                   3899:          for(i=1; i<=nlstate;i++)
                   3900:            prlim[i][i]=probs[(int)age][i][ij];
                   3901:        }else{ /* mobilav */ 
                   3902:          for(i=1; i<=nlstate;i++)
                   3903:            prlim[i][i]=mobaverage[(int)age][i][ij];
                   3904:        }
                   3905:       }
                   3906:   
                   3907:       for(j=1; j<= nlstate; j++){
                   3908:        for(h=0; h<=nhstepm; h++){
                   3909:          for(i=1, gp[h][j]=0.;i<=nlstate;i++)
                   3910:            gp[h][j] += prlim[i][i]*p3mat[i][j][h];
                   3911:        }
                   3912:       }
                   3913:       /* This for computing probability of death (h=1 means
                   3914:          computed over hstepm matrices product = hstepm*stepm months) 
                   3915:          as a weighted average of prlim.
                   3916:       */
                   3917:       for(j=nlstate+1;j<=nlstate+ndeath;j++){
                   3918:        for(i=1,gpp[j]=0.; i<= nlstate; i++)
                   3919:          gpp[j] += prlim[i][i]*p3mat[i][j][1];
                   3920:       }    
                   3921:       /* end probability of death */
                   3922: 
                   3923:       for(i=1; i<=npar; i++) /* Computes gradient x - delta */
                   3924:        xp[i] = x[i] - (i==theta ?delti[theta]:0);
                   3925:       hpxij(p3mat,nhstepm,age,hstepm,xp,nlstate,stepm,oldm,savm, ij);  
                   3926:       prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ij);
                   3927:  
                   3928:       if (popbased==1) {
                   3929:        if(mobilav ==0){
                   3930:          for(i=1; i<=nlstate;i++)
                   3931:            prlim[i][i]=probs[(int)age][i][ij];
                   3932:        }else{ /* mobilav */ 
                   3933:          for(i=1; i<=nlstate;i++)
                   3934:            prlim[i][i]=mobaverage[(int)age][i][ij];
                   3935:        }
                   3936:       }
                   3937: 
1.128     brouard  3938:       for(j=1; j<= nlstate; j++){  /* Sum of wi * eij = e.j */
1.126     brouard  3939:        for(h=0; h<=nhstepm; h++){
                   3940:          for(i=1, gm[h][j]=0.;i<=nlstate;i++)
                   3941:            gm[h][j] += prlim[i][i]*p3mat[i][j][h];
                   3942:        }
                   3943:       }
                   3944:       /* This for computing probability of death (h=1 means
                   3945:          computed over hstepm matrices product = hstepm*stepm months) 
                   3946:          as a weighted average of prlim.
                   3947:       */
                   3948:       for(j=nlstate+1;j<=nlstate+ndeath;j++){
                   3949:        for(i=1,gmp[j]=0.; i<= nlstate; i++)
                   3950:          gmp[j] += prlim[i][i]*p3mat[i][j][1];
                   3951:       }    
                   3952:       /* end probability of death */
                   3953: 
                   3954:       for(j=1; j<= nlstate; j++) /* vareij */
                   3955:        for(h=0; h<=nhstepm; h++){
                   3956:          gradg[h][theta][j]= (gp[h][j]-gm[h][j])/2./delti[theta];
                   3957:        }
                   3958: 
                   3959:       for(j=nlstate+1; j<= nlstate+ndeath; j++){ /* var mu */
                   3960:        gradgp[theta][j]= (gpp[j]-gmp[j])/2./delti[theta];
                   3961:       }
                   3962: 
                   3963:     } /* End theta */
                   3964: 
                   3965:     trgradg =ma3x(0,nhstepm,1,nlstate,1,npar); /* veij */
                   3966: 
                   3967:     for(h=0; h<=nhstepm; h++) /* veij */
                   3968:       for(j=1; j<=nlstate;j++)
                   3969:        for(theta=1; theta <=npar; theta++)
                   3970:          trgradg[h][j][theta]=gradg[h][theta][j];
                   3971: 
                   3972:     for(j=nlstate+1; j<=nlstate+ndeath;j++) /* mu */
                   3973:       for(theta=1; theta <=npar; theta++)
                   3974:        trgradgp[j][theta]=gradgp[theta][j];
                   3975:   
                   3976: 
                   3977:     hf=hstepm*stepm/YEARM;  /* Duration of hstepm expressed in year unit. */
                   3978:     for(i=1;i<=nlstate;i++)
                   3979:       for(j=1;j<=nlstate;j++)
                   3980:        vareij[i][j][(int)age] =0.;
                   3981: 
                   3982:     for(h=0;h<=nhstepm;h++){
                   3983:       for(k=0;k<=nhstepm;k++){
                   3984:        matprod2(dnewm,trgradg[h],1,nlstate,1,npar,1,npar,matcov);
                   3985:        matprod2(doldm,dnewm,1,nlstate,1,npar,1,nlstate,gradg[k]);
                   3986:        for(i=1;i<=nlstate;i++)
                   3987:          for(j=1;j<=nlstate;j++)
                   3988:            vareij[i][j][(int)age] += doldm[i][j]*hf*hf;
                   3989:       }
                   3990:     }
                   3991:   
                   3992:     /* pptj */
                   3993:     matprod2(dnewmp,trgradgp,nlstate+1,nlstate+ndeath,1,npar,1,npar,matcov);
                   3994:     matprod2(doldmp,dnewmp,nlstate+1,nlstate+ndeath,1,npar,nlstate+1,nlstate+ndeath,gradgp);
                   3995:     for(j=nlstate+1;j<=nlstate+ndeath;j++)
                   3996:       for(i=nlstate+1;i<=nlstate+ndeath;i++)
                   3997:        varppt[j][i]=doldmp[j][i];
                   3998:     /* end ppptj */
                   3999:     /*  x centered again */
                   4000:     hpxij(p3mat,nhstepm,age,hstepm,x,nlstate,stepm,oldm,savm, ij);  
                   4001:     prevalim(prlim,nlstate,x,age,oldm,savm,ftolpl,ij);
                   4002:  
                   4003:     if (popbased==1) {
                   4004:       if(mobilav ==0){
                   4005:        for(i=1; i<=nlstate;i++)
                   4006:          prlim[i][i]=probs[(int)age][i][ij];
                   4007:       }else{ /* mobilav */ 
                   4008:        for(i=1; i<=nlstate;i++)
                   4009:          prlim[i][i]=mobaverage[(int)age][i][ij];
                   4010:       }
                   4011:     }
                   4012:              
                   4013:     /* This for computing probability of death (h=1 means
                   4014:        computed over hstepm (estepm) matrices product = hstepm*stepm months) 
                   4015:        as a weighted average of prlim.
                   4016:     */
                   4017:     for(j=nlstate+1;j<=nlstate+ndeath;j++){
                   4018:       for(i=1,gmp[j]=0.;i<= nlstate; i++) 
                   4019:        gmp[j] += prlim[i][i]*p3mat[i][j][1]; 
                   4020:     }    
                   4021:     /* end probability of death */
                   4022: 
                   4023:     fprintf(ficresprobmorprev,"%3d %d ",(int) age, ij);
                   4024:     for(j=nlstate+1; j<=(nlstate+ndeath);j++){
                   4025:       fprintf(ficresprobmorprev," %11.3e %11.3e",gmp[j], sqrt(varppt[j][j]));
                   4026:       for(i=1; i<=nlstate;i++){
                   4027:        fprintf(ficresprobmorprev," %11.3e %11.3e ",prlim[i][i],p3mat[i][j][1]);
                   4028:       }
                   4029:     } 
                   4030:     fprintf(ficresprobmorprev,"\n");
                   4031: 
                   4032:     fprintf(ficresvij,"%.0f ",age );
                   4033:     for(i=1; i<=nlstate;i++)
                   4034:       for(j=1; j<=nlstate;j++){
                   4035:        fprintf(ficresvij," %.4f", vareij[i][j][(int)age]);
                   4036:       }
                   4037:     fprintf(ficresvij,"\n");
                   4038:     free_matrix(gp,0,nhstepm,1,nlstate);
                   4039:     free_matrix(gm,0,nhstepm,1,nlstate);
                   4040:     free_ma3x(gradg,0,nhstepm,1,npar,1,nlstate);
                   4041:     free_ma3x(trgradg,0,nhstepm,1,nlstate,1,npar);
                   4042:     free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   4043:   } /* End age */
                   4044:   free_vector(gpp,nlstate+1,nlstate+ndeath);
                   4045:   free_vector(gmp,nlstate+1,nlstate+ndeath);
                   4046:   free_matrix(gradgp,1,npar,nlstate+1,nlstate+ndeath);
                   4047:   free_matrix(trgradgp,nlstate+1,nlstate+ndeath,1,npar); /* mu or p point j*/
1.145     brouard  4048:   fprintf(ficgp,"\nunset parametric;unset label; set ter png small size 320, 240");
1.126     brouard  4049:   /* for(j=nlstate+1; j<= nlstate+ndeath; j++){ *//* Only the first actually */
1.131     brouard  4050:   fprintf(ficgp,"\n set log y; unset log x;set xlabel \"Age\"; set ylabel \"Force of mortality (year-1)\";");
1.126     brouard  4051: /*   fprintf(ficgp,"\n plot \"%s\"  u 1:($3*%6.3f) not w l 1 ",fileresprobmorprev,YEARM/estepm); */
                   4052: /*   fprintf(ficgp,"\n replot \"%s\"  u 1:(($3+1.96*$4)*%6.3f) t \"95\%% interval\" w l 2 ",fileresprobmorprev,YEARM/estepm); */
                   4053: /*   fprintf(ficgp,"\n replot \"%s\"  u 1:(($3-1.96*$4)*%6.3f) not w l 2 ",fileresprobmorprev,YEARM/estepm); */
1.145     brouard  4054:   fprintf(ficgp,"\n plot \"%s\"  u 1:($3) not w l lt 1 ",subdirf(fileresprobmorprev));
1.170     brouard  4055:   fprintf(ficgp,"\n replot \"%s\"  u 1:(($3+1.96*$4)) t \"95%% interval\" w l lt 2 ",subdirf(fileresprobmorprev));
1.145     brouard  4056:   fprintf(ficgp,"\n replot \"%s\"  u 1:(($3-1.96*$4)) not w l lt 2 ",subdirf(fileresprobmorprev));
1.126     brouard  4057:   fprintf(fichtm,"\n<br> File (multiple files are possible if covariates are present): <A href=\"%s\">%s</a>\n",subdirf(fileresprobmorprev),subdirf(fileresprobmorprev));
                   4058:   fprintf(fichtm,"\n<br> Probability is computed over estepm=%d months. <br> <img src=\"%s%s.png\"> <br>\n", estepm,subdirf3(optionfilefiname,"varmuptjgr",digitp),digit);
                   4059:   /*  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.png\"> <br>\n", stepm,YEARM,digitp,digit);
                   4060: */
                   4061: /*   fprintf(ficgp,"\nset out \"varmuptjgr%s%s%s.png\";replot;",digitp,optionfilefiname,digit); */
                   4062:   fprintf(ficgp,"\nset out \"%s%s.png\";replot;\n",subdirf3(optionfilefiname,"varmuptjgr",digitp),digit);
                   4063: 
                   4064:   free_vector(xp,1,npar);
                   4065:   free_matrix(doldm,1,nlstate,1,nlstate);
                   4066:   free_matrix(dnewm,1,nlstate,1,npar);
                   4067:   free_matrix(doldmp,nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);
                   4068:   free_matrix(dnewmp,nlstate+1,nlstate+ndeath,1,npar);
                   4069:   free_matrix(varppt,nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);
                   4070:   if (mobilav!=0) free_ma3x(mobaverage,1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
                   4071:   fclose(ficresprobmorprev);
                   4072:   fflush(ficgp);
                   4073:   fflush(fichtm); 
                   4074: }  /* end varevsij */
                   4075: 
                   4076: /************ Variance of prevlim ******************/
                   4077: 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 ij, char strstart[])
                   4078: {
                   4079:   /* Variance of prevalence limit */
                   4080:   /*  double **prevalim(double **prlim, int nlstate, double *xp, double age, double **oldm, double **savm,double ftolpl);*/
1.164     brouard  4081: 
1.126     brouard  4082:   double **dnewm,**doldm;
                   4083:   int i, j, nhstepm, hstepm;
                   4084:   double *xp;
                   4085:   double *gp, *gm;
                   4086:   double **gradg, **trgradg;
                   4087:   double age,agelim;
                   4088:   int theta;
                   4089:   
                   4090:   pstamp(ficresvpl);
                   4091:   fprintf(ficresvpl,"# Standard deviation of period (stable) prevalences \n");
                   4092:   fprintf(ficresvpl,"# Age");
                   4093:   for(i=1; i<=nlstate;i++)
                   4094:       fprintf(ficresvpl," %1d-%1d",i,i);
                   4095:   fprintf(ficresvpl,"\n");
                   4096: 
                   4097:   xp=vector(1,npar);
                   4098:   dnewm=matrix(1,nlstate,1,npar);
                   4099:   doldm=matrix(1,nlstate,1,nlstate);
                   4100:   
                   4101:   hstepm=1*YEARM; /* Every year of age */
                   4102:   hstepm=hstepm/stepm; /* Typically in stepm units, if j= 2 years, = 2/6 months = 4 */ 
                   4103:   agelim = AGESUP;
                   4104:   for (age=bage; age<=fage; age ++){ /* If stepm=6 months */
                   4105:     nhstepm=(int) rint((agelim-age)*YEARM/stepm); /* Typically 20 years = 20*12/6=40 */ 
                   4106:     if (stepm >= YEARM) hstepm=1;
                   4107:     nhstepm = nhstepm/hstepm; /* Typically 40/4=10 */
                   4108:     gradg=matrix(1,npar,1,nlstate);
                   4109:     gp=vector(1,nlstate);
                   4110:     gm=vector(1,nlstate);
                   4111: 
                   4112:     for(theta=1; theta <=npar; theta++){
                   4113:       for(i=1; i<=npar; i++){ /* Computes gradient */
                   4114:        xp[i] = x[i] + (i==theta ?delti[theta]:0);
                   4115:       }
                   4116:       prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ij);
                   4117:       for(i=1;i<=nlstate;i++)
                   4118:        gp[i] = prlim[i][i];
                   4119:     
                   4120:       for(i=1; i<=npar; i++) /* Computes gradient */
                   4121:        xp[i] = x[i] - (i==theta ?delti[theta]:0);
                   4122:       prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ij);
                   4123:       for(i=1;i<=nlstate;i++)
                   4124:        gm[i] = prlim[i][i];
                   4125: 
                   4126:       for(i=1;i<=nlstate;i++)
                   4127:        gradg[theta][i]= (gp[i]-gm[i])/2./delti[theta];
                   4128:     } /* End theta */
                   4129: 
                   4130:     trgradg =matrix(1,nlstate,1,npar);
                   4131: 
                   4132:     for(j=1; j<=nlstate;j++)
                   4133:       for(theta=1; theta <=npar; theta++)
                   4134:        trgradg[j][theta]=gradg[theta][j];
                   4135: 
                   4136:     for(i=1;i<=nlstate;i++)
                   4137:       varpl[i][(int)age] =0.;
                   4138:     matprod2(dnewm,trgradg,1,nlstate,1,npar,1,npar,matcov);
                   4139:     matprod2(doldm,dnewm,1,nlstate,1,npar,1,nlstate,gradg);
                   4140:     for(i=1;i<=nlstate;i++)
                   4141:       varpl[i][(int)age] = doldm[i][i]; /* Covariances are useless */
                   4142: 
                   4143:     fprintf(ficresvpl,"%.0f ",age );
                   4144:     for(i=1; i<=nlstate;i++)
                   4145:       fprintf(ficresvpl," %.5f (%.5f)",prlim[i][i],sqrt(varpl[i][(int)age]));
                   4146:     fprintf(ficresvpl,"\n");
                   4147:     free_vector(gp,1,nlstate);
                   4148:     free_vector(gm,1,nlstate);
                   4149:     free_matrix(gradg,1,npar,1,nlstate);
                   4150:     free_matrix(trgradg,1,nlstate,1,npar);
                   4151:   } /* End age */
                   4152: 
                   4153:   free_vector(xp,1,npar);
                   4154:   free_matrix(doldm,1,nlstate,1,npar);
                   4155:   free_matrix(dnewm,1,nlstate,1,nlstate);
                   4156: 
                   4157: }
                   4158: 
                   4159: /************ Variance of one-step probabilities  ******************/
                   4160: 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[])
                   4161: {
1.164     brouard  4162:   int i, j=0,  k1, l1, tj;
1.126     brouard  4163:   int k2, l2, j1,  z1;
1.164     brouard  4164:   int k=0, l;
1.145     brouard  4165:   int first=1, first1, first2;
1.126     brouard  4166:   double cv12, mu1, mu2, lc1, lc2, v12, v21, v11, v22,v1,v2, c12, tnalp;
                   4167:   double **dnewm,**doldm;
                   4168:   double *xp;
                   4169:   double *gp, *gm;
                   4170:   double **gradg, **trgradg;
                   4171:   double **mu;
1.164     brouard  4172:   double age, cov[NCOVMAX+1];
1.126     brouard  4173:   double std=2.0; /* Number of standard deviation wide of confidence ellipsoids */
                   4174:   int theta;
                   4175:   char fileresprob[FILENAMELENGTH];
                   4176:   char fileresprobcov[FILENAMELENGTH];
                   4177:   char fileresprobcor[FILENAMELENGTH];
                   4178:   double ***varpij;
                   4179: 
                   4180:   strcpy(fileresprob,"prob"); 
                   4181:   strcat(fileresprob,fileres);
                   4182:   if((ficresprob=fopen(fileresprob,"w"))==NULL) {
                   4183:     printf("Problem with resultfile: %s\n", fileresprob);
                   4184:     fprintf(ficlog,"Problem with resultfile: %s\n", fileresprob);
                   4185:   }
                   4186:   strcpy(fileresprobcov,"probcov"); 
                   4187:   strcat(fileresprobcov,fileres);
                   4188:   if((ficresprobcov=fopen(fileresprobcov,"w"))==NULL) {
                   4189:     printf("Problem with resultfile: %s\n", fileresprobcov);
                   4190:     fprintf(ficlog,"Problem with resultfile: %s\n", fileresprobcov);
                   4191:   }
                   4192:   strcpy(fileresprobcor,"probcor"); 
                   4193:   strcat(fileresprobcor,fileres);
                   4194:   if((ficresprobcor=fopen(fileresprobcor,"w"))==NULL) {
                   4195:     printf("Problem with resultfile: %s\n", fileresprobcor);
                   4196:     fprintf(ficlog,"Problem with resultfile: %s\n", fileresprobcor);
                   4197:   }
                   4198:   printf("Computing standard deviation of one-step probabilities: result on file '%s' \n",fileresprob);
                   4199:   fprintf(ficlog,"Computing standard deviation of one-step probabilities: result on file '%s' \n",fileresprob);
                   4200:   printf("Computing matrix of variance covariance of one-step probabilities: result on file '%s' \n",fileresprobcov);
                   4201:   fprintf(ficlog,"Computing matrix of variance covariance of one-step probabilities: result on file '%s' \n",fileresprobcov);
                   4202:   printf("and correlation matrix of one-step probabilities: result on file '%s' \n",fileresprobcor);
                   4203:   fprintf(ficlog,"and correlation matrix of one-step probabilities: result on file '%s' \n",fileresprobcor);
                   4204:   pstamp(ficresprob);
                   4205:   fprintf(ficresprob,"#One-step probabilities and stand. devi in ()\n");
                   4206:   fprintf(ficresprob,"# Age");
                   4207:   pstamp(ficresprobcov);
                   4208:   fprintf(ficresprobcov,"#One-step probabilities and covariance matrix\n");
                   4209:   fprintf(ficresprobcov,"# Age");
                   4210:   pstamp(ficresprobcor);
                   4211:   fprintf(ficresprobcor,"#One-step probabilities and correlation matrix\n");
                   4212:   fprintf(ficresprobcor,"# Age");
                   4213: 
                   4214: 
                   4215:   for(i=1; i<=nlstate;i++)
                   4216:     for(j=1; j<=(nlstate+ndeath);j++){
                   4217:       fprintf(ficresprob," p%1d-%1d (SE)",i,j);
                   4218:       fprintf(ficresprobcov," p%1d-%1d ",i,j);
                   4219:       fprintf(ficresprobcor," p%1d-%1d ",i,j);
                   4220:     }  
                   4221:  /* fprintf(ficresprob,"\n");
                   4222:   fprintf(ficresprobcov,"\n");
                   4223:   fprintf(ficresprobcor,"\n");
                   4224:  */
1.131     brouard  4225:   xp=vector(1,npar);
1.126     brouard  4226:   dnewm=matrix(1,(nlstate)*(nlstate+ndeath),1,npar);
                   4227:   doldm=matrix(1,(nlstate)*(nlstate+ndeath),1,(nlstate)*(nlstate+ndeath));
                   4228:   mu=matrix(1,(nlstate)*(nlstate+ndeath), (int) bage, (int)fage);
                   4229:   varpij=ma3x(1,nlstate*(nlstate+ndeath),1,nlstate*(nlstate+ndeath),(int) bage, (int) fage);
                   4230:   first=1;
                   4231:   fprintf(ficgp,"\n# Routine varprob");
                   4232:   fprintf(fichtm,"\n<li><h4> Computing and drawing one step probabilities with their confidence intervals</h4></li>\n");
                   4233:   fprintf(fichtm,"\n");
                   4234: 
1.197   ! brouard  4235:   fprintf(fichtm,"\n<li><h4> <a href=\"%s\">Matrix of variance-covariance of one-step probabilities (drawings)</a></h4></br>this page is important in order to visualize confidence intervals and especially correlation between disability and recovery</li>\n",optionfilehtmcov);
        !          4236:   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);
        !          4237:   fprintf(fichtmcov,"\nEllipsoids of confidence centered on point (p<inf>ij</inf>, p<inf>kl</inf>) are estimated \
1.126     brouard  4238: and drawn. It helps understanding how is the covariance between two incidences.\
                   4239:  They are expressed in year<sup>-1</sup> in order to be less dependent of stepm.<br>\n");
                   4240:   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. \
                   4241: It can be understood this way: if pij and pkl where uncorrelated the (2x2) matrix of covariance \
                   4242: would have been (1/(var pij), 0 , 0, 1/(var pkl)), and the confidence interval would be 2 \
                   4243: standard deviations wide on each axis. <br>\
                   4244:  Now, if both incidences are correlated (usual case) we diagonalised the inverse of the covariance matrix\
                   4245:  and made the appropriate rotation to look at the uncorrelated principal directions.<br>\
                   4246: To be simple, these graphs help to understand the significativity of each parameter in relation to a second other one.<br> \n");
                   4247: 
                   4248:   cov[1]=1;
1.145     brouard  4249:   /* tj=cptcoveff; */
                   4250:   tj = (int) pow(2,cptcoveff);
1.126     brouard  4251:   if (cptcovn<1) {tj=1;ncodemax[1]=1;}
                   4252:   j1=0;
1.145     brouard  4253:   for(j1=1; j1<=tj;j1++){
                   4254:     /*for(i1=1; i1<=ncodemax[t];i1++){ */
                   4255:     /*j1++;*/
1.126     brouard  4256:       if  (cptcovn>0) {
                   4257:        fprintf(ficresprob, "\n#********** Variable "); 
                   4258:        for (z1=1; z1<=cptcoveff; z1++) fprintf(ficresprob, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtab[j1][z1]]);
                   4259:        fprintf(ficresprob, "**********\n#\n");
                   4260:        fprintf(ficresprobcov, "\n#********** Variable "); 
                   4261:        for (z1=1; z1<=cptcoveff; z1++) fprintf(ficresprobcov, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtab[j1][z1]]);
                   4262:        fprintf(ficresprobcov, "**********\n#\n");
                   4263:        
                   4264:        fprintf(ficgp, "\n#********** Variable "); 
                   4265:        for (z1=1; z1<=cptcoveff; z1++) fprintf(ficgp, " V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtab[j1][z1]]);
                   4266:        fprintf(ficgp, "**********\n#\n");
                   4267:        
                   4268:        
                   4269:        fprintf(fichtmcov, "\n<hr  size=\"2\" color=\"#EC5E5E\">********** Variable "); 
                   4270:        for (z1=1; z1<=cptcoveff; z1++) fprintf(fichtm, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtab[j1][z1]]);
                   4271:        fprintf(fichtmcov, "**********\n<hr size=\"2\" color=\"#EC5E5E\">");
                   4272:        
                   4273:        fprintf(ficresprobcor, "\n#********** Variable ");    
                   4274:        for (z1=1; z1<=cptcoveff; z1++) fprintf(ficresprobcor, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtab[j1][z1]]);
                   4275:        fprintf(ficresprobcor, "**********\n#");    
                   4276:       }
                   4277:       
1.145     brouard  4278:       gradg=matrix(1,npar,1,(nlstate)*(nlstate+ndeath));
                   4279:       trgradg=matrix(1,(nlstate)*(nlstate+ndeath),1,npar);
                   4280:       gp=vector(1,(nlstate)*(nlstate+ndeath));
                   4281:       gm=vector(1,(nlstate)*(nlstate+ndeath));
1.126     brouard  4282:       for (age=bage; age<=fage; age ++){ 
                   4283:        cov[2]=age;
1.187     brouard  4284:        if(nagesqr==1)
                   4285:          cov[3]= age*age;
1.126     brouard  4286:        for (k=1; k<=cptcovn;k++) {
1.187     brouard  4287:          cov[2+nagesqr+k]=nbcode[Tvar[k]][codtab[j1][Tvar[k]]];/* j1 1 2 3 4
1.145     brouard  4288:                                                         * 1  1 1 1 1
                   4289:                                                         * 2  2 1 1 1
                   4290:                                                         * 3  1 2 1 1
                   4291:                                                         */
                   4292:          /* nbcode[1][1]=0 nbcode[1][2]=1;*/
1.126     brouard  4293:        }
1.186     brouard  4294:        /* for (k=1; k<=cptcovage;k++) cov[2+Tage[k]]=cov[2+Tage[k]]*cov[2]; */
                   4295:        for (k=1; k<=cptcovage;k++) cov[2+Tage[k]]=nbcode[Tvar[Tage[k]]][codtab[ij][Tvar[Tage[k]]]]*cov[2];
1.126     brouard  4296:        for (k=1; k<=cptcovprod;k++)
1.187     brouard  4297:          cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtab[ij][Tvard[k][1]]]*nbcode[Tvard[k][2]][codtab[ij][Tvard[k][2]]];
1.126     brouard  4298:        
                   4299:     
                   4300:        for(theta=1; theta <=npar; theta++){
                   4301:          for(i=1; i<=npar; i++)
                   4302:            xp[i] = x[i] + (i==theta ?delti[theta]:(double)0);
                   4303:          
                   4304:          pmij(pmmij,cov,ncovmodel,xp,nlstate);
                   4305:          
                   4306:          k=0;
                   4307:          for(i=1; i<= (nlstate); i++){
                   4308:            for(j=1; j<=(nlstate+ndeath);j++){
                   4309:              k=k+1;
                   4310:              gp[k]=pmmij[i][j];
                   4311:            }
                   4312:          }
                   4313:          
                   4314:          for(i=1; i<=npar; i++)
                   4315:            xp[i] = x[i] - (i==theta ?delti[theta]:(double)0);
                   4316:     
                   4317:          pmij(pmmij,cov,ncovmodel,xp,nlstate);
                   4318:          k=0;
                   4319:          for(i=1; i<=(nlstate); i++){
                   4320:            for(j=1; j<=(nlstate+ndeath);j++){
                   4321:              k=k+1;
                   4322:              gm[k]=pmmij[i][j];
                   4323:            }
                   4324:          }
                   4325:      
                   4326:          for(i=1; i<= (nlstate)*(nlstate+ndeath); i++) 
                   4327:            gradg[theta][i]=(gp[i]-gm[i])/(double)2./delti[theta];  
                   4328:        }
                   4329: 
                   4330:        for(j=1; j<=(nlstate)*(nlstate+ndeath);j++)
                   4331:          for(theta=1; theta <=npar; theta++)
                   4332:            trgradg[j][theta]=gradg[theta][j];
                   4333:        
                   4334:        matprod2(dnewm,trgradg,1,(nlstate)*(nlstate+ndeath),1,npar,1,npar,matcov); 
                   4335:        matprod2(doldm,dnewm,1,(nlstate)*(nlstate+ndeath),1,npar,1,(nlstate)*(nlstate+ndeath),gradg);
                   4336: 
                   4337:        pmij(pmmij,cov,ncovmodel,x,nlstate);
                   4338:        
                   4339:        k=0;
                   4340:        for(i=1; i<=(nlstate); i++){
                   4341:          for(j=1; j<=(nlstate+ndeath);j++){
                   4342:            k=k+1;
                   4343:            mu[k][(int) age]=pmmij[i][j];
                   4344:          }
                   4345:        }
                   4346:        for(i=1;i<=(nlstate)*(nlstate+ndeath);i++)
                   4347:          for(j=1;j<=(nlstate)*(nlstate+ndeath);j++)
                   4348:            varpij[i][j][(int)age] = doldm[i][j];
                   4349: 
                   4350:        /*printf("\n%d ",(int)age);
                   4351:          for (i=1; i<=(nlstate)*(nlstate+ndeath);i++){
                   4352:          printf("%e [%e ;%e] ",gm[i],gm[i]-2*sqrt(doldm[i][i]),gm[i]+2*sqrt(doldm[i][i]));
                   4353:          fprintf(ficlog,"%e [%e ;%e] ",gm[i],gm[i]-2*sqrt(doldm[i][i]),gm[i]+2*sqrt(doldm[i][i]));
                   4354:          }*/
                   4355: 
                   4356:        fprintf(ficresprob,"\n%d ",(int)age);
                   4357:        fprintf(ficresprobcov,"\n%d ",(int)age);
                   4358:        fprintf(ficresprobcor,"\n%d ",(int)age);
                   4359: 
                   4360:        for (i=1; i<=(nlstate)*(nlstate+ndeath);i++)
                   4361:          fprintf(ficresprob,"%11.3e (%11.3e) ",mu[i][(int) age],sqrt(varpij[i][i][(int)age]));
                   4362:        for (i=1; i<=(nlstate)*(nlstate+ndeath);i++){
                   4363:          fprintf(ficresprobcov,"%11.3e ",mu[i][(int) age]);
                   4364:          fprintf(ficresprobcor,"%11.3e ",mu[i][(int) age]);
                   4365:        }
                   4366:        i=0;
                   4367:        for (k=1; k<=(nlstate);k++){
                   4368:          for (l=1; l<=(nlstate+ndeath);l++){ 
1.145     brouard  4369:            i++;
1.126     brouard  4370:            fprintf(ficresprobcov,"\n%d %d-%d",(int)age,k,l);
                   4371:            fprintf(ficresprobcor,"\n%d %d-%d",(int)age,k,l);
                   4372:            for (j=1; j<=i;j++){
1.145     brouard  4373:              /* printf(" k=%d l=%d i=%d j=%d\n",k,l,i,j);fflush(stdout); */
1.126     brouard  4374:              fprintf(ficresprobcov," %11.3e",varpij[i][j][(int)age]);
                   4375:              fprintf(ficresprobcor," %11.3e",varpij[i][j][(int) age]/sqrt(varpij[i][i][(int) age])/sqrt(varpij[j][j][(int)age]));
                   4376:            }
                   4377:          }
                   4378:        }/* end of loop for state */
                   4379:       } /* end of loop for age */
1.145     brouard  4380:       free_vector(gp,1,(nlstate+ndeath)*(nlstate+ndeath));
                   4381:       free_vector(gm,1,(nlstate+ndeath)*(nlstate+ndeath));
                   4382:       free_matrix(trgradg,1,(nlstate+ndeath)*(nlstate+ndeath),1,npar);
                   4383:       free_matrix(gradg,1,(nlstate+ndeath)*(nlstate+ndeath),1,npar);
                   4384:       
1.126     brouard  4385:       /* Confidence intervalle of pij  */
                   4386:       /*
1.131     brouard  4387:        fprintf(ficgp,"\nunset parametric;unset label");
1.126     brouard  4388:        fprintf(ficgp,"\nset log y;unset log x; set xlabel \"Age\";set ylabel \"probability (year-1)\"");
                   4389:        fprintf(ficgp,"\nset ter png small\nset size 0.65,0.65");
                   4390:        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);
                   4391:        fprintf(fichtm,"\n<br><img src=\"pijgr%s.png\"> ",optionfilefiname);
                   4392:        fprintf(ficgp,"\nset out \"pijgr%s.png\"",optionfilefiname);
                   4393:        fprintf(ficgp,"\nplot \"%s\" every :::%d::%d u 1:2 \"\%%lf",k1,k2,xfilevarprob);
                   4394:       */
                   4395: 
                   4396:       /* Drawing ellipsoids of confidence of two variables p(k1-l1,k2-l2)*/
1.145     brouard  4397:       first1=1;first2=2;
1.126     brouard  4398:       for (k2=1; k2<=(nlstate);k2++){
                   4399:        for (l2=1; l2<=(nlstate+ndeath);l2++){ 
                   4400:          if(l2==k2) continue;
                   4401:          j=(k2-1)*(nlstate+ndeath)+l2;
                   4402:          for (k1=1; k1<=(nlstate);k1++){
                   4403:            for (l1=1; l1<=(nlstate+ndeath);l1++){ 
                   4404:              if(l1==k1) continue;
                   4405:              i=(k1-1)*(nlstate+ndeath)+l1;
                   4406:              if(i<=j) continue;
                   4407:              for (age=bage; age<=fage; age ++){ 
                   4408:                if ((int)age %5==0){
                   4409:                  v1=varpij[i][i][(int)age]/stepm*YEARM/stepm*YEARM;
                   4410:                  v2=varpij[j][j][(int)age]/stepm*YEARM/stepm*YEARM;
                   4411:                  cv12=varpij[i][j][(int)age]/stepm*YEARM/stepm*YEARM;
                   4412:                  mu1=mu[i][(int) age]/stepm*YEARM ;
                   4413:                  mu2=mu[j][(int) age]/stepm*YEARM;
                   4414:                  c12=cv12/sqrt(v1*v2);
                   4415:                  /* Computing eigen value of matrix of covariance */
                   4416:                  lc1=((v1+v2)+sqrt((v1+v2)*(v1+v2) - 4*(v1*v2-cv12*cv12)))/2.;
                   4417:                  lc2=((v1+v2)-sqrt((v1+v2)*(v1+v2) - 4*(v1*v2-cv12*cv12)))/2.;
1.135     brouard  4418:                  if ((lc2 <0) || (lc1 <0) ){
1.145     brouard  4419:                    if(first2==1){
                   4420:                      first1=0;
                   4421:                    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);
                   4422:                    }
                   4423:                    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);
                   4424:                    /* lc1=fabs(lc1); */ /* If we want to have them positive */
                   4425:                    /* lc2=fabs(lc2); */
1.135     brouard  4426:                  }
                   4427: 
1.126     brouard  4428:                  /* Eigen vectors */
                   4429:                  v11=(1./sqrt(1+(v1-lc1)*(v1-lc1)/cv12/cv12));
                   4430:                  /*v21=sqrt(1.-v11*v11); *//* error */
                   4431:                  v21=(lc1-v1)/cv12*v11;
                   4432:                  v12=-v21;
                   4433:                  v22=v11;
                   4434:                  tnalp=v21/v11;
                   4435:                  if(first1==1){
                   4436:                    first1=0;
                   4437:                    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);
                   4438:                  }
                   4439:                  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);
                   4440:                  /*printf(fignu*/
                   4441:                  /* mu1+ v11*lc1*cost + v12*lc2*sin(t) */
                   4442:                  /* mu2+ v21*lc1*cost + v22*lc2*sin(t) */
                   4443:                  if(first==1){
                   4444:                    first=0;
                   4445:                    fprintf(ficgp,"\nset parametric;unset label");
                   4446:                    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.145     brouard  4447:                    fprintf(ficgp,"\nset ter png small size 320, 240");
1.126     brouard  4448:                    fprintf(fichtmcov,"\n<br>Ellipsoids of confidence cov(p%1d%1d,p%1d%1d) expressed in year<sup>-1</sup>\
                   4449:  :<a href=\"%s%d%1d%1d-%1d%1d.png\">\
                   4450: %s%d%1d%1d-%1d%1d.png</A>, ",k1,l1,k2,l2,\
                   4451:                            subdirf2(optionfilefiname,"varpijgr"), j1,k1,l1,k2,l2,\
                   4452:                            subdirf2(optionfilefiname,"varpijgr"), j1,k1,l1,k2,l2);
                   4453:                    fprintf(fichtmcov,"\n<br><img src=\"%s%d%1d%1d-%1d%1d.png\"> ",subdirf2(optionfilefiname,"varpijgr"), j1,k1,l1,k2,l2);
                   4454:                    fprintf(fichtmcov,"\n<br> Correlation at age %d (%.3f),",(int) age, c12);
                   4455:                    fprintf(ficgp,"\nset out \"%s%d%1d%1d-%1d%1d.png\"",subdirf2(optionfilefiname,"varpijgr"), j1,k1,l1,k2,l2);
                   4456:                    fprintf(ficgp,"\nset label \"%d\" at %11.3e,%11.3e center",(int) age, mu1,mu2);
                   4457:                    fprintf(ficgp,"\n# Age %d, p%1d%1d - p%1d%1d",(int) age, k1,l1,k2,l2);
                   4458:                    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",\
                   4459:                            mu1,std,v11,sqrt(lc1),v12,sqrt(lc2),\
                   4460:                            mu2,std,v21,sqrt(lc1),v22,sqrt(lc2));
                   4461:                  }else{
                   4462:                    first=0;
                   4463:                    fprintf(fichtmcov," %d (%.3f),",(int) age, c12);
                   4464:                    fprintf(ficgp,"\n# Age %d, p%1d%1d - p%1d%1d",(int) age, k1,l1,k2,l2);
                   4465:                    fprintf(ficgp,"\nset label \"%d\" at %11.3e,%11.3e center",(int) age, mu1,mu2);
                   4466:                    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",\
                   4467:                            mu1,std,v11,sqrt(lc1),v12,sqrt(lc2),\
                   4468:                            mu2,std,v21,sqrt(lc1),v22,sqrt(lc2));
                   4469:                  }/* if first */
                   4470:                } /* age mod 5 */
                   4471:              } /* end loop age */
                   4472:              fprintf(ficgp,"\nset out \"%s%d%1d%1d-%1d%1d.png\";replot;",subdirf2(optionfilefiname,"varpijgr"), j1,k1,l1,k2,l2);
                   4473:              first=1;
                   4474:            } /*l12 */
                   4475:          } /* k12 */
                   4476:        } /*l1 */
                   4477:       }/* k1 */
1.169     brouard  4478:       /* } */ /* loop covariates */
1.126     brouard  4479:   }
                   4480:   free_ma3x(varpij,1,nlstate,1,nlstate+ndeath,(int) bage, (int)fage);
                   4481:   free_matrix(mu,1,(nlstate+ndeath)*(nlstate+ndeath),(int) bage, (int)fage);
                   4482:   free_matrix(doldm,1,(nlstate)*(nlstate+ndeath),1,(nlstate)*(nlstate+ndeath));
                   4483:   free_matrix(dnewm,1,(nlstate)*(nlstate+ndeath),1,npar);
                   4484:   free_vector(xp,1,npar);
                   4485:   fclose(ficresprob);
                   4486:   fclose(ficresprobcov);
                   4487:   fclose(ficresprobcor);
                   4488:   fflush(ficgp);
                   4489:   fflush(fichtmcov);
                   4490: }
                   4491: 
                   4492: 
                   4493: /******************* Printing html file ***********/
                   4494: void printinghtml(char fileres[], char title[], char datafile[], int firstpass, \
                   4495:                  int lastpass, int stepm, int weightopt, char model[],\
                   4496:                  int imx,int jmin, int jmax, double jmeanint,char rfileres[],\
                   4497:                  int popforecast, int estepm ,\
                   4498:                  double jprev1, double mprev1,double anprev1, \
                   4499:                  double jprev2, double mprev2,double anprev2){
                   4500:   int jj1, k1, i1, cpt;
                   4501: 
                   4502:    fprintf(fichtm,"<ul><li><a href='#firstorder'>Result files (first order: no variance)</a>\n \
                   4503:    <li><a href='#secondorder'>Result files (second order (variance)</a>\n \
                   4504: </ul>");
                   4505:    fprintf(fichtm,"<ul><li><h4><a name='firstorder'>Result files (first order: no variance)</a></h4>\n \
                   4506:  - Observed prevalence in each state (during the period defined between %.lf/%.lf/%.lf and %.lf/%.lf/%.lf): <a href=\"%s\">%s</a> <br>\n ",
                   4507:           jprev1, mprev1,anprev1,jprev2, mprev2,anprev2,subdirf2(fileres,"p"),subdirf2(fileres,"p"));
                   4508:    fprintf(fichtm,"\
                   4509:  - Estimated transition probabilities over %d (stepm) months: <a href=\"%s\">%s</a><br>\n ",
                   4510:           stepm,subdirf2(fileres,"pij"),subdirf2(fileres,"pij"));
                   4511:    fprintf(fichtm,"\
                   4512:  - Period (stable) prevalence in each health state: <a href=\"%s\">%s</a> <br>\n",
                   4513:           subdirf2(fileres,"pl"),subdirf2(fileres,"pl"));
                   4514:    fprintf(fichtm,"\
1.128     brouard  4515:  - (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  4516:    <a href=\"%s\">%s</a> <br>\n",
                   4517:           estepm,subdirf2(fileres,"e"),subdirf2(fileres,"e"));
                   4518:    fprintf(fichtm,"\
                   4519:  - Population projections by age and states: \
                   4520:    <a href=\"%s\">%s</a> <br>\n</li>", subdirf2(fileres,"f"),subdirf2(fileres,"f"));
                   4521: 
                   4522: fprintf(fichtm," \n<ul><li><b>Graphs</b></li><p>");
                   4523: 
1.145     brouard  4524:  m=pow(2,cptcoveff);
1.126     brouard  4525:  if (cptcovn < 1) {m=1;ncodemax[1]=1;}
                   4526: 
                   4527:  jj1=0;
                   4528:  for(k1=1; k1<=m;k1++){
1.192     brouard  4529:    /* for(i1=1; i1<=ncodemax[k1];i1++){ */
1.126     brouard  4530:      jj1++;
                   4531:      if (cptcovn > 0) {
                   4532:        fprintf(fichtm,"<hr  size=\"2\" color=\"#EC5E5E\">************ Results for covariates");
1.192     brouard  4533:        for (cpt=1; cpt<=cptcoveff;cpt++){ 
1.126     brouard  4534:         fprintf(fichtm," V%d=%d ",Tvaraff[cpt],nbcode[Tvaraff[cpt]][codtab[jj1][cpt]]);
1.192     brouard  4535:         printf(" V%d=%d ",Tvaraff[cpt],nbcode[Tvaraff[cpt]][codtab[jj1][cpt]]);fflush(stdout);
                   4536:        }
1.126     brouard  4537:        fprintf(fichtm," ************\n<hr size=\"2\" color=\"#EC5E5E\">");
                   4538:      }
                   4539:      /* Pij */
1.145     brouard  4540:      fprintf(fichtm,"<br>- Pij or Conditional probabilities to be observed in state j being in state i, %d (stepm) months before: <a href=\"%s%d_1.png\">%s%d_1.png</a><br> \
                   4541: <img src=\"%s%d_1.png\">",stepm,subdirf2(optionfilefiname,"pe"),jj1,subdirf2(optionfilefiname,"pe"),jj1,subdirf2(optionfilefiname,"pe"),jj1);     
1.126     brouard  4542:      /* Quasi-incidences */
                   4543:      fprintf(fichtm,"<br>- Pij or Conditional probabilities to be observed in state j being in state i %d (stepm) months\
1.145     brouard  4544:  before but expressed in per year i.e. quasi incidences if stepm is small and probabilities too: <a href=\"%s%d_2.png\">%s%d_2.png</a><br> \
                   4545: <img src=\"%s%d_2.png\">",stepm,subdirf2(optionfilefiname,"pe"),jj1,subdirf2(optionfilefiname,"pe"),jj1,subdirf2(optionfilefiname,"pe"),jj1); 
1.126     brouard  4546:        /* Period (stable) prevalence in each health state */
1.154     brouard  4547:        for(cpt=1; cpt<=nlstate;cpt++){
1.166     brouard  4548:         fprintf(fichtm,"<br>- 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.png\">%s%d_%d.png</a><br> \
                   4549: <img src=\"%s%d_%d.png\">", cpt, cpt, nlstate, subdirf2(optionfilefiname,"p"),cpt,jj1,subdirf2(optionfilefiname,"p"),cpt,jj1,subdirf2(optionfilefiname,"p"),cpt,jj1);
1.126     brouard  4550:        }
                   4551:      for(cpt=1; cpt<=nlstate;cpt++) {
1.154     brouard  4552:         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) : <a href=\"%s%d%d.png\">%s%d%d.png</a> <br> \
                   4553: <img src=\"%s%d%d.png\">",cpt,nlstate,subdirf2(optionfilefiname,"exp"),cpt,jj1,subdirf2(optionfilefiname,"exp"),cpt,jj1,subdirf2(optionfilefiname,"exp"),cpt,jj1);
1.126     brouard  4554:      }
1.192     brouard  4555:    /* } /\* end i1 *\/ */
1.126     brouard  4556:  }/* End k1 */
                   4557:  fprintf(fichtm,"</ul>");
                   4558: 
                   4559:  fprintf(fichtm,"\
                   4560: \n<br><li><h4> <a name='secondorder'>Result files (second order: variances)</a></h4>\n\
1.193     brouard  4561:  - Parameter file with estimated parameters and covariance matrix: <a href=\"%s\">%s</a> <br> \
1.197   ! brouard  4562:  - 95%% confidence intervals and Wald tests of the estimated parameters are in the log file.<br> \
        !          4563: But because parameters are usually highly correlated (a higher incidence of disability \
        !          4564: and a higher incidence of recovery can give very close observed transition) it might \
        !          4565: be very useful to look not only at linear confidence intervals estimated from the \
        !          4566: variances but at the covariance matrix. And instead of looking at the estimated coefficients \
        !          4567: (parameters) of the logistic regression, it might be more meaningful to visualize the \
        !          4568: covariance matrix of the one-step probabilities. \
        !          4569: See page 'Matrix of variance-covariance of one-step probabilities' below. \n", rfileres,rfileres);
1.126     brouard  4570: 
1.193     brouard  4571:  fprintf(fichtm," - Standard deviation of one-step probabilities: <a href=\"%s\">%s</a> <br>\n",
1.126     brouard  4572:         subdirf2(fileres,"prob"),subdirf2(fileres,"prob"));
                   4573:  fprintf(fichtm,"\
                   4574:  - Variance-covariance of one-step probabilities: <a href=\"%s\">%s</a> <br>\n",
                   4575:         subdirf2(fileres,"probcov"),subdirf2(fileres,"probcov"));
                   4576: 
                   4577:  fprintf(fichtm,"\
                   4578:  - Correlation matrix of one-step probabilities: <a href=\"%s\">%s</a> <br>\n",
                   4579:         subdirf2(fileres,"probcor"),subdirf2(fileres,"probcor"));
                   4580:  fprintf(fichtm,"\
                   4581:  - 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): \
                   4582:    <a href=\"%s\">%s</a> <br>\n</li>",
                   4583:           estepm,subdirf2(fileres,"cve"),subdirf2(fileres,"cve"));
                   4584:  fprintf(fichtm,"\
                   4585:  - (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): \
                   4586:    <a href=\"%s\">%s</a> <br>\n</li>",
                   4587:           estepm,subdirf2(fileres,"stde"),subdirf2(fileres,"stde"));
                   4588:  fprintf(fichtm,"\
1.128     brouard  4589:  - 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.126     brouard  4590:         estepm, subdirf2(fileres,"v"),subdirf2(fileres,"v"));
                   4591:  fprintf(fichtm,"\
1.128     brouard  4592:  - 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",
                   4593:         estepm, subdirf2(fileres,"t"),subdirf2(fileres,"t"));
1.126     brouard  4594:  fprintf(fichtm,"\
                   4595:  - Standard deviation of period (stable) prevalences: <a href=\"%s\">%s</a> <br>\n",\
                   4596:         subdirf2(fileres,"vpl"),subdirf2(fileres,"vpl"));
                   4597: 
                   4598: /*  if(popforecast==1) fprintf(fichtm,"\n */
                   4599: /*  - Prevalences forecasting: <a href=\"f%s\">f%s</a> <br>\n */
                   4600: /*  - Population forecasting (if popforecast=1): <a href=\"pop%s\">pop%s</a> <br>\n */
                   4601: /*     <br>",fileres,fileres,fileres,fileres); */
                   4602: /*  else  */
                   4603: /*    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); */
                   4604:  fflush(fichtm);
                   4605:  fprintf(fichtm," <ul><li><b>Graphs</b></li><p>");
                   4606: 
1.145     brouard  4607:  m=pow(2,cptcoveff);
1.126     brouard  4608:  if (cptcovn < 1) {m=1;ncodemax[1]=1;}
                   4609: 
                   4610:  jj1=0;
                   4611:  for(k1=1; k1<=m;k1++){
1.192     brouard  4612:    /* for(i1=1; i1<=ncodemax[k1];i1++){ */
1.126     brouard  4613:      jj1++;
                   4614:      if (cptcovn > 0) {
                   4615:        fprintf(fichtm,"<hr  size=\"2\" color=\"#EC5E5E\">************ Results for covariates");
                   4616:        for (cpt=1; cpt<=cptcoveff;cpt++) 
                   4617:         fprintf(fichtm," V%d=%d ",Tvaraff[cpt],nbcode[Tvaraff[cpt]][codtab[jj1][cpt]]);
                   4618:        fprintf(fichtm," ************\n<hr size=\"2\" color=\"#EC5E5E\">");
                   4619:      }
                   4620:      for(cpt=1; cpt<=nlstate;cpt++) {
                   4621:        fprintf(fichtm,"<br>- Observed (cross-sectional) and period (incidence based) \
1.145     brouard  4622: prevalence (with 95%% confidence interval) in state (%d): %s%d_%d.png <br>\
                   4623: <img src=\"%s%d_%d.png\">",cpt,subdirf2(optionfilefiname,"v"),cpt,jj1,subdirf2(optionfilefiname,"v"),cpt,jj1);  
1.126     brouard  4624:      }
                   4625:      fprintf(fichtm,"\n<br>- Total life expectancy by age and \
1.128     brouard  4626: health expectancies in states (1) and (2). If popbased=1 the smooth (due to the model) \
                   4627: true period expectancies (those weighted with period prevalences are also\
                   4628:  drawn in addition to the population based expectancies computed using\
                   4629:  observed and cahotic prevalences: %s%d.png<br>\
1.126     brouard  4630: <img src=\"%s%d.png\">",subdirf2(optionfilefiname,"e"),jj1,subdirf2(optionfilefiname,"e"),jj1);
1.192     brouard  4631:    /* } /\* end i1 *\/ */
1.126     brouard  4632:  }/* End k1 */
                   4633:  fprintf(fichtm,"</ul>");
                   4634:  fflush(fichtm);
                   4635: }
                   4636: 
                   4637: /******************* Gnuplot file **************/
                   4638: void printinggnuplot(char fileres[], char optionfilefiname[], double ageminpar, double agemaxpar, double fage , char pathc[], double p[]){
                   4639: 
                   4640:   char dirfileres[132],optfileres[132];
1.164     brouard  4641:   int cpt=0,k1=0,i=0,k=0,j=0,jk=0,k2=0,k3=0,ij=0,l=0;
1.130     brouard  4642:   int ng=0;
1.126     brouard  4643: /*   if((ficgp=fopen(optionfilegnuplot,"a"))==NULL) { */
                   4644: /*     printf("Problem with file %s",optionfilegnuplot); */
                   4645: /*     fprintf(ficlog,"Problem with file %s",optionfilegnuplot); */
                   4646: /*   } */
                   4647: 
                   4648:   /*#ifdef windows */
                   4649:   fprintf(ficgp,"cd \"%s\" \n",pathc);
                   4650:     /*#endif */
                   4651:   m=pow(2,cptcoveff);
                   4652: 
                   4653:   strcpy(dirfileres,optionfilefiname);
                   4654:   strcpy(optfileres,"vpl");
                   4655:  /* 1eme*/
1.153     brouard  4656:   fprintf(ficgp,"\n# 1st: Period (stable) prevalence with CI: 'vpl' files\n");
1.126     brouard  4657:   for (cpt=1; cpt<= nlstate ; cpt ++) {
1.145     brouard  4658:     for (k1=1; k1<= m ; k1 ++) { /* plot [100000000000000000000:-100000000000000000000] "mysbiaspar/vplrmysbiaspar.txt to check */
                   4659:      fprintf(ficgp,"\nset out \"%s%d_%d.png\" \n",subdirf2(optionfilefiname,"v"),cpt,k1);
                   4660:      fprintf(ficgp,"\n#set out \"v%s%d_%d.png\" \n",optionfilefiname,cpt,k1);
1.126     brouard  4661:      fprintf(ficgp,"set xlabel \"Age\" \n\
                   4662: set ylabel \"Probability\" \n\
1.145     brouard  4663: set ter png small size 320, 240\n\
1.170     brouard  4664: plot [%.f:%.f] \"%s\" every :::%d::%d u 1:2 \"%%lf",ageminpar,fage,subdirf2(fileres,"vpl"),k1-1,k1-1);
1.126     brouard  4665: 
                   4666:      for (i=1; i<= nlstate ; i ++) {
1.170     brouard  4667:        if (i==cpt) fprintf(ficgp," %%lf (%%lf)");
                   4668:        else        fprintf(ficgp," %%*lf (%%*lf)");
1.126     brouard  4669:      }
1.170     brouard  4670:      fprintf(ficgp,"\" t\"Period (stable) prevalence\" w l lt 0,\"%s\" every :::%d::%d u 1:($2+1.96*$3) \"%%lf",subdirf2(fileres,"vpl"),k1-1,k1-1);
1.126     brouard  4671:      for (i=1; i<= nlstate ; i ++) {
1.170     brouard  4672:        if (i==cpt) fprintf(ficgp," %%lf (%%lf)");
                   4673:        else fprintf(ficgp," %%*lf (%%*lf)");
1.126     brouard  4674:      } 
1.170     brouard  4675:      fprintf(ficgp,"\" t\"95%% CI\" w l lt 1,\"%s\" every :::%d::%d u 1:($2-1.96*$3) \"%%lf",subdirf2(fileres,"vpl"),k1-1,k1-1); 
1.126     brouard  4676:      for (i=1; i<= nlstate ; i ++) {
1.170     brouard  4677:        if (i==cpt) fprintf(ficgp," %%lf (%%lf)");
                   4678:        else fprintf(ficgp," %%*lf (%%*lf)");
1.126     brouard  4679:      }  
1.145     brouard  4680:      fprintf(ficgp,"\" t\"\" w l lt 1,\"%s\" every :::%d::%d u 1:($%d) t\"Observed prevalence \" w l lt 2",subdirf2(fileres,"p"),k1-1,k1-1,2+4*(cpt-1));
1.126     brouard  4681:    }
                   4682:   }
                   4683:   /*2 eme*/
1.153     brouard  4684:   fprintf(ficgp,"\n# 2nd: Total life expectancy with CI: 't' files\n");
1.126     brouard  4685:   for (k1=1; k1<= m ; k1 ++) { 
                   4686:     fprintf(ficgp,"\nset out \"%s%d.png\" \n",subdirf2(optionfilefiname,"e"),k1);
1.145     brouard  4687:     fprintf(ficgp,"set ylabel \"Years\" \nset ter png small size 320, 240\nplot [%.f:%.f] ",ageminpar,fage);
1.126     brouard  4688:     
                   4689:     for (i=1; i<= nlstate+1 ; i ++) {
                   4690:       k=2*i;
1.170     brouard  4691:       fprintf(ficgp,"\"%s\" every :::%d::%d u 1:2 \"%%lf",subdirf2(fileres,"t"),k1-1,k1-1);
1.126     brouard  4692:       for (j=1; j<= nlstate+1 ; j ++) {
1.170     brouard  4693:        if (j==i) fprintf(ficgp," %%lf (%%lf)");
                   4694:        else fprintf(ficgp," %%*lf (%%*lf)");
1.126     brouard  4695:       }   
                   4696:       if (i== 1) fprintf(ficgp,"\" t\"TLE\" w l ,");
                   4697:       else fprintf(ficgp,"\" t\"LE in state (%d)\" w l ,",i-1);
1.170     brouard  4698:       fprintf(ficgp,"\"%s\" every :::%d::%d u 1:($2-$3*2) \"%%lf",subdirf2(fileres,"t"),k1-1,k1-1);
1.126     brouard  4699:       for (j=1; j<= nlstate+1 ; j ++) {
1.170     brouard  4700:        if (j==i) fprintf(ficgp," %%lf (%%lf)");
                   4701:        else fprintf(ficgp," %%*lf (%%*lf)");
1.126     brouard  4702:       }   
1.145     brouard  4703:       fprintf(ficgp,"\" t\"\" w l lt 0,");
1.170     brouard  4704:       fprintf(ficgp,"\"%s\" every :::%d::%d u 1:($2+$3*2) \"%%lf",subdirf2(fileres,"t"),k1-1,k1-1);
1.126     brouard  4705:       for (j=1; j<= nlstate+1 ; j ++) {
1.170     brouard  4706:        if (j==i) fprintf(ficgp," %%lf (%%lf)");
                   4707:        else fprintf(ficgp," %%*lf (%%*lf)");
1.126     brouard  4708:       }   
1.145     brouard  4709:       if (i== (nlstate+1)) fprintf(ficgp,"\" t\"\" w l lt 0");
                   4710:       else fprintf(ficgp,"\" t\"\" w l lt 0,");
1.126     brouard  4711:     }
                   4712:   }
                   4713:   
                   4714:   /*3eme*/
                   4715:   
                   4716:   for (k1=1; k1<= m ; k1 ++) { 
                   4717:     for (cpt=1; cpt<= nlstate ; cpt ++) {
                   4718:       /*       k=2+nlstate*(2*cpt-2); */
                   4719:       k=2+(nlstate+1)*(cpt-1);
                   4720:       fprintf(ficgp,"\nset out \"%s%d%d.png\" \n",subdirf2(optionfilefiname,"exp"),cpt,k1);
1.145     brouard  4721:       fprintf(ficgp,"set ter png small size 320, 240\n\
1.126     brouard  4722: plot [%.f:%.f] \"%s\" every :::%d::%d u 1:%d t \"e%d1\" w l",ageminpar,fage,subdirf2(fileres,"e"),k1-1,k1-1,k,cpt);
                   4723:       /*fprintf(ficgp,",\"e%s\" every :::%d::%d u 1:($%d-2*$%d) \"\%%lf ",fileres,k1-1,k1-1,k,k+1);
                   4724:        for (i=1; i<= nlstate*2 ; i ++) fprintf(ficgp,"\%%lf (\%%lf) ");
                   4725:        fprintf(ficgp,"\" t \"e%d1\" w l",cpt);
                   4726:        fprintf(ficgp,",\"e%s\" every :::%d::%d u 1:($%d+2*$%d) \"\%%lf ",fileres,k1-1,k1-1,k,k+1);
                   4727:        for (i=1; i<= nlstate*2 ; i ++) fprintf(ficgp,"\%%lf (\%%lf) ");
                   4728:        fprintf(ficgp,"\" t \"e%d1\" w l",cpt);
                   4729:        
                   4730:       */
                   4731:       for (i=1; i< nlstate ; i ++) {
                   4732:        fprintf(ficgp," ,\"%s\" every :::%d::%d u 1:%d t \"e%d%d\" w l",subdirf2(fileres,"e"),k1-1,k1-1,k+i,cpt,i+1);
                   4733:        /*      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);*/
                   4734:        
                   4735:       } 
                   4736:       fprintf(ficgp," ,\"%s\" every :::%d::%d u 1:%d t \"e%d.\" w l",subdirf2(fileres,"e"),k1-1,k1-1,k+nlstate,cpt);
                   4737:     }
                   4738:   }
                   4739:   
                   4740:   /* CV preval stable (period) */
1.153     brouard  4741:   for (k1=1; k1<= m ; k1 ++) { /* For each multivariate if any */
                   4742:     for (cpt=1; cpt<=nlstate ; cpt ++) { /* For each life state */
1.126     brouard  4743:       k=3;
1.153     brouard  4744:       fprintf(ficgp,"\n#\n#\n#CV preval stable (period): 'pij' files, cov=%d state=%d",k1, cpt);
1.145     brouard  4745:       fprintf(ficgp,"\nset out \"%s%d_%d.png\" \n",subdirf2(optionfilefiname,"p"),cpt,k1);
1.126     brouard  4746:       fprintf(ficgp,"set xlabel \"Age\" \nset ylabel \"Probability\" \n\
1.145     brouard  4747: set ter png small size 320, 240\n\
1.126     brouard  4748: unset log y\n\
1.153     brouard  4749: plot [%.f:%.f]  ", ageminpar, agemaxpar);
                   4750:       for (i=1; i<= nlstate ; i ++){
                   4751:        if(i==1)
                   4752:          fprintf(ficgp,"\"%s\"",subdirf2(fileres,"pij"));
                   4753:        else
                   4754:          fprintf(ficgp,", '' ");
1.154     brouard  4755:        l=(nlstate+ndeath)*(i-1)+1;
                   4756:        fprintf(ficgp," u ($1==%d ? ($3):1/0):($%d/($%d",k1,k+l+(cpt-1),k+l);
1.153     brouard  4757:        for (j=1; j<= (nlstate-1) ; j ++)
                   4758:          fprintf(ficgp,"+$%d",k+l+j);
                   4759:        fprintf(ficgp,")) t \"prev(%d,%d)\" w l",i,cpt);
                   4760:       } /* nlstate */
                   4761:       fprintf(ficgp,"\n");
                   4762:     } /* end cpt state*/ 
                   4763:   } /* end covariate */  
1.126     brouard  4764:   
                   4765:   /* proba elementaires */
1.187     brouard  4766:   fprintf(ficgp,"\n##############\n#MLE estimated parameters\n#############\n");
1.126     brouard  4767:   for(i=1,jk=1; i <=nlstate; i++){
1.187     brouard  4768:     fprintf(ficgp,"# initial state %d\n",i);
1.126     brouard  4769:     for(k=1; k <=(nlstate+ndeath); k++){
                   4770:       if (k != i) {
1.187     brouard  4771:        fprintf(ficgp,"#   current state %d\n",k);
1.126     brouard  4772:        for(j=1; j <=ncovmodel; j++){
1.187     brouard  4773:          fprintf(ficgp,"p%d=%f; ",jk,p[jk]);
1.126     brouard  4774:          jk++; 
                   4775:        }
1.187     brouard  4776:        fprintf(ficgp,"\n");
1.126     brouard  4777:       }
                   4778:     }
                   4779:    }
1.187     brouard  4780:   fprintf(ficgp,"##############\n#\n");
                   4781: 
1.145     brouard  4782:   /*goto avoid;*/
1.187     brouard  4783:   fprintf(ficgp,"\n##############\n#Graphics of of probabilities or incidences\n#############\n");
                   4784:   fprintf(ficgp,"# logi(p12/p11)=a12+b12*age+c12age*age+d12*V1+e12*V1*age\n");
                   4785:   fprintf(ficgp,"# logi(p12/p11)=p1 +p2*age +p3*age*age+ p4*V1+ p5*V1*age\n");
                   4786:   fprintf(ficgp,"# logi(p13/p11)=a13+b13*age+c13age*age+d13*V1+e13*V1*age\n");
                   4787:   fprintf(ficgp,"# logi(p13/p11)=p6 +p7*age +p8*age*age+ p9*V1+ p10*V1*age\n");
                   4788:   fprintf(ficgp,"# p12+p13+p14+p11=1=p11(1+exp(a12+b12*age+c12age*age+d12*V1+e12*V1*age)\n");
                   4789:   fprintf(ficgp,"#                      +exp(a13+b13*age+c13age*age+d13*V1+e13*V1*age)+...)\n");
                   4790:   fprintf(ficgp,"# p11=1/(1+exp(a12+b12*age+c12age*age+d12*V1+e12*V1*age)\n");
                   4791:   fprintf(ficgp,"#                      +exp(a13+b13*age+c13age*age+d13*V1+e13*V1*age)+...)\n");
                   4792:   fprintf(ficgp,"# p12=exp(a12+b12*age+c12age*age+d12*V1+e12*V1*age)/\n");
                   4793:   fprintf(ficgp,"#     (1+exp(a12+b12*age+c12age*age+d12*V1+e12*V1*age)\n");
                   4794:   fprintf(ficgp,"#       +exp(a13+b13*age+c13age*age+d13*V1+e13*V1*age))\n");
                   4795:   fprintf(ficgp,"#       +exp(a14+b14*age+c14age*age+d14*V1+e14*V1*age)+...)\n");
                   4796:   fprintf(ficgp,"#\n");
1.126     brouard  4797:    for(ng=1; ng<=2;ng++){ /* Number of graphics: first is probabilities second is incidence per year*/
1.187     brouard  4798:      fprintf(ficgp,"# ng=%d\n",ng);
                   4799:      fprintf(ficgp,"#   jk=1 to 2^%d=%d\n",cptcoveff,m);
1.126     brouard  4800:      for(jk=1; jk <=m; jk++) {
1.187     brouard  4801:        fprintf(ficgp,"#    jk=%d\n",jk);
1.145     brouard  4802:        fprintf(ficgp,"\nset out \"%s%d_%d.png\" \n",subdirf2(optionfilefiname,"pe"),jk,ng); 
1.126     brouard  4803:        if (ng==2)
                   4804:         fprintf(ficgp,"\nset ylabel \"Quasi-incidence per year\"\n");
                   4805:        else
                   4806:         fprintf(ficgp,"\nset title \"Probability\"\n");
1.145     brouard  4807:        fprintf(ficgp,"\nset ter png small size 320, 240\nset log y\nplot  [%.f:%.f] ",ageminpar,agemaxpar);
1.126     brouard  4808:        i=1;
                   4809:        for(k2=1; k2<=nlstate; k2++) {
                   4810:         k3=i;
                   4811:         for(k=1; k<=(nlstate+ndeath); k++) {
                   4812:           if (k != k2){
                   4813:             if(ng==2)
1.187     brouard  4814:               if(nagesqr==0)
                   4815:                 fprintf(ficgp," %f*exp(p%d+p%d*x",YEARM/stepm,i,i+1);
                   4816:               else /* nagesqr =1 */
                   4817:                 fprintf(ficgp," %f*exp(p%d+p%d*x+p%d*x*x",YEARM/stepm,i,i+1,i+1+nagesqr);
1.126     brouard  4818:             else
1.187     brouard  4819:               if(nagesqr==0)
                   4820:                 fprintf(ficgp," exp(p%d+p%d*x",i,i+1);
                   4821:               else /* nagesqr =1 */
                   4822:                 fprintf(ficgp," exp(p%d+p%d*x+p%d*x*x",i,i+1,i+1+nagesqr);
1.141     brouard  4823:             ij=1;/* To be checked else nbcode[0][0] wrong */
1.187     brouard  4824:             for(j=3; j <=ncovmodel-nagesqr; j++) {
1.197   ! brouard  4825:               /* printf("Tage[%d]=%d, j=%d\n", ij, Tage[ij], j); */
        !          4826:               if(ij <=cptcovage) { /* Bug valgrind */
        !          4827:                 if((j-2)==Tage[ij]) { /* Bug valgrind */
        !          4828:                   fprintf(ficgp,"+p%d*%d*x",i+j+nagesqr-1,nbcode[Tvar[j-2]][codtab[jk][Tvar[j-2]]]);
        !          4829:                   ij++;
        !          4830:                 }
1.186     brouard  4831:               }
                   4832:               else
1.187     brouard  4833:                 fprintf(ficgp,"+p%d*%d",i+j+nagesqr-1,nbcode[Tvar[j-2]][codtab[jk][j-2]]);
1.126     brouard  4834:             }
                   4835:             fprintf(ficgp,")/(1");
                   4836:             
1.187     brouard  4837:             for(k1=1; k1 <=nlstate; k1++){ 
                   4838:               if(nagesqr==0)
                   4839:                 fprintf(ficgp,"+exp(p%d+p%d*x",k3+(k1-1)*ncovmodel,k3+(k1-1)*ncovmodel+1);
                   4840:               else /* nagesqr =1 */
                   4841:                 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);
                   4842:   
1.126     brouard  4843:               ij=1;
1.187     brouard  4844:               for(j=3; j <=ncovmodel-nagesqr; j++){
1.197   ! brouard  4845:                 if(ij <=cptcovage) { /* Bug valgrind */
        !          4846:                   if((j-2)==Tage[ij]) { /* Bug valgrind */
        !          4847:                     fprintf(ficgp,"+p%d*%d*x",k3+(k1-1)*ncovmodel+1+j-2+nagesqr,nbcode[Tvar[j-2]][codtab[jk][Tvar[j-2]]]);
        !          4848:                     ij++;
        !          4849:                   }
1.186     brouard  4850:                 }
                   4851:                 else
1.187     brouard  4852:                   fprintf(ficgp,"+p%d*%d",k3+(k1-1)*ncovmodel+1+j-2+nagesqr,nbcode[Tvar[j-2]][codtab[jk][j-2]]);
1.126     brouard  4853:               }
                   4854:               fprintf(ficgp,")");
                   4855:             }
                   4856:             fprintf(ficgp,") t \"p%d%d\" ", k2,k);
                   4857:             if ((k+k2)!= (nlstate*2+ndeath)) fprintf(ficgp,",");
                   4858:             i=i+ncovmodel;
                   4859:           }
                   4860:         } /* end k */
                   4861:        } /* end k2 */
                   4862:      } /* end jk */
                   4863:    } /* end ng */
1.164     brouard  4864:  /* avoid: */
1.126     brouard  4865:    fflush(ficgp); 
                   4866: }  /* end gnuplot */
                   4867: 
                   4868: 
                   4869: /*************** Moving average **************/
                   4870: int movingaverage(double ***probs, double bage,double fage, double ***mobaverage, int mobilav){
                   4871: 
                   4872:   int i, cpt, cptcod;
                   4873:   int modcovmax =1;
                   4874:   int mobilavrange, mob;
                   4875:   double age;
                   4876: 
                   4877:   modcovmax=2*cptcoveff;/* Max number of modalities. We suppose 
                   4878:                           a covariate has 2 modalities */
                   4879:   if (cptcovn<1) modcovmax=1; /* At least 1 pass */
                   4880: 
                   4881:   if(mobilav==1||mobilav ==3 ||mobilav==5 ||mobilav== 7){
                   4882:     if(mobilav==1) mobilavrange=5; /* default */
                   4883:     else mobilavrange=mobilav;
                   4884:     for (age=bage; age<=fage; age++)
                   4885:       for (i=1; i<=nlstate;i++)
                   4886:        for (cptcod=1;cptcod<=modcovmax;cptcod++)
                   4887:          mobaverage[(int)age][i][cptcod]=probs[(int)age][i][cptcod];
                   4888:     /* We keep the original values on the extreme ages bage, fage and for 
                   4889:        fage+1 and bage-1 we use a 3 terms moving average; for fage+2 bage+2
                   4890:        we use a 5 terms etc. until the borders are no more concerned. 
                   4891:     */ 
                   4892:     for (mob=3;mob <=mobilavrange;mob=mob+2){
                   4893:       for (age=bage+(mob-1)/2; age<=fage-(mob-1)/2; age++){
                   4894:        for (i=1; i<=nlstate;i++){
                   4895:          for (cptcod=1;cptcod<=modcovmax;cptcod++){
                   4896:            mobaverage[(int)age][i][cptcod] =probs[(int)age][i][cptcod];
                   4897:              for (cpt=1;cpt<=(mob-1)/2;cpt++){
                   4898:                mobaverage[(int)age][i][cptcod] +=probs[(int)age-cpt][i][cptcod];
                   4899:                mobaverage[(int)age][i][cptcod] +=probs[(int)age+cpt][i][cptcod];
                   4900:              }
                   4901:            mobaverage[(int)age][i][cptcod]=mobaverage[(int)age][i][cptcod]/mob;
                   4902:          }
                   4903:        }
                   4904:       }/* end age */
                   4905:     }/* end mob */
                   4906:   }else return -1;
                   4907:   return 0;
                   4908: }/* End movingaverage */
                   4909: 
                   4910: 
                   4911: /************** Forecasting ******************/
1.169     brouard  4912: 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  4913:   /* proj1, year, month, day of starting projection 
                   4914:      agemin, agemax range of age
                   4915:      dateprev1 dateprev2 range of dates during which prevalence is computed
                   4916:      anproj2 year of en of projection (same day and month as proj1).
                   4917:   */
1.164     brouard  4918:   int yearp, stepsize, hstepm, nhstepm, j, k, cptcod, i, h, i1;
1.126     brouard  4919:   double agec; /* generic age */
                   4920:   double agelim, ppij, yp,yp1,yp2,jprojmean,mprojmean,anprojmean;
                   4921:   double *popeffectif,*popcount;
                   4922:   double ***p3mat;
                   4923:   double ***mobaverage;
                   4924:   char fileresf[FILENAMELENGTH];
                   4925: 
                   4926:   agelim=AGESUP;
                   4927:   prevalence(probs, ageminpar, agemax, s, agev, nlstate, imx, Tvar, nbcode, ncodemax, mint, anint, dateprev1, dateprev2, firstpass, lastpass);
                   4928:  
                   4929:   strcpy(fileresf,"f"); 
                   4930:   strcat(fileresf,fileres);
                   4931:   if((ficresf=fopen(fileresf,"w"))==NULL) {
                   4932:     printf("Problem with forecast resultfile: %s\n", fileresf);
                   4933:     fprintf(ficlog,"Problem with forecast resultfile: %s\n", fileresf);
                   4934:   }
                   4935:   printf("Computing forecasting: result on file '%s' \n", fileresf);
                   4936:   fprintf(ficlog,"Computing forecasting: result on file '%s' \n", fileresf);
                   4937: 
                   4938:   if (cptcoveff==0) ncodemax[cptcoveff]=1;
                   4939: 
                   4940:   if (mobilav!=0) {
                   4941:     mobaverage= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
                   4942:     if (movingaverage(probs, ageminpar, fage, mobaverage,mobilav)!=0){
                   4943:       fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav);
                   4944:       printf(" Error in movingaverage mobilav=%d\n",mobilav);
                   4945:     }
                   4946:   }
                   4947: 
                   4948:   stepsize=(int) (stepm+YEARM-1)/YEARM;
                   4949:   if (stepm<=12) stepsize=1;
                   4950:   if(estepm < stepm){
                   4951:     printf ("Problem %d lower than %d\n",estepm, stepm);
                   4952:   }
                   4953:   else  hstepm=estepm;   
                   4954: 
                   4955:   hstepm=hstepm/stepm; 
                   4956:   yp1=modf(dateintmean,&yp);/* extracts integral of datemean in yp  and
                   4957:                                fractional in yp1 */
                   4958:   anprojmean=yp;
                   4959:   yp2=modf((yp1*12),&yp);
                   4960:   mprojmean=yp;
                   4961:   yp1=modf((yp2*30.5),&yp);
                   4962:   jprojmean=yp;
                   4963:   if(jprojmean==0) jprojmean=1;
                   4964:   if(mprojmean==0) jprojmean=1;
                   4965: 
                   4966:   i1=cptcoveff;
                   4967:   if (cptcovn < 1){i1=1;}
                   4968:   
                   4969:   fprintf(ficresf,"# Mean day of interviews %.lf/%.lf/%.lf (%.2f) between %.2f and %.2f \n",jprojmean,mprojmean,anprojmean,dateintmean,dateprev1,dateprev2); 
                   4970:   
                   4971:   fprintf(ficresf,"#****** Routine prevforecast **\n");
                   4972: 
                   4973: /*           if (h==(int)(YEARM*yearp)){ */
                   4974:   for(cptcov=1, k=0;cptcov<=i1;cptcov++){
                   4975:     for(cptcod=1;cptcod<=ncodemax[cptcoveff];cptcod++){
                   4976:       k=k+1;
                   4977:       fprintf(ficresf,"\n#******");
                   4978:       for(j=1;j<=cptcoveff;j++) {
                   4979:        fprintf(ficresf," V%d=%d, hpijx=probability over h years, hp.jx is weighted by observed prev ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
                   4980:       }
                   4981:       fprintf(ficresf,"******\n");
                   4982:       fprintf(ficresf,"# Covariate valuofcovar yearproj age");
                   4983:       for(j=1; j<=nlstate+ndeath;j++){ 
                   4984:        for(i=1; i<=nlstate;i++)              
                   4985:           fprintf(ficresf," p%d%d",i,j);
                   4986:        fprintf(ficresf," p.%d",j);
                   4987:       }
                   4988:       for (yearp=0; yearp<=(anproj2-anproj1);yearp +=stepsize) { 
                   4989:        fprintf(ficresf,"\n");
                   4990:        fprintf(ficresf,"\n# Forecasting at date %.lf/%.lf/%.lf ",jproj1,mproj1,anproj1+yearp);   
                   4991: 
                   4992:        for (agec=fage; agec>=(ageminpar-1); agec--){ 
                   4993:          nhstepm=(int) rint((agelim-agec)*YEARM/stepm); 
                   4994:          nhstepm = nhstepm/hstepm; 
                   4995:          p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   4996:          oldm=oldms;savm=savms;
                   4997:          hpxij(p3mat,nhstepm,agec,hstepm,p,nlstate,stepm,oldm,savm, k);  
                   4998:        
                   4999:          for (h=0; h<=nhstepm; h++){
                   5000:            if (h*hstepm/YEARM*stepm ==yearp) {
                   5001:               fprintf(ficresf,"\n");
                   5002:               for(j=1;j<=cptcoveff;j++) 
                   5003:                 fprintf(ficresf,"%d %d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
                   5004:              fprintf(ficresf,"%.f %.f ",anproj1+yearp,agec+h*hstepm/YEARM*stepm);
                   5005:            } 
                   5006:            for(j=1; j<=nlstate+ndeath;j++) {
                   5007:              ppij=0.;
                   5008:              for(i=1; i<=nlstate;i++) {
                   5009:                if (mobilav==1) 
                   5010:                  ppij=ppij+p3mat[i][j][h]*mobaverage[(int)agec][i][cptcod];
                   5011:                else {
                   5012:                  ppij=ppij+p3mat[i][j][h]*probs[(int)(agec)][i][cptcod];
                   5013:                }
                   5014:                if (h*hstepm/YEARM*stepm== yearp) {
                   5015:                  fprintf(ficresf," %.3f", p3mat[i][j][h]);
                   5016:                }
                   5017:              } /* end i */
                   5018:              if (h*hstepm/YEARM*stepm==yearp) {
                   5019:                fprintf(ficresf," %.3f", ppij);
                   5020:              }
                   5021:            }/* end j */
                   5022:          } /* end h */
                   5023:          free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   5024:        } /* end agec */
                   5025:       } /* end yearp */
                   5026:     } /* end cptcod */
                   5027:   } /* end  cptcov */
                   5028:        
                   5029:   if (mobilav!=0) free_ma3x(mobaverage,1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
                   5030: 
                   5031:   fclose(ficresf);
                   5032: }
                   5033: 
                   5034: /************** Forecasting *****not tested NB*************/
1.169     brouard  5035: 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  5036:   
                   5037:   int cpt, stepsize, hstepm, nhstepm, j,k,c, cptcod, i,h;
                   5038:   int *popage;
                   5039:   double calagedatem, agelim, kk1, kk2;
                   5040:   double *popeffectif,*popcount;
                   5041:   double ***p3mat,***tabpop,***tabpopprev;
                   5042:   double ***mobaverage;
                   5043:   char filerespop[FILENAMELENGTH];
                   5044: 
                   5045:   tabpop= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
                   5046:   tabpopprev= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
                   5047:   agelim=AGESUP;
                   5048:   calagedatem=(anpyram+mpyram/12.+jpyram/365.-dateintmean)*YEARM;
                   5049:   
                   5050:   prevalence(probs, ageminpar, agemax, s, agev, nlstate, imx, Tvar, nbcode, ncodemax, mint, anint, dateprev1, dateprev2, firstpass, lastpass);
                   5051:   
                   5052:   
                   5053:   strcpy(filerespop,"pop"); 
                   5054:   strcat(filerespop,fileres);
                   5055:   if((ficrespop=fopen(filerespop,"w"))==NULL) {
                   5056:     printf("Problem with forecast resultfile: %s\n", filerespop);
                   5057:     fprintf(ficlog,"Problem with forecast resultfile: %s\n", filerespop);
                   5058:   }
                   5059:   printf("Computing forecasting: result on file '%s' \n", filerespop);
                   5060:   fprintf(ficlog,"Computing forecasting: result on file '%s' \n", filerespop);
                   5061: 
                   5062:   if (cptcoveff==0) ncodemax[cptcoveff]=1;
                   5063: 
                   5064:   if (mobilav!=0) {
                   5065:     mobaverage= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
                   5066:     if (movingaverage(probs, ageminpar, fage, mobaverage,mobilav)!=0){
                   5067:       fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav);
                   5068:       printf(" Error in movingaverage mobilav=%d\n",mobilav);
                   5069:     }
                   5070:   }
                   5071: 
                   5072:   stepsize=(int) (stepm+YEARM-1)/YEARM;
                   5073:   if (stepm<=12) stepsize=1;
                   5074:   
                   5075:   agelim=AGESUP;
                   5076:   
                   5077:   hstepm=1;
                   5078:   hstepm=hstepm/stepm; 
                   5079:   
                   5080:   if (popforecast==1) {
                   5081:     if((ficpop=fopen(popfile,"r"))==NULL) {
                   5082:       printf("Problem with population file : %s\n",popfile);exit(0);
                   5083:       fprintf(ficlog,"Problem with population file : %s\n",popfile);exit(0);
                   5084:     } 
                   5085:     popage=ivector(0,AGESUP);
                   5086:     popeffectif=vector(0,AGESUP);
                   5087:     popcount=vector(0,AGESUP);
                   5088:     
                   5089:     i=1;   
                   5090:     while ((c=fscanf(ficpop,"%d %lf\n",&popage[i],&popcount[i])) != EOF) i=i+1;
                   5091:    
                   5092:     imx=i;
                   5093:     for (i=1; i<imx;i++) popeffectif[popage[i]]=popcount[i];
                   5094:   }
                   5095: 
                   5096:   for(cptcov=1,k=0;cptcov<=i2;cptcov++){
                   5097:    for(cptcod=1;cptcod<=ncodemax[cptcoveff];cptcod++){
                   5098:       k=k+1;
                   5099:       fprintf(ficrespop,"\n#******");
                   5100:       for(j=1;j<=cptcoveff;j++) {
                   5101:        fprintf(ficrespop," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
                   5102:       }
                   5103:       fprintf(ficrespop,"******\n");
                   5104:       fprintf(ficrespop,"# Age");
                   5105:       for(j=1; j<=nlstate+ndeath;j++) fprintf(ficrespop," P.%d",j);
                   5106:       if (popforecast==1)  fprintf(ficrespop," [Population]");
                   5107:       
                   5108:       for (cpt=0; cpt<=0;cpt++) { 
                   5109:        fprintf(ficrespop,"\n\n# Forecasting at date %.lf/%.lf/%.lf ",jpyram,mpyram,anpyram+cpt);   
                   5110:        
                   5111:        for (agedeb=(fage-((int)calagedatem %12/12.)); agedeb>=(ageminpar-((int)calagedatem %12)/12.); agedeb--){ 
                   5112:          nhstepm=(int) rint((agelim-agedeb)*YEARM/stepm); 
                   5113:          nhstepm = nhstepm/hstepm; 
                   5114:          
                   5115:          p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   5116:          oldm=oldms;savm=savms;
                   5117:          hpxij(p3mat,nhstepm,agedeb,hstepm,p,nlstate,stepm,oldm,savm, k);  
                   5118:        
                   5119:          for (h=0; h<=nhstepm; h++){
                   5120:            if (h==(int) (calagedatem+YEARM*cpt)) {
                   5121:              fprintf(ficrespop,"\n %3.f ",agedeb+h*hstepm/YEARM*stepm);
                   5122:            } 
                   5123:            for(j=1; j<=nlstate+ndeath;j++) {
                   5124:              kk1=0.;kk2=0;
                   5125:              for(i=1; i<=nlstate;i++) {              
                   5126:                if (mobilav==1) 
                   5127:                  kk1=kk1+p3mat[i][j][h]*mobaverage[(int)agedeb+1][i][cptcod];
                   5128:                else {
                   5129:                  kk1=kk1+p3mat[i][j][h]*probs[(int)(agedeb+1)][i][cptcod];
                   5130:                }
                   5131:              }
                   5132:              if (h==(int)(calagedatem+12*cpt)){
                   5133:                tabpop[(int)(agedeb)][j][cptcod]=kk1;
                   5134:                  /*fprintf(ficrespop," %.3f", kk1);
                   5135:                    if (popforecast==1) fprintf(ficrespop," [%.f]", kk1*popeffectif[(int)agedeb+1]);*/
                   5136:              }
                   5137:            }
                   5138:            for(i=1; i<=nlstate;i++){
                   5139:              kk1=0.;
                   5140:                for(j=1; j<=nlstate;j++){
                   5141:                  kk1= kk1+tabpop[(int)(agedeb)][j][cptcod]; 
                   5142:                }
                   5143:                  tabpopprev[(int)(agedeb)][i][cptcod]=tabpop[(int)(agedeb)][i][cptcod]/kk1*popeffectif[(int)(agedeb+(calagedatem+12*cpt)*hstepm/YEARM*stepm-1)];
                   5144:            }
                   5145: 
                   5146:            if (h==(int)(calagedatem+12*cpt)) for(j=1; j<=nlstate;j++) 
                   5147:              fprintf(ficrespop," %15.2f",tabpopprev[(int)(agedeb+1)][j][cptcod]);
                   5148:          }
                   5149:          free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   5150:        }
                   5151:       }
                   5152:  
                   5153:   /******/
                   5154: 
                   5155:       for (cpt=1; cpt<=(anpyram1-anpyram);cpt++) { 
                   5156:        fprintf(ficrespop,"\n\n# Forecasting at date %.lf/%.lf/%.lf ",jpyram,mpyram,anpyram+cpt);   
                   5157:        for (agedeb=(fage-((int)calagedatem %12/12.)); agedeb>=(ageminpar-((int)calagedatem %12)/12.); agedeb--){ 
                   5158:          nhstepm=(int) rint((agelim-agedeb)*YEARM/stepm); 
                   5159:          nhstepm = nhstepm/hstepm; 
                   5160:          
                   5161:          p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   5162:          oldm=oldms;savm=savms;
                   5163:          hpxij(p3mat,nhstepm,agedeb,hstepm,p,nlstate,stepm,oldm,savm, k);  
                   5164:          for (h=0; h<=nhstepm; h++){
                   5165:            if (h==(int) (calagedatem+YEARM*cpt)) {
                   5166:              fprintf(ficresf,"\n %3.f ",agedeb+h*hstepm/YEARM*stepm);
                   5167:            } 
                   5168:            for(j=1; j<=nlstate+ndeath;j++) {
                   5169:              kk1=0.;kk2=0;
                   5170:              for(i=1; i<=nlstate;i++) {              
                   5171:                kk1=kk1+p3mat[i][j][h]*tabpopprev[(int)agedeb+1][i][cptcod];    
                   5172:              }
                   5173:              if (h==(int)(calagedatem+12*cpt)) fprintf(ficresf," %15.2f", kk1);        
                   5174:            }
                   5175:          }
                   5176:          free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   5177:        }
                   5178:       }
                   5179:    } 
                   5180:   }
                   5181:  
                   5182:   if (mobilav!=0) free_ma3x(mobaverage,1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
                   5183: 
                   5184:   if (popforecast==1) {
                   5185:     free_ivector(popage,0,AGESUP);
                   5186:     free_vector(popeffectif,0,AGESUP);
                   5187:     free_vector(popcount,0,AGESUP);
                   5188:   }
                   5189:   free_ma3x(tabpop,1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
                   5190:   free_ma3x(tabpopprev,1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
                   5191:   fclose(ficrespop);
                   5192: } /* End of popforecast */
                   5193: 
                   5194: int fileappend(FILE *fichier, char *optionfich)
                   5195: {
                   5196:   if((fichier=fopen(optionfich,"a"))==NULL) {
                   5197:     printf("Problem with file: %s\n", optionfich);
                   5198:     fprintf(ficlog,"Problem with file: %s\n", optionfich);
                   5199:     return (0);
                   5200:   }
                   5201:   fflush(fichier);
                   5202:   return (1);
                   5203: }
                   5204: 
                   5205: 
                   5206: /**************** function prwizard **********************/
                   5207: void prwizard(int ncovmodel, int nlstate, int ndeath,  char model[], FILE *ficparo)
                   5208: {
                   5209: 
                   5210:   /* Wizard to print covariance matrix template */
                   5211: 
1.164     brouard  5212:   char ca[32], cb[32];
                   5213:   int i,j, k, li, lj, lk, ll, jj, npar, itimes;
1.126     brouard  5214:   int numlinepar;
                   5215: 
                   5216:   printf("# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
                   5217:   fprintf(ficparo,"# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
                   5218:   for(i=1; i <=nlstate; i++){
                   5219:     jj=0;
                   5220:     for(j=1; j <=nlstate+ndeath; j++){
                   5221:       if(j==i) continue;
                   5222:       jj++;
                   5223:       /*ca[0]= k+'a'-1;ca[1]='\0';*/
                   5224:       printf("%1d%1d",i,j);
                   5225:       fprintf(ficparo,"%1d%1d",i,j);
                   5226:       for(k=1; k<=ncovmodel;k++){
                   5227:        /*        printf(" %lf",param[i][j][k]); */
                   5228:        /*        fprintf(ficparo," %lf",param[i][j][k]); */
                   5229:        printf(" 0.");
                   5230:        fprintf(ficparo," 0.");
                   5231:       }
                   5232:       printf("\n");
                   5233:       fprintf(ficparo,"\n");
                   5234:     }
                   5235:   }
                   5236:   printf("# Scales (for hessian or gradient estimation)\n");
                   5237:   fprintf(ficparo,"# Scales (for hessian or gradient estimation)\n");
                   5238:   npar= (nlstate+ndeath-1)*nlstate*ncovmodel; /* Number of parameters*/ 
                   5239:   for(i=1; i <=nlstate; i++){
                   5240:     jj=0;
                   5241:     for(j=1; j <=nlstate+ndeath; j++){
                   5242:       if(j==i) continue;
                   5243:       jj++;
                   5244:       fprintf(ficparo,"%1d%1d",i,j);
                   5245:       printf("%1d%1d",i,j);
                   5246:       fflush(stdout);
                   5247:       for(k=1; k<=ncovmodel;k++){
                   5248:        /*      printf(" %le",delti3[i][j][k]); */
                   5249:        /*      fprintf(ficparo," %le",delti3[i][j][k]); */
                   5250:        printf(" 0.");
                   5251:        fprintf(ficparo," 0.");
                   5252:       }
                   5253:       numlinepar++;
                   5254:       printf("\n");
                   5255:       fprintf(ficparo,"\n");
                   5256:     }
                   5257:   }
                   5258:   printf("# Covariance matrix\n");
                   5259: /* # 121 Var(a12)\n\ */
                   5260: /* # 122 Cov(b12,a12) Var(b12)\n\ */
                   5261: /* # 131 Cov(a13,a12) Cov(a13,b12, Var(a13)\n\ */
                   5262: /* # 132 Cov(b13,a12) Cov(b13,b12, Cov(b13,a13) Var(b13)\n\ */
                   5263: /* # 212 Cov(a21,a12) Cov(a21,b12, Cov(a21,a13) Cov(a21,b13) Var(a21)\n\ */
                   5264: /* # 212 Cov(b21,a12) Cov(b21,b12, Cov(b21,a13) Cov(b21,b13) Cov(b21,a21) Var(b21)\n\ */
                   5265: /* # 232 Cov(a23,a12) Cov(a23,b12, Cov(a23,a13) Cov(a23,b13) Cov(a23,a21) Cov(a23,b21) Var(a23)\n\ */
                   5266: /* # 232 Cov(b23,a12) Cov(b23,b12) ... Var (b23)\n" */
                   5267:   fflush(stdout);
                   5268:   fprintf(ficparo,"# Covariance matrix\n");
                   5269:   /* # 121 Var(a12)\n\ */
                   5270:   /* # 122 Cov(b12,a12) Var(b12)\n\ */
                   5271:   /* #   ...\n\ */
                   5272:   /* # 232 Cov(b23,a12)  Cov(b23,b12) ... Var (b23)\n" */
                   5273:   
                   5274:   for(itimes=1;itimes<=2;itimes++){
                   5275:     jj=0;
                   5276:     for(i=1; i <=nlstate; i++){
                   5277:       for(j=1; j <=nlstate+ndeath; j++){
                   5278:        if(j==i) continue;
                   5279:        for(k=1; k<=ncovmodel;k++){
                   5280:          jj++;
                   5281:          ca[0]= k+'a'-1;ca[1]='\0';
                   5282:          if(itimes==1){
                   5283:            printf("#%1d%1d%d",i,j,k);
                   5284:            fprintf(ficparo,"#%1d%1d%d",i,j,k);
                   5285:          }else{
                   5286:            printf("%1d%1d%d",i,j,k);
                   5287:            fprintf(ficparo,"%1d%1d%d",i,j,k);
                   5288:            /*  printf(" %.5le",matcov[i][j]); */
                   5289:          }
                   5290:          ll=0;
                   5291:          for(li=1;li <=nlstate; li++){
                   5292:            for(lj=1;lj <=nlstate+ndeath; lj++){
                   5293:              if(lj==li) continue;
                   5294:              for(lk=1;lk<=ncovmodel;lk++){
                   5295:                ll++;
                   5296:                if(ll<=jj){
                   5297:                  cb[0]= lk +'a'-1;cb[1]='\0';
                   5298:                  if(ll<jj){
                   5299:                    if(itimes==1){
                   5300:                      printf(" Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
                   5301:                      fprintf(ficparo," Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
                   5302:                    }else{
                   5303:                      printf(" 0.");
                   5304:                      fprintf(ficparo," 0.");
                   5305:                    }
                   5306:                  }else{
                   5307:                    if(itimes==1){
                   5308:                      printf(" Var(%s%1d%1d)",ca,i,j);
                   5309:                      fprintf(ficparo," Var(%s%1d%1d)",ca,i,j);
                   5310:                    }else{
                   5311:                      printf(" 0.");
                   5312:                      fprintf(ficparo," 0.");
                   5313:                    }
                   5314:                  }
                   5315:                }
                   5316:              } /* end lk */
                   5317:            } /* end lj */
                   5318:          } /* end li */
                   5319:          printf("\n");
                   5320:          fprintf(ficparo,"\n");
                   5321:          numlinepar++;
                   5322:        } /* end k*/
                   5323:       } /*end j */
                   5324:     } /* end i */
                   5325:   } /* end itimes */
                   5326: 
                   5327: } /* end of prwizard */
                   5328: /******************* Gompertz Likelihood ******************************/
                   5329: double gompertz(double x[])
                   5330: { 
                   5331:   double A,B,L=0.0,sump=0.,num=0.;
                   5332:   int i,n=0; /* n is the size of the sample */
                   5333: 
                   5334:   for (i=0;i<=imx-1 ; i++) {
                   5335:     sump=sump+weight[i];
                   5336:     /*    sump=sump+1;*/
                   5337:     num=num+1;
                   5338:   }
                   5339:  
                   5340:  
                   5341:   /* for (i=0; i<=imx; i++) 
                   5342:      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]);*/
                   5343: 
                   5344:   for (i=1;i<=imx ; i++)
                   5345:     {
                   5346:       if (cens[i] == 1 && wav[i]>1)
                   5347:        A=-x[1]/(x[2])*(exp(x[2]*(agecens[i]-agegomp))-exp(x[2]*(ageexmed[i]-agegomp)));
                   5348:       
                   5349:       if (cens[i] == 0 && wav[i]>1)
                   5350:        A=-x[1]/(x[2])*(exp(x[2]*(agedc[i]-agegomp))-exp(x[2]*(ageexmed[i]-agegomp)))
                   5351:             +log(x[1]/YEARM)+x[2]*(agedc[i]-agegomp)+log(YEARM);  
                   5352:       
                   5353:       /*if (wav[i] > 1 && agecens[i] > 15) {*/ /* ??? */
                   5354:       if (wav[i] > 1 ) { /* ??? */
                   5355:        L=L+A*weight[i];
                   5356:        /*      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]);*/
                   5357:       }
                   5358:     }
                   5359: 
                   5360:  /*printf("x1=%2.9f x2=%2.9f x3=%2.9f L=%f\n",x[1],x[2],x[3],L);*/
                   5361:  
                   5362:   return -2*L*num/sump;
                   5363: }
                   5364: 
1.136     brouard  5365: #ifdef GSL
                   5366: /******************* Gompertz_f Likelihood ******************************/
                   5367: double gompertz_f(const gsl_vector *v, void *params)
                   5368: { 
                   5369:   double A,B,LL=0.0,sump=0.,num=0.;
                   5370:   double *x= (double *) v->data;
                   5371:   int i,n=0; /* n is the size of the sample */
                   5372: 
                   5373:   for (i=0;i<=imx-1 ; i++) {
                   5374:     sump=sump+weight[i];
                   5375:     /*    sump=sump+1;*/
                   5376:     num=num+1;
                   5377:   }
                   5378:  
                   5379:  
                   5380:   /* for (i=0; i<=imx; i++) 
                   5381:      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]);*/
                   5382:   printf("x[0]=%lf x[1]=%lf\n",x[0],x[1]);
                   5383:   for (i=1;i<=imx ; i++)
                   5384:     {
                   5385:       if (cens[i] == 1 && wav[i]>1)
                   5386:        A=-x[0]/(x[1])*(exp(x[1]*(agecens[i]-agegomp))-exp(x[1]*(ageexmed[i]-agegomp)));
                   5387:       
                   5388:       if (cens[i] == 0 && wav[i]>1)
                   5389:        A=-x[0]/(x[1])*(exp(x[1]*(agedc[i]-agegomp))-exp(x[1]*(ageexmed[i]-agegomp)))
                   5390:             +log(x[0]/YEARM)+x[1]*(agedc[i]-agegomp)+log(YEARM);  
                   5391:       
                   5392:       /*if (wav[i] > 1 && agecens[i] > 15) {*/ /* ??? */
                   5393:       if (wav[i] > 1 ) { /* ??? */
                   5394:        LL=LL+A*weight[i];
                   5395:        /*      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]);*/
                   5396:       }
                   5397:     }
                   5398: 
                   5399:  /*printf("x1=%2.9f x2=%2.9f x3=%2.9f L=%f\n",x[1],x[2],x[3],L);*/
                   5400:   printf("x[0]=%lf x[1]=%lf -2*LL*num/sump=%lf\n",x[0],x[1],-2*LL*num/sump);
                   5401:  
                   5402:   return -2*LL*num/sump;
                   5403: }
                   5404: #endif
                   5405: 
1.126     brouard  5406: /******************* Printing html file ***********/
                   5407: void printinghtmlmort(char fileres[], char title[], char datafile[], int firstpass, \
                   5408:                  int lastpass, int stepm, int weightopt, char model[],\
                   5409:                  int imx,  double p[],double **matcov,double agemortsup){
                   5410:   int i,k;
                   5411: 
                   5412:   fprintf(fichtm,"<ul><li><h4>Result files </h4>\n Force of mortality. Parameters of the Gompertz fit (with confidence interval in brackets):<br>");
                   5413:   fprintf(fichtm,"  mu(age) =%lf*exp(%lf*(age-%d)) per year<br><br>",p[1],p[2],agegomp);
                   5414:   for (i=1;i<=2;i++) 
                   5415:     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]));
                   5416:   fprintf(fichtm,"<br><br><img src=\"graphmort.png\">");
                   5417:   fprintf(fichtm,"</ul>");
                   5418: 
                   5419: fprintf(fichtm,"<ul><li><h4>Life table</h4>\n <br>");
                   5420: 
                   5421:  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>");
                   5422: 
                   5423:  for (k=agegomp;k<(agemortsup-2);k++) 
                   5424:    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]);
                   5425: 
                   5426:  
                   5427:   fflush(fichtm);
                   5428: }
                   5429: 
                   5430: /******************* Gnuplot file **************/
                   5431: void printinggnuplotmort(char fileres[], char optionfilefiname[], double ageminpar, double agemaxpar, double fage , char pathc[], double p[]){
                   5432: 
                   5433:   char dirfileres[132],optfileres[132];
1.164     brouard  5434: 
1.126     brouard  5435:   int ng;
                   5436: 
                   5437: 
                   5438:   /*#ifdef windows */
                   5439:   fprintf(ficgp,"cd \"%s\" \n",pathc);
                   5440:     /*#endif */
                   5441: 
                   5442: 
                   5443:   strcpy(dirfileres,optionfilefiname);
                   5444:   strcpy(optfileres,"vpl");
                   5445:   fprintf(ficgp,"set out \"graphmort.png\"\n "); 
                   5446:   fprintf(ficgp,"set xlabel \"Age\"\n set ylabel \"Force of mortality (per year)\" \n "); 
1.145     brouard  5447:   fprintf(ficgp, "set ter png small size 320, 240\n set log y\n"); 
                   5448:   /* fprintf(ficgp, "set size 0.65,0.65\n"); */
1.126     brouard  5449:   fprintf(ficgp,"plot [%d:100] %lf*exp(%lf*(x-%d))",agegomp,p[1],p[2],agegomp);
                   5450: 
                   5451: } 
                   5452: 
1.136     brouard  5453: int readdata(char datafile[], int firstobs, int lastobs, int *imax)
                   5454: {
1.126     brouard  5455: 
1.136     brouard  5456:   /*-------- data file ----------*/
                   5457:   FILE *fic;
                   5458:   char dummy[]="                         ";
1.164     brouard  5459:   int i=0, j=0, n=0;
1.136     brouard  5460:   int linei, month, year,iout;
                   5461:   char line[MAXLINE], linetmp[MAXLINE];
1.164     brouard  5462:   char stra[MAXLINE], strb[MAXLINE];
1.136     brouard  5463:   char *stratrunc;
                   5464:   int lstra;
1.126     brouard  5465: 
                   5466: 
1.136     brouard  5467:   if((fic=fopen(datafile,"r"))==NULL)    {
1.195     brouard  5468:     printf("Problem while opening datafile: %s\n", datafile);fflush(stdout);
                   5469:     fprintf(ficlog,"Problem while opening datafile: %s\n", datafile);fflush(ficlog);return 1;
1.136     brouard  5470:   }
1.126     brouard  5471: 
1.136     brouard  5472:   i=1;
                   5473:   linei=0;
                   5474:   while ((fgets(line, MAXLINE, fic) != NULL) &&((i >= firstobs) && (i <=lastobs))) {
                   5475:     linei=linei+1;
                   5476:     for(j=strlen(line); j>=0;j--){  /* Untabifies line */
                   5477:       if(line[j] == '\t')
                   5478:        line[j] = ' ';
                   5479:     }
                   5480:     for(j=strlen(line)-1; (line[j]==' ')||(line[j]==10)||(line[j]==13);j--){
                   5481:       ;
                   5482:     };
                   5483:     line[j+1]=0;  /* Trims blanks at end of line */
                   5484:     if(line[0]=='#'){
                   5485:       fprintf(ficlog,"Comment line\n%s\n",line);
                   5486:       printf("Comment line\n%s\n",line);
                   5487:       continue;
                   5488:     }
                   5489:     trimbb(linetmp,line); /* Trims multiple blanks in line */
1.164     brouard  5490:     strcpy(line, linetmp);
1.136     brouard  5491:   
1.126     brouard  5492: 
1.136     brouard  5493:     for (j=maxwav;j>=1;j--){
1.137     brouard  5494:       cutv(stra, strb, line, ' '); 
1.136     brouard  5495:       if(strb[0]=='.') { /* Missing status */
                   5496:        lval=-1;
                   5497:       }else{
                   5498:        errno=0;
                   5499:        lval=strtol(strb,&endptr,10); 
                   5500:       /*       if (errno == ERANGE && (lval == LONG_MAX || lval == LONG_MIN))*/
                   5501:        if( strb[0]=='\0' || (*endptr != '\0')){
1.141     brouard  5502:          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);
                   5503:          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  5504:          return 1;
                   5505:        }
                   5506:       }
                   5507:       s[j][i]=lval;
                   5508:       
                   5509:       strcpy(line,stra);
                   5510:       cutv(stra, strb,line,' ');
1.169     brouard  5511:       if( (iout=sscanf(strb,"%d/%d",&month, &year)) != 0){
1.136     brouard  5512:       }
1.169     brouard  5513:       else  if( (iout=sscanf(strb,"%s.",dummy)) != 0){
1.136     brouard  5514:        month=99;
                   5515:        year=9999;
                   5516:       }else{
1.141     brouard  5517:        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);
                   5518:        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  5519:        return 1;
                   5520:       }
                   5521:       anint[j][i]= (double) year; 
                   5522:       mint[j][i]= (double)month; 
                   5523:       strcpy(line,stra);
                   5524:     } /* ENd Waves */
                   5525:     
                   5526:     cutv(stra, strb,line,' '); 
1.169     brouard  5527:     if( (iout=sscanf(strb,"%d/%d",&month, &year)) != 0){
1.136     brouard  5528:     }
1.169     brouard  5529:     else  if( (iout=sscanf(strb,"%s.",dummy)) != 0){
1.136     brouard  5530:       month=99;
                   5531:       year=9999;
                   5532:     }else{
1.141     brouard  5533:       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);
                   5534:        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  5535:        return 1;
                   5536:     }
                   5537:     andc[i]=(double) year; 
                   5538:     moisdc[i]=(double) month; 
                   5539:     strcpy(line,stra);
                   5540:     
                   5541:     cutv(stra, strb,line,' '); 
1.169     brouard  5542:     if( (iout=sscanf(strb,"%d/%d",&month, &year)) != 0){
1.136     brouard  5543:     }
1.169     brouard  5544:     else  if( (iout=sscanf(strb,"%s.", dummy)) != 0){
1.136     brouard  5545:       month=99;
                   5546:       year=9999;
                   5547:     }else{
1.141     brouard  5548:       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);
                   5549:       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  5550:        return 1;
                   5551:     }
                   5552:     if (year==9999) {
1.141     brouard  5553:       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);
                   5554:       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  5555:        return 1;
1.126     brouard  5556: 
1.136     brouard  5557:     }
                   5558:     annais[i]=(double)(year);
                   5559:     moisnais[i]=(double)(month); 
                   5560:     strcpy(line,stra);
                   5561:     
                   5562:     cutv(stra, strb,line,' '); 
                   5563:     errno=0;
                   5564:     dval=strtod(strb,&endptr); 
                   5565:     if( strb[0]=='\0' || (*endptr != '\0')){
1.141     brouard  5566:       printf("Error reading data around '%f' at line number %d, \"%s\" for individual %d\nShould be a weight.  Exiting.\n",dval, i,line,linei);
                   5567:       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  5568:       fflush(ficlog);
                   5569:       return 1;
                   5570:     }
                   5571:     weight[i]=dval; 
                   5572:     strcpy(line,stra);
                   5573:     
                   5574:     for (j=ncovcol;j>=1;j--){
                   5575:       cutv(stra, strb,line,' '); 
                   5576:       if(strb[0]=='.') { /* Missing status */
                   5577:        lval=-1;
                   5578:       }else{
                   5579:        errno=0;
                   5580:        lval=strtol(strb,&endptr,10); 
                   5581:        if( strb[0]=='\0' || (*endptr != '\0')){
1.141     brouard  5582:          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);
                   5583:          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  5584:          return 1;
                   5585:        }
                   5586:       }
                   5587:       if(lval <-1 || lval >1){
1.141     brouard  5588:        printf("Error reading data around '%ld' at line number %d for individual %d, '%s'\n \
1.136     brouard  5589:  Should be a value of %d(nth) covariate (0 should be the value for the reference and 1\n \
                   5590:  for the alternative. IMaCh does not build design variables automatically, do it yourself.\n \
                   5591:  For example, for multinomial values like 1, 2 and 3,\n \
                   5592:  build V1=0 V2=0 for the reference value (1),\n \
                   5593:         V1=1 V2=0 for (2) \n \
                   5594:  and V1=0 V2=1 for (3). V1=1 V2=1 should not exist and the corresponding\n \
                   5595:  output of IMaCh is often meaningless.\n \
                   5596:  Exiting.\n",lval,linei, i,line,j);
1.141     brouard  5597:        fprintf(ficlog,"Error reading data around '%ld' at line number %d for individual %d, '%s'\n \
1.136     brouard  5598:  Should be a value of %d(nth) covariate (0 should be the value for the reference and 1\n \
                   5599:  for the alternative. IMaCh does not build design variables automatically, do it yourself.\n \
                   5600:  For example, for multinomial values like 1, 2 and 3,\n \
                   5601:  build V1=0 V2=0 for the reference value (1),\n \
                   5602:         V1=1 V2=0 for (2) \n \
                   5603:  and V1=0 V2=1 for (3). V1=1 V2=1 should not exist and the corresponding\n \
                   5604:  output of IMaCh is often meaningless.\n \
                   5605:  Exiting.\n",lval,linei, i,line,j);fflush(ficlog);
                   5606:        return 1;
                   5607:       }
                   5608:       covar[j][i]=(double)(lval);
                   5609:       strcpy(line,stra);
                   5610:     }  
                   5611:     lstra=strlen(stra);
                   5612:      
                   5613:     if(lstra > 9){ /* More than 2**32 or max of what printf can write with %ld */
                   5614:       stratrunc = &(stra[lstra-9]);
                   5615:       num[i]=atol(stratrunc);
                   5616:     }
                   5617:     else
                   5618:       num[i]=atol(stra);
                   5619:     /*if((s[2][i]==2) && (s[3][i]==-1)&&(s[4][i]==9)){
                   5620:       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;}*/
                   5621:     
                   5622:     i=i+1;
                   5623:   } /* End loop reading  data */
1.126     brouard  5624: 
1.136     brouard  5625:   *imax=i-1; /* Number of individuals */
                   5626:   fclose(fic);
                   5627:  
                   5628:   return (0);
1.164     brouard  5629:   /* endread: */
1.136     brouard  5630:     printf("Exiting readdata: ");
                   5631:     fclose(fic);
                   5632:     return (1);
1.126     brouard  5633: 
                   5634: 
                   5635: 
1.136     brouard  5636: }
1.145     brouard  5637: void removespace(char *str) {
                   5638:   char *p1 = str, *p2 = str;
                   5639:   do
                   5640:     while (*p2 == ' ')
                   5641:       p2++;
1.169     brouard  5642:   while (*p1++ == *p2++);
1.145     brouard  5643: }
                   5644: 
                   5645: int decodemodel ( char model[], int lastobs) /**< This routine decode the model and returns:
1.187     brouard  5646:    * Model  V1+V2+V3+V8+V7*V8+V5*V6+V8*age+V3*age+age*age
                   5647:    * - nagesqr = 1 if age*age in the model, otherwise 0.
                   5648:    * - cptcovt total number of covariates of the model nbocc(+)+1 = 8 excepting constant and age and age*age
                   5649:    * - cptcovn or number of covariates k of the models excluding age*products =6 and age*age
1.145     brouard  5650:    * - cptcovage number of covariates with age*products =2
                   5651:    * - cptcovs number of simple covariates
                   5652:    * - 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
                   5653:    *     which is a new column after the 9 (ncovcol) variables. 
                   5654:    * - if k is a product Vn*Vm covar[k][i] is filled with correct values for each individual
                   5655:    * - Tprod[l] gives the kth covariates of the product Vn*Vm l=1 to cptcovprod-cptcovage
                   5656:    *    Tprod[1]@2 {5, 6}: position of first product V7*V8 is 5, and second V5*V6 is 6.
                   5657:    * - Tvard[k]  p Tvard[1][1]@4 {7, 8, 5, 6} for V7*V8 and V5*V6 .
                   5658:  */
1.136     brouard  5659: {
1.145     brouard  5660:   int i, j, k, ks;
1.164     brouard  5661:   int  j1, k1, k2;
1.136     brouard  5662:   char modelsav[80];
1.145     brouard  5663:   char stra[80], strb[80], strc[80], strd[80],stre[80];
1.187     brouard  5664:   char *strpt;
1.136     brouard  5665: 
1.145     brouard  5666:   /*removespace(model);*/
1.136     brouard  5667:   if (strlen(model) >1){ /* If there is at least 1 covariate */
1.145     brouard  5668:     j=0, j1=0, k1=0, k2=-1, ks=0, cptcovn=0;
1.137     brouard  5669:     if (strstr(model,"AGE") !=0){
1.192     brouard  5670:       printf("Error. AGE must be in lower case 'age' model=1+age+%s. ",model);
                   5671:       fprintf(ficlog,"Error. AGE must be in lower case model=1+age+%s. ",model);fflush(ficlog);
1.136     brouard  5672:       return 1;
                   5673:     }
1.141     brouard  5674:     if (strstr(model,"v") !=0){
                   5675:       printf("Error. 'v' must be in upper case 'V' model=%s ",model);
                   5676:       fprintf(ficlog,"Error. 'v' must be in upper case model=%s ",model);fflush(ficlog);
                   5677:       return 1;
                   5678:     }
1.187     brouard  5679:     strcpy(modelsav,model); 
                   5680:     if ((strpt=strstr(model,"age*age")) !=0){
                   5681:       printf(" strpt=%s, model=%s\n",strpt, model);
                   5682:       if(strpt != model){
                   5683:       printf("Error in model: 'model=%s'; 'age*age' should in first place before other covariates\n \
1.192     brouard  5684:  'model=1+age+age*age+V1.' or 'model=1+age+age*age+V1+V1*age.', please swap as well as \n \
1.187     brouard  5685:  corresponding column of parameters.\n",model);
                   5686:       fprintf(ficlog,"Error in model: 'model=%s'; 'age*age' should in first place before other covariates\n \
1.192     brouard  5687:  'model=1+age+age*age+V1.' or 'model=1+age+age*age+V1+V1*age.', please swap as well as \n \
1.187     brouard  5688:  corresponding column of parameters.\n",model); fflush(ficlog);
                   5689:       return 1;
                   5690:     }
                   5691: 
                   5692:       nagesqr=1;
                   5693:       if (strstr(model,"+age*age") !=0)
                   5694:        substrchaine(modelsav, model, "+age*age");
                   5695:       else if (strstr(model,"age*age+") !=0)
                   5696:        substrchaine(modelsav, model, "age*age+");
                   5697:       else 
                   5698:        substrchaine(modelsav, model, "age*age");
                   5699:     }else
                   5700:       nagesqr=0;
                   5701:     if (strlen(modelsav) >1){
                   5702:       j=nbocc(modelsav,'+'); /**< j=Number of '+' */
                   5703:       j1=nbocc(modelsav,'*'); /**< j1=Number of '*' */
                   5704:       cptcovs=j+1-j1; /**<  Number of simple covariates V1+V1*age+V3 +V3*V4+age*age=> V1 + V3 =2  */
                   5705:       cptcovt= j+1; /* Number of total covariates in the model, not including
                   5706:                   * cst, age and age*age 
                   5707:                   * V1+V1*age+ V3 + V3*V4+age*age=> 4*/
                   5708:                   /* including age products which are counted in cptcovage.
                   5709:                  * but the covariates which are products must be treated 
                   5710:                  * separately: ncovn=4- 2=2 (V1+V3). */
                   5711:       cptcovprod=j1; /**< Number of products  V1*V2 +v3*age = 2 */
                   5712:       cptcovprodnoage=0; /**< Number of covariate products without age: V3*V4 =1  */
                   5713: 
                   5714:     
                   5715:       /*   Design
                   5716:        *  V1   V2   V3   V4  V5  V6  V7  V8  V9 Weight
                   5717:        *  <          ncovcol=8                >
                   5718:        * Model V2 + V1 + V3*age + V3 + V5*V6 + V7*V8 + V8*age + V8
                   5719:        *   k=  1    2      3       4     5       6      7        8
                   5720:        *  cptcovn number of covariates (not including constant and age ) = # of + plus 1 = 7+1=8
                   5721:        *  covar[k,i], value of kth covariate if not including age for individual i:
                   5722:        *       covar[1][i]= (V2), covar[4][i]=(V3), covar[8][i]=(V8)
                   5723:        *  Tvar[k] # of the kth covariate:  Tvar[1]=2  Tvar[4]=3 Tvar[8]=8
                   5724:        *       if multiplied by age: V3*age Tvar[3=V3*age]=3 (V3) Tvar[7]=8 and 
                   5725:        *  Tage[++cptcovage]=k
                   5726:        *       if products, new covar are created after ncovcol with k1
                   5727:        *  Tvar[k]=ncovcol+k1; # of the kth covariate product:  Tvar[5]=ncovcol+1=10  Tvar[6]=ncovcol+1=11
                   5728:        *  Tprod[k1]=k; Tprod[1]=5 Tprod[2]= 6; gives the position of the k1th product
                   5729:        *  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
                   5730:        *  Tvar[cptcovn+k2]=Tvard[k1][1];Tvar[cptcovn+k2+1]=Tvard[k1][2];
                   5731:        *  Tvar[8+1]=5;Tvar[8+2]=6;Tvar[8+3]=7;Tvar[8+4]=8 inverted
                   5732:        *  V1   V2   V3   V4  V5  V6  V7  V8  V9  V10  V11
                   5733:        *  <          ncovcol=8                >
                   5734:        *       Model V2 + V1 + V3*age + V3 + V5*V6 + V7*V8 + V8*age + V8    d1   d1   d2  d2
                   5735:        *          k=  1    2      3       4     5       6      7        8    9   10   11  12
                   5736:        *     Tvar[k]= 2    1      3       3    10      11      8        8    5    6    7   8
                   5737:        * p Tvar[1]@12={2,   1,     3,      3,   11,     10,     8,       8,   7,   8,   5,  6}
                   5738:        * p Tprod[1]@2={                         6, 5}
                   5739:        *p Tvard[1][1]@4= {7, 8, 5, 6}
                   5740:        * covar[k][i]= V2   V1      ?      V3    V5*V6?   V7*V8?  ?       V8   
                   5741:        *  cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*cov[2];
                   5742:        *How to reorganize?
                   5743:        * Model V1 + V2 + V3 + V8 + V5*V6 + V7*V8 + V3*age + V8*age
                   5744:        * Tvars {2,   1,     3,      3,   11,     10,     8,       8,   7,   8,   5,  6}
                   5745:        *       {2,   1,     4,      8,    5,      6,     3,       7}
                   5746:        * Struct []
                   5747:        */
1.145     brouard  5748: 
1.187     brouard  5749:       /* This loop fills the array Tvar from the string 'model'.*/
                   5750:       /* j is the number of + signs in the model V1+V2+V3 j=2 i=3 to 1 */
                   5751:       /*   modelsav=V2+V1+V4+age*V3 strb=age*V3 stra=V2+V1+V4  */
                   5752:       /*       k=4 (age*V3) Tvar[k=4]= 3 (from V3) Tage[cptcovage=1]=4 */
                   5753:       /*       k=3 V4 Tvar[k=3]= 4 (from V4) */
                   5754:       /*       k=2 V1 Tvar[k=2]= 1 (from V1) */
                   5755:       /*       k=1 Tvar[1]=2 (from V2) */
                   5756:       /*       k=5 Tvar[5] */
                   5757:       /* for (k=1; k<=cptcovn;k++) { */
                   5758:       /*       cov[2+k]=nbcode[Tvar[k]][codtab[ij][Tvar[k]]]; */
                   5759:       /*       } */
                   5760:       /* for (k=1; k<=cptcovage;k++) cov[2+Tage[k]]=nbcode[Tvar[Tage[k]]][codtab[ij][Tvar[Tage[k]]]]*cov[2]; */
                   5761:       /*
                   5762:        * Treating invertedly V2+V1+V3*age+V2*V4 is as if written V2*V4 +V3*age + V1 + V2 */
                   5763:       for(k=cptcovt; k>=1;k--) /**< Number of covariates */
1.145     brouard  5764:         Tvar[k]=0;
1.187     brouard  5765:       cptcovage=0;
                   5766:       for(k=1; k<=cptcovt;k++){ /* Loop on total covariates of the model */
                   5767:        cutl(stra,strb,modelsav,'+'); /* keeps in strb after the first '+' 
                   5768:                                         modelsav==V2+V1+V4+V3*age strb=V3*age stra=V2+V1+V4 */ 
                   5769:        if (nbocc(modelsav,'+')==0) strcpy(strb,modelsav); /* and analyzes it */
                   5770:        /*      printf("i=%d a=%s b=%s sav=%s\n",i, stra,strb,modelsav);*/
                   5771:        /*scanf("%d",i);*/
                   5772:        if (strchr(strb,'*')) {  /**< Model includes a product V2+V1+V4+V3*age strb=V3*age */
                   5773:          cutl(strc,strd,strb,'*'); /**< strd*strc  Vm*Vn: strb=V3*age(input) strc=age strd=V3 ; V3*V2 strc=V2, strd=V3 */
                   5774:          if (strcmp(strc,"age")==0) { /**< Model includes age: Vn*age */
                   5775:            /* covar is not filled and then is empty */
                   5776:            cptcovprod--;
                   5777:            cutl(stre,strb,strd,'V'); /* strd=V3(input): stre="3" */
                   5778:            Tvar[k]=atoi(stre);  /* V2+V1+V4+V3*age Tvar[4]=3 ; V1+V2*age Tvar[2]=2; V1+V1*age Tvar[2]=1 */
                   5779:            cptcovage++; /* Sums the number of covariates which include age as a product */
                   5780:            Tage[cptcovage]=k;  /* Tvar[4]=3, Tage[1] = 4 or V1+V1*age Tvar[2]=1, Tage[1]=2 */
                   5781:            /*printf("stre=%s ", stre);*/
                   5782:          } else if (strcmp(strd,"age")==0) { /* or age*Vn */
                   5783:            cptcovprod--;
                   5784:            cutl(stre,strb,strc,'V');
                   5785:            Tvar[k]=atoi(stre);
                   5786:            cptcovage++;
                   5787:            Tage[cptcovage]=k;
                   5788:          } else {  /* Age is not in the model product V2+V1+V1*V4+V3*age+V3*V2  strb=V3*V2*/
                   5789:            /* loops on k1=1 (V3*V2) and k1=2 V4*V3 */
                   5790:            cptcovn++;
                   5791:            cptcovprodnoage++;k1++;
                   5792:            cutl(stre,strb,strc,'V'); /* strc= Vn, stre is n; strb=V3*V2 stre=3 strc=*/
                   5793:            Tvar[k]=ncovcol+k1; /* For model-covariate k tells which data-covariate to use but
                   5794:                                   because this model-covariate is a construction we invent a new column
                   5795:                                   ncovcol + k1
                   5796:                                   If already ncovcol=4 and model=V2+V1+V1*V4+age*V3+V3*V2
                   5797:                                   Tvar[3=V1*V4]=4+1 Tvar[5=V3*V2]=4 + 2= 6, etc */
                   5798:            cutl(strc,strb,strd,'V'); /* strd was Vm, strc is m */
                   5799:            Tprod[k1]=k;  /* Tprod[1]=3(=V1*V4) for V2+V1+V1*V4+age*V3+V3*V2  */
                   5800:            Tvard[k1][1] =atoi(strc); /* m 1 for V1*/
                   5801:            Tvard[k1][2] =atoi(stre); /* n 4 for V4*/
                   5802:            k2=k2+2;
                   5803:            Tvar[cptcovt+k2]=Tvard[k1][1]; /* Tvar[(cptcovt=4+k2=1)=5]= 1 (V1) */
                   5804:            Tvar[cptcovt+k2+1]=Tvard[k1][2];  /* Tvar[(cptcovt=4+(k2=1)+1)=6]= 4 (V4) */
                   5805:            for (i=1; i<=lastobs;i++){
                   5806:              /* Computes the new covariate which is a product of
                   5807:                 covar[n][i]* covar[m][i] and stores it at ncovol+k1 May not be defined */
                   5808:              covar[ncovcol+k1][i]=covar[atoi(stre)][i]*covar[atoi(strc)][i];
                   5809:            }
                   5810:          } /* End age is not in the model */
                   5811:        } /* End if model includes a product */
                   5812:        else { /* no more sum */
                   5813:          /*printf("d=%s c=%s b=%s\n", strd,strc,strb);*/
                   5814:          /*  scanf("%d",i);*/
                   5815:          cutl(strd,strc,strb,'V');
                   5816:          ks++; /**< Number of simple covariates */
1.145     brouard  5817:          cptcovn++;
1.187     brouard  5818:          Tvar[k]=atoi(strd);
                   5819:        }
                   5820:        strcpy(modelsav,stra);  /* modelsav=V2+V1+V4 stra=V2+V1+V4 */ 
                   5821:        /*printf("a=%s b=%s sav=%s\n", stra,strb,modelsav);
                   5822:          scanf("%d",i);*/
                   5823:       } /* end of loop + on total covariates */
                   5824:     } /* end if strlen(modelsave == 0) age*age might exist */
                   5825:   } /* end if strlen(model == 0) */
1.136     brouard  5826:   
                   5827:   /*The number n of Vn is stored in Tvar. cptcovage =number of age covariate. Tage gives the position of age. cptcovprod= number of products.
                   5828:     If model=V1+V1*age then Tvar[1]=1 Tvar[2]=1 cptcovage=1 Tage[1]=2 cptcovprod=0*/
                   5829: 
                   5830:   /* printf("tvar1=%d tvar2=%d tvar3=%d cptcovage=%d Tage=%d",Tvar[1],Tvar[2],Tvar[3],cptcovage,Tage[1]);
                   5831:   printf("cptcovprod=%d ", cptcovprod);
                   5832:   fprintf(ficlog,"cptcovprod=%d ", cptcovprod);
                   5833: 
                   5834:   scanf("%d ",i);*/
                   5835: 
                   5836: 
1.137     brouard  5837:   return (0); /* with covar[new additional covariate if product] and Tage if age */ 
1.164     brouard  5838:   /*endread:*/
1.136     brouard  5839:     printf("Exiting decodemodel: ");
                   5840:     return (1);
                   5841: }
                   5842: 
1.169     brouard  5843: int calandcheckages(int imx, int maxwav, double *agemin, double *agemax, int *nberr, int *nbwarn )
1.136     brouard  5844: {
                   5845:   int i, m;
                   5846: 
                   5847:   for (i=1; i<=imx; i++) {
                   5848:     for(m=2; (m<= maxwav); m++) {
                   5849:       if (((int)mint[m][i]== 99) && (s[m][i] <= nlstate)){
                   5850:        anint[m][i]=9999;
                   5851:        s[m][i]=-1;
                   5852:       }
                   5853:       if((int)moisdc[i]==99 && (int)andc[i]==9999 && s[m][i]>nlstate){
1.169     brouard  5854:        *nberr = *nberr + 1;
                   5855:        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);
                   5856:        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  5857:        s[m][i]=-1;
                   5858:       }
                   5859:       if((int)moisdc[i]==99 && (int)andc[i]!=9999 && s[m][i]>nlstate){
1.169     brouard  5860:        (*nberr)++;
1.136     brouard  5861:        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]); 
                   5862:        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]); 
                   5863:        s[m][i]=-1; /* We prefer to skip it (and to skip it in version 0.8a1 too */
                   5864:       }
                   5865:     }
                   5866:   }
                   5867: 
                   5868:   for (i=1; i<=imx; i++)  {
                   5869:     agedc[i]=(moisdc[i]/12.+andc[i])-(moisnais[i]/12.+annais[i]);
                   5870:     for(m=firstpass; (m<= lastpass); m++){
                   5871:       if(s[m][i] >0 || s[m][i]==-2 || s[m][i]==-4 || s[m][i]==-5){
                   5872:        if (s[m][i] >= nlstate+1) {
1.169     brouard  5873:          if(agedc[i]>0){
                   5874:            if((int)moisdc[i]!=99 && (int)andc[i]!=9999){
1.136     brouard  5875:              agev[m][i]=agedc[i];
                   5876:          /*if(moisdc[i]==99 && andc[i]==9999) s[m][i]=-1;*/
1.169     brouard  5877:            }else {
1.136     brouard  5878:              if ((int)andc[i]!=9999){
                   5879:                nbwarn++;
                   5880:                printf("Warning negative age at death: %ld line:%d\n",num[i],i);
                   5881:                fprintf(ficlog,"Warning negative age at death: %ld line:%d\n",num[i],i);
                   5882:                agev[m][i]=-1;
                   5883:              }
                   5884:            }
1.169     brouard  5885:          } /* agedc > 0 */
1.136     brouard  5886:        }
                   5887:        else if(s[m][i] !=9){ /* Standard case, age in fractional
                   5888:                                 years but with the precision of a month */
                   5889:          agev[m][i]=(mint[m][i]/12.+1./24.+anint[m][i])-(moisnais[i]/12.+1./24.+annais[i]);
                   5890:          if((int)mint[m][i]==99 || (int)anint[m][i]==9999)
                   5891:            agev[m][i]=1;
                   5892:          else if(agev[m][i] < *agemin){ 
                   5893:            *agemin=agev[m][i];
                   5894:            printf(" Min anint[%d][%d]=%.2f annais[%d]=%.2f, agemin=%.2f\n",m,i,anint[m][i], i,annais[i], *agemin);
                   5895:          }
                   5896:          else if(agev[m][i] >*agemax){
                   5897:            *agemax=agev[m][i];
1.156     brouard  5898:            /* printf(" Max anint[%d][%d]=%.0f annais[%d]=%.0f, agemax=%.2f\n",m,i,anint[m][i], i,annais[i], *agemax);*/
1.136     brouard  5899:          }
                   5900:          /*agev[m][i]=anint[m][i]-annais[i];*/
                   5901:          /*     agev[m][i] = age[i]+2*m;*/
                   5902:        }
                   5903:        else { /* =9 */
                   5904:          agev[m][i]=1;
                   5905:          s[m][i]=-1;
                   5906:        }
                   5907:       }
                   5908:       else /*= 0 Unknown */
                   5909:        agev[m][i]=1;
                   5910:     }
                   5911:     
                   5912:   }
                   5913:   for (i=1; i<=imx; i++)  {
                   5914:     for(m=firstpass; (m<=lastpass); m++){
                   5915:       if (s[m][i] > (nlstate+ndeath)) {
1.169     brouard  5916:        (*nberr)++;
1.136     brouard  5917:        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);     
                   5918:        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);     
                   5919:        return 1;
                   5920:       }
                   5921:     }
                   5922:   }
                   5923: 
                   5924:   /*for (i=1; i<=imx; i++){
                   5925:   for (m=firstpass; (m<lastpass); m++){
                   5926:      printf("%ld %d %.lf %d %d\n", num[i],(covar[1][i]),agev[m][i],s[m][i],s[m+1][i]);
                   5927: }
                   5928: 
                   5929: }*/
                   5930: 
                   5931: 
1.139     brouard  5932:   printf("Total number of individuals= %d, Agemin = %.2f, Agemax= %.2f\n\n", imx, *agemin, *agemax);
                   5933:   fprintf(ficlog,"Total number of individuals= %d, Agemin = %.2f, Agemax= %.2f\n\n", imx, *agemin, *agemax); 
1.136     brouard  5934: 
                   5935:   return (0);
1.164     brouard  5936:  /* endread:*/
1.136     brouard  5937:     printf("Exiting calandcheckages: ");
                   5938:     return (1);
                   5939: }
                   5940: 
1.172     brouard  5941: #if defined(_MSC_VER)
                   5942: /*printf("Visual C++ compiler: %s \n;", _MSC_FULL_VER);*/
                   5943: /*fprintf(ficlog, "Visual C++ compiler: %s \n;", _MSC_FULL_VER);*/
                   5944: //#include "stdafx.h"
                   5945: //#include <stdio.h>
                   5946: //#include <tchar.h>
                   5947: //#include <windows.h>
                   5948: //#include <iostream>
                   5949: typedef BOOL(WINAPI *LPFN_ISWOW64PROCESS) (HANDLE, PBOOL);
                   5950: 
                   5951: LPFN_ISWOW64PROCESS fnIsWow64Process;
                   5952: 
                   5953: BOOL IsWow64()
                   5954: {
                   5955:        BOOL bIsWow64 = FALSE;
                   5956: 
                   5957:        //typedef BOOL (APIENTRY *LPFN_ISWOW64PROCESS)
                   5958:        //  (HANDLE, PBOOL);
                   5959: 
                   5960:        //LPFN_ISWOW64PROCESS fnIsWow64Process;
                   5961: 
                   5962:        HMODULE module = GetModuleHandle(_T("kernel32"));
                   5963:        const char funcName[] = "IsWow64Process";
                   5964:        fnIsWow64Process = (LPFN_ISWOW64PROCESS)
                   5965:                GetProcAddress(module, funcName);
                   5966: 
                   5967:        if (NULL != fnIsWow64Process)
                   5968:        {
                   5969:                if (!fnIsWow64Process(GetCurrentProcess(),
                   5970:                        &bIsWow64))
                   5971:                        //throw std::exception("Unknown error");
                   5972:                        printf("Unknown error\n");
                   5973:        }
                   5974:        return bIsWow64 != FALSE;
                   5975: }
                   5976: #endif
1.177     brouard  5977: 
1.191     brouard  5978: void syscompilerinfo(int logged)
1.167     brouard  5979:  {
                   5980:    /* #include "syscompilerinfo.h"*/
1.185     brouard  5981:    /* command line Intel compiler 32bit windows, XP compatible:*/
                   5982:    /* /GS /W3 /Gy
                   5983:       /Zc:wchar_t /Zi /O2 /Fd"Release\vc120.pdb" /D "WIN32" /D "NDEBUG" /D
                   5984:       "_CONSOLE" /D "_LIB" /D "_USING_V110_SDK71_" /D "_UNICODE" /D
                   5985:       "UNICODE" /Qipo /Zc:forScope /Gd /Oi /MT /Fa"Release\" /EHsc /nologo
1.186     brouard  5986:       /Fo"Release\" /Qprof-dir "Release\" /Fp"Release\IMaCh.pch"
                   5987:    */ 
                   5988:    /* 64 bits */
1.185     brouard  5989:    /*
                   5990:      /GS /W3 /Gy
                   5991:      /Zc:wchar_t /Zi /O2 /Fd"x64\Release\vc120.pdb" /D "WIN32" /D "NDEBUG"
                   5992:      /D "_CONSOLE" /D "_LIB" /D "_UNICODE" /D "UNICODE" /Qipo /Zc:forScope
                   5993:      /Oi /MD /Fa"x64\Release\" /EHsc /nologo /Fo"x64\Release\" /Qprof-dir
                   5994:      "x64\Release\" /Fp"x64\Release\IMaCh.pch" */
                   5995:    /* Optimization are useless and O3 is slower than O2 */
                   5996:    /*
                   5997:      /GS /W3 /Gy /Zc:wchar_t /Zi /O3 /Fd"x64\Release\vc120.pdb" /D "WIN32" 
                   5998:      /D "NDEBUG" /D "_CONSOLE" /D "_LIB" /D "_UNICODE" /D "UNICODE" /Qipo 
                   5999:      /Zc:forScope /Oi /MD /Fa"x64\Release\" /EHsc /nologo /Qparallel 
                   6000:      /Fo"x64\Release\" /Qprof-dir "x64\Release\" /Fp"x64\Release\IMaCh.pch" 
                   6001:    */
1.186     brouard  6002:    /* Link is */ /* /OUT:"visual studio
1.185     brouard  6003:       2013\Projects\IMaCh\Release\IMaCh.exe" /MANIFEST /NXCOMPAT
                   6004:       /PDB:"visual studio
                   6005:       2013\Projects\IMaCh\Release\IMaCh.pdb" /DYNAMICBASE
                   6006:       "kernel32.lib" "user32.lib" "gdi32.lib" "winspool.lib"
                   6007:       "comdlg32.lib" "advapi32.lib" "shell32.lib" "ole32.lib"
                   6008:       "oleaut32.lib" "uuid.lib" "odbc32.lib" "odbccp32.lib"
                   6009:       /MACHINE:X86 /OPT:REF /SAFESEH /INCREMENTAL:NO
                   6010:       /SUBSYSTEM:CONSOLE",5.01" /MANIFESTUAC:"level='asInvoker'
                   6011:       uiAccess='false'"
                   6012:       /ManifestFile:"Release\IMaCh.exe.intermediate.manifest" /OPT:ICF
                   6013:       /NOLOGO /TLBID:1
                   6014:    */
1.177     brouard  6015: #if defined __INTEL_COMPILER
1.178     brouard  6016: #if defined(__GNUC__)
                   6017:        struct utsname sysInfo;  /* For Intel on Linux and OS/X */
                   6018: #endif
1.177     brouard  6019: #elif defined(__GNUC__) 
1.179     brouard  6020: #ifndef  __APPLE__
1.174     brouard  6021: #include <gnu/libc-version.h>  /* Only on gnu */
1.179     brouard  6022: #endif
1.177     brouard  6023:    struct utsname sysInfo;
1.178     brouard  6024:    int cross = CROSS;
                   6025:    if (cross){
                   6026:           printf("Cross-");
1.191     brouard  6027:           if(logged) fprintf(ficlog, "Cross-");
1.178     brouard  6028:    }
1.174     brouard  6029: #endif
                   6030: 
1.171     brouard  6031: #include <stdint.h>
1.178     brouard  6032: 
1.191     brouard  6033:    printf("Compiled with:");if(logged)fprintf(ficlog,"Compiled with:");
1.169     brouard  6034: #if defined(__clang__)
1.191     brouard  6035:    printf(" Clang/LLVM");if(logged)fprintf(ficlog," Clang/LLVM");      /* Clang/LLVM. ---------------------------------------------- */
1.169     brouard  6036: #endif
                   6037: #if defined(__ICC) || defined(__INTEL_COMPILER)
1.191     brouard  6038:    printf(" Intel ICC/ICPC");if(logged)fprintf(ficlog," Intel ICC/ICPC");/* Intel ICC/ICPC. ------------------------------------------ */
1.169     brouard  6039: #endif
                   6040: #if defined(__GNUC__) || defined(__GNUG__)
1.191     brouard  6041:    printf(" GNU GCC/G++");if(logged)fprintf(ficlog," GNU GCC/G++");/* GNU GCC/G++. --------------------------------------------- */
1.169     brouard  6042: #endif
                   6043: #if defined(__HP_cc) || defined(__HP_aCC)
1.191     brouard  6044:    printf(" Hewlett-Packard C/aC++");if(logged)fprintf(fcilog," Hewlett-Packard C/aC++"); /* Hewlett-Packard C/aC++. ---------------------------------- */
1.169     brouard  6045: #endif
                   6046: #if defined(__IBMC__) || defined(__IBMCPP__)
1.191     brouard  6047:    printf(" IBM XL C/C++"); if(logged) fprintf(ficlog," IBM XL C/C++");/* IBM XL C/C++. -------------------------------------------- */
1.169     brouard  6048: #endif
                   6049: #if defined(_MSC_VER)
1.191     brouard  6050:    printf(" Microsoft Visual Studio");if(logged)fprintf(ficlog," Microsoft Visual Studio");/* Microsoft Visual Studio. --------------------------------- */
1.169     brouard  6051: #endif
                   6052: #if defined(__PGI)
1.191     brouard  6053:    printf(" Portland Group PGCC/PGCPP");if(logged) fprintf(ficlog," Portland Group PGCC/PGCPP");/* Portland Group PGCC/PGCPP. ------------------------------- */
1.169     brouard  6054: #endif
                   6055: #if defined(__SUNPRO_C) || defined(__SUNPRO_CC)
1.191     brouard  6056:    printf(" Oracle Solaris Studio");if(logged)fprintf(ficlog," Oracle Solaris Studio\n");/* Oracle Solaris Studio. ----------------------------------- */
1.167     brouard  6057: #endif
1.191     brouard  6058:    printf(" for "); if (logged) fprintf(ficlog, " for ");
1.169     brouard  6059:    
1.167     brouard  6060: // http://stackoverflow.com/questions/4605842/how-to-identify-platform-compiler-from-preprocessor-macros
                   6061: #ifdef _WIN32 // note the underscore: without it, it's not msdn official!
                   6062:     // Windows (x64 and x86)
1.191     brouard  6063:    printf("Windows (x64 and x86) ");if(logged) fprintf(ficlog,"Windows (x64 and x86) ");
1.167     brouard  6064: #elif __unix__ // all unices, not all compilers
                   6065:     // Unix
1.191     brouard  6066:    printf("Unix ");if(logged) fprintf(ficlog,"Unix ");
1.167     brouard  6067: #elif __linux__
                   6068:     // linux
1.191     brouard  6069:    printf("linux ");if(logged) fprintf(ficlog,"linux ");
1.167     brouard  6070: #elif __APPLE__
1.174     brouard  6071:     // Mac OS, not sure if this is covered by __posix__ and/or __unix__ though..
1.191     brouard  6072:    printf("Mac OS ");if(logged) fprintf(ficlog,"Mac OS ");
1.167     brouard  6073: #endif
                   6074: 
                   6075: /*  __MINGW32__          */
                   6076: /*  __CYGWIN__  */
                   6077: /* __MINGW64__  */
                   6078: // http://msdn.microsoft.com/en-us/library/b0084kay.aspx
                   6079: /* _MSC_VER  //the Visual C++ compiler is 17.00.51106.1, the _MSC_VER macro evaluates to 1700. Type cl /?  */
                   6080: /* _MSC_FULL_VER //the Visual C++ compiler is 15.00.20706.01, the _MSC_FULL_VER macro evaluates to 150020706 */
                   6081: /* _WIN64  // Defined for applications for Win64. */
                   6082: /* _M_X64 // Defined for compilations that target x64 processors. */
                   6083: /* _DEBUG // Defined when you compile with /LDd, /MDd, and /MTd. */
1.171     brouard  6084: 
1.167     brouard  6085: #if UINTPTR_MAX == 0xffffffff
1.191     brouard  6086:    printf(" 32-bit"); if(logged) fprintf(ficlog," 32-bit");/* 32-bit */
1.167     brouard  6087: #elif UINTPTR_MAX == 0xffffffffffffffff
1.191     brouard  6088:    printf(" 64-bit"); if(logged) fprintf(ficlog," 64-bit");/* 64-bit */
1.167     brouard  6089: #else
1.191     brouard  6090:    printf(" wtf-bit"); if(logged) fprintf(ficlog," wtf-bit");/* wtf */
1.167     brouard  6091: #endif
                   6092: 
1.169     brouard  6093: #if defined(__GNUC__)
                   6094: # if defined(__GNUC_PATCHLEVEL__)
                   6095: #  define __GNUC_VERSION__ (__GNUC__ * 10000 \
                   6096:                             + __GNUC_MINOR__ * 100 \
                   6097:                             + __GNUC_PATCHLEVEL__)
                   6098: # else
                   6099: #  define __GNUC_VERSION__ (__GNUC__ * 10000 \
                   6100:                             + __GNUC_MINOR__ * 100)
                   6101: # endif
1.174     brouard  6102:    printf(" using GNU C version %d.\n", __GNUC_VERSION__);
1.191     brouard  6103:    if(logged) fprintf(ficlog, " using GNU C version %d.\n", __GNUC_VERSION__);
1.176     brouard  6104: 
                   6105:    if (uname(&sysInfo) != -1) {
                   6106:      printf("Running on: %s %s %s %s %s\n",sysInfo.sysname, sysInfo.nodename, sysInfo.release, sysInfo.version, sysInfo.machine);
1.191     brouard  6107:         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  6108:    }
                   6109:    else
                   6110:       perror("uname() error");
1.179     brouard  6111:    //#ifndef __INTEL_COMPILER 
                   6112: #if !defined (__INTEL_COMPILER) && !defined(__APPLE__)
1.174     brouard  6113:    printf("GNU libc version: %s\n", gnu_get_libc_version()); 
1.191     brouard  6114:    if(logged) fprintf(ficlog,"GNU libc version: %s\n", gnu_get_libc_version());
1.177     brouard  6115: #endif
1.169     brouard  6116: #endif
1.172     brouard  6117: 
                   6118:    //   void main()
                   6119:    //   {
1.169     brouard  6120: #if defined(_MSC_VER)
1.174     brouard  6121:    if (IsWow64()){
1.191     brouard  6122:           printf("\nThe program (probably compiled for 32bit) is running under WOW64 (64bit) emulation.\n");
                   6123:           if (logged) fprintf(ficlog, "\nThe program (probably compiled for 32bit) is running under WOW64 (64bit) emulation.\n");
1.174     brouard  6124:    }
                   6125:    else{
1.191     brouard  6126:           printf("\nThe program is not running under WOW64 (i.e probably on a 64bit Windows).\n");
                   6127:           if (logged) fprintf(ficlog, "\nThe programm is not running under WOW64 (i.e probably on a 64bit Windows).\n");
1.174     brouard  6128:    }
1.172     brouard  6129:    //     printf("\nPress Enter to continue...");
                   6130:    //     getchar();
                   6131:    //   }
                   6132: 
1.169     brouard  6133: #endif
                   6134:    
1.167     brouard  6135: 
                   6136:  }
1.136     brouard  6137: 
1.180     brouard  6138: int prevalence_limit(double *p, double **prlim, double ageminpar, double agemaxpar){
                   6139:   /*--------------- Prevalence limit  (period or stable prevalence) --------------*/
                   6140:   int i, j, k, i1 ;
                   6141:   double ftolpl = 1.e-10;
                   6142:   double age, agebase, agelim;
                   6143: 
                   6144:     strcpy(filerespl,"pl");
                   6145:     strcat(filerespl,fileres);
                   6146:     if((ficrespl=fopen(filerespl,"w"))==NULL) {
                   6147:       printf("Problem with period (stable) prevalence resultfile: %s\n", filerespl);return 1;
                   6148:       fprintf(ficlog,"Problem with period (stable) prevalence resultfile: %s\n", filerespl);return 1;
                   6149:     }
                   6150:     printf("Computing period (stable) prevalence: result on file '%s' \n", filerespl);
                   6151:     fprintf(ficlog,"Computing period (stable) prevalence: result on file '%s' \n", filerespl);
                   6152:     pstamp(ficrespl);
                   6153:     fprintf(ficrespl,"# Period (stable) prevalence \n");
                   6154:     fprintf(ficrespl,"#Age ");
                   6155:     for(i=1; i<=nlstate;i++) fprintf(ficrespl,"%d-%d ",i,i);
                   6156:     fprintf(ficrespl,"\n");
                   6157:   
                   6158:     /* prlim=matrix(1,nlstate,1,nlstate);*/ /* back in main */
                   6159: 
                   6160:     agebase=ageminpar;
                   6161:     agelim=agemaxpar;
                   6162: 
                   6163:     i1=pow(2,cptcoveff);
                   6164:     if (cptcovn < 1){i1=1;}
                   6165: 
                   6166:     for(cptcov=1,k=0;cptcov<=i1;cptcov++){
                   6167:     /* for(cptcov=1,k=0;cptcov<=1;cptcov++){ */
                   6168:       //for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){
                   6169:        k=k+1;
                   6170:        /* to clean */
                   6171:        //printf("cptcov=%d cptcod=%d codtab=%d\n",cptcov, cptcod,codtab[cptcod][cptcov]);
                   6172:        fprintf(ficrespl,"\n#******");
                   6173:        printf("\n#******");
                   6174:        fprintf(ficlog,"\n#******");
                   6175:        for(j=1;j<=cptcoveff;j++) {
                   6176:          fprintf(ficrespl," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
                   6177:          printf(" V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
                   6178:          fprintf(ficlog," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
                   6179:        }
                   6180:        fprintf(ficrespl,"******\n");
                   6181:        printf("******\n");
                   6182:        fprintf(ficlog,"******\n");
                   6183: 
                   6184:        fprintf(ficrespl,"#Age ");
                   6185:        for(j=1;j<=cptcoveff;j++) {
                   6186:          fprintf(ficrespl,"V%d %d",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
                   6187:        }
                   6188:        for(i=1; i<=nlstate;i++) fprintf(ficrespl,"%d-%d ",i,i);
                   6189:        fprintf(ficrespl,"\n");
                   6190:        
                   6191:        for (age=agebase; age<=agelim; age++){
                   6192:        /* for (age=agebase; age<=agebase; age++){ */
                   6193:          prevalim(prlim, nlstate, p, age, oldm, savm,ftolpl,k);
                   6194:          fprintf(ficrespl,"%.0f ",age );
                   6195:          for(j=1;j<=cptcoveff;j++)
                   6196:            fprintf(ficrespl,"%d %d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
                   6197:          for(i=1; i<=nlstate;i++)
                   6198:            fprintf(ficrespl," %.5f", prlim[i][i]);
                   6199:          fprintf(ficrespl,"\n");
                   6200:        } /* Age */
                   6201:        /* was end of cptcod */
                   6202:     } /* cptcov */
1.184     brouard  6203:        return 0;
1.180     brouard  6204: }
                   6205: 
                   6206: int hPijx(double *p, int bage, int fage){
                   6207:     /*------------- h Pij x at various ages ------------*/
                   6208: 
                   6209:   int stepsize;
                   6210:   int agelim;
                   6211:   int hstepm;
                   6212:   int nhstepm;
                   6213:   int h, i, i1, j, k;
                   6214: 
                   6215:   double agedeb;
                   6216:   double ***p3mat;
                   6217: 
                   6218:     strcpy(filerespij,"pij");  strcat(filerespij,fileres);
                   6219:     if((ficrespij=fopen(filerespij,"w"))==NULL) {
                   6220:       printf("Problem with Pij resultfile: %s\n", filerespij); return 1;
                   6221:       fprintf(ficlog,"Problem with Pij resultfile: %s\n", filerespij); return 1;
                   6222:     }
                   6223:     printf("Computing pij: result on file '%s' \n", filerespij);
                   6224:     fprintf(ficlog,"Computing pij: result on file '%s' \n", filerespij);
                   6225:   
                   6226:     stepsize=(int) (stepm+YEARM-1)/YEARM;
                   6227:     /*if (stepm<=24) stepsize=2;*/
                   6228: 
                   6229:     agelim=AGESUP;
                   6230:     hstepm=stepsize*YEARM; /* Every year of age */
                   6231:     hstepm=hstepm/stepm; /* Typically 2 years, = 2/6 months = 4 */ 
                   6232: 
                   6233:     /* hstepm=1;   aff par mois*/
                   6234:     pstamp(ficrespij);
                   6235:     fprintf(ficrespij,"#****** h Pij x Probability to be in state j at age x+h being in i at x ");
                   6236:     i1= pow(2,cptcoveff);
1.183     brouard  6237:    /* for(cptcov=1,k=0;cptcov<=i1;cptcov++){ */
                   6238:    /*    /\*for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){*\/ */
                   6239:    /*          k=k+1;  */
                   6240:     for (k=1; k <= (int) pow(2,cptcoveff); k++){
                   6241:       fprintf(ficrespij,"\n#****** ");
                   6242:       for(j=1;j<=cptcoveff;j++) 
                   6243:        fprintf(ficrespij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
                   6244:       fprintf(ficrespij,"******\n");
                   6245:       
                   6246:       for (agedeb=fage; agedeb>=bage; agedeb--){ /* If stepm=6 months */
                   6247:        nhstepm=(int) rint((agelim-agedeb)*YEARM/stepm); /* Typically 20 years = 20*12/6=40 */ 
                   6248:        nhstepm = nhstepm/hstepm; /* Typically 40/4=10 */
                   6249:        
                   6250:        /*        nhstepm=nhstepm*YEARM; aff par mois*/
1.180     brouard  6251:        
1.183     brouard  6252:        p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   6253:        oldm=oldms;savm=savms;
                   6254:        hpxij(p3mat,nhstepm,agedeb,hstepm,p,nlstate,stepm,oldm,savm, k);  
                   6255:        fprintf(ficrespij,"# Cov Agex agex+h hpijx with i,j=");
                   6256:        for(i=1; i<=nlstate;i++)
                   6257:          for(j=1; j<=nlstate+ndeath;j++)
                   6258:            fprintf(ficrespij," %1d-%1d",i,j);
                   6259:        fprintf(ficrespij,"\n");
                   6260:        for (h=0; h<=nhstepm; h++){
                   6261:          /*agedebphstep = agedeb + h*hstepm/YEARM*stepm;*/
                   6262:          fprintf(ficrespij,"%d %3.f %3.f",k, agedeb, agedeb + h*hstepm/YEARM*stepm );
1.180     brouard  6263:          for(i=1; i<=nlstate;i++)
                   6264:            for(j=1; j<=nlstate+ndeath;j++)
1.183     brouard  6265:              fprintf(ficrespij," %.5f", p3mat[i][j][h]);
1.180     brouard  6266:          fprintf(ficrespij,"\n");
                   6267:        }
1.183     brouard  6268:        free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   6269:        fprintf(ficrespij,"\n");
                   6270:       }
1.180     brouard  6271:       /*}*/
                   6272:     }
1.184     brouard  6273:        return 0;
1.180     brouard  6274: }
                   6275: 
                   6276: 
1.136     brouard  6277: /***********************************************/
                   6278: /**************** Main Program *****************/
                   6279: /***********************************************/
                   6280: 
                   6281: int main(int argc, char *argv[])
                   6282: {
                   6283: #ifdef GSL
                   6284:   const gsl_multimin_fminimizer_type *T;
                   6285:   size_t iteri = 0, it;
                   6286:   int rval = GSL_CONTINUE;
                   6287:   int status = GSL_SUCCESS;
                   6288:   double ssval;
                   6289: #endif
                   6290:   int movingaverage(double ***probs, double bage,double fage, double ***mobaverage, int mobilav);
1.164     brouard  6291:   int i,j, k, n=MAXN,iter=0,m,size=100, cptcod;
                   6292: 
                   6293:   int jj, ll, li, lj, lk;
1.136     brouard  6294:   int numlinepar=0; /* Current linenumber of parameter file */
1.197   ! brouard  6295:   int num_filled;
1.136     brouard  6296:   int itimes;
                   6297:   int NDIM=2;
                   6298:   int vpopbased=0;
                   6299: 
1.164     brouard  6300:   char ca[32], cb[32];
1.136     brouard  6301:   /*  FILE *fichtm; *//* Html File */
                   6302:   /* FILE *ficgp;*/ /*Gnuplot File */
                   6303:   struct stat info;
1.191     brouard  6304:   double agedeb=0.;
1.194     brouard  6305: 
                   6306:   double ageminpar=AGEOVERFLOW,agemin=AGEOVERFLOW, agemaxpar=-AGEOVERFLOW, agemax=-AGEOVERFLOW;
1.136     brouard  6307: 
1.165     brouard  6308:   double fret;
1.191     brouard  6309:   double dum=0.; /* Dummy variable */
1.136     brouard  6310:   double ***p3mat;
                   6311:   double ***mobaverage;
1.164     brouard  6312: 
                   6313:   char line[MAXLINE];
1.197   ! brouard  6314:   char path[MAXLINE],pathc[MAXLINE],pathcd[MAXLINE],pathtot[MAXLINE];
        !          6315: 
        !          6316:   char model[MAXLINE], modeltemp[MAXLINE];
1.136     brouard  6317:   char pathr[MAXLINE], pathimach[MAXLINE]; 
1.164     brouard  6318:   char *tok, *val; /* pathtot */
1.136     brouard  6319:   int firstobs=1, lastobs=10;
1.195     brouard  6320:   int c,  h , cpt, c2;
1.191     brouard  6321:   int jl=0;
                   6322:   int i1, j1, jk, stepsize=0;
1.194     brouard  6323:   int count=0;
                   6324: 
1.164     brouard  6325:   int *tab; 
1.136     brouard  6326:   int mobilavproj=0 , prevfcast=0 ; /* moving average of prev, If prevfcast=1 prevalence projection */
                   6327:   int mobilav=0,popforecast=0;
1.191     brouard  6328:   int hstepm=0, nhstepm=0;
1.136     brouard  6329:   int agemortsup;
                   6330:   float  sumlpop=0.;
                   6331:   double jprev1=1, mprev1=1,anprev1=2000,jprev2=1, mprev2=1,anprev2=2000;
                   6332:   double jpyram=1, mpyram=1,anpyram=2000,jpyram1=1, mpyram1=1,anpyram1=2000;
                   6333: 
1.191     brouard  6334:   double bage=0, fage=110., age, agelim=0., agebase=0.;
1.136     brouard  6335:   double ftolpl=FTOL;
                   6336:   double **prlim;
                   6337:   double ***param; /* Matrix of parameters */
                   6338:   double  *p;
                   6339:   double **matcov; /* Matrix of covariance */
                   6340:   double ***delti3; /* Scale */
                   6341:   double *delti; /* Scale */
                   6342:   double ***eij, ***vareij;
                   6343:   double **varpl; /* Variances of prevalence limits by age */
                   6344:   double *epj, vepp;
1.164     brouard  6345: 
1.136     brouard  6346:   double dateprev1, dateprev2,jproj1=1,mproj1=1,anproj1=2000,jproj2=1,mproj2=1,anproj2=2000;
                   6347:   double **ximort;
1.145     brouard  6348:   char *alph[]={"a","a","b","c","d","e"}, str[4]="1234";
1.136     brouard  6349:   int *dcwave;
                   6350: 
1.164     brouard  6351:   char z[1]="c";
1.136     brouard  6352: 
                   6353:   /*char  *strt;*/
                   6354:   char strtend[80];
1.126     brouard  6355: 
1.164     brouard  6356: 
1.126     brouard  6357: /*   setlocale (LC_ALL, ""); */
                   6358: /*   bindtextdomain (PACKAGE, LOCALEDIR); */
                   6359: /*   textdomain (PACKAGE); */
                   6360: /*   setlocale (LC_CTYPE, ""); */
                   6361: /*   setlocale (LC_MESSAGES, ""); */
                   6362: 
                   6363:   /*   gettimeofday(&start_time, (struct timezone*)0); */ /* at first time */
1.157     brouard  6364:   rstart_time = time(NULL);  
                   6365:   /*  (void) gettimeofday(&start_time,&tzp);*/
                   6366:   start_time = *localtime(&rstart_time);
1.126     brouard  6367:   curr_time=start_time;
1.157     brouard  6368:   /*tml = *localtime(&start_time.tm_sec);*/
                   6369:   /* strcpy(strstart,asctime(&tml)); */
                   6370:   strcpy(strstart,asctime(&start_time));
1.126     brouard  6371: 
                   6372: /*  printf("Localtime (at start)=%s",strstart); */
1.157     brouard  6373: /*  tp.tm_sec = tp.tm_sec +86400; */
                   6374: /*  tm = *localtime(&start_time.tm_sec); */
1.126     brouard  6375: /*   tmg.tm_year=tmg.tm_year +dsign*dyear; */
                   6376: /*   tmg.tm_mon=tmg.tm_mon +dsign*dmonth; */
                   6377: /*   tmg.tm_hour=tmg.tm_hour + 1; */
1.157     brouard  6378: /*   tp.tm_sec = mktime(&tmg); */
1.126     brouard  6379: /*   strt=asctime(&tmg); */
                   6380: /*   printf("Time(after) =%s",strstart);  */
                   6381: /*  (void) time (&time_value);
                   6382: *  printf("time=%d,t-=%d\n",time_value,time_value-86400);
                   6383: *  tm = *localtime(&time_value);
                   6384: *  strstart=asctime(&tm);
                   6385: *  printf("tim_value=%d,asctime=%s\n",time_value,strstart); 
                   6386: */
                   6387: 
                   6388:   nberr=0; /* Number of errors and warnings */
                   6389:   nbwarn=0;
1.184     brouard  6390: #ifdef WIN32
                   6391:   _getcwd(pathcd, size);
                   6392: #else
1.126     brouard  6393:   getcwd(pathcd, size);
1.184     brouard  6394: #endif
1.191     brouard  6395:   syscompilerinfo(0);
1.196     brouard  6396:   printf("\nIMaCh version %s, %s\n%s",version, copyright, fullversion);
1.126     brouard  6397:   if(argc <=1){
                   6398:     printf("\nEnter the parameter file name: ");
                   6399:     fgets(pathr,FILENAMELENGTH,stdin);
                   6400:     i=strlen(pathr);
                   6401:     if(pathr[i-1]=='\n')
                   6402:       pathr[i-1]='\0';
1.156     brouard  6403:     i=strlen(pathr);
                   6404:     if(pathr[i-1]==' ') /* This may happen when dragging on oS/X! */
                   6405:       pathr[i-1]='\0';
1.126     brouard  6406:    for (tok = pathr; tok != NULL; ){
                   6407:       printf("Pathr |%s|\n",pathr);
                   6408:       while ((val = strsep(&tok, "\"" )) != NULL && *val == '\0');
                   6409:       printf("val= |%s| pathr=%s\n",val,pathr);
                   6410:       strcpy (pathtot, val);
                   6411:       if(pathr[0] == '\0') break; /* Dirty */
                   6412:     }
                   6413:   }
                   6414:   else{
                   6415:     strcpy(pathtot,argv[1]);
                   6416:   }
                   6417:   /*if(getcwd(pathcd, MAXLINE)!= NULL)printf ("Error pathcd\n");*/
                   6418:   /*cygwin_split_path(pathtot,path,optionfile);
                   6419:     printf("pathtot=%s, path=%s, optionfile=%s\n",pathtot,path,optionfile);*/
                   6420:   /* cutv(path,optionfile,pathtot,'\\');*/
                   6421: 
                   6422:   /* Split argv[0], imach program to get pathimach */
                   6423:   printf("\nargv[0]=%s argv[1]=%s, \n",argv[0],argv[1]);
                   6424:   split(argv[0],pathimach,optionfile,optionfilext,optionfilefiname);
                   6425:   printf("\nargv[0]=%s pathimach=%s, \noptionfile=%s \noptionfilext=%s \noptionfilefiname=%s\n",argv[0],pathimach,optionfile,optionfilext,optionfilefiname);
                   6426:  /*   strcpy(pathimach,argv[0]); */
                   6427:   /* Split argv[1]=pathtot, parameter file name to get path, optionfile, extension and name */
                   6428:   split(pathtot,path,optionfile,optionfilext,optionfilefiname);
                   6429:   printf("\npathtot=%s,\npath=%s,\noptionfile=%s \noptionfilext=%s \noptionfilefiname=%s\n",pathtot,path,optionfile,optionfilext,optionfilefiname);
1.184     brouard  6430: #ifdef WIN32
                   6431:   _chdir(path); /* Can be a relative path */
                   6432:   if(_getcwd(pathcd,MAXLINE) > 0) /* So pathcd is the full path */
                   6433: #else
1.126     brouard  6434:   chdir(path); /* Can be a relative path */
1.184     brouard  6435:   if (getcwd(pathcd, MAXLINE) > 0) /* So pathcd is the full path */
                   6436: #endif
                   6437:   printf("Current directory %s!\n",pathcd);
1.126     brouard  6438:   strcpy(command,"mkdir ");
                   6439:   strcat(command,optionfilefiname);
                   6440:   if((outcmd=system(command)) != 0){
1.169     brouard  6441:     printf("Directory already exists (or can't create it) %s%s, err=%d\n",path,optionfilefiname,outcmd);
1.126     brouard  6442:     /* fprintf(ficlog,"Problem creating directory %s%s\n",path,optionfilefiname); */
                   6443:     /* fclose(ficlog); */
                   6444: /*     exit(1); */
                   6445:   }
                   6446: /*   if((imk=mkdir(optionfilefiname))<0){ */
                   6447: /*     perror("mkdir"); */
                   6448: /*   } */
                   6449: 
                   6450:   /*-------- arguments in the command line --------*/
                   6451: 
1.186     brouard  6452:   /* Main Log file */
1.126     brouard  6453:   strcat(filelog, optionfilefiname);
                   6454:   strcat(filelog,".log");    /* */
                   6455:   if((ficlog=fopen(filelog,"w"))==NULL)    {
                   6456:     printf("Problem with logfile %s\n",filelog);
                   6457:     goto end;
                   6458:   }
                   6459:   fprintf(ficlog,"Log filename:%s\n",filelog);
1.197   ! brouard  6460:   fprintf(ficlog,"Version %s %s",version,fullversion);
1.126     brouard  6461:   fprintf(ficlog,"\nEnter the parameter file name: \n");
                   6462:   fprintf(ficlog,"pathimach=%s\npathtot=%s\n\
                   6463:  path=%s \n\
                   6464:  optionfile=%s\n\
                   6465:  optionfilext=%s\n\
1.156     brouard  6466:  optionfilefiname='%s'\n",pathimach,pathtot,path,optionfile,optionfilext,optionfilefiname);
1.126     brouard  6467: 
1.197   ! brouard  6468:   syscompilerinfo(1);
1.167     brouard  6469: 
1.126     brouard  6470:   printf("Local time (at start):%s",strstart);
                   6471:   fprintf(ficlog,"Local time (at start): %s",strstart);
                   6472:   fflush(ficlog);
                   6473: /*   (void) gettimeofday(&curr_time,&tzp); */
1.157     brouard  6474: /*   printf("Elapsed time %d\n", asc_diff_time(curr_time.tm_sec-start_time.tm_sec,tmpout)); */
1.126     brouard  6475: 
                   6476:   /* */
                   6477:   strcpy(fileres,"r");
                   6478:   strcat(fileres, optionfilefiname);
                   6479:   strcat(fileres,".txt");    /* Other files have txt extension */
                   6480: 
1.186     brouard  6481:   /* Main ---------arguments file --------*/
1.126     brouard  6482: 
                   6483:   if((ficpar=fopen(optionfile,"r"))==NULL)    {
1.155     brouard  6484:     printf("Problem with optionfile '%s' with errno='%s'\n",optionfile,strerror(errno));
                   6485:     fprintf(ficlog,"Problem with optionfile '%s' with errno='%s'\n",optionfile,strerror(errno));
1.126     brouard  6486:     fflush(ficlog);
1.149     brouard  6487:     /* goto end; */
                   6488:     exit(70); 
1.126     brouard  6489:   }
                   6490: 
                   6491: 
                   6492: 
                   6493:   strcpy(filereso,"o");
                   6494:   strcat(filereso,fileres);
                   6495:   if((ficparo=fopen(filereso,"w"))==NULL) { /* opened on subdirectory */
                   6496:     printf("Problem with Output resultfile: %s\n", filereso);
                   6497:     fprintf(ficlog,"Problem with Output resultfile: %s\n", filereso);
                   6498:     fflush(ficlog);
                   6499:     goto end;
                   6500:   }
                   6501: 
                   6502:   /* Reads comments: lines beginning with '#' */
                   6503:   numlinepar=0;
1.197   ! brouard  6504: 
        !          6505:     /* First parameter line */
        !          6506:   while(fgets(line, MAXLINE, ficpar)) {
        !          6507:     /* If line starts with a # it is a comment */
        !          6508:     if (line[0] == '#') {
        !          6509:       numlinepar++;
        !          6510:       fputs(line,stdout);
        !          6511:       fputs(line,ficparo);
        !          6512:       fputs(line,ficlog);
        !          6513:       continue;
        !          6514:     }else
        !          6515:       break;
        !          6516:   }
        !          6517:   if((num_filled=sscanf(line,"title=%s datafile=%s lastobs=%d firstpass=%d lastpass=%d\n", \
        !          6518:                        title, datafile, &lastobs, &firstpass,&lastpass)) !=EOF){
        !          6519:     if (num_filled != 5) {
        !          6520:       printf("Should be 5 parameters\n");
        !          6521:     }
1.126     brouard  6522:     numlinepar++;
1.197   ! brouard  6523:     printf("title=%s datafile=%s lastobs=%d firstpass=%d lastpass=%d\n", title, datafile, lastobs, firstpass,lastpass);
        !          6524:   }
        !          6525:   /* Second parameter line */
        !          6526:   while(fgets(line, MAXLINE, ficpar)) {
        !          6527:     /* If line starts with a # it is a comment */
        !          6528:     if (line[0] == '#') {
        !          6529:       numlinepar++;
        !          6530:       fputs(line,stdout);
        !          6531:       fputs(line,ficparo);
        !          6532:       fputs(line,ficlog);
        !          6533:       continue;
        !          6534:     }else
        !          6535:       break;
        !          6536:   }
        !          6537:   if((num_filled=sscanf(line,"ftol=%lf stepm=%d ncovcol=%d nlstate=%d ndeath=%d maxwav=%d mle=%d weight=%d\n", \
        !          6538:                        &ftol, &stepm, &ncovcol, &nlstate, &ndeath, &maxwav, &mle, &weightopt)) !=EOF){
        !          6539:     if (num_filled != 8) {
        !          6540:       printf("Not 8\n");
        !          6541:     }
        !          6542:     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  6543:   }
                   6544: 
1.197   ! brouard  6545:   /* Third parameter line */
        !          6546:   while(fgets(line, MAXLINE, ficpar)) {
        !          6547:     /* If line starts with a # it is a comment */
        !          6548:     if (line[0] == '#') {
        !          6549:       numlinepar++;
        !          6550:       fputs(line,stdout);
        !          6551:       fputs(line,ficparo);
        !          6552:       fputs(line,ficlog);
        !          6553:       continue;
        !          6554:     }else
        !          6555:       break;
        !          6556:   }
        !          6557:   if((num_filled=sscanf(line,"model=1+age%[^.\n]\n", model)) !=EOF){
        !          6558:     if (num_filled != 1) {
        !          6559:       printf("ERROR %d: Model should be at minimum 'model=1+age.' %s\n",num_filled, line);
        !          6560:       fprintf(ficlog,"ERROR %d: Model should be at minimum 'model=1+age.' %s\n",num_filled, line);
        !          6561:       model[0]='\0';
        !          6562:       goto end;
        !          6563:     }
        !          6564:     else{
        !          6565:       if (model[0]=='+'){
        !          6566:        for(i=1; i<=strlen(model);i++)
        !          6567:          modeltemp[i-1]=model[i];
        !          6568:       }
        !          6569:       strcpy(model,modeltemp); 
        !          6570:     }
        !          6571:     printf(" model=1+age%s modeltemp= %s, model=%s\n",model, modeltemp, model);fflush(stdout);
        !          6572:   }
        !          6573:   /* 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); */
        !          6574:   /* numlinepar=numlinepar+3; /\* In general *\/ */
        !          6575:   /* 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.187     brouard  6576:   if(model[strlen(model)-1]=='.') /* Suppressing leading dot in the model */
                   6577:     model[strlen(model)-1]='\0';
1.197   ! brouard  6578:   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);
        !          6579:   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  6580:   fflush(ficlog);
1.190     brouard  6581:   /* if(model[0]=='#'|| model[0]== '\0'){ */
                   6582:   if(model[0]=='#'){
1.187     brouard  6583:     printf("Error in 'model' line: model should start with 'model=1+age+' and end with '.' \n \
                   6584:  'model=1+age+.' or 'model=1+age+V1.' or 'model=1+age+age*age+V1+V1*age.' or \n \
                   6585:  'model=1+age+V1+V2.' or 'model=1+age+V1+V2+V1*V2.' etc. \n");         \
                   6586:     if(mle != -1){
                   6587:       printf("Fix the model line and run imach with mle=-1 to get a correct template of the parameter file.\n");
                   6588:       exit(1);
                   6589:     }
                   6590:   }
1.126     brouard  6591:   while((c=getc(ficpar))=='#' && c!= EOF){
                   6592:     ungetc(c,ficpar);
                   6593:     fgets(line, MAXLINE, ficpar);
                   6594:     numlinepar++;
1.195     brouard  6595:     if(line[1]=='q'){ /* This #q will quit imach (the answer is q) */
                   6596:       z[0]=line[1];
                   6597:     }
                   6598:     /* printf("****line [1] = %c \n",line[1]); */
1.141     brouard  6599:     fputs(line, stdout);
                   6600:     //puts(line);
1.126     brouard  6601:     fputs(line,ficparo);
                   6602:     fputs(line,ficlog);
                   6603:   }
                   6604:   ungetc(c,ficpar);
                   6605: 
                   6606:    
1.145     brouard  6607:   covar=matrix(0,NCOVMAX,1,n);  /**< used in readdata */
1.136     brouard  6608:   cptcovn=0; /*Number of covariates, i.e. number of '+' in model statement plus one, indepently of n in Vn*/
                   6609:   /* v1+v2+v3+v2*v4+v5*age makes cptcovn = 5
                   6610:      v1+v2*age+v2*v3 makes cptcovn = 3
                   6611:   */
                   6612:   if (strlen(model)>1) 
1.187     brouard  6613:     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  6614:   else
1.187     brouard  6615:     ncovmodel=2; /* Constant and age */
1.133     brouard  6616:   nforce= (nlstate+ndeath-1)*nlstate; /* Number of forces ij from state i to j */
                   6617:   npar= nforce*ncovmodel; /* Number of parameters like aij*/
1.131     brouard  6618:   if(npar >MAXPARM || nlstate >NLSTATEMAX || ndeath >NDEATHMAX || ncovmodel>NCOVMAX){
                   6619:     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);
                   6620:     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);
                   6621:     fflush(stdout);
                   6622:     fclose (ficlog);
                   6623:     goto end;
                   6624:   }
1.126     brouard  6625:   delti3= ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel);
                   6626:   delti=delti3[1][1];
                   6627:   /*delti=vector(1,npar); *//* Scale of each paramater (output from hesscov)*/
                   6628:   if(mle==-1){ /* Print a wizard for help writing covariance matrix */
                   6629:     prwizard(ncovmodel, nlstate, ndeath, model, ficparo);
1.191     brouard  6630:     printf(" You chose mle=-1, look at file %s for a template of covariance matrix \n",filereso);
                   6631:     fprintf(ficlog," You chose mle=-1, look at file %s for a template of covariance matrix \n",filereso);
1.126     brouard  6632:     free_ma3x(delti3,1,nlstate,1, nlstate+ndeath-1,1,ncovmodel); 
                   6633:     fclose (ficparo);
                   6634:     fclose (ficlog);
                   6635:     goto end;
                   6636:     exit(0);
                   6637:   }
1.186     brouard  6638:   else if(mle==-3) { /* Main Wizard */
1.126     brouard  6639:     prwizard(ncovmodel, nlstate, ndeath, model, ficparo);
1.192     brouard  6640:     printf(" You chose mle=-3, look at file %s for a template of covariance matrix \n",filereso);
                   6641:     fprintf(ficlog," You chose mle=-3, look at file %s for a template of covariance matrix \n",filereso);
1.126     brouard  6642:     param= ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel);
                   6643:     matcov=matrix(1,npar,1,npar);
                   6644:   }
                   6645:   else{
1.145     brouard  6646:     /* Read guessed parameters */
1.126     brouard  6647:     /* Reads comments: lines beginning with '#' */
                   6648:     while((c=getc(ficpar))=='#' && c!= EOF){
                   6649:       ungetc(c,ficpar);
                   6650:       fgets(line, MAXLINE, ficpar);
                   6651:       numlinepar++;
1.141     brouard  6652:       fputs(line,stdout);
1.126     brouard  6653:       fputs(line,ficparo);
                   6654:       fputs(line,ficlog);
                   6655:     }
                   6656:     ungetc(c,ficpar);
                   6657:     
                   6658:     param= ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel);
                   6659:     for(i=1; i <=nlstate; i++){
                   6660:       j=0;
                   6661:       for(jj=1; jj <=nlstate+ndeath; jj++){
                   6662:        if(jj==i) continue;
                   6663:        j++;
                   6664:        fscanf(ficpar,"%1d%1d",&i1,&j1);
1.193     brouard  6665:        if ((i1 != i) || (j1 != jj)){
1.126     brouard  6666:          printf("Error in line parameters number %d, %1d%1d instead of %1d%1d \n \
                   6667: It might be a problem of design; if ncovcol and the model are correct\n \
                   6668: run imach with mle=-1 to get a correct template of the parameter file.\n",numlinepar, i,j, i1, j1);
                   6669:          exit(1);
                   6670:        }
                   6671:        fprintf(ficparo,"%1d%1d",i1,j1);
                   6672:        if(mle==1)
1.193     brouard  6673:          printf("%1d%1d",i,jj);
                   6674:        fprintf(ficlog,"%1d%1d",i,jj);
1.126     brouard  6675:        for(k=1; k<=ncovmodel;k++){
                   6676:          fscanf(ficpar," %lf",&param[i][j][k]);
                   6677:          if(mle==1){
                   6678:            printf(" %lf",param[i][j][k]);
                   6679:            fprintf(ficlog," %lf",param[i][j][k]);
                   6680:          }
                   6681:          else
                   6682:            fprintf(ficlog," %lf",param[i][j][k]);
                   6683:          fprintf(ficparo," %lf",param[i][j][k]);
                   6684:        }
                   6685:        fscanf(ficpar,"\n");
                   6686:        numlinepar++;
                   6687:        if(mle==1)
                   6688:          printf("\n");
                   6689:        fprintf(ficlog,"\n");
                   6690:        fprintf(ficparo,"\n");
                   6691:       }
                   6692:     }  
                   6693:     fflush(ficlog);
                   6694: 
1.145     brouard  6695:     /* Reads scales values */
1.126     brouard  6696:     p=param[1][1];
                   6697:     
                   6698:     /* Reads comments: lines beginning with '#' */
                   6699:     while((c=getc(ficpar))=='#' && c!= EOF){
                   6700:       ungetc(c,ficpar);
                   6701:       fgets(line, MAXLINE, ficpar);
                   6702:       numlinepar++;
1.141     brouard  6703:       fputs(line,stdout);
1.126     brouard  6704:       fputs(line,ficparo);
                   6705:       fputs(line,ficlog);
                   6706:     }
                   6707:     ungetc(c,ficpar);
                   6708: 
                   6709:     for(i=1; i <=nlstate; i++){
                   6710:       for(j=1; j <=nlstate+ndeath-1; j++){
                   6711:        fscanf(ficpar,"%1d%1d",&i1,&j1);
1.164     brouard  6712:        if ( (i1-i) * (j1-j) != 0){
1.126     brouard  6713:          printf("Error in line parameters number %d, %1d%1d instead of %1d%1d \n",numlinepar, i,j, i1, j1);
                   6714:          exit(1);
                   6715:        }
                   6716:        printf("%1d%1d",i,j);
                   6717:        fprintf(ficparo,"%1d%1d",i1,j1);
                   6718:        fprintf(ficlog,"%1d%1d",i1,j1);
                   6719:        for(k=1; k<=ncovmodel;k++){
                   6720:          fscanf(ficpar,"%le",&delti3[i][j][k]);
                   6721:          printf(" %le",delti3[i][j][k]);
                   6722:          fprintf(ficparo," %le",delti3[i][j][k]);
                   6723:          fprintf(ficlog," %le",delti3[i][j][k]);
                   6724:        }
                   6725:        fscanf(ficpar,"\n");
                   6726:        numlinepar++;
                   6727:        printf("\n");
                   6728:        fprintf(ficparo,"\n");
                   6729:        fprintf(ficlog,"\n");
                   6730:       }
                   6731:     }
                   6732:     fflush(ficlog);
                   6733: 
1.145     brouard  6734:     /* Reads covariance matrix */
1.126     brouard  6735:     delti=delti3[1][1];
                   6736: 
                   6737: 
                   6738:     /* free_ma3x(delti3,1,nlstate,1,nlstate+ndeath-1,1,ncovmodel); */ /* Hasn't to to freed here otherwise delti is no more allocated */
                   6739:   
                   6740:     /* Reads comments: lines beginning with '#' */
                   6741:     while((c=getc(ficpar))=='#' && c!= EOF){
                   6742:       ungetc(c,ficpar);
                   6743:       fgets(line, MAXLINE, ficpar);
                   6744:       numlinepar++;
1.141     brouard  6745:       fputs(line,stdout);
1.126     brouard  6746:       fputs(line,ficparo);
                   6747:       fputs(line,ficlog);
                   6748:     }
                   6749:     ungetc(c,ficpar);
                   6750:   
                   6751:     matcov=matrix(1,npar,1,npar);
1.131     brouard  6752:     for(i=1; i <=npar; i++)
                   6753:       for(j=1; j <=npar; j++) matcov[i][j]=0.;
                   6754:       
1.194     brouard  6755:     /* Scans npar lines */
1.126     brouard  6756:     for(i=1; i <=npar; i++){
1.194     brouard  6757:       count=fscanf(ficpar,"%1d%1d%1d",&i1,&j1,&jk);
                   6758:       if(count != 3){
                   6759:        printf("Error! Error in parameter file %s at line %d after line starting with %1d%1d%1d\n\
                   6760: This is probably because your covariance matrix doesn't \n  contain exactly %d lines corresponding to your model line '1+age+%s'.\n\
                   6761: Please run with mle=-1 to get a correct covariance matrix.\n",optionfile,numlinepar, i1,j1,jk, npar, model);
                   6762:        fprintf(ficlog,"Error! Error in parameter file %s at line %d after line starting with %1d%1d%1d\n\
                   6763: This is probably because your covariance matrix doesn't \n  contain exactly %d lines corresponding to your model line '1+age+%s'.\n\
                   6764: Please run with mle=-1 to get a correct covariance matrix.\n",optionfile,numlinepar, i1,j1,jk, npar, model);
                   6765:        exit(1);
                   6766:       }else
1.126     brouard  6767:       if(mle==1)
1.194     brouard  6768:        printf("%1d%1d%1d",i1,j1,jk);
                   6769:       fprintf(ficlog,"%1d%1d%1d",i1,j1,jk);
                   6770:       fprintf(ficparo,"%1d%1d%1d",i1,j1,jk);
1.126     brouard  6771:       for(j=1; j <=i; j++){
                   6772:        fscanf(ficpar," %le",&matcov[i][j]);
                   6773:        if(mle==1){
                   6774:          printf(" %.5le",matcov[i][j]);
                   6775:        }
                   6776:        fprintf(ficlog," %.5le",matcov[i][j]);
                   6777:        fprintf(ficparo," %.5le",matcov[i][j]);
                   6778:       }
                   6779:       fscanf(ficpar,"\n");
                   6780:       numlinepar++;
                   6781:       if(mle==1)
                   6782:        printf("\n");
                   6783:       fprintf(ficlog,"\n");
                   6784:       fprintf(ficparo,"\n");
                   6785:     }
1.194     brouard  6786:     /* End of read covariance matrix npar lines */
1.126     brouard  6787:     for(i=1; i <=npar; i++)
                   6788:       for(j=i+1;j<=npar;j++)
                   6789:        matcov[i][j]=matcov[j][i];
                   6790:     
                   6791:     if(mle==1)
                   6792:       printf("\n");
                   6793:     fprintf(ficlog,"\n");
                   6794:     
                   6795:     fflush(ficlog);
                   6796:     
                   6797:     /*-------- Rewriting parameter file ----------*/
                   6798:     strcpy(rfileres,"r");    /* "Rparameterfile */
                   6799:     strcat(rfileres,optionfilefiname);    /* Parameter file first name*/
                   6800:     strcat(rfileres,".");    /* */
                   6801:     strcat(rfileres,optionfilext);    /* Other files have txt extension */
                   6802:     if((ficres =fopen(rfileres,"w"))==NULL) {
                   6803:       printf("Problem writing new parameter file: %s\n", fileres);goto end;
                   6804:       fprintf(ficlog,"Problem writing new parameter file: %s\n", fileres);goto end;
                   6805:     }
                   6806:     fprintf(ficres,"#%s\n",version);
                   6807:   }    /* End of mle != -3 */
                   6808: 
1.186     brouard  6809:   /*  Main data
                   6810:    */
1.126     brouard  6811:   n= lastobs;
                   6812:   num=lvector(1,n);
                   6813:   moisnais=vector(1,n);
                   6814:   annais=vector(1,n);
                   6815:   moisdc=vector(1,n);
                   6816:   andc=vector(1,n);
                   6817:   agedc=vector(1,n);
                   6818:   cod=ivector(1,n);
                   6819:   weight=vector(1,n);
                   6820:   for(i=1;i<=n;i++) weight[i]=1.0; /* Equal weights, 1 by default */
                   6821:   mint=matrix(1,maxwav,1,n);
                   6822:   anint=matrix(1,maxwav,1,n);
1.131     brouard  6823:   s=imatrix(1,maxwav+1,1,n); /* s[i][j] health state for wave i and individual j */ 
1.126     brouard  6824:   tab=ivector(1,NCOVMAX);
1.144     brouard  6825:   ncodemax=ivector(1,NCOVMAX); /* Number of code per covariate; if O and 1 only, 2**ncov; V1+V2+V3+V4=>16 */
1.192     brouard  6826:   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  6827: 
1.136     brouard  6828:   /* Reads data from file datafile */
                   6829:   if (readdata(datafile, firstobs, lastobs, &imx)==1)
                   6830:     goto end;
                   6831: 
                   6832:   /* Calculation of the number of parameters from char model */
1.137     brouard  6833:     /*    modelsav=V2+V1+V4+age*V3 strb=age*V3 stra=V2+V1+V4 
                   6834:        k=4 (age*V3) Tvar[k=4]= 3 (from V3) Tag[cptcovage=1]=4
                   6835:        k=3 V4 Tvar[k=3]= 4 (from V4)
                   6836:        k=2 V1 Tvar[k=2]= 1 (from V1)
                   6837:        k=1 Tvar[1]=2 (from V2)
                   6838:     */
                   6839:   Tvar=ivector(1,NCOVMAX); /* Was 15 changed to NCOVMAX. */
                   6840:   /*  V2+V1+V4+age*V3 is a model with 4 covariates (3 plus signs). 
                   6841:       For each model-covariate stores the data-covariate id. Tvar[1]=2, Tvar[2]=1, Tvar[3]=4, 
                   6842:       Tvar[4=age*V3] is 3 and 'age' is recorded in Tage.
                   6843:   */
                   6844:   /* For model-covariate k tells which data-covariate to use but
                   6845:     because this model-covariate is a construction we invent a new column
                   6846:     ncovcol + k1
                   6847:     If already ncovcol=4 and model=V2+V1+V1*V4+age*V3
                   6848:     Tvar[3=V1*V4]=4+1 etc */
1.145     brouard  6849:   Tprod=ivector(1,NCOVMAX); /* Gives the position of a product */
1.137     brouard  6850:   /* Tprod[k1=1]=3(=V1*V4) for V2+V1+V1*V4+age*V3
                   6851:      if  V2+V1+V1*V4+age*V3+V3*V2   TProd[k1=2]=5 (V3*V2)
                   6852:   */
1.145     brouard  6853:   Tvaraff=ivector(1,NCOVMAX); /* Unclear */
                   6854:   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  6855:                            * For V3*V2 (in V2+V1+V1*V4+age*V3+V3*V2), V3*V2 position is 2nd. 
                   6856:                            * Tvard[k1=2][1]=3 (V3) Tvard[k1=2][2]=2(V2) */
1.145     brouard  6857:   Tage=ivector(1,NCOVMAX); /* Gives the covariate id of covariates associated with age: V2 + V1 + age*V4 + V3*age
1.137     brouard  6858:                         4 covariates (3 plus signs)
                   6859:                         Tage[1=V3*age]= 4; Tage[2=age*V4] = 3
                   6860:                      */  
1.136     brouard  6861: 
1.186     brouard  6862: /* Main decodemodel */
                   6863: 
1.187     brouard  6864: 
1.136     brouard  6865:   if(decodemodel(model, lastobs) == 1)
                   6866:     goto end;
                   6867: 
1.137     brouard  6868:   if((double)(lastobs-imx)/(double)imx > 1.10){
                   6869:     nbwarn++;
                   6870:     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); 
                   6871:     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); 
                   6872:   }
1.136     brouard  6873:     /*  if(mle==1){*/
1.137     brouard  6874:   if (weightopt != 1) { /* Maximisation without weights. We can have weights different from 1 but want no weight*/
                   6875:     for(i=1;i<=imx;i++) weight[i]=1.0; /* changed to imx */
1.136     brouard  6876:   }
                   6877: 
                   6878:     /*-calculation of age at interview from date of interview and age at death -*/
                   6879:   agev=matrix(1,maxwav,1,imx);
                   6880: 
                   6881:   if(calandcheckages(imx, maxwav, &agemin, &agemax, &nberr, &nbwarn) == 1)
                   6882:     goto end;
                   6883: 
1.126     brouard  6884: 
1.136     brouard  6885:   agegomp=(int)agemin;
                   6886:   free_vector(moisnais,1,n);
                   6887:   free_vector(annais,1,n);
1.126     brouard  6888:   /* free_matrix(mint,1,maxwav,1,n);
                   6889:      free_matrix(anint,1,maxwav,1,n);*/
                   6890:   free_vector(moisdc,1,n);
                   6891:   free_vector(andc,1,n);
1.145     brouard  6892:   /* */
                   6893:   
1.126     brouard  6894:   wav=ivector(1,imx);
                   6895:   dh=imatrix(1,lastpass-firstpass+1,1,imx);
                   6896:   bh=imatrix(1,lastpass-firstpass+1,1,imx);
                   6897:   mw=imatrix(1,lastpass-firstpass+1,1,imx);
                   6898:    
                   6899:   /* Concatenates waves */
                   6900:   concatwav(wav, dh, bh, mw, s, agedc, agev,  firstpass, lastpass, imx, nlstate, stepm);
1.145     brouard  6901:   /* */
                   6902:  
1.126     brouard  6903:   /* Routine tricode is to calculate cptcoveff (real number of unique covariates) and to associate covariable number and modality */
                   6904: 
                   6905:   nbcode=imatrix(0,NCOVMAX,0,NCOVMAX); 
                   6906:   ncodemax[1]=1;
1.145     brouard  6907:   Ndum =ivector(-1,NCOVMAX);  
1.187     brouard  6908:   if (ncovmodel-nagesqr > 2 ) /* That is if covariate other than cst, age and age*age */
1.145     brouard  6909:     tricode(Tvar,nbcode,imx, Ndum); /**< Fills nbcode[Tvar[j]][l]; */
1.186     brouard  6910:   /* Nbcode gives the value of the lth modality of jth covariate, in
                   6911:      V2+V1*age, there are 3 covariates Tvar[2]=1 (V1).*/
                   6912:   /* 1 to ncodemax[j] is the maximum value of this jth covariate */
1.145     brouard  6913: 
                   6914:   codtab=imatrix(1,100,1,10); /* codtab[h,k]=( (h-1) - mod(k-1,2**(k-1) )/2**(k-1) */
                   6915:   /*printf(" codtab[1,1],codtab[100,10]=%d,%d\n", codtab[1][1],codtab[100][10]);*/
1.186     brouard  6916:   /* codtab gives the value 1 or 2 of the hth combination of k covariates (1 or 2).*/
1.145     brouard  6917:   h=0;
                   6918: 
                   6919: 
                   6920:   /*if (cptcovn > 0) */
1.126     brouard  6921:       
1.145     brouard  6922:  
1.126     brouard  6923:   m=pow(2,cptcoveff);
                   6924:  
1.144     brouard  6925:          /**< codtab(h,k)  k   = codtab[h,k]=( (h-1) - mod(k-1,2**(k-1) )/2**(k-1) + 1
1.186     brouard  6926:           * For k=4 covariates, h goes from 1 to 2**k
                   6927:           * codtabm(h,k)=  1 & (h-1) >> (k-1) ;
                   6928:           *     h\k   1     2     3     4
1.143     brouard  6929:           *______________________________  
                   6930:           *     1 i=1 1 i=1 1 i=1 1 i=1 1
                   6931:           *     2     2     1     1     1
                   6932:           *     3 i=2 1     2     1     1
                   6933:           *     4     2     2     1     1
                   6934:           *     5 i=3 1 i=2 1     2     1
                   6935:           *     6     2     1     2     1
                   6936:           *     7 i=4 1     2     2     1
                   6937:           *     8     2     2     2     1
1.197   ! brouard  6938:           *     9 i=5 1 i=3 1 i=2 1     2
        !          6939:           *    10     2     1     1     2
        !          6940:           *    11 i=6 1     2     1     2
        !          6941:           *    12     2     2     1     2
        !          6942:           *    13 i=7 1 i=4 1     2     2    
        !          6943:           *    14     2     1     2     2
        !          6944:           *    15 i=8 1     2     2     2
        !          6945:           *    16     2     2     2     2
1.143     brouard  6946:           */
1.197   ! brouard  6947:   for(h=1; h <=100 ;h++){ 
        !          6948:     /* printf("h=%2d ", h); */
        !          6949:      for(k=1; k <=10; k++){
        !          6950:        /* printf("k=%d %d ",k,codtabm(h,k)); */
        !          6951:        codtab[h][k]=codtabm(h,k);
        !          6952:      }
        !          6953:      /* printf("\n"); */
        !          6954:   }
        !          6955:   /* for(k=1;k<=cptcoveff; k++){ /\* scans any effective covariate *\/ */
        !          6956:   /*   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 *\/  */
        !          6957:   /*     for(j=1; j <= ncodemax[k]; j++){ /\* For each modality of this covariate ncodemax=2*\/ */
        !          6958:   /*   for(cpt=1; cpt <=pow(2,k-1); cpt++){  /\* cpt=1 to 8/2**(3+1-1 or 3+1-3) =1 or 4 *\/  */
        !          6959:   /*     h++; */
        !          6960:   /*     if (h>m)  */
        !          6961:   /*       h=1; */
        !          6962:   /*     codtab[h][k]=j; */
        !          6963:   /*     /\* codtab[12][3]=1; *\/ */
        !          6964:   /*     /\*codtab[h][Tvar[k]]=j;*\/ */
        !          6965:   /*     /\* 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]]); *\/ */
        !          6966:   /*   }  */
        !          6967:   /*     } */
        !          6968:   /*   } */
        !          6969:   /* }  */
1.126     brouard  6970:   /* printf("codtab[1][2]=%d codtab[2][2]=%d",codtab[1][2],codtab[2][2]); 
                   6971:      codtab[1][2]=1;codtab[2][2]=2; */
1.197   ! brouard  6972:   /* for(i=1; i <=m ;i++){  */
        !          6973:   /*    for(k=1; k <=cptcovn; k++){ */
        !          6974:   /*      printf("i=%d k=%d %d %d ",i,k,codtab[i][k], cptcoveff); */
        !          6975:   /*    } */
        !          6976:   /*    printf("\n"); */
        !          6977:   /* } */
        !          6978:   /*   scanf("%d",i);*/
1.145     brouard  6979: 
                   6980:  free_ivector(Ndum,-1,NCOVMAX);
                   6981: 
                   6982: 
1.126     brouard  6983:     
1.186     brouard  6984:   /* Initialisation of ----------- gnuplot -------------*/
1.126     brouard  6985:   strcpy(optionfilegnuplot,optionfilefiname);
                   6986:   if(mle==-3)
                   6987:     strcat(optionfilegnuplot,"-mort");
                   6988:   strcat(optionfilegnuplot,".gp");
                   6989: 
                   6990:   if((ficgp=fopen(optionfilegnuplot,"w"))==NULL) {
                   6991:     printf("Problem with file %s",optionfilegnuplot);
                   6992:   }
                   6993:   else{
                   6994:     fprintf(ficgp,"\n# %s\n", version); 
                   6995:     fprintf(ficgp,"# %s\n", optionfilegnuplot); 
1.141     brouard  6996:     //fprintf(ficgp,"set missing 'NaNq'\n");
                   6997:     fprintf(ficgp,"set datafile missing 'NaNq'\n");
1.126     brouard  6998:   }
                   6999:   /*  fclose(ficgp);*/
1.186     brouard  7000: 
                   7001: 
                   7002:   /* Initialisation of --------- index.htm --------*/
1.126     brouard  7003: 
                   7004:   strcpy(optionfilehtm,optionfilefiname); /* Main html file */
                   7005:   if(mle==-3)
                   7006:     strcat(optionfilehtm,"-mort");
                   7007:   strcat(optionfilehtm,".htm");
                   7008:   if((fichtm=fopen(optionfilehtm,"w"))==NULL)    {
1.131     brouard  7009:     printf("Problem with %s \n",optionfilehtm);
                   7010:     exit(0);
1.126     brouard  7011:   }
                   7012: 
                   7013:   strcpy(optionfilehtmcov,optionfilefiname); /* Only for matrix of covariance */
                   7014:   strcat(optionfilehtmcov,"-cov.htm");
                   7015:   if((fichtmcov=fopen(optionfilehtmcov,"w"))==NULL)    {
                   7016:     printf("Problem with %s \n",optionfilehtmcov), exit(0);
                   7017:   }
                   7018:   else{
                   7019:   fprintf(fichtmcov,"<html><head>\n<title>IMaCh Cov %s</title></head>\n <body><font size=\"2\">%s <br> %s</font> \
                   7020: <hr size=\"2\" color=\"#EC5E5E\"> \n\
                   7021: Title=%s <br>Datafile=%s Firstpass=%d Lastpass=%d Stepm=%d Weight=%d Model=%s<br>\n",\
                   7022:          optionfilehtmcov,version,fullversion,title,datafile,firstpass,lastpass,stepm, weightopt, model);
                   7023:   }
                   7024: 
                   7025:   fprintf(fichtm,"<html><head>\n<title>IMaCh %s</title></head>\n <body><font size=\"2\">%s <br> %s</font> \
                   7026: <hr size=\"2\" color=\"#EC5E5E\"> \n\
                   7027: Title=%s <br>Datafile=%s Firstpass=%d Lastpass=%d Stepm=%d Weight=%d Model=%s<br>\n\
                   7028: \n\
                   7029: <hr  size=\"2\" color=\"#EC5E5E\">\
                   7030:  <ul><li><h4>Parameter files</h4>\n\
                   7031:  - Parameter file: <a href=\"%s.%s\">%s.%s</a><br>\n\
                   7032:  - Copy of the parameter file: <a href=\"o%s\">o%s</a><br>\n\
                   7033:  - Log file of the run: <a href=\"%s\">%s</a><br>\n\
                   7034:  - Gnuplot file name: <a href=\"%s\">%s</a><br>\n\
                   7035:  - Date and time at start: %s</ul>\n",\
                   7036:          optionfilehtm,version,fullversion,title,datafile,firstpass,lastpass,stepm, weightopt, model,\
                   7037:          optionfilefiname,optionfilext,optionfilefiname,optionfilext,\
                   7038:          fileres,fileres,\
                   7039:          filelog,filelog,optionfilegnuplot,optionfilegnuplot,strstart);
                   7040:   fflush(fichtm);
                   7041: 
                   7042:   strcpy(pathr,path);
                   7043:   strcat(pathr,optionfilefiname);
1.184     brouard  7044: #ifdef WIN32
                   7045:   _chdir(optionfilefiname); /* Move to directory named optionfile */
                   7046: #else
1.126     brouard  7047:   chdir(optionfilefiname); /* Move to directory named optionfile */
1.184     brouard  7048: #endif
                   7049:          
1.126     brouard  7050:   
                   7051:   /* Calculates basic frequencies. Computes observed prevalence at single age
                   7052:      and prints on file fileres'p'. */
                   7053:   freqsummary(fileres, agemin, agemax, s, agev, nlstate, imx,Tvaraff,nbcode, ncodemax,mint,anint,strstart);
                   7054: 
                   7055:   fprintf(fichtm,"\n");
                   7056:   fprintf(fichtm,"<br>Total number of observations=%d <br>\n\
                   7057: Youngest age at first (selected) pass %.2f, oldest age %.2f<br>\n\
                   7058: Interval (in months) between two waves: Min=%d Max=%d Mean=%.2lf<br>\n",\
                   7059:          imx,agemin,agemax,jmin,jmax,jmean);
                   7060:   pmmij= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
                   7061:     oldms= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
                   7062:     newms= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
                   7063:     savms= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
                   7064:     oldm=oldms; newm=newms; savm=savms; /* Keeps fixed addresses to free */
                   7065:     
                   7066:    
                   7067:   /* For Powell, parameters are in a vector p[] starting at p[1]
                   7068:      so we point p on param[1][1] so that p[1] maps on param[1][1][1] */
                   7069:   p=param[1][1]; /* *(*(*(param +1)+1)+0) */
                   7070: 
                   7071:   globpr=0; /* To get the number ipmx of contributions and the sum of weights*/
1.186     brouard  7072:   /* For mortality only */
1.126     brouard  7073:   if (mle==-3){
1.136     brouard  7074:     ximort=matrix(1,NDIM,1,NDIM); 
1.186     brouard  7075:     /*     ximort=gsl_matrix_alloc(1,NDIM,1,NDIM); */
1.126     brouard  7076:     cens=ivector(1,n);
                   7077:     ageexmed=vector(1,n);
                   7078:     agecens=vector(1,n);
                   7079:     dcwave=ivector(1,n);
                   7080:  
                   7081:     for (i=1; i<=imx; i++){
                   7082:       dcwave[i]=-1;
                   7083:       for (m=firstpass; m<=lastpass; m++)
                   7084:        if (s[m][i]>nlstate) {
                   7085:          dcwave[i]=m;
                   7086:          /*    printf("i=%d j=%d s=%d dcwave=%d\n",i,j, s[j][i],dcwave[i]);*/
                   7087:          break;
                   7088:        }
                   7089:     }
                   7090: 
                   7091:     for (i=1; i<=imx; i++) {
                   7092:       if (wav[i]>0){
                   7093:        ageexmed[i]=agev[mw[1][i]][i];
                   7094:        j=wav[i];
                   7095:        agecens[i]=1.; 
                   7096: 
                   7097:        if (ageexmed[i]> 1 && wav[i] > 0){
                   7098:          agecens[i]=agev[mw[j][i]][i];
                   7099:          cens[i]= 1;
                   7100:        }else if (ageexmed[i]< 1) 
                   7101:          cens[i]= -1;
                   7102:        if (agedc[i]< AGESUP && agedc[i]>1 && dcwave[i]>firstpass && dcwave[i]<=lastpass)
                   7103:          cens[i]=0 ;
                   7104:       }
                   7105:       else cens[i]=-1;
                   7106:     }
                   7107:     
                   7108:     for (i=1;i<=NDIM;i++) {
                   7109:       for (j=1;j<=NDIM;j++)
                   7110:        ximort[i][j]=(i == j ? 1.0 : 0.0);
                   7111:     }
                   7112:     
1.145     brouard  7113:     /*p[1]=0.0268; p[NDIM]=0.083;*/
1.126     brouard  7114:     /*printf("%lf %lf", p[1], p[2]);*/
                   7115:     
                   7116:     
1.136     brouard  7117: #ifdef GSL
                   7118:     printf("GSL optimization\n");  fprintf(ficlog,"Powell\n");
1.162     brouard  7119: #else
1.126     brouard  7120:     printf("Powell\n");  fprintf(ficlog,"Powell\n");
1.136     brouard  7121: #endif
1.126     brouard  7122:     strcpy(filerespow,"pow-mort"); 
                   7123:     strcat(filerespow,fileres);
                   7124:     if((ficrespow=fopen(filerespow,"w"))==NULL) {
                   7125:       printf("Problem with resultfile: %s\n", filerespow);
                   7126:       fprintf(ficlog,"Problem with resultfile: %s\n", filerespow);
                   7127:     }
1.136     brouard  7128: #ifdef GSL
                   7129:     fprintf(ficrespow,"# GSL optimization\n# iter -2*LL");
1.162     brouard  7130: #else
1.126     brouard  7131:     fprintf(ficrespow,"# Powell\n# iter -2*LL");
1.136     brouard  7132: #endif
1.126     brouard  7133:     /*  for (i=1;i<=nlstate;i++)
                   7134:        for(j=1;j<=nlstate+ndeath;j++)
                   7135:        if(j!=i)fprintf(ficrespow," p%1d%1d",i,j);
                   7136:     */
                   7137:     fprintf(ficrespow,"\n");
1.136     brouard  7138: #ifdef GSL
                   7139:     /* gsl starts here */ 
                   7140:     T = gsl_multimin_fminimizer_nmsimplex;
                   7141:     gsl_multimin_fminimizer *sfm = NULL;
                   7142:     gsl_vector *ss, *x;
                   7143:     gsl_multimin_function minex_func;
                   7144: 
                   7145:     /* Initial vertex size vector */
                   7146:     ss = gsl_vector_alloc (NDIM);
                   7147:     
                   7148:     if (ss == NULL){
                   7149:       GSL_ERROR_VAL ("failed to allocate space for ss", GSL_ENOMEM, 0);
                   7150:     }
                   7151:     /* Set all step sizes to 1 */
                   7152:     gsl_vector_set_all (ss, 0.001);
                   7153: 
                   7154:     /* Starting point */
1.126     brouard  7155:     
1.136     brouard  7156:     x = gsl_vector_alloc (NDIM);
                   7157:     
                   7158:     if (x == NULL){
                   7159:       gsl_vector_free(ss);
                   7160:       GSL_ERROR_VAL ("failed to allocate space for x", GSL_ENOMEM, 0);
                   7161:     }
                   7162:   
                   7163:     /* Initialize method and iterate */
                   7164:     /*     p[1]=0.0268; p[NDIM]=0.083; */
1.186     brouard  7165:     /*     gsl_vector_set(x, 0, 0.0268); */
                   7166:     /*     gsl_vector_set(x, 1, 0.083); */
1.136     brouard  7167:     gsl_vector_set(x, 0, p[1]);
                   7168:     gsl_vector_set(x, 1, p[2]);
                   7169: 
                   7170:     minex_func.f = &gompertz_f;
                   7171:     minex_func.n = NDIM;
                   7172:     minex_func.params = (void *)&p; /* ??? */
                   7173:     
                   7174:     sfm = gsl_multimin_fminimizer_alloc (T, NDIM);
                   7175:     gsl_multimin_fminimizer_set (sfm, &minex_func, x, ss);
                   7176:     
                   7177:     printf("Iterations beginning .....\n\n");
                   7178:     printf("Iter. #    Intercept       Slope     -Log Likelihood     Simplex size\n");
                   7179: 
                   7180:     iteri=0;
                   7181:     while (rval == GSL_CONTINUE){
                   7182:       iteri++;
                   7183:       status = gsl_multimin_fminimizer_iterate(sfm);
                   7184:       
                   7185:       if (status) printf("error: %s\n", gsl_strerror (status));
                   7186:       fflush(0);
                   7187:       
                   7188:       if (status) 
                   7189:         break;
                   7190:       
                   7191:       rval = gsl_multimin_test_size (gsl_multimin_fminimizer_size (sfm), 1e-6);
                   7192:       ssval = gsl_multimin_fminimizer_size (sfm);
                   7193:       
                   7194:       if (rval == GSL_SUCCESS)
                   7195:         printf ("converged to a local maximum at\n");
                   7196:       
                   7197:       printf("%5d ", iteri);
                   7198:       for (it = 0; it < NDIM; it++){
                   7199:        printf ("%10.5f ", gsl_vector_get (sfm->x, it));
                   7200:       }
                   7201:       printf("f() = %-10.5f ssize = %.7f\n", sfm->fval, ssval);
                   7202:     }
                   7203:     
                   7204:     printf("\n\n Please note: Program should be run many times with varying starting points to detemine global maximum\n\n");
                   7205:     
                   7206:     gsl_vector_free(x); /* initial values */
                   7207:     gsl_vector_free(ss); /* inital step size */
                   7208:     for (it=0; it<NDIM; it++){
                   7209:       p[it+1]=gsl_vector_get(sfm->x,it);
                   7210:       fprintf(ficrespow," %.12lf", p[it]);
                   7211:     }
                   7212:     gsl_multimin_fminimizer_free (sfm); /* p *(sfm.x.data) et p *(sfm.x.data+1)  */
                   7213: #endif
                   7214: #ifdef POWELL
                   7215:      powell(p,ximort,NDIM,ftol,&iter,&fret,gompertz);
                   7216: #endif  
1.126     brouard  7217:     fclose(ficrespow);
                   7218:     
                   7219:     hesscov(matcov, p, NDIM, delti, 1e-4, gompertz); 
                   7220: 
                   7221:     for(i=1; i <=NDIM; i++)
                   7222:       for(j=i+1;j<=NDIM;j++)
                   7223:        matcov[i][j]=matcov[j][i];
                   7224:     
                   7225:     printf("\nCovariance matrix\n ");
                   7226:     for(i=1; i <=NDIM; i++) {
                   7227:       for(j=1;j<=NDIM;j++){ 
                   7228:        printf("%f ",matcov[i][j]);
                   7229:       }
                   7230:       printf("\n ");
                   7231:     }
                   7232:     
                   7233:     printf("iter=%d MLE=%f Eq=%lf*exp(%lf*(age-%d))\n",iter,-gompertz(p),p[1],p[2],agegomp);
1.193     brouard  7234:     for (i=1;i<=NDIM;i++) {
1.126     brouard  7235:       printf("%f [%f ; %f]\n",p[i],p[i]-2*sqrt(matcov[i][i]),p[i]+2*sqrt(matcov[i][i]));
1.193     brouard  7236:       fprintf(ficlog,"%f [%f ; %f]\n",p[i],p[i]-2*sqrt(matcov[i][i]),p[i]+2*sqrt(matcov[i][i]));
                   7237:     }
1.126     brouard  7238:     lsurv=vector(1,AGESUP);
                   7239:     lpop=vector(1,AGESUP);
                   7240:     tpop=vector(1,AGESUP);
                   7241:     lsurv[agegomp]=100000;
                   7242:     
                   7243:     for (k=agegomp;k<=AGESUP;k++) {
                   7244:       agemortsup=k;
                   7245:       if (p[1]*exp(p[2]*(k-agegomp))>1) break;
                   7246:     }
                   7247:     
                   7248:     for (k=agegomp;k<agemortsup;k++)
                   7249:       lsurv[k+1]=lsurv[k]-lsurv[k]*(p[1]*exp(p[2]*(k-agegomp)));
                   7250:     
                   7251:     for (k=agegomp;k<agemortsup;k++){
                   7252:       lpop[k]=(lsurv[k]+lsurv[k+1])/2.;
                   7253:       sumlpop=sumlpop+lpop[k];
                   7254:     }
                   7255:     
                   7256:     tpop[agegomp]=sumlpop;
                   7257:     for (k=agegomp;k<(agemortsup-3);k++){
                   7258:       /*  tpop[k+1]=2;*/
                   7259:       tpop[k+1]=tpop[k]-lpop[k];
                   7260:     }
                   7261:     
                   7262:     
                   7263:     printf("\nAge   lx     qx    dx    Lx     Tx     e(x)\n");
                   7264:     for (k=agegomp;k<(agemortsup-2);k++) 
                   7265:       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]);
                   7266:     
                   7267:     
                   7268:     replace_back_to_slash(pathc,pathcd); /* Even gnuplot wants a / */
1.194     brouard  7269:     if(ageminpar == AGEOVERFLOW ||agemaxpar == AGEOVERFLOW){
                   7270:        printf("Warning! Error in gnuplot file with ageminpar %f or agemaxpar %f overflow\n\
                   7271: This is probably because your parameter file doesn't \n  contain the exact number of lines (or columns) corresponding to your model line.\n\
                   7272: Please run with mle=-1 to get a correct covariance matrix.\n",ageminpar,agemaxpar);
                   7273:        fprintf(ficlog,"Warning! Error in gnuplot file with ageminpar %f or agemaxpar %f overflow\n\
                   7274: This is probably because your parameter file doesn't \n  contain the exact number of lines (or columns) corresponding to your model line.\n\
                   7275: Please run with mle=-1 to get a correct covariance matrix.\n",ageminpar,agemaxpar);
                   7276:     }else
                   7277:       printinggnuplotmort(fileres, optionfilefiname,ageminpar,agemaxpar,fage, pathc,p);
1.126     brouard  7278:     printinghtmlmort(fileres,title,datafile, firstpass, lastpass, \
                   7279:                     stepm, weightopt,\
                   7280:                     model,imx,p,matcov,agemortsup);
                   7281:     
                   7282:     free_vector(lsurv,1,AGESUP);
                   7283:     free_vector(lpop,1,AGESUP);
                   7284:     free_vector(tpop,1,AGESUP);
1.136     brouard  7285: #ifdef GSL
                   7286:     free_ivector(cens,1,n);
                   7287:     free_vector(agecens,1,n);
                   7288:     free_ivector(dcwave,1,n);
                   7289:     free_matrix(ximort,1,NDIM,1,NDIM);
                   7290: #endif
1.186     brouard  7291:   } /* Endof if mle==-3 mortality only */
                   7292:   /* Standard maximisation */
1.126     brouard  7293:   else{ /* For mle >=1 */
1.132     brouard  7294:     globpr=0;/* debug */
1.186     brouard  7295:     /* Computes likelihood for initial parameters */
1.132     brouard  7296:     likelione(ficres, p, npar, nlstate, &globpr, &ipmx, &sw, &fretone, funcone); /* Prints the contributions to the likelihood */
1.126     brouard  7297:     printf("First Likeli=%12.6f ipmx=%ld sw=%12.6f",fretone,ipmx,sw);
                   7298:     for (k=1; k<=npar;k++)
                   7299:       printf(" %d %8.5f",k,p[k]);
                   7300:     printf("\n");
1.186     brouard  7301:     globpr=1; /* again, to print the contributions */
1.126     brouard  7302:     likelione(ficres, p, npar, nlstate, &globpr, &ipmx, &sw, &fretone, funcone); /* Prints the contributions to the likelihood */
                   7303:     printf("Second Likeli=%12.6f ipmx=%ld sw=%12.6f",fretone,ipmx,sw);
                   7304:     for (k=1; k<=npar;k++)
                   7305:       printf(" %d %8.5f",k,p[k]);
                   7306:     printf("\n");
1.186     brouard  7307:     if(mle>=1){ /* Could be 1 or 2, Real Maximisation */
1.126     brouard  7308:       mlikeli(ficres,p, npar, ncovmodel, nlstate, ftol, func);
                   7309:     }
                   7310:     
                   7311:     /*--------- results files --------------*/
1.192     brouard  7312:     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  7313:     
                   7314:     
                   7315:     fprintf(ficres,"# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
                   7316:     printf("# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
                   7317:     fprintf(ficlog,"# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
                   7318:     for(i=1,jk=1; i <=nlstate; i++){
                   7319:       for(k=1; k <=(nlstate+ndeath); k++){
                   7320:        if (k != i) {
                   7321:          printf("%d%d ",i,k);
                   7322:          fprintf(ficlog,"%d%d ",i,k);
                   7323:          fprintf(ficres,"%1d%1d ",i,k);
                   7324:          for(j=1; j <=ncovmodel; j++){
1.190     brouard  7325:            printf("%12.7f ",p[jk]);
                   7326:            fprintf(ficlog,"%12.7f ",p[jk]);
                   7327:            fprintf(ficres,"%12.7f ",p[jk]);
1.126     brouard  7328:            jk++; 
                   7329:          }
                   7330:          printf("\n");
                   7331:          fprintf(ficlog,"\n");
                   7332:          fprintf(ficres,"\n");
                   7333:        }
                   7334:       }
                   7335:     }
                   7336:     if(mle!=0){
                   7337:       /* Computing hessian and covariance matrix */
                   7338:       ftolhess=ftol; /* Usually correct */
                   7339:       hesscov(matcov, p, npar, delti, ftolhess, func);
                   7340:     }
1.197   ! brouard  7341:     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");
        !          7342:     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");
1.193     brouard  7343:     for(i=1,jk=1; i <=nlstate; i++){
                   7344:       for(k=1; k <=(nlstate+ndeath); k++){
                   7345:        if (k != i) {
                   7346:          printf("%d%d ",i,k);
                   7347:          fprintf(ficlog,"%d%d ",i,k);
                   7348:          for(j=1; j <=ncovmodel; j++){
1.197   ! brouard  7349:            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]));
        !          7350:            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]));
1.193     brouard  7351:            jk++; 
                   7352:          }
                   7353:          printf("\n");
                   7354:          fprintf(ficlog,"\n");
                   7355:        }
                   7356:       }
                   7357:     }
                   7358: 
1.126     brouard  7359:     fprintf(ficres,"# Scales (for hessian or gradient estimation)\n");
                   7360:     printf("# Scales (for hessian or gradient estimation)\n");
                   7361:     fprintf(ficlog,"# Scales (for hessian or gradient estimation)\n");
                   7362:     for(i=1,jk=1; i <=nlstate; i++){
                   7363:       for(j=1; j <=nlstate+ndeath; j++){
                   7364:        if (j!=i) {
                   7365:          fprintf(ficres,"%1d%1d",i,j);
                   7366:          printf("%1d%1d",i,j);
                   7367:          fprintf(ficlog,"%1d%1d",i,j);
                   7368:          for(k=1; k<=ncovmodel;k++){
                   7369:            printf(" %.5e",delti[jk]);
                   7370:            fprintf(ficlog," %.5e",delti[jk]);
                   7371:            fprintf(ficres," %.5e",delti[jk]);
                   7372:            jk++;
                   7373:          }
                   7374:          printf("\n");
                   7375:          fprintf(ficlog,"\n");
                   7376:          fprintf(ficres,"\n");
                   7377:        }
                   7378:       }
                   7379:     }
                   7380:     
                   7381:     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");
                   7382:     if(mle>=1)
                   7383:       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");
                   7384:     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");
                   7385:     /* # 121 Var(a12)\n\ */
                   7386:     /* # 122 Cov(b12,a12) Var(b12)\n\ */
                   7387:     /* # 131 Cov(a13,a12) Cov(a13,b12, Var(a13)\n\ */
                   7388:     /* # 132 Cov(b13,a12) Cov(b13,b12, Cov(b13,a13) Var(b13)\n\ */
                   7389:     /* # 212 Cov(a21,a12) Cov(a21,b12, Cov(a21,a13) Cov(a21,b13) Var(a21)\n\ */
                   7390:     /* # 212 Cov(b21,a12) Cov(b21,b12, Cov(b21,a13) Cov(b21,b13) Cov(b21,a21) Var(b21)\n\ */
                   7391:     /* # 232 Cov(a23,a12) Cov(a23,b12, Cov(a23,a13) Cov(a23,b13) Cov(a23,a21) Cov(a23,b21) Var(a23)\n\ */
                   7392:     /* # 232 Cov(b23,a12) Cov(b23,b12) ... Var (b23)\n" */
                   7393:     
                   7394:     
                   7395:     /* Just to have a covariance matrix which will be more understandable
                   7396:        even is we still don't want to manage dictionary of variables
                   7397:     */
                   7398:     for(itimes=1;itimes<=2;itimes++){
                   7399:       jj=0;
                   7400:       for(i=1; i <=nlstate; i++){
                   7401:        for(j=1; j <=nlstate+ndeath; j++){
                   7402:          if(j==i) continue;
                   7403:          for(k=1; k<=ncovmodel;k++){
                   7404:            jj++;
                   7405:            ca[0]= k+'a'-1;ca[1]='\0';
                   7406:            if(itimes==1){
                   7407:              if(mle>=1)
                   7408:                printf("#%1d%1d%d",i,j,k);
                   7409:              fprintf(ficlog,"#%1d%1d%d",i,j,k);
                   7410:              fprintf(ficres,"#%1d%1d%d",i,j,k);
                   7411:            }else{
                   7412:              if(mle>=1)
                   7413:                printf("%1d%1d%d",i,j,k);
                   7414:              fprintf(ficlog,"%1d%1d%d",i,j,k);
                   7415:              fprintf(ficres,"%1d%1d%d",i,j,k);
                   7416:            }
                   7417:            ll=0;
                   7418:            for(li=1;li <=nlstate; li++){
                   7419:              for(lj=1;lj <=nlstate+ndeath; lj++){
                   7420:                if(lj==li) continue;
                   7421:                for(lk=1;lk<=ncovmodel;lk++){
                   7422:                  ll++;
                   7423:                  if(ll<=jj){
                   7424:                    cb[0]= lk +'a'-1;cb[1]='\0';
                   7425:                    if(ll<jj){
                   7426:                      if(itimes==1){
                   7427:                        if(mle>=1)
                   7428:                          printf(" Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
                   7429:                        fprintf(ficlog," Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
                   7430:                        fprintf(ficres," Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
                   7431:                      }else{
                   7432:                        if(mle>=1)
                   7433:                          printf(" %.5e",matcov[jj][ll]); 
                   7434:                        fprintf(ficlog," %.5e",matcov[jj][ll]); 
                   7435:                        fprintf(ficres," %.5e",matcov[jj][ll]); 
                   7436:                      }
                   7437:                    }else{
                   7438:                      if(itimes==1){
                   7439:                        if(mle>=1)
                   7440:                          printf(" Var(%s%1d%1d)",ca,i,j);
                   7441:                        fprintf(ficlog," Var(%s%1d%1d)",ca,i,j);
                   7442:                        fprintf(ficres," Var(%s%1d%1d)",ca,i,j);
                   7443:                      }else{
                   7444:                        if(mle>=1)
                   7445:                          printf(" %.5e",matcov[jj][ll]); 
                   7446:                        fprintf(ficlog," %.5e",matcov[jj][ll]); 
                   7447:                        fprintf(ficres," %.5e",matcov[jj][ll]); 
                   7448:                      }
                   7449:                    }
                   7450:                  }
                   7451:                } /* end lk */
                   7452:              } /* end lj */
                   7453:            } /* end li */
                   7454:            if(mle>=1)
                   7455:              printf("\n");
                   7456:            fprintf(ficlog,"\n");
                   7457:            fprintf(ficres,"\n");
                   7458:            numlinepar++;
                   7459:          } /* end k*/
                   7460:        } /*end j */
                   7461:       } /* end i */
                   7462:     } /* end itimes */
                   7463:     
                   7464:     fflush(ficlog);
                   7465:     fflush(ficres);
                   7466:     
                   7467:     while((c=getc(ficpar))=='#' && c!= EOF){
                   7468:       ungetc(c,ficpar);
                   7469:       fgets(line, MAXLINE, ficpar);
1.141     brouard  7470:       fputs(line,stdout);
1.126     brouard  7471:       fputs(line,ficparo);
                   7472:     }
                   7473:     ungetc(c,ficpar);
                   7474:     
                   7475:     estepm=0;
                   7476:     fscanf(ficpar,"agemin=%lf agemax=%lf bage=%lf fage=%lf estepm=%d\n",&ageminpar,&agemaxpar, &bage, &fage, &estepm);
                   7477:     if (estepm==0 || estepm < stepm) estepm=stepm;
                   7478:     if (fage <= 2) {
                   7479:       bage = ageminpar;
                   7480:       fage = agemaxpar;
                   7481:     }
                   7482:     
                   7483:     fprintf(ficres,"# agemin agemax for life expectancy, bage fage (if mle==0 ie no data nor Max likelihood).\n");
                   7484:     fprintf(ficres,"agemin=%.0f agemax=%.0f bage=%.0f fage=%.0f estepm=%d\n",ageminpar,agemaxpar,bage,fage, estepm);
                   7485:     fprintf(ficparo,"agemin=%.0f agemax=%.0f bage=%.0f fage=%.0f estepm=%d\n",ageminpar,agemaxpar,bage,fage, estepm);
1.186     brouard  7486: 
                   7487:     /* Other stuffs, more or less useful */    
1.126     brouard  7488:     while((c=getc(ficpar))=='#' && c!= EOF){
                   7489:       ungetc(c,ficpar);
                   7490:       fgets(line, MAXLINE, ficpar);
1.141     brouard  7491:       fputs(line,stdout);
1.126     brouard  7492:       fputs(line,ficparo);
                   7493:     }
                   7494:     ungetc(c,ficpar);
                   7495:     
                   7496:     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);
                   7497:     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);
                   7498:     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);
                   7499:     printf("begin-prev-date=%.lf/%.lf/%.lf end-prev-date=%.lf/%.lf/%.lf mov_average=%d\n",jprev1, mprev1,anprev1,jprev2, mprev2,anprev2,mobilav);
                   7500:     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);
                   7501:     
                   7502:     while((c=getc(ficpar))=='#' && c!= EOF){
                   7503:       ungetc(c,ficpar);
                   7504:       fgets(line, MAXLINE, ficpar);
1.141     brouard  7505:       fputs(line,stdout);
1.126     brouard  7506:       fputs(line,ficparo);
                   7507:     }
                   7508:     ungetc(c,ficpar);
                   7509:     
                   7510:     
                   7511:     dateprev1=anprev1+(mprev1-1)/12.+(jprev1-1)/365.;
                   7512:     dateprev2=anprev2+(mprev2-1)/12.+(jprev2-1)/365.;
                   7513:     
                   7514:     fscanf(ficpar,"pop_based=%d\n",&popbased);
1.193     brouard  7515:     fprintf(ficlog,"pop_based=%d\n",popbased);
1.126     brouard  7516:     fprintf(ficparo,"pop_based=%d\n",popbased);   
                   7517:     fprintf(ficres,"pop_based=%d\n",popbased);   
                   7518:     
                   7519:     while((c=getc(ficpar))=='#' && c!= EOF){
                   7520:       ungetc(c,ficpar);
                   7521:       fgets(line, MAXLINE, ficpar);
1.141     brouard  7522:       fputs(line,stdout);
1.126     brouard  7523:       fputs(line,ficparo);
                   7524:     }
                   7525:     ungetc(c,ficpar);
                   7526:     
                   7527:     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);
                   7528:     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);
                   7529:     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);
                   7530:     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);
                   7531:     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);
                   7532:     /* day and month of proj2 are not used but only year anproj2.*/
                   7533:     
                   7534:     
                   7535:     
1.145     brouard  7536:      /* freqsummary(fileres, agemin, agemax, s, agev, nlstate, imx,Tvaraff,nbcode, ncodemax,mint,anint); */
                   7537:     /* ,dateprev1,dateprev2,jprev1, mprev1,anprev1,jprev2, mprev2,anprev2); */
1.126     brouard  7538:     
                   7539:     replace_back_to_slash(pathc,pathcd); /* Even gnuplot wants a / */
1.194     brouard  7540:     if(ageminpar == AGEOVERFLOW ||agemaxpar == -AGEOVERFLOW){
                   7541:        printf("Warning! Error in gnuplot file with ageminpar %f or agemaxpar %f overflow\n\
                   7542: This is probably because your parameter file doesn't \n  contain the exact number of lines (or columns) corresponding to your model line.\n\
                   7543: Please run with mle=-1 to get a correct covariance matrix.\n",ageminpar,agemaxpar);
                   7544:        fprintf(ficlog,"Warning! Error in gnuplot file with ageminpar %f or agemaxpar %f overflow\n\
                   7545: This is probably because your parameter file doesn't \n  contain the exact number of lines (or columns) corresponding to your model line.\n\
                   7546: Please run with mle=-1 to get a correct covariance matrix.\n",ageminpar,agemaxpar);
                   7547:     }else
                   7548:       printinggnuplot(fileres, optionfilefiname,ageminpar,agemaxpar,fage, pathc,p);
1.126     brouard  7549:     
                   7550:     printinghtml(fileres,title,datafile, firstpass, lastpass, stepm, weightopt,\
                   7551:                 model,imx,jmin,jmax,jmean,rfileres,popforecast,estepm,\
                   7552:                 jprev1,mprev1,anprev1,jprev2,mprev2,anprev2);
                   7553:       
                   7554:    /*------------ free_vector  -------------*/
                   7555:    /*  chdir(path); */
                   7556:  
                   7557:     free_ivector(wav,1,imx);
                   7558:     free_imatrix(dh,1,lastpass-firstpass+1,1,imx);
                   7559:     free_imatrix(bh,1,lastpass-firstpass+1,1,imx);
                   7560:     free_imatrix(mw,1,lastpass-firstpass+1,1,imx);   
                   7561:     free_lvector(num,1,n);
                   7562:     free_vector(agedc,1,n);
                   7563:     /*free_matrix(covar,0,NCOVMAX,1,n);*/
                   7564:     /*free_matrix(covar,1,NCOVMAX,1,n);*/
                   7565:     fclose(ficparo);
                   7566:     fclose(ficres);
                   7567: 
                   7568: 
1.186     brouard  7569:     /* Other results (useful)*/
                   7570: 
                   7571: 
1.126     brouard  7572:     /*--------------- Prevalence limit  (period or stable prevalence) --------------*/
1.180     brouard  7573:     /*#include "prevlim.h"*/  /* Use ficrespl, ficlog */
                   7574:     prlim=matrix(1,nlstate,1,nlstate);
                   7575:     prevalence_limit(p, prlim,  ageminpar, agemaxpar);
1.126     brouard  7576:     fclose(ficrespl);
                   7577: 
1.145     brouard  7578: #ifdef FREEEXIT2
                   7579: #include "freeexit2.h"
                   7580: #endif
                   7581: 
1.126     brouard  7582:     /*------------- h Pij x at various ages ------------*/
1.180     brouard  7583:     /*#include "hpijx.h"*/
                   7584:     hPijx(p, bage, fage);
1.145     brouard  7585:     fclose(ficrespij);
1.126     brouard  7586: 
1.145     brouard  7587:   /*-------------- Variance of one-step probabilities---*/
                   7588:     k=1;
1.126     brouard  7589:     varprob(optionfilefiname, matcov, p, delti, nlstate, bage, fage,k,Tvar,nbcode, ncodemax,strstart);
                   7590: 
                   7591: 
                   7592:     probs= ma3x(1,AGESUP,1,NCOVMAX, 1,NCOVMAX);
                   7593:     for(i=1;i<=AGESUP;i++)
                   7594:       for(j=1;j<=NCOVMAX;j++)
                   7595:        for(k=1;k<=NCOVMAX;k++)
                   7596:          probs[i][j][k]=0.;
                   7597: 
                   7598:     /*---------- Forecasting ------------------*/
                   7599:     /*if((stepm == 1) && (strcmp(model,".")==0)){*/
                   7600:     if(prevfcast==1){
                   7601:       /*    if(stepm ==1){*/
                   7602:       prevforecast(fileres, anproj1, mproj1, jproj1, agemin, agemax, dateprev1, dateprev2, mobilavproj, bage, fage, firstpass, lastpass, anproj2, p, cptcoveff);
                   7603:       /* (popforecast==1) populforecast(fileres, anpyram,mpyram,jpyram, agemin,agemax, dateprev1, dateprev2,mobilav, agedeb, fage, popforecast, popfile, anpyram1,p, i1);*/
                   7604:       /*      }  */
                   7605:       /*      else{ */
                   7606:       /*        erreur=108; */
                   7607:       /*        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); */
                   7608:       /*        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); */
                   7609:       /*      } */
                   7610:     }
1.186     brouard  7611:  
                   7612:     /* ------ Other prevalence ratios------------ */
1.126     brouard  7613: 
1.127     brouard  7614:     /* Computes prevalence between agemin (i.e minimal age computed) and no more ageminpar */
                   7615: 
                   7616:     prevalence(probs, agemin, agemax, s, agev, nlstate, imx, Tvar, nbcode, ncodemax, mint, anint, dateprev1, dateprev2, firstpass, lastpass);
                   7617:     /*  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",\
                   7618:        ageminpar, agemax, s[lastpass][imx], agev[lastpass][imx], nlstate, imx, mint[lastpass][imx],anint[lastpass][imx], dateprev1, dateprev2, firstpass, lastpass);
                   7619:     */
1.126     brouard  7620: 
1.127     brouard  7621:     if (mobilav!=0) {
                   7622:       mobaverage= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
                   7623:       if (movingaverage(probs, bage, fage, mobaverage,mobilav)!=0){
                   7624:        fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav);
                   7625:        printf(" Error in movingaverage mobilav=%d\n",mobilav);
                   7626:       }
1.126     brouard  7627:     }
                   7628: 
                   7629: 
1.127     brouard  7630:     /*---------- Health expectancies, no variances ------------*/
                   7631: 
1.126     brouard  7632:     strcpy(filerese,"e");
                   7633:     strcat(filerese,fileres);
                   7634:     if((ficreseij=fopen(filerese,"w"))==NULL) {
                   7635:       printf("Problem with Health Exp. resultfile: %s\n", filerese); exit(0);
                   7636:       fprintf(ficlog,"Problem with Health Exp. resultfile: %s\n", filerese); exit(0);
                   7637:     }
                   7638:     printf("Computing Health Expectancies: result on file '%s' \n", filerese);
                   7639:     fprintf(ficlog,"Computing Health Expectancies: result on file '%s' \n", filerese);
1.145     brouard  7640:     /*for(cptcov=1,k=0;cptcov<=i1;cptcov++){
                   7641:       for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){*/
                   7642:           
                   7643:     for (k=1; k <= (int) pow(2,cptcoveff); k++){
1.127     brouard  7644:        fprintf(ficreseij,"\n#****** ");
                   7645:        for(j=1;j<=cptcoveff;j++) {
                   7646:          fprintf(ficreseij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
                   7647:        }
                   7648:        fprintf(ficreseij,"******\n");
                   7649: 
                   7650:        eij=ma3x(1,nlstate,1,nlstate,(int) bage, (int) fage);
                   7651:        oldm=oldms;savm=savms;
                   7652:        evsij(eij, p, nlstate, stepm, (int) bage, (int)fage, oldm, savm, k, estepm, strstart);  
                   7653:       
                   7654:        free_ma3x(eij,1,nlstate,1,nlstate,(int) bage, (int)fage);
1.145     brouard  7655:       /*}*/
1.127     brouard  7656:     }
                   7657:     fclose(ficreseij);
                   7658: 
                   7659: 
                   7660:     /*---------- Health expectancies and variances ------------*/
                   7661: 
                   7662: 
                   7663:     strcpy(filerest,"t");
                   7664:     strcat(filerest,fileres);
                   7665:     if((ficrest=fopen(filerest,"w"))==NULL) {
                   7666:       printf("Problem with total LE resultfile: %s\n", filerest);goto end;
                   7667:       fprintf(ficlog,"Problem with total LE resultfile: %s\n", filerest);goto end;
                   7668:     }
                   7669:     printf("Computing Total Life expectancies with their standard errors: file '%s' \n", filerest); 
                   7670:     fprintf(ficlog,"Computing Total Life expectancies with their standard errors: file '%s' \n", filerest); 
                   7671: 
1.126     brouard  7672: 
                   7673:     strcpy(fileresstde,"stde");
                   7674:     strcat(fileresstde,fileres);
                   7675:     if((ficresstdeij=fopen(fileresstde,"w"))==NULL) {
                   7676:       printf("Problem with Health Exp. and std errors resultfile: %s\n", fileresstde); exit(0);
                   7677:       fprintf(ficlog,"Problem with Health Exp. and std errors resultfile: %s\n", fileresstde); exit(0);
                   7678:     }
                   7679:     printf("Computing Health Expectancies and standard errors: result on file '%s' \n", fileresstde);
                   7680:     fprintf(ficlog,"Computing Health Expectancies and standard errors: result on file '%s' \n", fileresstde);
                   7681: 
                   7682:     strcpy(filerescve,"cve");
                   7683:     strcat(filerescve,fileres);
                   7684:     if((ficrescveij=fopen(filerescve,"w"))==NULL) {
                   7685:       printf("Problem with Covar. Health Exp. resultfile: %s\n", filerescve); exit(0);
                   7686:       fprintf(ficlog,"Problem with Covar. Health Exp. resultfile: %s\n", filerescve); exit(0);
                   7687:     }
                   7688:     printf("Computing Covar. of Health Expectancies: result on file '%s' \n", filerescve);
                   7689:     fprintf(ficlog,"Computing Covar. of Health Expectancies: result on file '%s' \n", filerescve);
                   7690: 
                   7691:     strcpy(fileresv,"v");
                   7692:     strcat(fileresv,fileres);
                   7693:     if((ficresvij=fopen(fileresv,"w"))==NULL) {
                   7694:       printf("Problem with variance resultfile: %s\n", fileresv);exit(0);
                   7695:       fprintf(ficlog,"Problem with variance resultfile: %s\n", fileresv);exit(0);
                   7696:     }
                   7697:     printf("Computing Variance-covariance of DFLEs: file '%s' \n", fileresv);
                   7698:     fprintf(ficlog,"Computing Variance-covariance of DFLEs: file '%s' \n", fileresv);
                   7699: 
1.145     brouard  7700:     /*for(cptcov=1,k=0;cptcov<=i1;cptcov++){
                   7701:       for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){*/
                   7702:           
                   7703:     for (k=1; k <= (int) pow(2,cptcoveff); k++){
                   7704:        fprintf(ficrest,"\n#****** ");
1.126     brouard  7705:        for(j=1;j<=cptcoveff;j++) 
                   7706:          fprintf(ficrest,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
                   7707:        fprintf(ficrest,"******\n");
                   7708: 
                   7709:        fprintf(ficresstdeij,"\n#****** ");
                   7710:        fprintf(ficrescveij,"\n#****** ");
                   7711:        for(j=1;j<=cptcoveff;j++) {
                   7712:          fprintf(ficresstdeij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
                   7713:          fprintf(ficrescveij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
                   7714:        }
                   7715:        fprintf(ficresstdeij,"******\n");
                   7716:        fprintf(ficrescveij,"******\n");
                   7717: 
                   7718:        fprintf(ficresvij,"\n#****** ");
                   7719:        for(j=1;j<=cptcoveff;j++) 
                   7720:          fprintf(ficresvij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
                   7721:        fprintf(ficresvij,"******\n");
                   7722: 
                   7723:        eij=ma3x(1,nlstate,1,nlstate,(int) bage, (int) fage);
                   7724:        oldm=oldms;savm=savms;
1.127     brouard  7725:        cvevsij(eij, p, nlstate, stepm, (int) bage, (int)fage, oldm, savm, k, estepm, delti, matcov, strstart);  
1.145     brouard  7726:        /*
                   7727:         */
                   7728:        /* goto endfree; */
1.126     brouard  7729:  
                   7730:        vareij=ma3x(1,nlstate,1,nlstate,(int) bage, (int) fage);
                   7731:        pstamp(ficrest);
1.145     brouard  7732: 
                   7733: 
1.128     brouard  7734:        for(vpopbased=0; vpopbased <= popbased; vpopbased++){ /* Done for vpopbased=0 and vpopbased=1 if popbased==1*/
1.145     brouard  7735:          oldm=oldms;savm=savms; /* Segmentation fault */
1.161     brouard  7736:          cptcod= 0; /* To be deleted */
                   7737:          varevsij(optionfilefiname, vareij, matcov, p, delti, nlstate, stepm, (int) bage, (int) fage, oldm, savm, prlim, ftolpl,k, estepm, cptcov,cptcod,vpopbased,mobilav, strstart); /* cptcod not initialized Intel */
1.145     brouard  7738:          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  7739:          if(vpopbased==1)
                   7740:            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);
                   7741:          else
                   7742:            fprintf(ficrest,"the age specific period (stable) prevalences in each health state \n");
                   7743:          fprintf(ficrest,"# Age e.. (std) ");
                   7744:          for (i=1;i<=nlstate;i++) fprintf(ficrest,"e.%d (std) ",i);
                   7745:          fprintf(ficrest,"\n");
1.126     brouard  7746: 
1.128     brouard  7747:          epj=vector(1,nlstate+1);
                   7748:          for(age=bage; age <=fage ;age++){
                   7749:            prevalim(prlim, nlstate, p, age, oldm, savm,ftolpl,k);
                   7750:            if (vpopbased==1) {
                   7751:              if(mobilav ==0){
                   7752:                for(i=1; i<=nlstate;i++)
                   7753:                  prlim[i][i]=probs[(int)age][i][k];
                   7754:              }else{ /* mobilav */ 
                   7755:                for(i=1; i<=nlstate;i++)
                   7756:                  prlim[i][i]=mobaverage[(int)age][i][k];
                   7757:              }
1.126     brouard  7758:            }
                   7759:        
1.128     brouard  7760:            fprintf(ficrest," %4.0f",age);
                   7761:            for(j=1, epj[nlstate+1]=0.;j <=nlstate;j++){
                   7762:              for(i=1, epj[j]=0.;i <=nlstate;i++) {
                   7763:                epj[j] += prlim[i][i]*eij[i][j][(int)age];
                   7764:                /*  printf("%lf %lf ", prlim[i][i] ,eij[i][j][(int)age]);*/
                   7765:              }
                   7766:              epj[nlstate+1] +=epj[j];
1.126     brouard  7767:            }
                   7768: 
1.128     brouard  7769:            for(i=1, vepp=0.;i <=nlstate;i++)
                   7770:              for(j=1;j <=nlstate;j++)
                   7771:                vepp += vareij[i][j][(int)age];
                   7772:            fprintf(ficrest," %7.3f (%7.3f)", epj[nlstate+1],sqrt(vepp));
                   7773:            for(j=1;j <=nlstate;j++){
                   7774:              fprintf(ficrest," %7.3f (%7.3f)", epj[j],sqrt(vareij[j][j][(int)age]));
                   7775:            }
                   7776:            fprintf(ficrest,"\n");
1.126     brouard  7777:          }
                   7778:        }
                   7779:        free_ma3x(eij,1,nlstate,1,nlstate,(int) bage, (int)fage);
                   7780:        free_ma3x(vareij,1,nlstate,1,nlstate,(int) bage, (int)fage);
                   7781:        free_vector(epj,1,nlstate+1);
1.145     brouard  7782:       /*}*/
1.126     brouard  7783:     }
                   7784:     free_vector(weight,1,n);
1.145     brouard  7785:     free_imatrix(Tvard,1,NCOVMAX,1,2);
1.126     brouard  7786:     free_imatrix(s,1,maxwav+1,1,n);
                   7787:     free_matrix(anint,1,maxwav,1,n); 
                   7788:     free_matrix(mint,1,maxwav,1,n);
                   7789:     free_ivector(cod,1,n);
                   7790:     free_ivector(tab,1,NCOVMAX);
                   7791:     fclose(ficresstdeij);
                   7792:     fclose(ficrescveij);
                   7793:     fclose(ficresvij);
                   7794:     fclose(ficrest);
                   7795:     fclose(ficpar);
                   7796:   
                   7797:     /*------- Variance of period (stable) prevalence------*/   
                   7798: 
                   7799:     strcpy(fileresvpl,"vpl");
                   7800:     strcat(fileresvpl,fileres);
                   7801:     if((ficresvpl=fopen(fileresvpl,"w"))==NULL) {
                   7802:       printf("Problem with variance of period (stable) prevalence  resultfile: %s\n", fileresvpl);
                   7803:       exit(0);
                   7804:     }
                   7805:     printf("Computing Variance-covariance of period (stable) prevalence: file '%s' \n", fileresvpl);
                   7806: 
1.145     brouard  7807:     /*for(cptcov=1,k=0;cptcov<=i1;cptcov++){
                   7808:       for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){*/
                   7809:           
                   7810:     for (k=1; k <= (int) pow(2,cptcoveff); k++){
                   7811:        fprintf(ficresvpl,"\n#****** ");
1.126     brouard  7812:        for(j=1;j<=cptcoveff;j++) 
                   7813:          fprintf(ficresvpl,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
                   7814:        fprintf(ficresvpl,"******\n");
                   7815:       
                   7816:        varpl=matrix(1,nlstate,(int) bage, (int) fage);
                   7817:        oldm=oldms;savm=savms;
                   7818:        varprevlim(fileres, varpl, matcov, p, delti, nlstate, stepm, (int) bage, (int) fage, oldm, savm, prlim, ftolpl,k,strstart);
                   7819:        free_matrix(varpl,1,nlstate,(int) bage, (int)fage);
1.145     brouard  7820:       /*}*/
1.126     brouard  7821:     }
                   7822: 
                   7823:     fclose(ficresvpl);
                   7824: 
                   7825:     /*---------- End : free ----------------*/
                   7826:     if (mobilav!=0) free_ma3x(mobaverage,1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
                   7827:     free_ma3x(probs,1,AGESUP,1,NCOVMAX, 1,NCOVMAX);
                   7828:   }  /* mle==-3 arrives here for freeing */
1.164     brouard  7829:  /* endfree:*/
1.141     brouard  7830:     free_matrix(prlim,1,nlstate,1,nlstate); /*here or after loop ? */
1.126     brouard  7831:     free_matrix(pmmij,1,nlstate+ndeath,1,nlstate+ndeath);
                   7832:     free_matrix(oldms, 1,nlstate+ndeath,1,nlstate+ndeath);
                   7833:     free_matrix(newms, 1,nlstate+ndeath,1,nlstate+ndeath);
                   7834:     free_matrix(savms, 1,nlstate+ndeath,1,nlstate+ndeath);
                   7835:     free_matrix(covar,0,NCOVMAX,1,n);
                   7836:     free_matrix(matcov,1,npar,1,npar);
                   7837:     /*free_vector(delti,1,npar);*/
                   7838:     free_ma3x(delti3,1,nlstate,1, nlstate+ndeath-1,1,ncovmodel); 
                   7839:     free_matrix(agev,1,maxwav,1,imx);
                   7840:     free_ma3x(param,1,nlstate,1, nlstate+ndeath-1,1,ncovmodel);
                   7841: 
1.145     brouard  7842:     free_ivector(ncodemax,1,NCOVMAX);
1.192     brouard  7843:     free_ivector(ncodemaxwundef,1,NCOVMAX);
1.145     brouard  7844:     free_ivector(Tvar,1,NCOVMAX);
                   7845:     free_ivector(Tprod,1,NCOVMAX);
                   7846:     free_ivector(Tvaraff,1,NCOVMAX);
                   7847:     free_ivector(Tage,1,NCOVMAX);
1.126     brouard  7848: 
                   7849:     free_imatrix(nbcode,0,NCOVMAX,0,NCOVMAX);
                   7850:     free_imatrix(codtab,1,100,1,10);
                   7851:   fflush(fichtm);
                   7852:   fflush(ficgp);
                   7853:   
                   7854: 
                   7855:   if((nberr >0) || (nbwarn>0)){
                   7856:     printf("End of Imach with %d errors and/or %d warnings\n",nberr,nbwarn);
                   7857:     fprintf(ficlog,"End of Imach with %d errors and/or warnings %d\n",nberr,nbwarn);
                   7858:   }else{
                   7859:     printf("End of Imach\n");
                   7860:     fprintf(ficlog,"End of Imach\n");
                   7861:   }
                   7862:   printf("See log file on %s\n",filelog);
                   7863:   /*  gettimeofday(&end_time, (struct timezone*)0);*/  /* after time */
1.157     brouard  7864:   /*(void) gettimeofday(&end_time,&tzp);*/
                   7865:   rend_time = time(NULL);  
                   7866:   end_time = *localtime(&rend_time);
                   7867:   /* tml = *localtime(&end_time.tm_sec); */
                   7868:   strcpy(strtend,asctime(&end_time));
1.126     brouard  7869:   printf("Local time at start %s\nLocal time at end   %s",strstart, strtend); 
                   7870:   fprintf(ficlog,"Local time at start %s\nLocal time at end   %s\n",strstart, strtend); 
1.157     brouard  7871:   printf("Total time used %s\n", asc_diff_time(rend_time -rstart_time,tmpout));
1.126     brouard  7872: 
1.157     brouard  7873:   printf("Total time was %.0lf Sec.\n", difftime(rend_time,rstart_time));
                   7874:   fprintf(ficlog,"Total time used %s\n", asc_diff_time(rend_time -rstart_time,tmpout));
                   7875:   fprintf(ficlog,"Total time was %.0lf Sec.\n", difftime(rend_time,rstart_time));
1.126     brouard  7876:   /*  printf("Total time was %d uSec.\n", total_usecs);*/
                   7877: /*   if(fileappend(fichtm,optionfilehtm)){ */
                   7878:   fprintf(fichtm,"<br>Local time at start %s<br>Local time at end   %s<br>\n</body></html>",strstart, strtend);
                   7879:   fclose(fichtm);
                   7880:   fprintf(fichtmcov,"<br>Local time at start %s<br>Local time at end   %s<br>\n</body></html>",strstart, strtend);
                   7881:   fclose(fichtmcov);
                   7882:   fclose(ficgp);
                   7883:   fclose(ficlog);
                   7884:   /*------ End -----------*/
                   7885: 
                   7886: 
                   7887:    printf("Before Current directory %s!\n",pathcd);
1.184     brouard  7888: #ifdef WIN32
                   7889:    if (_chdir(pathcd) != 0)
                   7890:           printf("Can't move to directory %s!\n",path);
                   7891:    if(_getcwd(pathcd,MAXLINE) > 0)
                   7892: #else
1.126     brouard  7893:    if(chdir(pathcd) != 0)
1.184     brouard  7894:           printf("Can't move to directory %s!\n", path);
                   7895:    if (getcwd(pathcd, MAXLINE) > 0)
                   7896: #endif 
1.126     brouard  7897:     printf("Current directory %s!\n",pathcd);
                   7898:   /*strcat(plotcmd,CHARSEPARATOR);*/
                   7899:   sprintf(plotcmd,"gnuplot");
1.157     brouard  7900: #ifdef _WIN32
1.126     brouard  7901:   sprintf(plotcmd,"\"%sgnuplot.exe\"",pathimach);
                   7902: #endif
                   7903:   if(!stat(plotcmd,&info)){
1.158     brouard  7904:     printf("Error or gnuplot program not found: '%s'\n",plotcmd);fflush(stdout);
1.126     brouard  7905:     if(!stat(getenv("GNUPLOTBIN"),&info)){
1.158     brouard  7906:       printf("Error or gnuplot program not found: '%s' Environment GNUPLOTBIN not set.\n",plotcmd);fflush(stdout);
1.126     brouard  7907:     }else
                   7908:       strcpy(pplotcmd,plotcmd);
1.157     brouard  7909: #ifdef __unix
1.126     brouard  7910:     strcpy(plotcmd,GNUPLOTPROGRAM);
                   7911:     if(!stat(plotcmd,&info)){
1.158     brouard  7912:       printf("Error gnuplot program not found: '%s'\n",plotcmd);fflush(stdout);
1.126     brouard  7913:     }else
                   7914:       strcpy(pplotcmd,plotcmd);
                   7915: #endif
                   7916:   }else
                   7917:     strcpy(pplotcmd,plotcmd);
                   7918:   
                   7919:   sprintf(plotcmd,"%s %s",pplotcmd, optionfilegnuplot);
1.158     brouard  7920:   printf("Starting graphs with: '%s'\n",plotcmd);fflush(stdout);
1.126     brouard  7921: 
                   7922:   if((outcmd=system(plotcmd)) != 0){
1.158     brouard  7923:     printf("gnuplot command might not be in your path: '%s', err=%d\n", plotcmd, outcmd);
1.154     brouard  7924:     printf("\n Trying if gnuplot resides on the same directory that IMaCh\n");
1.152     brouard  7925:     sprintf(plotcmd,"%sgnuplot %s", pathimach, optionfilegnuplot);
1.150     brouard  7926:     if((outcmd=system(plotcmd)) != 0)
1.153     brouard  7927:       printf("\n Still a problem with gnuplot command %s, err=%d\n", plotcmd, outcmd);
1.126     brouard  7928:   }
1.158     brouard  7929:   printf(" Successful, please wait...");
1.126     brouard  7930:   while (z[0] != 'q') {
                   7931:     /* chdir(path); */
1.154     brouard  7932:     printf("\nType e to edit results with your browser, g to graph again and q for exit: ");
1.126     brouard  7933:     scanf("%s",z);
                   7934: /*     if (z[0] == 'c') system("./imach"); */
                   7935:     if (z[0] == 'e') {
1.158     brouard  7936: #ifdef __APPLE__
1.152     brouard  7937:       sprintf(pplotcmd, "open %s", optionfilehtm);
1.157     brouard  7938: #elif __linux
                   7939:       sprintf(pplotcmd, "xdg-open %s", optionfilehtm);
1.153     brouard  7940: #else
1.152     brouard  7941:       sprintf(pplotcmd, "%s", optionfilehtm);
1.153     brouard  7942: #endif
                   7943:       printf("Starting browser with: %s",pplotcmd);fflush(stdout);
                   7944:       system(pplotcmd);
1.126     brouard  7945:     }
                   7946:     else if (z[0] == 'g') system(plotcmd);
                   7947:     else if (z[0] == 'q') exit(0);
                   7948:   }
                   7949:   end:
                   7950:   while (z[0] != 'q') {
1.195     brouard  7951:     printf("\nType  q for exiting: "); fflush(stdout);
1.126     brouard  7952:     scanf("%s",z);
                   7953:   }
                   7954: }

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