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

1.196   ! brouard     1: /* $Id: imach.c,v 1.195 2015/08/18 16:28:39 brouard Exp $
1.126     brouard     2:   $State: Exp $
1.163     brouard     3:   $Log: imach.c,v $
1.196   ! brouard     4:   Revision 1.195  2015/08/18 16:28:39  brouard
        !             5:   Summary: Adding a hack for testing purpose
        !             6: 
        !             7:   After reading the title, ftol and model lines, if the comment line has
        !             8:   a q, starting with #q, the answer at the end of the run is quit. It
        !             9:   permits to run test files in batch with ctest. The former workaround was
        !            10:   $ echo q | imach foo.imach
        !            11: 
1.195     brouard    12:   Revision 1.194  2015/08/18 13:32:00  brouard
                     13:   Summary:  Adding error when the covariance matrix doesn't contain the exact number of lines required by the model line.
                     14: 
1.194     brouard    15:   Revision 1.193  2015/08/04 07:17:42  brouard
                     16:   Summary: 0.98q4
                     17: 
1.193     brouard    18:   Revision 1.192  2015/07/16 16:49:02  brouard
                     19:   Summary: Fixing some outputs
                     20: 
1.192     brouard    21:   Revision 1.191  2015/07/14 10:00:33  brouard
                     22:   Summary: Some fixes
                     23: 
1.191     brouard    24:   Revision 1.190  2015/05/05 08:51:13  brouard
                     25:   Summary: Adding digits in output parameters (7 digits instead of 6)
                     26: 
                     27:   Fix 1+age+.
                     28: 
1.190     brouard    29:   Revision 1.189  2015/04/30 14:45:16  brouard
                     30:   Summary: 0.98q2
                     31: 
1.189     brouard    32:   Revision 1.188  2015/04/30 08:27:53  brouard
                     33:   *** empty log message ***
                     34: 
1.188     brouard    35:   Revision 1.187  2015/04/29 09:11:15  brouard
                     36:   *** empty log message ***
                     37: 
1.187     brouard    38:   Revision 1.186  2015/04/23 12:01:52  brouard
                     39:   Summary: V1*age is working now, version 0.98q1
                     40: 
                     41:   Some codes had been disabled in order to simplify and Vn*age was
                     42:   working in the optimization phase, ie, giving correct MLE parameters,
                     43:   but, as usual, outputs were not correct and program core dumped.
                     44: 
1.186     brouard    45:   Revision 1.185  2015/03/11 13:26:42  brouard
                     46:   Summary: Inclusion of compile and links command line for Intel Compiler
                     47: 
1.185     brouard    48:   Revision 1.184  2015/03/11 11:52:39  brouard
                     49:   Summary: Back from Windows 8. Intel Compiler
                     50: 
1.184     brouard    51:   Revision 1.183  2015/03/10 20:34:32  brouard
                     52:   Summary: 0.98q0, trying with directest, mnbrak fixed
                     53: 
                     54:   We use directest instead of original Powell test; probably no
                     55:   incidence on the results, but better justifications;
                     56:   We fixed Numerical Recipes mnbrak routine which was wrong and gave
                     57:   wrong results.
                     58: 
1.183     brouard    59:   Revision 1.182  2015/02/12 08:19:57  brouard
                     60:   Summary: Trying to keep directest which seems simpler and more general
                     61:   Author: Nicolas Brouard
                     62: 
1.182     brouard    63:   Revision 1.181  2015/02/11 23:22:24  brouard
                     64:   Summary: Comments on Powell added
                     65: 
                     66:   Author:
                     67: 
1.181     brouard    68:   Revision 1.180  2015/02/11 17:33:45  brouard
                     69:   Summary: Finishing move from main to function (hpijx and prevalence_limit)
                     70: 
1.180     brouard    71:   Revision 1.179  2015/01/04 09:57:06  brouard
                     72:   Summary: back to OS/X
                     73: 
1.179     brouard    74:   Revision 1.178  2015/01/04 09:35:48  brouard
                     75:   *** empty log message ***
                     76: 
1.178     brouard    77:   Revision 1.177  2015/01/03 18:40:56  brouard
                     78:   Summary: Still testing ilc32 on OSX
                     79: 
1.177     brouard    80:   Revision 1.176  2015/01/03 16:45:04  brouard
                     81:   *** empty log message ***
                     82: 
1.176     brouard    83:   Revision 1.175  2015/01/03 16:33:42  brouard
                     84:   *** empty log message ***
                     85: 
1.175     brouard    86:   Revision 1.174  2015/01/03 16:15:49  brouard
                     87:   Summary: Still in cross-compilation
                     88: 
1.174     brouard    89:   Revision 1.173  2015/01/03 12:06:26  brouard
                     90:   Summary: trying to detect cross-compilation
                     91: 
1.173     brouard    92:   Revision 1.172  2014/12/27 12:07:47  brouard
                     93:   Summary: Back from Visual Studio and Intel, options for compiling for Windows XP
                     94: 
1.172     brouard    95:   Revision 1.171  2014/12/23 13:26:59  brouard
                     96:   Summary: Back from Visual C
                     97: 
                     98:   Still problem with utsname.h on Windows
                     99: 
1.171     brouard   100:   Revision 1.170  2014/12/23 11:17:12  brouard
                    101:   Summary: Cleaning some \%% back to %%
                    102: 
                    103:   The escape was mandatory for a specific compiler (which one?), but too many warnings.
                    104: 
1.170     brouard   105:   Revision 1.169  2014/12/22 23:08:31  brouard
                    106:   Summary: 0.98p
                    107: 
                    108:   Outputs some informations on compiler used, OS etc. Testing on different platforms.
                    109: 
1.169     brouard   110:   Revision 1.168  2014/12/22 15:17:42  brouard
1.170     brouard   111:   Summary: update
1.169     brouard   112: 
1.168     brouard   113:   Revision 1.167  2014/12/22 13:50:56  brouard
                    114:   Summary: Testing uname and compiler version and if compiled 32 or 64
                    115: 
                    116:   Testing on Linux 64
                    117: 
1.167     brouard   118:   Revision 1.166  2014/12/22 11:40:47  brouard
                    119:   *** empty log message ***
                    120: 
1.166     brouard   121:   Revision 1.165  2014/12/16 11:20:36  brouard
                    122:   Summary: After compiling on Visual C
                    123: 
                    124:   * imach.c (Module): Merging 1.61 to 1.162
                    125: 
1.165     brouard   126:   Revision 1.164  2014/12/16 10:52:11  brouard
                    127:   Summary: Merging with Visual C after suppressing some warnings for unused variables. Also fixing Saito's bug 0.98Xn
                    128: 
                    129:   * imach.c (Module): Merging 1.61 to 1.162
                    130: 
1.164     brouard   131:   Revision 1.163  2014/12/16 10:30:11  brouard
                    132:   * imach.c (Module): Merging 1.61 to 1.162
                    133: 
1.163     brouard   134:   Revision 1.162  2014/09/25 11:43:39  brouard
                    135:   Summary: temporary backup 0.99!
                    136: 
1.162     brouard   137:   Revision 1.1  2014/09/16 11:06:58  brouard
                    138:   Summary: With some code (wrong) for nlopt
                    139: 
                    140:   Author:
                    141: 
                    142:   Revision 1.161  2014/09/15 20:41:41  brouard
                    143:   Summary: Problem with macro SQR on Intel compiler
                    144: 
1.161     brouard   145:   Revision 1.160  2014/09/02 09:24:05  brouard
                    146:   *** empty log message ***
                    147: 
1.160     brouard   148:   Revision 1.159  2014/09/01 10:34:10  brouard
                    149:   Summary: WIN32
                    150:   Author: Brouard
                    151: 
1.159     brouard   152:   Revision 1.158  2014/08/27 17:11:51  brouard
                    153:   *** empty log message ***
                    154: 
1.158     brouard   155:   Revision 1.157  2014/08/27 16:26:55  brouard
                    156:   Summary: Preparing windows Visual studio version
                    157:   Author: Brouard
                    158: 
                    159:   In order to compile on Visual studio, time.h is now correct and time_t
                    160:   and tm struct should be used. difftime should be used but sometimes I
                    161:   just make the differences in raw time format (time(&now).
                    162:   Trying to suppress #ifdef LINUX
                    163:   Add xdg-open for __linux in order to open default browser.
                    164: 
1.157     brouard   165:   Revision 1.156  2014/08/25 20:10:10  brouard
                    166:   *** empty log message ***
                    167: 
1.156     brouard   168:   Revision 1.155  2014/08/25 18:32:34  brouard
                    169:   Summary: New compile, minor changes
                    170:   Author: Brouard
                    171: 
1.155     brouard   172:   Revision 1.154  2014/06/20 17:32:08  brouard
                    173:   Summary: Outputs now all graphs of convergence to period prevalence
                    174: 
1.154     brouard   175:   Revision 1.153  2014/06/20 16:45:46  brouard
                    176:   Summary: If 3 live state, convergence to period prevalence on same graph
                    177:   Author: Brouard
                    178: 
1.153     brouard   179:   Revision 1.152  2014/06/18 17:54:09  brouard
                    180:   Summary: open browser, use gnuplot on same dir than imach if not found in the path
                    181: 
1.152     brouard   182:   Revision 1.151  2014/06/18 16:43:30  brouard
                    183:   *** empty log message ***
                    184: 
1.151     brouard   185:   Revision 1.150  2014/06/18 16:42:35  brouard
                    186:   Summary: If gnuplot is not in the path try on same directory than imach binary (OSX)
                    187:   Author: brouard
                    188: 
1.150     brouard   189:   Revision 1.149  2014/06/18 15:51:14  brouard
                    190:   Summary: Some fixes in parameter files errors
                    191:   Author: Nicolas Brouard
                    192: 
1.149     brouard   193:   Revision 1.148  2014/06/17 17:38:48  brouard
                    194:   Summary: Nothing new
                    195:   Author: Brouard
                    196: 
                    197:   Just a new packaging for OS/X version 0.98nS
                    198: 
1.148     brouard   199:   Revision 1.147  2014/06/16 10:33:11  brouard
                    200:   *** empty log message ***
                    201: 
1.147     brouard   202:   Revision 1.146  2014/06/16 10:20:28  brouard
                    203:   Summary: Merge
                    204:   Author: Brouard
                    205: 
                    206:   Merge, before building revised version.
                    207: 
1.146     brouard   208:   Revision 1.145  2014/06/10 21:23:15  brouard
                    209:   Summary: Debugging with valgrind
                    210:   Author: Nicolas Brouard
                    211: 
                    212:   Lot of changes in order to output the results with some covariates
                    213:   After the Edimburgh REVES conference 2014, it seems mandatory to
                    214:   improve the code.
                    215:   No more memory valgrind error but a lot has to be done in order to
                    216:   continue the work of splitting the code into subroutines.
                    217:   Also, decodemodel has been improved. Tricode is still not
                    218:   optimal. nbcode should be improved. Documentation has been added in
                    219:   the source code.
                    220: 
1.144     brouard   221:   Revision 1.143  2014/01/26 09:45:38  brouard
                    222:   Summary: Version 0.98nR (to be improved, but gives same optimization results as 0.98k. Nice, promising
                    223: 
                    224:   * imach.c (Module): Trying to merge old staffs together while being at Tokyo. Not tested...
                    225:   (Module): Version 0.98nR Running ok, but output format still only works for three covariates.
                    226: 
1.143     brouard   227:   Revision 1.142  2014/01/26 03:57:36  brouard
                    228:   Summary: gnuplot changed plot w l 1 has to be changed to plot w l lt 2
                    229: 
                    230:   * imach.c (Module): Trying to merge old staffs together while being at Tokyo. Not tested...
                    231: 
1.142     brouard   232:   Revision 1.141  2014/01/26 02:42:01  brouard
                    233:   * imach.c (Module): Trying to merge old staffs together while being at Tokyo. Not tested...
                    234: 
1.141     brouard   235:   Revision 1.140  2011/09/02 10:37:54  brouard
                    236:   Summary: times.h is ok with mingw32 now.
                    237: 
1.140     brouard   238:   Revision 1.139  2010/06/14 07:50:17  brouard
                    239:   After the theft of my laptop, I probably lost some lines of codes which were not uploaded to the CVS tree.
                    240:   I remember having already fixed agemin agemax which are pointers now but not cvs saved.
                    241: 
1.139     brouard   242:   Revision 1.138  2010/04/30 18:19:40  brouard
                    243:   *** empty log message ***
                    244: 
1.138     brouard   245:   Revision 1.137  2010/04/29 18:11:38  brouard
                    246:   (Module): Checking covariates for more complex models
                    247:   than V1+V2. A lot of change to be done. Unstable.
                    248: 
1.137     brouard   249:   Revision 1.136  2010/04/26 20:30:53  brouard
                    250:   (Module): merging some libgsl code. Fixing computation
                    251:   of likelione (using inter/intrapolation if mle = 0) in order to
                    252:   get same likelihood as if mle=1.
                    253:   Some cleaning of code and comments added.
                    254: 
1.136     brouard   255:   Revision 1.135  2009/10/29 15:33:14  brouard
                    256:   (Module): Now imach stops if date of birth, at least year of birth, is not given. Some cleaning of the code.
                    257: 
1.135     brouard   258:   Revision 1.134  2009/10/29 13:18:53  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.134     brouard   261:   Revision 1.133  2009/07/06 10:21:25  brouard
                    262:   just nforces
                    263: 
1.133     brouard   264:   Revision 1.132  2009/07/06 08:22:05  brouard
                    265:   Many tings
                    266: 
1.132     brouard   267:   Revision 1.131  2009/06/20 16:22:47  brouard
                    268:   Some dimensions resccaled
                    269: 
1.131     brouard   270:   Revision 1.130  2009/05/26 06:44:34  brouard
                    271:   (Module): Max Covariate is now set to 20 instead of 8. A
                    272:   lot of cleaning with variables initialized to 0. Trying to make
                    273:   V2+V3*age+V1+V4 strb=V3*age+V1+V4 working better.
                    274: 
1.130     brouard   275:   Revision 1.129  2007/08/31 13:49:27  lievre
                    276:   Modification of the way of exiting when the covariate is not binary in order to see on the window the error message before exiting
                    277: 
1.129     lievre    278:   Revision 1.128  2006/06/30 13:02:05  brouard
                    279:   (Module): Clarifications on computing e.j
                    280: 
1.128     brouard   281:   Revision 1.127  2006/04/28 18:11:50  brouard
                    282:   (Module): Yes the sum of survivors was wrong since
                    283:   imach-114 because nhstepm was no more computed in the age
                    284:   loop. Now we define nhstepma in the age loop.
                    285:   (Module): In order to speed up (in case of numerous covariates) we
                    286:   compute health expectancies (without variances) in a first step
                    287:   and then all the health expectancies with variances or standard
                    288:   deviation (needs data from the Hessian matrices) which slows the
                    289:   computation.
                    290:   In the future we should be able to stop the program is only health
                    291:   expectancies and graph are needed without standard deviations.
                    292: 
1.127     brouard   293:   Revision 1.126  2006/04/28 17:23:28  brouard
                    294:   (Module): Yes the sum of survivors was wrong since
                    295:   imach-114 because nhstepm was no more computed in the age
                    296:   loop. Now we define nhstepma in the age loop.
                    297:   Version 0.98h
                    298: 
1.126     brouard   299:   Revision 1.125  2006/04/04 15:20:31  lievre
                    300:   Errors in calculation of health expectancies. Age was not initialized.
                    301:   Forecasting file added.
                    302: 
                    303:   Revision 1.124  2006/03/22 17:13:53  lievre
                    304:   Parameters are printed with %lf instead of %f (more numbers after the comma).
                    305:   The log-likelihood is printed in the log file
                    306: 
                    307:   Revision 1.123  2006/03/20 10:52:43  brouard
                    308:   * imach.c (Module): <title> changed, corresponds to .htm file
                    309:   name. <head> headers where missing.
                    310: 
                    311:   * imach.c (Module): Weights can have a decimal point as for
                    312:   English (a comma might work with a correct LC_NUMERIC environment,
                    313:   otherwise the weight is truncated).
                    314:   Modification of warning when the covariates values are not 0 or
                    315:   1.
                    316:   Version 0.98g
                    317: 
                    318:   Revision 1.122  2006/03/20 09:45:41  brouard
                    319:   (Module): Weights can have a decimal point as for
                    320:   English (a comma might work with a correct LC_NUMERIC environment,
                    321:   otherwise the weight is truncated).
                    322:   Modification of warning when the covariates values are not 0 or
                    323:   1.
                    324:   Version 0.98g
                    325: 
                    326:   Revision 1.121  2006/03/16 17:45:01  lievre
                    327:   * imach.c (Module): Comments concerning covariates added
                    328: 
                    329:   * imach.c (Module): refinements in the computation of lli if
                    330:   status=-2 in order to have more reliable computation if stepm is
                    331:   not 1 month. Version 0.98f
                    332: 
                    333:   Revision 1.120  2006/03/16 15:10:38  lievre
                    334:   (Module): refinements in the computation of lli if
                    335:   status=-2 in order to have more reliable computation if stepm is
                    336:   not 1 month. Version 0.98f
                    337: 
                    338:   Revision 1.119  2006/03/15 17:42:26  brouard
                    339:   (Module): Bug if status = -2, the loglikelihood was
                    340:   computed as likelihood omitting the logarithm. Version O.98e
                    341: 
                    342:   Revision 1.118  2006/03/14 18:20:07  brouard
                    343:   (Module): varevsij Comments added explaining the second
                    344:   table of variances if popbased=1 .
                    345:   (Module): Covariances of eij, ekl added, graphs fixed, new html link.
                    346:   (Module): Function pstamp added
                    347:   (Module): Version 0.98d
                    348: 
                    349:   Revision 1.117  2006/03/14 17:16:22  brouard
                    350:   (Module): varevsij Comments added explaining the second
                    351:   table of variances if popbased=1 .
                    352:   (Module): Covariances of eij, ekl added, graphs fixed, new html link.
                    353:   (Module): Function pstamp added
                    354:   (Module): Version 0.98d
                    355: 
                    356:   Revision 1.116  2006/03/06 10:29:27  brouard
                    357:   (Module): Variance-covariance wrong links and
                    358:   varian-covariance of ej. is needed (Saito).
                    359: 
                    360:   Revision 1.115  2006/02/27 12:17:45  brouard
                    361:   (Module): One freematrix added in mlikeli! 0.98c
                    362: 
                    363:   Revision 1.114  2006/02/26 12:57:58  brouard
                    364:   (Module): Some improvements in processing parameter
                    365:   filename with strsep.
                    366: 
                    367:   Revision 1.113  2006/02/24 14:20:24  brouard
                    368:   (Module): Memory leaks checks with valgrind and:
                    369:   datafile was not closed, some imatrix were not freed and on matrix
                    370:   allocation too.
                    371: 
                    372:   Revision 1.112  2006/01/30 09:55:26  brouard
                    373:   (Module): Back to gnuplot.exe instead of wgnuplot.exe
                    374: 
                    375:   Revision 1.111  2006/01/25 20:38:18  brouard
                    376:   (Module): Lots of cleaning and bugs added (Gompertz)
                    377:   (Module): Comments can be added in data file. Missing date values
                    378:   can be a simple dot '.'.
                    379: 
                    380:   Revision 1.110  2006/01/25 00:51:50  brouard
                    381:   (Module): Lots of cleaning and bugs added (Gompertz)
                    382: 
                    383:   Revision 1.109  2006/01/24 19:37:15  brouard
                    384:   (Module): Comments (lines starting with a #) are allowed in data.
                    385: 
                    386:   Revision 1.108  2006/01/19 18:05:42  lievre
                    387:   Gnuplot problem appeared...
                    388:   To be fixed
                    389: 
                    390:   Revision 1.107  2006/01/19 16:20:37  brouard
                    391:   Test existence of gnuplot in imach path
                    392: 
                    393:   Revision 1.106  2006/01/19 13:24:36  brouard
                    394:   Some cleaning and links added in html output
                    395: 
                    396:   Revision 1.105  2006/01/05 20:23:19  lievre
                    397:   *** empty log message ***
                    398: 
                    399:   Revision 1.104  2005/09/30 16:11:43  lievre
                    400:   (Module): sump fixed, loop imx fixed, and simplifications.
                    401:   (Module): If the status is missing at the last wave but we know
                    402:   that the person is alive, then we can code his/her status as -2
                    403:   (instead of missing=-1 in earlier versions) and his/her
                    404:   contributions to the likelihood is 1 - Prob of dying from last
                    405:   health status (= 1-p13= p11+p12 in the easiest case of somebody in
                    406:   the healthy state at last known wave). Version is 0.98
                    407: 
                    408:   Revision 1.103  2005/09/30 15:54:49  lievre
                    409:   (Module): sump fixed, loop imx fixed, and simplifications.
                    410: 
                    411:   Revision 1.102  2004/09/15 17:31:30  brouard
                    412:   Add the possibility to read data file including tab characters.
                    413: 
                    414:   Revision 1.101  2004/09/15 10:38:38  brouard
                    415:   Fix on curr_time
                    416: 
                    417:   Revision 1.100  2004/07/12 18:29:06  brouard
                    418:   Add version for Mac OS X. Just define UNIX in Makefile
                    419: 
                    420:   Revision 1.99  2004/06/05 08:57:40  brouard
                    421:   *** empty log message ***
                    422: 
                    423:   Revision 1.98  2004/05/16 15:05:56  brouard
                    424:   New version 0.97 . First attempt to estimate force of mortality
                    425:   directly from the data i.e. without the need of knowing the health
                    426:   state at each age, but using a Gompertz model: log u =a + b*age .
                    427:   This is the basic analysis of mortality and should be done before any
                    428:   other analysis, in order to test if the mortality estimated from the
                    429:   cross-longitudinal survey is different from the mortality estimated
                    430:   from other sources like vital statistic data.
                    431: 
                    432:   The same imach parameter file can be used but the option for mle should be -3.
                    433: 
1.133     brouard   434:   Agnès, who wrote this part of the code, tried to keep most of the
1.126     brouard   435:   former routines in order to include the new code within the former code.
                    436: 
                    437:   The output is very simple: only an estimate of the intercept and of
                    438:   the slope with 95% confident intervals.
                    439: 
                    440:   Current limitations:
                    441:   A) Even if you enter covariates, i.e. with the
                    442:   model= V1+V2 equation for example, the programm does only estimate a unique global model without covariates.
                    443:   B) There is no computation of Life Expectancy nor Life Table.
                    444: 
                    445:   Revision 1.97  2004/02/20 13:25:42  lievre
                    446:   Version 0.96d. Population forecasting command line is (temporarily)
                    447:   suppressed.
                    448: 
                    449:   Revision 1.96  2003/07/15 15:38:55  brouard
                    450:   * imach.c (Repository): Errors in subdirf, 2, 3 while printing tmpout is
                    451:   rewritten within the same printf. Workaround: many printfs.
                    452: 
                    453:   Revision 1.95  2003/07/08 07:54:34  brouard
                    454:   * imach.c (Repository):
                    455:   (Repository): Using imachwizard code to output a more meaningful covariance
                    456:   matrix (cov(a12,c31) instead of numbers.
                    457: 
                    458:   Revision 1.94  2003/06/27 13:00:02  brouard
                    459:   Just cleaning
                    460: 
                    461:   Revision 1.93  2003/06/25 16:33:55  brouard
                    462:   (Module): On windows (cygwin) function asctime_r doesn't
                    463:   exist so I changed back to asctime which exists.
                    464:   (Module): Version 0.96b
                    465: 
                    466:   Revision 1.92  2003/06/25 16:30:45  brouard
                    467:   (Module): On windows (cygwin) function asctime_r doesn't
                    468:   exist so I changed back to asctime which exists.
                    469: 
                    470:   Revision 1.91  2003/06/25 15:30:29  brouard
                    471:   * imach.c (Repository): Duplicated warning errors corrected.
                    472:   (Repository): Elapsed time after each iteration is now output. It
                    473:   helps to forecast when convergence will be reached. Elapsed time
                    474:   is stamped in powell.  We created a new html file for the graphs
                    475:   concerning matrix of covariance. It has extension -cov.htm.
                    476: 
                    477:   Revision 1.90  2003/06/24 12:34:15  brouard
                    478:   (Module): Some bugs corrected for windows. Also, when
                    479:   mle=-1 a template is output in file "or"mypar.txt with the design
                    480:   of the covariance matrix to be input.
                    481: 
                    482:   Revision 1.89  2003/06/24 12:30:52  brouard
                    483:   (Module): Some bugs corrected for windows. Also, when
                    484:   mle=-1 a template is output in file "or"mypar.txt with the design
                    485:   of the covariance matrix to be input.
                    486: 
                    487:   Revision 1.88  2003/06/23 17:54:56  brouard
                    488:   * 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.
                    489: 
                    490:   Revision 1.87  2003/06/18 12:26:01  brouard
                    491:   Version 0.96
                    492: 
                    493:   Revision 1.86  2003/06/17 20:04:08  brouard
                    494:   (Module): Change position of html and gnuplot routines and added
                    495:   routine fileappend.
                    496: 
                    497:   Revision 1.85  2003/06/17 13:12:43  brouard
                    498:   * imach.c (Repository): Check when date of death was earlier that
                    499:   current date of interview. It may happen when the death was just
                    500:   prior to the death. In this case, dh was negative and likelihood
                    501:   was wrong (infinity). We still send an "Error" but patch by
                    502:   assuming that the date of death was just one stepm after the
                    503:   interview.
                    504:   (Repository): Because some people have very long ID (first column)
                    505:   we changed int to long in num[] and we added a new lvector for
                    506:   memory allocation. But we also truncated to 8 characters (left
                    507:   truncation)
                    508:   (Repository): No more line truncation errors.
                    509: 
                    510:   Revision 1.84  2003/06/13 21:44:43  brouard
                    511:   * imach.c (Repository): Replace "freqsummary" at a correct
                    512:   place. It differs from routine "prevalence" which may be called
                    513:   many times. Probs is memory consuming and must be used with
                    514:   parcimony.
                    515:   Version 0.95a3 (should output exactly the same maximization than 0.8a2)
                    516: 
                    517:   Revision 1.83  2003/06/10 13:39:11  lievre
                    518:   *** empty log message ***
                    519: 
                    520:   Revision 1.82  2003/06/05 15:57:20  brouard
                    521:   Add log in  imach.c and  fullversion number is now printed.
                    522: 
                    523: */
                    524: /*
                    525:    Interpolated Markov Chain
                    526: 
                    527:   Short summary of the programme:
                    528:   
                    529:   This program computes Healthy Life Expectancies from
                    530:   cross-longitudinal data. Cross-longitudinal data consist in: -1- a
                    531:   first survey ("cross") where individuals from different ages are
                    532:   interviewed on their health status or degree of disability (in the
                    533:   case of a health survey which is our main interest) -2- at least a
                    534:   second wave of interviews ("longitudinal") which measure each change
                    535:   (if any) in individual health status.  Health expectancies are
                    536:   computed from the time spent in each health state according to a
                    537:   model. More health states you consider, more time is necessary to reach the
                    538:   Maximum Likelihood of the parameters involved in the model.  The
                    539:   simplest model is the multinomial logistic model where pij is the
                    540:   probability to be observed in state j at the second wave
                    541:   conditional to be observed in state i at the first wave. Therefore
                    542:   the model is: log(pij/pii)= aij + bij*age+ cij*sex + etc , where
                    543:   'age' is age and 'sex' is a covariate. If you want to have a more
                    544:   complex model than "constant and age", you should modify the program
                    545:   where the markup *Covariates have to be included here again* invites
                    546:   you to do it.  More covariates you add, slower the
                    547:   convergence.
                    548: 
                    549:   The advantage of this computer programme, compared to a simple
                    550:   multinomial logistic model, is clear when the delay between waves is not
                    551:   identical for each individual. Also, if a individual missed an
                    552:   intermediate interview, the information is lost, but taken into
                    553:   account using an interpolation or extrapolation.  
                    554: 
                    555:   hPijx is the probability to be observed in state i at age x+h
                    556:   conditional to the observed state i at age x. The delay 'h' can be
                    557:   split into an exact number (nh*stepm) of unobserved intermediate
                    558:   states. This elementary transition (by month, quarter,
                    559:   semester or year) is modelled as a multinomial logistic.  The hPx
                    560:   matrix is simply the matrix product of nh*stepm elementary matrices
                    561:   and the contribution of each individual to the likelihood is simply
                    562:   hPijx.
                    563: 
                    564:   Also this programme outputs the covariance matrix of the parameters but also
                    565:   of the life expectancies. It also computes the period (stable) prevalence. 
                    566:   
1.133     brouard   567:   Authors: Nicolas Brouard (brouard@ined.fr) and Agnès Lièvre (lievre@ined.fr).
                    568:            Institut national d'études démographiques, Paris.
1.126     brouard   569:   This software have been partly granted by Euro-REVES, a concerted action
                    570:   from the European Union.
                    571:   It is copyrighted identically to a GNU software product, ie programme and
                    572:   software can be distributed freely for non commercial use. Latest version
                    573:   can be accessed at http://euroreves.ined.fr/imach .
                    574: 
                    575:   Help to debug: LD_PRELOAD=/usr/local/lib/libnjamd.so ./imach foo.imach
                    576:   or better on gdb : set env LD_PRELOAD=/usr/local/lib/libnjamd.so
                    577:   
                    578:   **********************************************************************/
                    579: /*
                    580:   main
                    581:   read parameterfile
                    582:   read datafile
                    583:   concatwav
                    584:   freqsummary
                    585:   if (mle >= 1)
                    586:     mlikeli
                    587:   print results files
                    588:   if mle==1 
                    589:      computes hessian
                    590:   read end of parameter file: agemin, agemax, bage, fage, estepm
                    591:       begin-prev-date,...
                    592:   open gnuplot file
                    593:   open html file
1.145     brouard   594:   period (stable) prevalence      | pl_nom    1-1 2-2 etc by covariate
                    595:    for age prevalim()             | #****** V1=0  V2=1  V3=1  V4=0 ******
                    596:                                   | 65 1 0 2 1 3 1 4 0  0.96326 0.03674
                    597:     freexexit2 possible for memory heap.
                    598: 
                    599:   h Pij x                         | pij_nom  ficrestpij
                    600:    # Cov Agex agex+h hpijx with i,j= 1-1 1-2     1-3     2-1     2-2     2-3
                    601:        1  85   85    1.00000             0.00000 0.00000 0.00000 1.00000 0.00000
                    602:        1  85   86    0.68299             0.22291 0.09410 0.71093 0.00000 0.28907
                    603: 
                    604:        1  65   99    0.00364             0.00322 0.99314 0.00350 0.00310 0.99340
                    605:        1  65  100    0.00214             0.00204 0.99581 0.00206 0.00196 0.99597
                    606:   variance of p one-step probabilities varprob  | prob_nom   ficresprob #One-step probabilities and stand. devi in ()
                    607:    Standard deviation of one-step probabilities | probcor_nom   ficresprobcor #One-step probabilities and correlation matrix
                    608:    Matrix of variance covariance of one-step probabilities |  probcov_nom ficresprobcov #One-step probabilities and covariance matrix
                    609: 
1.126     brouard   610:   forecasting if prevfcast==1 prevforecast call prevalence()
                    611:   health expectancies
                    612:   Variance-covariance of DFLE
                    613:   prevalence()
                    614:    movingaverage()
                    615:   varevsij() 
                    616:   if popbased==1 varevsij(,popbased)
                    617:   total life expectancies
                    618:   Variance of period (stable) prevalence
                    619:  end
                    620: */
                    621: 
1.187     brouard   622: /* #define DEBUG */
                    623: /* #define DEBUGBRENT */
1.165     brouard   624: #define POWELL /* Instead of NLOPT */
1.192     brouard   625: #define POWELLF1F3 /* Skip test */
1.186     brouard   626: /* #define POWELLORIGINAL /\* Don't use Directest to decide new direction but original Powell test *\/ */
                    627: /* #define MNBRAKORIGINAL /\* Don't use mnbrak fix *\/ */
1.126     brouard   628: 
                    629: #include <math.h>
                    630: #include <stdio.h>
                    631: #include <stdlib.h>
                    632: #include <string.h>
1.159     brouard   633: 
                    634: #ifdef _WIN32
                    635: #include <io.h>
1.172     brouard   636: #include <windows.h>
                    637: #include <tchar.h>
1.159     brouard   638: #else
1.126     brouard   639: #include <unistd.h>
1.159     brouard   640: #endif
1.126     brouard   641: 
                    642: #include <limits.h>
                    643: #include <sys/types.h>
1.171     brouard   644: 
                    645: #if defined(__GNUC__)
                    646: #include <sys/utsname.h> /* Doesn't work on Windows */
                    647: #endif
                    648: 
1.126     brouard   649: #include <sys/stat.h>
                    650: #include <errno.h>
1.159     brouard   651: /* extern int errno; */
1.126     brouard   652: 
1.157     brouard   653: /* #ifdef LINUX */
                    654: /* #include <time.h> */
                    655: /* #include "timeval.h" */
                    656: /* #else */
                    657: /* #include <sys/time.h> */
                    658: /* #endif */
                    659: 
1.126     brouard   660: #include <time.h>
                    661: 
1.136     brouard   662: #ifdef GSL
                    663: #include <gsl/gsl_errno.h>
                    664: #include <gsl/gsl_multimin.h>
                    665: #endif
                    666: 
1.167     brouard   667: 
1.162     brouard   668: #ifdef NLOPT
                    669: #include <nlopt.h>
                    670: typedef struct {
                    671:   double (* function)(double [] );
                    672: } myfunc_data ;
                    673: #endif
                    674: 
1.126     brouard   675: /* #include <libintl.h> */
                    676: /* #define _(String) gettext (String) */
                    677: 
1.141     brouard   678: #define MAXLINE 1024 /* Was 256. Overflow with 312 with 2 states and 4 covariates. Should be ok */
1.126     brouard   679: 
                    680: #define GNUPLOTPROGRAM "gnuplot"
                    681: /*#define GNUPLOTPROGRAM "..\\gp37mgw\\wgnuplot"*/
                    682: #define FILENAMELENGTH 132
                    683: 
                    684: #define        GLOCK_ERROR_NOPATH              -1      /* empty path */
                    685: #define        GLOCK_ERROR_GETCWD              -2      /* cannot get cwd */
                    686: 
1.144     brouard   687: #define MAXPARM 128 /**< Maximum number of parameters for the optimization */
                    688: #define NPARMAX 64 /**< (nlstate+ndeath-1)*nlstate*ncovmodel */
1.126     brouard   689: 
                    690: #define NINTERVMAX 8
1.144     brouard   691: #define NLSTATEMAX 8 /**< Maximum number of live states (for func) */
                    692: #define NDEATHMAX 8 /**< Maximum number of dead states (for func) */
                    693: #define NCOVMAX 20 /**< Maximum number of covariates, including generated covariates V1*V2 */
1.145     brouard   694: #define codtabm(h,k)  1 & (h-1) >> (k-1) ;
1.126     brouard   695: #define MAXN 20000
1.144     brouard   696: #define YEARM 12. /**< Number of months per year */
1.126     brouard   697: #define AGESUP 130
                    698: #define AGEBASE 40
1.194     brouard   699: #define AGEOVERFLOW 1.e20
1.164     brouard   700: #define AGEGOMP 10 /**< Minimal age for Gompertz adjustment */
1.157     brouard   701: #ifdef _WIN32
                    702: #define DIRSEPARATOR '\\'
                    703: #define CHARSEPARATOR "\\"
                    704: #define ODIRSEPARATOR '/'
                    705: #else
1.126     brouard   706: #define DIRSEPARATOR '/'
                    707: #define CHARSEPARATOR "/"
                    708: #define ODIRSEPARATOR '\\'
                    709: #endif
                    710: 
1.196   ! brouard   711: /* $Id: imach.c,v 1.195 2015/08/18 16:28:39 brouard Exp $ */
1.126     brouard   712: /* $State: Exp $ */
1.196   ! brouard   713: #include "version.h"
        !           714: char version[]=__IMACH_VERSION__;
        !           715: char copyright[]="August 2015,INED-EUROREVES-Institut de longevite-Japan Society for the Promotion of Science (Grant-in-Aid for Scientific Research 25293121), Intel Software 2015";
        !           716: char fullversion[]="$Revision: 1.195 $ $Date: 2015/08/18 16:28:39 $"; 
1.126     brouard   717: char strstart[80];
                    718: char optionfilext[10], optionfilefiname[FILENAMELENGTH];
1.130     brouard   719: int erreur=0, nberr=0, nbwarn=0; /* Error number, number of errors number of warnings  */
1.187     brouard   720: int nagesqr=0, nforce=0; /* nagesqr=1 if model is including age*age, number of forces */
1.145     brouard   721: /* Number of covariates model=V2+V1+ V3*age+V2*V4 */
                    722: int cptcovn=0; /**< cptcovn number of covariates added in the model (excepting constant and age and age*product) */
                    723: int cptcovt=0; /**< cptcovt number of covariates added in the model (excepting constant and age) */
                    724: int cptcovs=0; /**< cptcovs number of simple covariates V2+V1 =2 */
                    725: int cptcovage=0; /**< Number of covariates with age: V3*age only =1 */
                    726: int cptcovprodnoage=0; /**< Number of covariate products without age */   
                    727: int cptcoveff=0; /* Total number of covariates to vary for printing results */
                    728: int cptcov=0; /* Working variable */
1.126     brouard   729: int npar=NPARMAX;
                    730: int nlstate=2; /* Number of live states */
                    731: int ndeath=1; /* Number of dead states */
1.130     brouard   732: int ncovmodel=0, ncovcol=0;     /* Total number of covariables including constant a12*1 +b12*x ncovmodel=2 */
1.126     brouard   733: int popbased=0;
                    734: 
                    735: int *wav; /* Number of waves for this individuual 0 is possible */
1.130     brouard   736: int maxwav=0; /* Maxim number of waves */
                    737: int jmin=0, jmax=0; /* min, max spacing between 2 waves */
                    738: int ijmin=0, ijmax=0; /* Individuals having jmin and jmax */ 
                    739: int gipmx=0, gsw=0; /* Global variables on the number of contributions 
1.126     brouard   740:                   to the likelihood and the sum of weights (done by funcone)*/
1.130     brouard   741: int mle=1, weightopt=0;
1.126     brouard   742: int **mw; /* mw[mi][i] is number of the mi wave for this individual */
                    743: int **dh; /* dh[mi][i] is number of steps between mi,mi+1 for this individual */
                    744: int **bh; /* bh[mi][i] is the bias (+ or -) for this individual if the delay between
                    745:           * wave mi and wave mi+1 is not an exact multiple of stepm. */
1.162     brouard   746: int countcallfunc=0;  /* Count the number of calls to func */
1.130     brouard   747: double jmean=1; /* Mean space between 2 waves */
1.145     brouard   748: double **matprod2(); /* test */
1.126     brouard   749: double **oldm, **newm, **savm; /* Working pointers to matrices */
                    750: double **oldms, **newms, **savms; /* Fixed working pointers to matrices */
1.136     brouard   751: /*FILE *fic ; */ /* Used in readdata only */
                    752: FILE *ficpar, *ficparo,*ficres, *ficresp, *ficrespl, *ficrespij, *ficrest,*ficresf,*ficrespop;
1.126     brouard   753: FILE *ficlog, *ficrespow;
1.130     brouard   754: int globpr=0; /* Global variable for printing or not */
1.126     brouard   755: double fretone; /* Only one call to likelihood */
1.130     brouard   756: long ipmx=0; /* Number of contributions */
1.126     brouard   757: double sw; /* Sum of weights */
                    758: char filerespow[FILENAMELENGTH];
                    759: char fileresilk[FILENAMELENGTH]; /* File of individual contributions to the likelihood */
                    760: FILE *ficresilk;
                    761: FILE *ficgp,*ficresprob,*ficpop, *ficresprobcov, *ficresprobcor;
                    762: FILE *ficresprobmorprev;
                    763: FILE *fichtm, *fichtmcov; /* Html File */
                    764: FILE *ficreseij;
                    765: char filerese[FILENAMELENGTH];
                    766: FILE *ficresstdeij;
                    767: char fileresstde[FILENAMELENGTH];
                    768: FILE *ficrescveij;
                    769: char filerescve[FILENAMELENGTH];
                    770: FILE  *ficresvij;
                    771: char fileresv[FILENAMELENGTH];
                    772: FILE  *ficresvpl;
                    773: char fileresvpl[FILENAMELENGTH];
                    774: char title[MAXLINE];
                    775: char optionfile[FILENAMELENGTH], datafile[FILENAMELENGTH],  filerespl[FILENAMELENGTH];
                    776: char plotcmd[FILENAMELENGTH], pplotcmd[FILENAMELENGTH];
                    777: char tmpout[FILENAMELENGTH],  tmpout2[FILENAMELENGTH]; 
                    778: char command[FILENAMELENGTH];
                    779: int  outcmd=0;
                    780: 
                    781: char fileres[FILENAMELENGTH], filerespij[FILENAMELENGTH], filereso[FILENAMELENGTH], rfileres[FILENAMELENGTH];
                    782: 
                    783: char filelog[FILENAMELENGTH]; /* Log file */
                    784: char filerest[FILENAMELENGTH];
                    785: char fileregp[FILENAMELENGTH];
                    786: char popfile[FILENAMELENGTH];
                    787: 
                    788: char optionfilegnuplot[FILENAMELENGTH], optionfilehtm[FILENAMELENGTH], optionfilehtmcov[FILENAMELENGTH] ;
                    789: 
1.157     brouard   790: /* struct timeval start_time, end_time, curr_time, last_time, forecast_time; */
                    791: /* struct timezone tzp; */
                    792: /* extern int gettimeofday(); */
                    793: struct tm tml, *gmtime(), *localtime();
                    794: 
                    795: extern time_t time();
                    796: 
                    797: struct tm start_time, end_time, curr_time, last_time, forecast_time;
                    798: time_t  rstart_time, rend_time, rcurr_time, rlast_time, rforecast_time; /* raw time */
                    799: struct tm tm;
                    800: 
1.126     brouard   801: char strcurr[80], strfor[80];
                    802: 
                    803: char *endptr;
                    804: long lval;
                    805: double dval;
                    806: 
                    807: #define NR_END 1
                    808: #define FREE_ARG char*
                    809: #define FTOL 1.0e-10
                    810: 
                    811: #define NRANSI 
                    812: #define ITMAX 200 
                    813: 
                    814: #define TOL 2.0e-4 
                    815: 
                    816: #define CGOLD 0.3819660 
                    817: #define ZEPS 1.0e-10 
                    818: #define SHFT(a,b,c,d) (a)=(b);(b)=(c);(c)=(d); 
                    819: 
                    820: #define GOLD 1.618034 
                    821: #define GLIMIT 100.0 
                    822: #define TINY 1.0e-20 
                    823: 
                    824: static double maxarg1,maxarg2;
                    825: #define FMAX(a,b) (maxarg1=(a),maxarg2=(b),(maxarg1)>(maxarg2)? (maxarg1):(maxarg2))
                    826: #define FMIN(a,b) (maxarg1=(a),maxarg2=(b),(maxarg1)<(maxarg2)? (maxarg1):(maxarg2))
                    827:   
                    828: #define SIGN(a,b) ((b)>0.0 ? fabs(a) : -fabs(a))
                    829: #define rint(a) floor(a+0.5)
1.166     brouard   830: /* http://www.thphys.uni-heidelberg.de/~robbers/cmbeasy/doc/html/myutils_8h-source.html */
1.183     brouard   831: #define mytinydouble 1.0e-16
1.166     brouard   832: /* #define DEQUAL(a,b) (fabs((a)-(b))<mytinydouble) */
                    833: /* http://www.thphys.uni-heidelberg.de/~robbers/cmbeasy/doc/html/mynrutils_8h-source.html */
                    834: /* static double dsqrarg; */
                    835: /* #define DSQR(a) (DEQUAL((dsqrarg=(a)),0.0) ? 0.0 : dsqrarg*dsqrarg) */
1.126     brouard   836: static double sqrarg;
                    837: #define SQR(a) ((sqrarg=(a)) == 0.0 ? 0.0 :sqrarg*sqrarg)
                    838: #define SWAP(a,b) {temp=(a);(a)=(b);(b)=temp;} 
                    839: int agegomp= AGEGOMP;
                    840: 
                    841: int imx; 
                    842: int stepm=1;
                    843: /* Stepm, step in month: minimum step interpolation*/
                    844: 
                    845: int estepm;
                    846: /* Estepm, step in month to interpolate survival function in order to approximate Life Expectancy*/
                    847: 
                    848: int m,nb;
                    849: long *num;
1.192     brouard   850: int firstpass=0, lastpass=4,*cod, *Tage,*cens;
                    851: int *ncodemax;  /* ncodemax[j]= Number of modalities of the j th
                    852:                   covariate for which somebody answered excluding 
                    853:                   undefined. Usually 2: 0 and 1. */
                    854: int *ncodemaxwundef;  /* ncodemax[j]= Number of modalities of the j th
                    855:                             covariate for which somebody answered including 
                    856:                             undefined. Usually 3: -1, 0 and 1. */
1.126     brouard   857: double **agev,*moisnais, *annais, *moisdc, *andc,**mint, **anint;
                    858: double **pmmij, ***probs;
                    859: double *ageexmed,*agecens;
                    860: double dateintmean=0;
                    861: 
                    862: double *weight;
                    863: int **s; /* Status */
1.141     brouard   864: double *agedc;
1.145     brouard   865: double  **covar; /**< covar[j,i], value of jth covariate for individual i,
1.141     brouard   866:                  * covar=matrix(0,NCOVMAX,1,n); 
1.187     brouard   867:                  * cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*age; */
1.141     brouard   868: double  idx; 
                    869: int **nbcode, *Tvar; /**< model=V2 => Tvar[1]= 2 */
1.145     brouard   870: int *Ndum; /** Freq of modality (tricode */
1.141     brouard   871: int **codtab; /**< codtab=imatrix(1,100,1,10); */
                    872: int **Tvard, *Tprod, cptcovprod, *Tvaraff;
1.126     brouard   873: double *lsurv, *lpop, *tpop;
                    874: 
1.143     brouard   875: double ftol=FTOL; /**< Tolerance for computing Max Likelihood */
                    876: double ftolhess; /**< Tolerance for computing hessian */
1.126     brouard   877: 
                    878: /**************** split *************************/
                    879: static int split( char *path, char *dirc, char *name, char *ext, char *finame )
                    880: {
                    881:   /* From a file name with (full) path (either Unix or Windows) we extract the directory (dirc)
                    882:      the name of the file (name), its extension only (ext) and its first part of the name (finame)
                    883:   */ 
                    884:   char *ss;                            /* pointer */
1.186     brouard   885:   int  l1=0, l2=0;                             /* length counters */
1.126     brouard   886: 
                    887:   l1 = strlen(path );                  /* length of path */
                    888:   if ( l1 == 0 ) return( GLOCK_ERROR_NOPATH );
                    889:   ss= strrchr( path, DIRSEPARATOR );           /* find last / */
                    890:   if ( ss == NULL ) {                  /* no directory, so determine current directory */
                    891:     strcpy( name, path );              /* we got the fullname name because no directory */
                    892:     /*if(strrchr(path, ODIRSEPARATOR )==NULL)
                    893:       printf("Warning you should use %s as a separator\n",DIRSEPARATOR);*/
                    894:     /* get current working directory */
                    895:     /*    extern  char* getcwd ( char *buf , int len);*/
1.184     brouard   896: #ifdef WIN32
                    897:     if (_getcwd( dirc, FILENAME_MAX ) == NULL ) {
                    898: #else
                    899:        if (getcwd(dirc, FILENAME_MAX) == NULL) {
                    900: #endif
1.126     brouard   901:       return( GLOCK_ERROR_GETCWD );
                    902:     }
                    903:     /* got dirc from getcwd*/
                    904:     printf(" DIRC = %s \n",dirc);
                    905:   } else {                             /* strip direcotry from path */
                    906:     ss++;                              /* after this, the filename */
                    907:     l2 = strlen( ss );                 /* length of filename */
                    908:     if ( l2 == 0 ) return( GLOCK_ERROR_NOPATH );
                    909:     strcpy( name, ss );                /* save file name */
                    910:     strncpy( dirc, path, l1 - l2 );    /* now the directory */
1.186     brouard   911:     dirc[l1-l2] = '\0';                        /* add zero */
1.126     brouard   912:     printf(" DIRC2 = %s \n",dirc);
                    913:   }
                    914:   /* We add a separator at the end of dirc if not exists */
                    915:   l1 = strlen( dirc );                 /* length of directory */
                    916:   if( dirc[l1-1] != DIRSEPARATOR ){
                    917:     dirc[l1] =  DIRSEPARATOR;
                    918:     dirc[l1+1] = 0; 
                    919:     printf(" DIRC3 = %s \n",dirc);
                    920:   }
                    921:   ss = strrchr( name, '.' );           /* find last / */
                    922:   if (ss >0){
                    923:     ss++;
                    924:     strcpy(ext,ss);                    /* save extension */
                    925:     l1= strlen( name);
                    926:     l2= strlen(ss)+1;
                    927:     strncpy( finame, name, l1-l2);
                    928:     finame[l1-l2]= 0;
                    929:   }
                    930: 
                    931:   return( 0 );                         /* we're done */
                    932: }
                    933: 
                    934: 
                    935: /******************************************/
                    936: 
                    937: void replace_back_to_slash(char *s, char*t)
                    938: {
                    939:   int i;
                    940:   int lg=0;
                    941:   i=0;
                    942:   lg=strlen(t);
                    943:   for(i=0; i<= lg; i++) {
                    944:     (s[i] = t[i]);
                    945:     if (t[i]== '\\') s[i]='/';
                    946:   }
                    947: }
                    948: 
1.132     brouard   949: char *trimbb(char *out, char *in)
1.137     brouard   950: { /* Trim multiple blanks in line but keeps first blanks if line starts with blanks */
1.132     brouard   951:   char *s;
                    952:   s=out;
                    953:   while (*in != '\0'){
1.137     brouard   954:     while( *in == ' ' && *(in+1) == ' '){ /* && *(in+1) != '\0'){*/
1.132     brouard   955:       in++;
                    956:     }
                    957:     *out++ = *in++;
                    958:   }
                    959:   *out='\0';
                    960:   return s;
                    961: }
                    962: 
1.187     brouard   963: /* char *substrchaine(char *out, char *in, char *chain) */
                    964: /* { */
                    965: /*   /\* Substract chain 'chain' from 'in', return and output 'out' *\/ */
                    966: /*   char *s, *t; */
                    967: /*   t=in;s=out; */
                    968: /*   while ((*in != *chain) && (*in != '\0')){ */
                    969: /*     *out++ = *in++; */
                    970: /*   } */
                    971: 
                    972: /*   /\* *in matches *chain *\/ */
                    973: /*   while ((*in++ == *chain++) && (*in != '\0')){ */
                    974: /*     printf("*in = %c, *out= %c *chain= %c \n", *in, *out, *chain);  */
                    975: /*   } */
                    976: /*   in--; chain--; */
                    977: /*   while ( (*in != '\0')){ */
                    978: /*     printf("Bef *in = %c, *out= %c *chain= %c \n", *in, *out, *chain);  */
                    979: /*     *out++ = *in++; */
                    980: /*     printf("Aft *in = %c, *out= %c *chain= %c \n", *in, *out, *chain);  */
                    981: /*   } */
                    982: /*   *out='\0'; */
                    983: /*   out=s; */
                    984: /*   return out; */
                    985: /* } */
                    986: char *substrchaine(char *out, char *in, char *chain)
                    987: {
                    988:   /* Substract chain 'chain' from 'in', return and output 'out' */
                    989:   /* in="V1+V1*age+age*age+V2", chain="age*age" */
                    990: 
                    991:   char *strloc;
                    992: 
                    993:   strcpy (out, in); 
                    994:   strloc = strstr(out, chain); /* strloc points to out at age*age+V2 */
                    995:   printf("Bef strloc=%s chain=%s out=%s \n", strloc, chain, out);
                    996:   if(strloc != NULL){ 
                    997:     /* will affect out */ /* strloc+strlenc(chain)=+V2 */ /* Will also work in Unicode */
                    998:     memmove(strloc,strloc+strlen(chain), strlen(strloc+strlen(chain))+1);
                    999:     /* strcpy (strloc, strloc +strlen(chain));*/
                   1000:   }
                   1001:   printf("Aft strloc=%s chain=%s in=%s out=%s \n", strloc, chain, in, out);
                   1002:   return out;
                   1003: }
                   1004: 
                   1005: 
1.145     brouard  1006: char *cutl(char *blocc, char *alocc, char *in, char occ)
                   1007: {
1.187     brouard  1008:   /* cuts string in into blocc and alocc where blocc ends before FIRST occurence of char 'occ' 
1.145     brouard  1009:      and alocc starts after first occurence of char 'occ' : ex cutv(blocc,alocc,"abcdef2ghi2j",'2')
1.187     brouard  1010:      gives blocc="abcdef" and alocc="ghi2j".
1.145     brouard  1011:      If occ is not found blocc is null and alocc is equal to in. Returns blocc
                   1012:   */
1.160     brouard  1013:   char *s, *t;
1.145     brouard  1014:   t=in;s=in;
                   1015:   while ((*in != occ) && (*in != '\0')){
                   1016:     *alocc++ = *in++;
                   1017:   }
                   1018:   if( *in == occ){
                   1019:     *(alocc)='\0';
                   1020:     s=++in;
                   1021:   }
                   1022:  
                   1023:   if (s == t) {/* occ not found */
                   1024:     *(alocc-(in-s))='\0';
                   1025:     in=s;
                   1026:   }
                   1027:   while ( *in != '\0'){
                   1028:     *blocc++ = *in++;
                   1029:   }
                   1030: 
                   1031:   *blocc='\0';
                   1032:   return t;
                   1033: }
1.137     brouard  1034: char *cutv(char *blocc, char *alocc, char *in, char occ)
                   1035: {
1.187     brouard  1036:   /* cuts string in into blocc and alocc where blocc ends before LAST occurence of char 'occ' 
1.137     brouard  1037:      and alocc starts after last occurence of char 'occ' : ex cutv(blocc,alocc,"abcdef2ghi2j",'2')
                   1038:      gives blocc="abcdef2ghi" and alocc="j".
                   1039:      If occ is not found blocc is null and alocc is equal to in. Returns alocc
                   1040:   */
                   1041:   char *s, *t;
                   1042:   t=in;s=in;
                   1043:   while (*in != '\0'){
                   1044:     while( *in == occ){
                   1045:       *blocc++ = *in++;
                   1046:       s=in;
                   1047:     }
                   1048:     *blocc++ = *in++;
                   1049:   }
                   1050:   if (s == t) /* occ not found */
                   1051:     *(blocc-(in-s))='\0';
                   1052:   else
                   1053:     *(blocc-(in-s)-1)='\0';
                   1054:   in=s;
                   1055:   while ( *in != '\0'){
                   1056:     *alocc++ = *in++;
                   1057:   }
                   1058: 
                   1059:   *alocc='\0';
                   1060:   return s;
                   1061: }
                   1062: 
1.126     brouard  1063: int nbocc(char *s, char occ)
                   1064: {
                   1065:   int i,j=0;
                   1066:   int lg=20;
                   1067:   i=0;
                   1068:   lg=strlen(s);
                   1069:   for(i=0; i<= lg; i++) {
                   1070:   if  (s[i] == occ ) j++;
                   1071:   }
                   1072:   return j;
                   1073: }
                   1074: 
1.137     brouard  1075: /* void cutv(char *u,char *v, char*t, char occ) */
                   1076: /* { */
                   1077: /*   /\* cuts string t into u and v where u ends before last occurence of char 'occ'  */
                   1078: /*      and v starts after last occurence of char 'occ' : ex cutv(u,v,"abcdef2ghi2j",'2') */
                   1079: /*      gives u="abcdef2ghi" and v="j" *\/ */
                   1080: /*   int i,lg,j,p=0; */
                   1081: /*   i=0; */
                   1082: /*   lg=strlen(t); */
                   1083: /*   for(j=0; j<=lg-1; j++) { */
                   1084: /*     if((t[j]!= occ) && (t[j+1]== occ)) p=j+1; */
                   1085: /*   } */
1.126     brouard  1086: 
1.137     brouard  1087: /*   for(j=0; j<p; j++) { */
                   1088: /*     (u[j] = t[j]); */
                   1089: /*   } */
                   1090: /*      u[p]='\0'; */
1.126     brouard  1091: 
1.137     brouard  1092: /*    for(j=0; j<= lg; j++) { */
                   1093: /*     if (j>=(p+1))(v[j-p-1] = t[j]); */
                   1094: /*   } */
                   1095: /* } */
1.126     brouard  1096: 
1.160     brouard  1097: #ifdef _WIN32
                   1098: char * strsep(char **pp, const char *delim)
                   1099: {
                   1100:   char *p, *q;
                   1101:          
                   1102:   if ((p = *pp) == NULL)
                   1103:     return 0;
                   1104:   if ((q = strpbrk (p, delim)) != NULL)
                   1105:   {
                   1106:     *pp = q + 1;
                   1107:     *q = '\0';
                   1108:   }
                   1109:   else
                   1110:     *pp = 0;
                   1111:   return p;
                   1112: }
                   1113: #endif
                   1114: 
1.126     brouard  1115: /********************** nrerror ********************/
                   1116: 
                   1117: void nrerror(char error_text[])
                   1118: {
                   1119:   fprintf(stderr,"ERREUR ...\n");
                   1120:   fprintf(stderr,"%s\n",error_text);
                   1121:   exit(EXIT_FAILURE);
                   1122: }
                   1123: /*********************** vector *******************/
                   1124: double *vector(int nl, int nh)
                   1125: {
                   1126:   double *v;
                   1127:   v=(double *) malloc((size_t)((nh-nl+1+NR_END)*sizeof(double)));
                   1128:   if (!v) nrerror("allocation failure in vector");
                   1129:   return v-nl+NR_END;
                   1130: }
                   1131: 
                   1132: /************************ free vector ******************/
                   1133: void free_vector(double*v, int nl, int nh)
                   1134: {
                   1135:   free((FREE_ARG)(v+nl-NR_END));
                   1136: }
                   1137: 
                   1138: /************************ivector *******************************/
                   1139: int *ivector(long nl,long nh)
                   1140: {
                   1141:   int *v;
                   1142:   v=(int *) malloc((size_t)((nh-nl+1+NR_END)*sizeof(int)));
                   1143:   if (!v) nrerror("allocation failure in ivector");
                   1144:   return v-nl+NR_END;
                   1145: }
                   1146: 
                   1147: /******************free ivector **************************/
                   1148: void free_ivector(int *v, long nl, long nh)
                   1149: {
                   1150:   free((FREE_ARG)(v+nl-NR_END));
                   1151: }
                   1152: 
                   1153: /************************lvector *******************************/
                   1154: long *lvector(long nl,long nh)
                   1155: {
                   1156:   long *v;
                   1157:   v=(long *) malloc((size_t)((nh-nl+1+NR_END)*sizeof(long)));
                   1158:   if (!v) nrerror("allocation failure in ivector");
                   1159:   return v-nl+NR_END;
                   1160: }
                   1161: 
                   1162: /******************free lvector **************************/
                   1163: void free_lvector(long *v, long nl, long nh)
                   1164: {
                   1165:   free((FREE_ARG)(v+nl-NR_END));
                   1166: }
                   1167: 
                   1168: /******************* imatrix *******************************/
                   1169: int **imatrix(long nrl, long nrh, long ncl, long nch) 
                   1170:      /* allocate a int matrix with subscript range m[nrl..nrh][ncl..nch] */ 
                   1171: { 
                   1172:   long i, nrow=nrh-nrl+1,ncol=nch-ncl+1; 
                   1173:   int **m; 
                   1174:   
                   1175:   /* allocate pointers to rows */ 
                   1176:   m=(int **) malloc((size_t)((nrow+NR_END)*sizeof(int*))); 
                   1177:   if (!m) nrerror("allocation failure 1 in matrix()"); 
                   1178:   m += NR_END; 
                   1179:   m -= nrl; 
                   1180:   
                   1181:   
                   1182:   /* allocate rows and set pointers to them */ 
                   1183:   m[nrl]=(int *) malloc((size_t)((nrow*ncol+NR_END)*sizeof(int))); 
                   1184:   if (!m[nrl]) nrerror("allocation failure 2 in matrix()"); 
                   1185:   m[nrl] += NR_END; 
                   1186:   m[nrl] -= ncl; 
                   1187:   
                   1188:   for(i=nrl+1;i<=nrh;i++) m[i]=m[i-1]+ncol; 
                   1189:   
                   1190:   /* return pointer to array of pointers to rows */ 
                   1191:   return m; 
                   1192: } 
                   1193: 
                   1194: /****************** free_imatrix *************************/
                   1195: void free_imatrix(m,nrl,nrh,ncl,nch)
                   1196:       int **m;
                   1197:       long nch,ncl,nrh,nrl; 
                   1198:      /* free an int matrix allocated by imatrix() */ 
                   1199: { 
                   1200:   free((FREE_ARG) (m[nrl]+ncl-NR_END)); 
                   1201:   free((FREE_ARG) (m+nrl-NR_END)); 
                   1202: } 
                   1203: 
                   1204: /******************* matrix *******************************/
                   1205: double **matrix(long nrl, long nrh, long ncl, long nch)
                   1206: {
                   1207:   long i, nrow=nrh-nrl+1, ncol=nch-ncl+1;
                   1208:   double **m;
                   1209: 
                   1210:   m=(double **) malloc((size_t)((nrow+NR_END)*sizeof(double*)));
                   1211:   if (!m) nrerror("allocation failure 1 in matrix()");
                   1212:   m += NR_END;
                   1213:   m -= nrl;
                   1214: 
                   1215:   m[nrl]=(double *) malloc((size_t)((nrow*ncol+NR_END)*sizeof(double)));
                   1216:   if (!m[nrl]) nrerror("allocation failure 2 in matrix()");
                   1217:   m[nrl] += NR_END;
                   1218:   m[nrl] -= ncl;
                   1219: 
                   1220:   for (i=nrl+1; i<=nrh; i++) m[i]=m[i-1]+ncol;
                   1221:   return m;
1.145     brouard  1222:   /* print *(*(m+1)+70) or print m[1][70]; print m+1 or print &(m[1]) or &(m[1][0])
                   1223: m[i] = address of ith row of the table. &(m[i]) is its value which is another adress
                   1224: that of m[i][0]. In order to get the value p m[i][0] but it is unitialized.
1.126     brouard  1225:    */
                   1226: }
                   1227: 
                   1228: /*************************free matrix ************************/
                   1229: void free_matrix(double **m, long nrl, long nrh, long ncl, long nch)
                   1230: {
                   1231:   free((FREE_ARG)(m[nrl]+ncl-NR_END));
                   1232:   free((FREE_ARG)(m+nrl-NR_END));
                   1233: }
                   1234: 
                   1235: /******************* ma3x *******************************/
                   1236: double ***ma3x(long nrl, long nrh, long ncl, long nch, long nll, long nlh)
                   1237: {
                   1238:   long i, j, nrow=nrh-nrl+1, ncol=nch-ncl+1, nlay=nlh-nll+1;
                   1239:   double ***m;
                   1240: 
                   1241:   m=(double ***) malloc((size_t)((nrow+NR_END)*sizeof(double*)));
                   1242:   if (!m) nrerror("allocation failure 1 in matrix()");
                   1243:   m += NR_END;
                   1244:   m -= nrl;
                   1245: 
                   1246:   m[nrl]=(double **) malloc((size_t)((nrow*ncol+NR_END)*sizeof(double)));
                   1247:   if (!m[nrl]) nrerror("allocation failure 2 in matrix()");
                   1248:   m[nrl] += NR_END;
                   1249:   m[nrl] -= ncl;
                   1250: 
                   1251:   for (i=nrl+1; i<=nrh; i++) m[i]=m[i-1]+ncol;
                   1252: 
                   1253:   m[nrl][ncl]=(double *) malloc((size_t)((nrow*ncol*nlay+NR_END)*sizeof(double)));
                   1254:   if (!m[nrl][ncl]) nrerror("allocation failure 3 in matrix()");
                   1255:   m[nrl][ncl] += NR_END;
                   1256:   m[nrl][ncl] -= nll;
                   1257:   for (j=ncl+1; j<=nch; j++) 
                   1258:     m[nrl][j]=m[nrl][j-1]+nlay;
                   1259:   
                   1260:   for (i=nrl+1; i<=nrh; i++) {
                   1261:     m[i][ncl]=m[i-1l][ncl]+ncol*nlay;
                   1262:     for (j=ncl+1; j<=nch; j++) 
                   1263:       m[i][j]=m[i][j-1]+nlay;
                   1264:   }
                   1265:   return m; 
                   1266:   /*  gdb: p *(m+1) <=> p m[1] and p (m+1) <=> p (m+1) <=> p &(m[1])
                   1267:            &(m[i][j][k]) <=> *((*(m+i) + j)+k)
                   1268:   */
                   1269: }
                   1270: 
                   1271: /*************************free ma3x ************************/
                   1272: void free_ma3x(double ***m, long nrl, long nrh, long ncl, long nch,long nll, long nlh)
                   1273: {
                   1274:   free((FREE_ARG)(m[nrl][ncl]+ nll-NR_END));
                   1275:   free((FREE_ARG)(m[nrl]+ncl-NR_END));
                   1276:   free((FREE_ARG)(m+nrl-NR_END));
                   1277: }
                   1278: 
                   1279: /*************** function subdirf ***********/
                   1280: char *subdirf(char fileres[])
                   1281: {
                   1282:   /* Caution optionfilefiname is hidden */
                   1283:   strcpy(tmpout,optionfilefiname);
                   1284:   strcat(tmpout,"/"); /* Add to the right */
                   1285:   strcat(tmpout,fileres);
                   1286:   return tmpout;
                   1287: }
                   1288: 
                   1289: /*************** function subdirf2 ***********/
                   1290: char *subdirf2(char fileres[], char *preop)
                   1291: {
                   1292:   
                   1293:   /* Caution optionfilefiname is hidden */
                   1294:   strcpy(tmpout,optionfilefiname);
                   1295:   strcat(tmpout,"/");
                   1296:   strcat(tmpout,preop);
                   1297:   strcat(tmpout,fileres);
                   1298:   return tmpout;
                   1299: }
                   1300: 
                   1301: /*************** function subdirf3 ***********/
                   1302: char *subdirf3(char fileres[], char *preop, char *preop2)
                   1303: {
                   1304:   
                   1305:   /* Caution optionfilefiname is hidden */
                   1306:   strcpy(tmpout,optionfilefiname);
                   1307:   strcat(tmpout,"/");
                   1308:   strcat(tmpout,preop);
                   1309:   strcat(tmpout,preop2);
                   1310:   strcat(tmpout,fileres);
                   1311:   return tmpout;
                   1312: }
                   1313: 
1.162     brouard  1314: char *asc_diff_time(long time_sec, char ascdiff[])
                   1315: {
                   1316:   long sec_left, days, hours, minutes;
                   1317:   days = (time_sec) / (60*60*24);
                   1318:   sec_left = (time_sec) % (60*60*24);
                   1319:   hours = (sec_left) / (60*60) ;
                   1320:   sec_left = (sec_left) %(60*60);
                   1321:   minutes = (sec_left) /60;
                   1322:   sec_left = (sec_left) % (60);
                   1323:   sprintf(ascdiff,"%ld day(s) %ld hour(s) %ld minute(s) %ld second(s)",days, hours, minutes, sec_left);  
                   1324:   return ascdiff;
                   1325: }
                   1326: 
1.126     brouard  1327: /***************** f1dim *************************/
                   1328: extern int ncom; 
                   1329: extern double *pcom,*xicom;
                   1330: extern double (*nrfunc)(double []); 
                   1331:  
                   1332: double f1dim(double x) 
                   1333: { 
                   1334:   int j; 
                   1335:   double f;
                   1336:   double *xt; 
                   1337:  
                   1338:   xt=vector(1,ncom); 
                   1339:   for (j=1;j<=ncom;j++) xt[j]=pcom[j]+x*xicom[j]; 
                   1340:   f=(*nrfunc)(xt); 
                   1341:   free_vector(xt,1,ncom); 
                   1342:   return f; 
                   1343: } 
                   1344: 
                   1345: /*****************brent *************************/
                   1346: double brent(double ax, double bx, double cx, double (*f)(double), double tol,         double *xmin) 
1.187     brouard  1347: {
                   1348:   /* Given a function f, and given a bracketing triplet of abscissas ax, bx, cx (such that bx is
                   1349:    * between ax and cx, and f(bx) is less than both f(ax) and f(cx) ), this routine isolates
                   1350:    * the minimum to a fractional precision of about tol using Brent’s method. The abscissa of
                   1351:    * the minimum is returned as xmin, and the minimum function value is returned as brent , the
                   1352:    * returned function value. 
                   1353:   */
1.126     brouard  1354:   int iter; 
                   1355:   double a,b,d,etemp;
1.159     brouard  1356:   double fu=0,fv,fw,fx;
1.164     brouard  1357:   double ftemp=0.;
1.126     brouard  1358:   double p,q,r,tol1,tol2,u,v,w,x,xm; 
                   1359:   double e=0.0; 
                   1360:  
                   1361:   a=(ax < cx ? ax : cx); 
                   1362:   b=(ax > cx ? ax : cx); 
                   1363:   x=w=v=bx; 
                   1364:   fw=fv=fx=(*f)(x); 
                   1365:   for (iter=1;iter<=ITMAX;iter++) { 
                   1366:     xm=0.5*(a+b); 
                   1367:     tol2=2.0*(tol1=tol*fabs(x)+ZEPS); 
                   1368:     /*         if (2.0*fabs(fp-(*fret)) <= ftol*(fabs(fp)+fabs(*fret)))*/
                   1369:     printf(".");fflush(stdout);
                   1370:     fprintf(ficlog,".");fflush(ficlog);
1.162     brouard  1371: #ifdef DEBUGBRENT
1.126     brouard  1372:     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);
                   1373:     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);
                   1374:     /*         if ((fabs(x-xm) <= (tol2-0.5*(b-a)))||(2.0*fabs(fu-ftemp) <= ftol*1.e-2*(fabs(fu)+fabs(ftemp)))) { */
                   1375: #endif
                   1376:     if (fabs(x-xm) <= (tol2-0.5*(b-a))){ 
                   1377:       *xmin=x; 
                   1378:       return fx; 
                   1379:     } 
                   1380:     ftemp=fu;
                   1381:     if (fabs(e) > tol1) { 
                   1382:       r=(x-w)*(fx-fv); 
                   1383:       q=(x-v)*(fx-fw); 
                   1384:       p=(x-v)*q-(x-w)*r; 
                   1385:       q=2.0*(q-r); 
                   1386:       if (q > 0.0) p = -p; 
                   1387:       q=fabs(q); 
                   1388:       etemp=e; 
                   1389:       e=d; 
                   1390:       if (fabs(p) >= fabs(0.5*q*etemp) || p <= q*(a-x) || p >= q*(b-x)) 
                   1391:        d=CGOLD*(e=(x >= xm ? a-x : b-x)); 
                   1392:       else { 
                   1393:        d=p/q; 
                   1394:        u=x+d; 
                   1395:        if (u-a < tol2 || b-u < tol2) 
                   1396:          d=SIGN(tol1,xm-x); 
                   1397:       } 
                   1398:     } else { 
                   1399:       d=CGOLD*(e=(x >= xm ? a-x : b-x)); 
                   1400:     } 
                   1401:     u=(fabs(d) >= tol1 ? x+d : x+SIGN(tol1,d)); 
                   1402:     fu=(*f)(u); 
                   1403:     if (fu <= fx) { 
                   1404:       if (u >= x) a=x; else b=x; 
                   1405:       SHFT(v,w,x,u) 
1.183     brouard  1406:       SHFT(fv,fw,fx,fu) 
                   1407:     } else { 
                   1408:       if (u < x) a=u; else b=u; 
                   1409:       if (fu <= fw || w == x) { 
                   1410:        v=w; 
                   1411:        w=u; 
                   1412:        fv=fw; 
                   1413:        fw=fu; 
                   1414:       } else if (fu <= fv || v == x || v == w) { 
                   1415:        v=u; 
                   1416:        fv=fu; 
                   1417:       } 
                   1418:     } 
1.126     brouard  1419:   } 
                   1420:   nrerror("Too many iterations in brent"); 
                   1421:   *xmin=x; 
                   1422:   return fx; 
                   1423: } 
                   1424: 
                   1425: /****************** mnbrak ***********************/
                   1426: 
                   1427: void mnbrak(double *ax, double *bx, double *cx, double *fa, double *fb, double *fc, 
                   1428:            double (*func)(double)) 
1.183     brouard  1429: { /* Given a function func , and given distinct initial points ax and bx , this routine searches in
                   1430: the downhill direction (defined by the function as evaluated at the initial points) and returns
                   1431: new points ax , bx , cx that bracket a minimum of the function. Also returned are the function
                   1432: values at the three points, fa, fb , and fc such that fa > fb and fb < fc.
                   1433:    */
1.126     brouard  1434:   double ulim,u,r,q, dum;
                   1435:   double fu; 
1.187     brouard  1436: 
                   1437:   double scale=10.;
                   1438:   int iterscale=0;
                   1439: 
                   1440:   *fa=(*func)(*ax); /*  xta[j]=pcom[j]+(*ax)*xicom[j]; fa=f(xta[j])*/
                   1441:   *fb=(*func)(*bx); /*  xtb[j]=pcom[j]+(*bx)*xicom[j]; fb=f(xtb[j]) */
                   1442: 
                   1443: 
                   1444:   /* while(*fb != *fb){ /\* *ax should be ok, reducing distance to *ax *\/ */
                   1445:   /*   printf("Warning mnbrak *fb = %lf, *bx=%lf *ax=%lf *fa==%lf iter=%d\n",*fb, *bx, *ax, *fa, iterscale++); */
                   1446:   /*   *bx = *ax - (*ax - *bx)/scale; */
                   1447:   /*   *fb=(*func)(*bx);  /\*  xtb[j]=pcom[j]+(*bx)*xicom[j]; fb=f(xtb[j]) *\/ */
                   1448:   /* } */
                   1449: 
1.126     brouard  1450:   if (*fb > *fa) { 
                   1451:     SHFT(dum,*ax,*bx,dum) 
1.183     brouard  1452:     SHFT(dum,*fb,*fa,dum) 
                   1453:   } 
1.126     brouard  1454:   *cx=(*bx)+GOLD*(*bx-*ax); 
                   1455:   *fc=(*func)(*cx); 
1.183     brouard  1456: #ifdef DEBUG
                   1457:   printf("mnbrak0 *fb=%.12e *fc=%.12e\n",*fb,*fc);
                   1458:   fprintf(ficlog,"mnbrak0 *fb=%.12e *fc=%.12e\n",*fb,*fc);
                   1459: #endif
                   1460:   while (*fb > *fc) { /* Declining a,b,c with fa> fb > fc */
1.126     brouard  1461:     r=(*bx-*ax)*(*fb-*fc); 
                   1462:     q=(*bx-*cx)*(*fb-*fa); 
                   1463:     u=(*bx)-((*bx-*cx)*q-(*bx-*ax)*r)/ 
1.183     brouard  1464:       (2.0*SIGN(FMAX(fabs(q-r),TINY),q-r)); /* Minimum abscissa of a parabolic estimated from (a,fa), (b,fb) and (c,fc). */
                   1465:     ulim=(*bx)+GLIMIT*(*cx-*bx); /* Maximum abscissa where function should be evaluated */
                   1466:     if ((*bx-u)*(u-*cx) > 0.0) { /* if u_p is between b and c */
1.126     brouard  1467:       fu=(*func)(u); 
1.163     brouard  1468: #ifdef DEBUG
                   1469:       /* f(x)=A(x-u)**2+f(u) */
                   1470:       double A, fparabu; 
                   1471:       A= (*fb - *fa)/(*bx-*ax)/(*bx+*ax-2*u);
                   1472:       fparabu= *fa - A*(*ax-u)*(*ax-u);
                   1473:       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);
                   1474:       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  1475:       /* And thus,it can be that fu > *fc even if fparabu < *fc */
                   1476:       /* mnbrak (*ax=7.666299858533, *fa=299039.693133272231), (*bx=8.595447774979, *fb=298976.598289369489),
                   1477:         (*cx=10.098840694817, *fc=298946.631474258087),  (*u=9.852501168332, fu=298948.773013752128, fparabu=298945.434711494134) */
                   1478:       /* In that case, there is no bracket in the output! Routine is wrong with many consequences.*/
1.163     brouard  1479: #endif 
1.184     brouard  1480: #ifdef MNBRAKORIGINAL
1.183     brouard  1481: #else
1.191     brouard  1482: /*       if (fu > *fc) { */
                   1483: /* #ifdef DEBUG */
                   1484: /*       printf("mnbrak4  fu > fc \n"); */
                   1485: /*       fprintf(ficlog, "mnbrak4 fu > fc\n"); */
                   1486: /* #endif */
                   1487: /*     /\* 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 *\\/  *\/ */
                   1488: /*     /\* SHFT(*fa,*fc,fu,*fc) /\\* (b, u, c) is a bracket while test fb > fc will be fu > fc  will exit *\\/ *\/ */
                   1489: /*     dum=u; /\* Shifting c and u *\/ */
                   1490: /*     u = *cx; */
                   1491: /*     *cx = dum; */
                   1492: /*     dum = fu; */
                   1493: /*     fu = *fc; */
                   1494: /*     *fc =dum; */
                   1495: /*       } else { /\* end *\/ */
                   1496: /* #ifdef DEBUG */
                   1497: /*       printf("mnbrak3  fu < fc \n"); */
                   1498: /*       fprintf(ficlog, "mnbrak3 fu < fc\n"); */
                   1499: /* #endif */
                   1500: /*     dum=u; /\* Shifting c and u *\/ */
                   1501: /*     u = *cx; */
                   1502: /*     *cx = dum; */
                   1503: /*     dum = fu; */
                   1504: /*     fu = *fc; */
                   1505: /*     *fc =dum; */
                   1506: /*       } */
1.183     brouard  1507: #ifdef DEBUG
1.191     brouard  1508:       printf("mnbrak34  fu < or >= fc \n");
                   1509:       fprintf(ficlog, "mnbrak34 fu < fc\n");
1.183     brouard  1510: #endif
1.191     brouard  1511:       dum=u; /* Shifting c and u */
                   1512:       u = *cx;
                   1513:       *cx = dum;
                   1514:       dum = fu;
                   1515:       fu = *fc;
                   1516:       *fc =dum;
1.183     brouard  1517: #endif
1.162     brouard  1518:     } else if ((*cx-u)*(u-ulim) > 0.0) { /* u is after c but before ulim */
1.183     brouard  1519: #ifdef DEBUG
                   1520:       printf("mnbrak2  u after c but before ulim\n");
                   1521:       fprintf(ficlog, "mnbrak2 u after c but before ulim\n");
                   1522: #endif
1.126     brouard  1523:       fu=(*func)(u); 
                   1524:       if (fu < *fc) { 
1.183     brouard  1525: #ifdef DEBUG
                   1526:       printf("mnbrak2  u after c but before ulim AND fu < fc\n");
                   1527:       fprintf(ficlog, "mnbrak2 u after c but before ulim AND fu <fc \n");
                   1528: #endif
1.126     brouard  1529:        SHFT(*bx,*cx,u,*cx+GOLD*(*cx-*bx)) 
1.183     brouard  1530:        SHFT(*fb,*fc,fu,(*func)(u)) 
                   1531:       } 
1.162     brouard  1532:     } else if ((u-ulim)*(ulim-*cx) >= 0.0) { /* u outside ulim (verifying that ulim is beyond c) */
1.183     brouard  1533: #ifdef DEBUG
                   1534:       printf("mnbrak2  u outside ulim (verifying that ulim is beyond c)\n");
                   1535:       fprintf(ficlog, "mnbrak2 u outside ulim (verifying that ulim is beyond c)\n");
                   1536: #endif
1.126     brouard  1537:       u=ulim; 
                   1538:       fu=(*func)(u); 
1.183     brouard  1539:     } else { /* u could be left to b (if r > q parabola has a maximum) */
                   1540: #ifdef DEBUG
                   1541:       printf("mnbrak2  u could be left to b (if r > q parabola has a maximum)\n");
                   1542:       fprintf(ficlog, "mnbrak2  u could be left to b (if r > q parabola has a maximum)\n");
                   1543: #endif
1.126     brouard  1544:       u=(*cx)+GOLD*(*cx-*bx); 
                   1545:       fu=(*func)(u); 
1.183     brouard  1546:     } /* end tests */
1.126     brouard  1547:     SHFT(*ax,*bx,*cx,u) 
1.183     brouard  1548:     SHFT(*fa,*fb,*fc,fu) 
                   1549: #ifdef DEBUG
                   1550:       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);
                   1551:       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);
                   1552: #endif
                   1553:   } /* 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  1554: } 
                   1555: 
                   1556: /*************** linmin ************************/
1.162     brouard  1557: /* Given an n -dimensional point p[1..n] and an n -dimensional direction xi[1..n] , moves and
                   1558: resets p to where the function func(p) takes on a minimum along the direction xi from p ,
                   1559: and replaces xi by the actual vector displacement that p was moved. Also returns as fret
                   1560: the value of func at the returned location p . This is actually all accomplished by calling the
                   1561: routines mnbrak and brent .*/
1.126     brouard  1562: int ncom; 
                   1563: double *pcom,*xicom;
                   1564: double (*nrfunc)(double []); 
                   1565:  
                   1566: void linmin(double p[], double xi[], int n, double *fret,double (*func)(double [])) 
                   1567: { 
                   1568:   double brent(double ax, double bx, double cx, 
                   1569:               double (*f)(double), double tol, double *xmin); 
                   1570:   double f1dim(double x); 
                   1571:   void mnbrak(double *ax, double *bx, double *cx, double *fa, double *fb, 
                   1572:              double *fc, double (*func)(double)); 
                   1573:   int j; 
                   1574:   double xx,xmin,bx,ax; 
                   1575:   double fx,fb,fa;
1.187     brouard  1576: 
                   1577:   double scale=10., axs, xxs, xxss; /* Scale added for infinity */
1.126     brouard  1578:  
                   1579:   ncom=n; 
                   1580:   pcom=vector(1,n); 
                   1581:   xicom=vector(1,n); 
                   1582:   nrfunc=func; 
                   1583:   for (j=1;j<=n;j++) { 
                   1584:     pcom[j]=p[j]; 
                   1585:     xicom[j]=xi[j]; 
                   1586:   } 
1.187     brouard  1587: 
1.192     brouard  1588:   /* axs=0.0; */
                   1589:   /* xxss=1; /\* 1 and using scale *\/ */
1.187     brouard  1590:   xxs=1;
1.192     brouard  1591:   /* do{ */
1.187     brouard  1592:     ax=0.;
                   1593:     xx= xxs;
                   1594:     mnbrak(&ax,&xx,&bx,&fa,&fx,&fb,f1dim);  /* Outputs: xtx[j]=pcom[j]+(*xx)*xicom[j]; fx=f(xtx[j]) */
                   1595:     /* brackets with inputs ax=0 and xx=1, but points, pcom=p, and directions values, xicom=xi, are sent via f1dim(x) */
                   1596:     /* 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))   */
                   1597:     /* Outputs: fa=f(p(j)) and fx=f(p(j) + xxs * xi(j) ) and f(bx)= f(p(j)+ bx* xi(j)) */
                   1598:     /* Given input ax=axs and xx=xxs, xx might be too far from ax to get a finite f(xx) */
                   1599:     /* Searches on line, outputs (ax, xx, bx) such that fx < min(fa and fb) */
                   1600:     /* 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  1601:   /*   if (fx != fx){ */
                   1602:   /*   xxs=xxs/scale; /\* Trying a smaller xx, closer to initial ax=0 *\/ */
                   1603:   /*   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); */
                   1604:   /*   } */
                   1605:   /* }while(fx != fx); */
1.187     brouard  1606: 
1.191     brouard  1607: #ifdef DEBUGLINMIN
                   1608:   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);
                   1609: #endif
1.187     brouard  1610:   *fret=brent(ax,xx,bx,f1dim,TOL,&xmin); /* Giving a bracketting triplet (ax, xx, bx), find a minimum, xmin, according to f1dim, *fret(xmin),*/
                   1611:   /* fa = f(p[j] + ax * xi[j]), fx = f(p[j] + xx * xi[j]), fb = f(p[j] + bx * xi[j]) */
                   1612:   /* fmin = f(p[j] + xmin * xi[j]) */
                   1613:   /* P+lambda n in that direction (lambdamin), with TOL between abscisses */
                   1614:   /* f1dim(xmin): for (j=1;j<=ncom;j++) xt[j]=pcom[j]+xmin*xicom[j]; */
1.126     brouard  1615: #ifdef DEBUG
                   1616:   printf("retour brent fret=%.12e xmin=%.12e\n",*fret,xmin);
                   1617:   fprintf(ficlog,"retour brent fret=%.12e xmin=%.12e\n",*fret,xmin);
                   1618: #endif
1.191     brouard  1619: #ifdef DEBUGLINMIN
                   1620:   printf("linmin end ");
                   1621: #endif
1.126     brouard  1622:   for (j=1;j<=n;j++) { 
1.188     brouard  1623:     /* printf(" before xi[%d]=%12.8f", j,xi[j]); */
1.187     brouard  1624:     xi[j] *= xmin; /* xi rescaled by xmin: if xmin=-1.237 and xi=(1,0,...,0) xi=(-1.237,0,...,0) */
1.189     brouard  1625:     /* if(xxs <1.0) */
                   1626:     /*   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  1627:     p[j] += xi[j]; /* Parameters values are updated accordingly */
1.126     brouard  1628:   } 
1.189     brouard  1629:   /* printf("\n"); */
1.191     brouard  1630: #ifdef DEBUGLINMIN
                   1631:   printf("Comparing last *frec(xmin=%12.8f)=%12.8f from Brent and frec(0.)=%12.8f \n", xmin, *fret, (*func)(p));
                   1632:   for (j=1;j<=n;j++) { 
                   1633:     printf(" xi[%d]= %12.7f p[%d]= %12.7f",j,xi[j],j,p[j]);
                   1634:     if(j % ncovmodel == 0)
                   1635:       printf("\n");
                   1636:   }
                   1637: #endif
1.126     brouard  1638:   free_vector(xicom,1,n); 
                   1639:   free_vector(pcom,1,n); 
                   1640: } 
                   1641: 
                   1642: 
                   1643: /*************** powell ************************/
1.162     brouard  1644: /*
                   1645: Minimization of a function func of n variables. Input consists of an initial starting point
                   1646: p[1..n] ; an initial matrix xi[1..n][1..n] , whose columns contain the initial set of di-
                   1647: rections (usually the n unit vectors); and ftol , the fractional tolerance in the function value
                   1648: such that failure to decrease by more than this amount on one iteration signals doneness. On
                   1649: output, p is set to the best point found, xi is the then-current direction set, fret is the returned
                   1650: function value at p , and iter is the number of iterations taken. The routine linmin is used.
                   1651:  */
1.126     brouard  1652: void powell(double p[], double **xi, int n, double ftol, int *iter, double *fret, 
                   1653:            double (*func)(double [])) 
                   1654: { 
                   1655:   void linmin(double p[], double xi[], int n, double *fret, 
                   1656:              double (*func)(double [])); 
                   1657:   int i,ibig,j; 
                   1658:   double del,t,*pt,*ptt,*xit;
1.181     brouard  1659:   double directest;
1.126     brouard  1660:   double fp,fptt;
                   1661:   double *xits;
                   1662:   int niterf, itmp;
                   1663: 
                   1664:   pt=vector(1,n); 
                   1665:   ptt=vector(1,n); 
                   1666:   xit=vector(1,n); 
                   1667:   xits=vector(1,n); 
                   1668:   *fret=(*func)(p); 
                   1669:   for (j=1;j<=n;j++) pt[j]=p[j]; 
1.157     brouard  1670:     rcurr_time = time(NULL);  
1.126     brouard  1671:   for (*iter=1;;++(*iter)) { 
1.187     brouard  1672:     fp=(*fret); /* From former iteration or initial value */
1.126     brouard  1673:     ibig=0; 
                   1674:     del=0.0; 
1.157     brouard  1675:     rlast_time=rcurr_time;
                   1676:     /* (void) gettimeofday(&curr_time,&tzp); */
                   1677:     rcurr_time = time(NULL);  
                   1678:     curr_time = *localtime(&rcurr_time);
                   1679:     printf("\nPowell iter=%d -2*LL=%.12f %ld sec. %ld sec.",*iter,*fret, rcurr_time-rlast_time, rcurr_time-rstart_time);fflush(stdout);
                   1680:     fprintf(ficlog,"\nPowell iter=%d -2*LL=%.12f %ld sec. %ld sec.",*iter,*fret,rcurr_time-rlast_time, rcurr_time-rstart_time); fflush(ficlog);
                   1681: /*     fprintf(ficrespow,"%d %.12f %ld",*iter,*fret,curr_time.tm_sec-start_time.tm_sec); */
1.192     brouard  1682:     for (i=1;i<=n;i++) {
1.126     brouard  1683:       printf(" %d %.12f",i, p[i]);
                   1684:       fprintf(ficlog," %d %.12lf",i, p[i]);
                   1685:       fprintf(ficrespow," %.12lf", p[i]);
                   1686:     }
                   1687:     printf("\n");
                   1688:     fprintf(ficlog,"\n");
                   1689:     fprintf(ficrespow,"\n");fflush(ficrespow);
                   1690:     if(*iter <=3){
1.157     brouard  1691:       tml = *localtime(&rcurr_time);
                   1692:       strcpy(strcurr,asctime(&tml));
                   1693:       rforecast_time=rcurr_time; 
1.126     brouard  1694:       itmp = strlen(strcurr);
                   1695:       if(strcurr[itmp-1]=='\n')  /* Windows outputs with a new line */
                   1696:        strcurr[itmp-1]='\0';
1.162     brouard  1697:       printf("\nConsidering the time needed for the last iteration #%d: %ld seconds,\n",*iter,rcurr_time-rlast_time);
1.157     brouard  1698:       fprintf(ficlog,"\nConsidering the time needed for this last iteration #%d: %ld seconds,\n",*iter,rcurr_time-rlast_time);
1.126     brouard  1699:       for(niterf=10;niterf<=30;niterf+=10){
1.157     brouard  1700:        rforecast_time=rcurr_time+(niterf-*iter)*(rcurr_time-rlast_time);
                   1701:        forecast_time = *localtime(&rforecast_time);
                   1702:        strcpy(strfor,asctime(&forecast_time));
1.126     brouard  1703:        itmp = strlen(strfor);
                   1704:        if(strfor[itmp-1]=='\n')
                   1705:        strfor[itmp-1]='\0';
1.157     brouard  1706:        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);
                   1707:        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  1708:       }
                   1709:     }
1.187     brouard  1710:     for (i=1;i<=n;i++) { /* For each direction i */
                   1711:       for (j=1;j<=n;j++) xit[j]=xi[j][i]; /* Directions stored from previous iteration with previous scales */
1.126     brouard  1712:       fptt=(*fret); 
                   1713: #ifdef DEBUG
1.164     brouard  1714:          printf("fret=%lf, %lf, %lf \n", *fret, *fret, *fret);
                   1715:          fprintf(ficlog, "fret=%lf, %lf, %lf \n", *fret, *fret, *fret);
1.126     brouard  1716: #endif
1.187     brouard  1717:          printf("%d",i);fflush(stdout); /* print direction (parameter) i */
1.126     brouard  1718:       fprintf(ficlog,"%d",i);fflush(ficlog);
1.188     brouard  1719:       linmin(p,xit,n,fret,func); /* Point p[n]. xit[n] has been loaded for direction i as input.*/
                   1720:                                    /* Outputs are fret(new point p) p is updated and xit rescaled */
                   1721:       if (fabs(fptt-(*fret)) > del) { /* We are keeping the max gain on each of the n directions */
                   1722:        /* because that direction will be replaced unless the gain del is small */
                   1723:        /* in comparison with the 'probable' gain, mu^2, with the last average direction. */
                   1724:        /* Unless the n directions are conjugate some gain in the determinant may be obtained */
                   1725:        /* with the new direction. */
1.126     brouard  1726:        del=fabs(fptt-(*fret)); 
                   1727:        ibig=i; 
                   1728:       } 
                   1729: #ifdef DEBUG
                   1730:       printf("%d %.12e",i,(*fret));
                   1731:       fprintf(ficlog,"%d %.12e",i,(*fret));
                   1732:       for (j=1;j<=n;j++) {
                   1733:        xits[j]=FMAX(fabs(p[j]-pt[j]),1.e-5);
                   1734:        printf(" x(%d)=%.12e",j,xit[j]);
                   1735:        fprintf(ficlog," x(%d)=%.12e",j,xit[j]);
                   1736:       }
                   1737:       for(j=1;j<=n;j++) {
1.162     brouard  1738:        printf(" p(%d)=%.12e",j,p[j]);
                   1739:        fprintf(ficlog," p(%d)=%.12e",j,p[j]);
1.126     brouard  1740:       }
                   1741:       printf("\n");
                   1742:       fprintf(ficlog,"\n");
                   1743: #endif
1.187     brouard  1744:     } /* end loop on each direction i */
                   1745:     /* Convergence test will use last linmin estimation (fret) and compare former iteration (fp) */ 
1.188     brouard  1746:     /* But p and xit have been updated at the end of linmin, *fret corresponds to new p, xit  */
1.187     brouard  1747:     /* New value of last point Pn is not computed, P(n-1) */
1.182     brouard  1748:     if (2.0*fabs(fp-(*fret)) <= ftol*(fabs(fp)+fabs(*fret))) { /* Did we reach enough precision? */
1.188     brouard  1749:       /* We could compare with a chi^2. chisquare(0.95,ddl=1)=3.84 */
                   1750:       /* By adding age*age in a model, the new -2LL should be lower and the difference follows a */
                   1751:       /* a chisquare statistics with 1 degree. To be significant at the 95% level, it should have */
                   1752:       /* decreased of more than 3.84  */
                   1753:       /* By adding age*age and V1*age the gain (-2LL) should be more than 5.99 (ddl=2) */
                   1754:       /* By using V1+V2+V3, the gain should be  7.82, compared with basic 1+age. */
                   1755:       /* By adding 10 parameters more the gain should be 18.31 */
                   1756: 
                   1757:       /* Starting the program with initial values given by a former maximization will simply change */
                   1758:       /* the scales of the directions and the directions, because the are reset to canonical directions */
                   1759:       /* Thus the first calls to linmin will give new points and better maximizations until fp-(*fret) is */
                   1760:       /* under the tolerance value. If the tolerance is very small 1.e-9, it could last long.  */
1.126     brouard  1761: #ifdef DEBUG
                   1762:       int k[2],l;
                   1763:       k[0]=1;
                   1764:       k[1]=-1;
                   1765:       printf("Max: %.12e",(*func)(p));
                   1766:       fprintf(ficlog,"Max: %.12e",(*func)(p));
                   1767:       for (j=1;j<=n;j++) {
                   1768:        printf(" %.12e",p[j]);
                   1769:        fprintf(ficlog," %.12e",p[j]);
                   1770:       }
                   1771:       printf("\n");
                   1772:       fprintf(ficlog,"\n");
                   1773:       for(l=0;l<=1;l++) {
                   1774:        for (j=1;j<=n;j++) {
                   1775:          ptt[j]=p[j]+(p[j]-pt[j])*k[l];
                   1776:          printf("l=%d j=%d ptt=%.12e, xits=%.12e, p=%.12e, xit=%.12e", l,j,ptt[j],xits[j],p[j],xit[j]);
                   1777:          fprintf(ficlog,"l=%d j=%d ptt=%.12e, xits=%.12e, p=%.12e, xit=%.12e", l,j,ptt[j],xits[j],p[j],xit[j]);
                   1778:        }
                   1779:        printf("func(ptt)=%.12e, deriv=%.12e\n",(*func)(ptt),(ptt[j]-p[j])/((*func)(ptt)-(*func)(p)));
                   1780:        fprintf(ficlog,"func(ptt)=%.12e, deriv=%.12e\n",(*func)(ptt),(ptt[j]-p[j])/((*func)(ptt)-(*func)(p)));
                   1781:       }
                   1782: #endif
                   1783: 
                   1784: 
                   1785:       free_vector(xit,1,n); 
                   1786:       free_vector(xits,1,n); 
                   1787:       free_vector(ptt,1,n); 
                   1788:       free_vector(pt,1,n); 
                   1789:       return; 
1.192     brouard  1790:     } /* enough precision */ 
1.126     brouard  1791:     if (*iter == ITMAX) nrerror("powell exceeding maximum iterations."); 
1.181     brouard  1792:     for (j=1;j<=n;j++) { /* Computes the extrapolated point P_0 + 2 (P_n-P_0) */
1.126     brouard  1793:       ptt[j]=2.0*p[j]-pt[j]; 
                   1794:       xit[j]=p[j]-pt[j]; 
                   1795:       pt[j]=p[j]; 
                   1796:     } 
1.181     brouard  1797:     fptt=(*func)(ptt); /* f_3 */
1.192     brouard  1798: #ifdef POWELLF1F3
                   1799: #else
1.161     brouard  1800:     if (fptt < fp) { /* If extrapolated point is better, decide if we keep that new direction or not */
1.192     brouard  1801: #endif
1.162     brouard  1802:       /* (x1 f1=fp), (x2 f2=*fret), (x3 f3=fptt), (xm fm) */
1.161     brouard  1803:       /* From x1 (P0) distance of x2 is at h and x3 is 2h */
1.162     brouard  1804:       /* Let f"(x2) be the 2nd derivative equal everywhere.  */
                   1805:       /* Then the parabolic through (x1,f1), (x2,f2) and (x3,f3) */
                   1806:       /* will reach at f3 = fm + h^2/2 f"m  ; f" = (f1 -2f2 +f3 ) / h**2 */
1.181     brouard  1807:       /* Conditional for using this new direction is that mu^2 = (f1-2f2+f3)^2 /2 < del */
1.161     brouard  1808:       /* t=2.0*(fp-2.0*(*fret)+fptt)*SQR(fp-(*fret)-del)-del*SQR(fp-fptt); */
1.183     brouard  1809: #ifdef NRCORIGINAL
                   1810:       t=2.0*(fp-2.0*(*fret)+fptt)*SQR(fp-(*fret)-del)- del*SQR(fp-fptt); /* Original Numerical Recipes in C*/
                   1811: #else
                   1812:       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  1813:       t= t- del*SQR(fp-fptt);
1.183     brouard  1814: #endif
1.182     brouard  1815:       directest = fp-2.0*(*fret)+fptt - 2.0 * del; /* If del was big enough we change it for a new direction */
1.161     brouard  1816: #ifdef DEBUG
1.181     brouard  1817:       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);
                   1818:       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  1819:       printf("t3= %.12lf, t4= %.12lf, t3*= %.12lf, t4*= %.12lf\n",SQR(fp-(*fret)-del),SQR(fp-fptt),
                   1820:             (fp-(*fret)-del)*(fp-(*fret)-del),(fp-fptt)*(fp-fptt));
                   1821:       fprintf(ficlog,"t3= %.12lf, t4= %.12lf, t3*= %.12lf, t4*= %.12lf\n",SQR(fp-(*fret)-del),SQR(fp-fptt),
                   1822:             (fp-(*fret)-del)*(fp-(*fret)-del),(fp-fptt)*(fp-fptt));
                   1823:       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);
                   1824:       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);
                   1825: #endif
1.183     brouard  1826: #ifdef POWELLORIGINAL
                   1827:       if (t < 0.0) { /* Then we use it for new direction */
                   1828: #else
1.182     brouard  1829:       if (directest*t < 0.0) { /* Contradiction between both tests */
1.192     brouard  1830:        printf("directest= %.12lf, t= %.12lf, f1= %.12lf,f2= %.12lf,f3= %.12lf, del= %.12lf\n",directest, t, fp,(*fret),fptt,del);
                   1831:         printf("f1-2f2+f3= %.12lf, f1-f2-del= %.12lf, f1-f3= %.12lf\n",fp-2.0*(*fret)+fptt, fp -(*fret) -del, fp-fptt);
                   1832:         fprintf(ficlog,"directest= %.12lf, t= %.12lf, f1= %.12lf,f2= %.12lf,f3= %.12lf, del= %.12lf\n",directest, t, fp,(*fret),fptt, del);
                   1833:         fprintf(ficlog,"f1-2f2+f3= %.12lf, f1-f2-del= %.12lf, f1-f3= %.12lf\n",fp-2.0*(*fret)+fptt, fp -(*fret) -del, fp-fptt);
                   1834:       } 
1.181     brouard  1835:       if (directest < 0.0) { /* Then we use it for new direction */
                   1836: #endif
1.191     brouard  1837: #ifdef DEBUGLINMIN
                   1838:        printf("Before linmin in direction P%d-P0\n",n);
                   1839:        for (j=1;j<=n;j++) { 
                   1840:          printf("Before xit[%d]= %12.7f p[%d]= %12.7f",j,xit[j],j,p[j]);
                   1841:          if(j % ncovmodel == 0)
                   1842:            printf("\n");
                   1843:        }
                   1844: #endif
1.187     brouard  1845:        linmin(p,xit,n,fret,func); /* computes minimum on the extrapolated direction: changes p and rescales xit.*/
1.191     brouard  1846: #ifdef DEBUGLINMIN
                   1847:        for (j=1;j<=n;j++) { 
                   1848:          printf("After xit[%d]= %12.7f p[%d]= %12.7f",j,xit[j],j,p[j]);
                   1849:          if(j % ncovmodel == 0)
                   1850:            printf("\n");
                   1851:        }
                   1852: #endif
1.126     brouard  1853:        for (j=1;j<=n;j++) { 
1.181     brouard  1854:          xi[j][ibig]=xi[j][n]; /* Replace direction with biggest decrease by last direction n */
                   1855:          xi[j][n]=xit[j];      /* and this nth direction by the by the average p_0 p_n */
1.126     brouard  1856:        }
1.181     brouard  1857:        printf("Gaining to use new average direction of P0 P%d instead of biggest increase direction %d :\n",n,ibig);
                   1858:        fprintf(ficlog,"Gaining to use new average direction of P0 P%d instead of biggest increase direction %d :\n",n,ibig);
1.161     brouard  1859: 
1.126     brouard  1860: #ifdef DEBUG
1.164     brouard  1861:        printf("Direction changed  last moved %d in place of ibig=%d, new last is the average:\n",n,ibig);
                   1862:        fprintf(ficlog,"Direction changed  last moved %d in place of ibig=%d, new last is the average:\n",n,ibig);
1.126     brouard  1863:        for(j=1;j<=n;j++){
                   1864:          printf(" %.12e",xit[j]);
                   1865:          fprintf(ficlog," %.12e",xit[j]);
                   1866:        }
                   1867:        printf("\n");
                   1868:        fprintf(ficlog,"\n");
                   1869: #endif
1.192     brouard  1870:       } /* end of t or directest negative */
                   1871: #ifdef POWELLF1F3
                   1872: #else
1.162     brouard  1873:     } /* end if (fptt < fp)  */
1.192     brouard  1874: #endif
                   1875:   } /* loop iteration */ 
1.126     brouard  1876: } 
                   1877: 
                   1878: /**** Prevalence limit (stable or period prevalence)  ****************/
                   1879: 
                   1880: double **prevalim(double **prlim, int nlstate, double x[], double age, double **oldm, double **savm, double ftolpl, int ij)
                   1881: {
                   1882:   /* Computes the prevalence limit in each live state at age x by left multiplying the unit
                   1883:      matrix by transitions matrix until convergence is reached */
1.169     brouard  1884:   
1.126     brouard  1885:   int i, ii,j,k;
                   1886:   double min, max, maxmin, maxmax,sumnew=0.;
1.145     brouard  1887:   /* double **matprod2(); */ /* test */
1.131     brouard  1888:   double **out, cov[NCOVMAX+1], **pmij();
1.126     brouard  1889:   double **newm;
                   1890:   double agefin, delaymax=50 ; /* Max number of years to converge */
1.169     brouard  1891:   
1.126     brouard  1892:   for (ii=1;ii<=nlstate+ndeath;ii++)
                   1893:     for (j=1;j<=nlstate+ndeath;j++){
                   1894:       oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   1895:     }
1.169     brouard  1896:   
                   1897:   cov[1]=1.;
                   1898:   
                   1899:   /* Even if hstepm = 1, at least one multiplication by the unit matrix */
1.126     brouard  1900:   for(agefin=age-stepm/YEARM; agefin>=age-delaymax; agefin=agefin-stepm/YEARM){
                   1901:     newm=savm;
                   1902:     /* Covariates have to be included here again */
1.138     brouard  1903:     cov[2]=agefin;
1.187     brouard  1904:     if(nagesqr==1)
                   1905:       cov[3]= agefin*agefin;;
1.138     brouard  1906:     for (k=1; k<=cptcovn;k++) {
1.187     brouard  1907:       cov[2+nagesqr+k]=nbcode[Tvar[k]][codtab[ij][Tvar[k]]];
1.145     brouard  1908:       /*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  1909:     }
1.186     brouard  1910:     /*wrong? for (k=1; k<=cptcovage;k++) cov[2+Tage[k]]=cov[2+Tage[k]]*cov[2]; */
1.187     brouard  1911:     for (k=1; k<=cptcovage;k++) cov[2+nagesqr+Tage[k]]=nbcode[Tvar[k]][codtab[ij][Tvar[k]]]*cov[2];
1.186     brouard  1912:     for (k=1; k<=cptcovprod;k++) /* Useless */
1.187     brouard  1913:       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  1914:     
                   1915:     /*printf("ij=%d cptcovprod=%d tvar=%d ", ij, cptcovprod, Tvar[1]);*/
                   1916:     /*printf("ij=%d cov[3]=%lf cov[4]=%lf \n",ij, cov[3],cov[4]);*/
                   1917:     /*printf("ij=%d cov[3]=%lf \n",ij, cov[3]);*/
1.145     brouard  1918:     /* savm=pmij(pmmij,cov,ncovmodel,x,nlstate); */
                   1919:     /* out=matprod2(newm, pmij(pmmij,cov,ncovmodel,x,nlstate),1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, oldm); /\* Bug Valgrind *\/ */
1.142     brouard  1920:     out=matprod2(newm, pmij(pmmij,cov,ncovmodel,x,nlstate),1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, oldm); /* Bug Valgrind */
1.138     brouard  1921:     
1.126     brouard  1922:     savm=oldm;
                   1923:     oldm=newm;
                   1924:     maxmax=0.;
                   1925:     for(j=1;j<=nlstate;j++){
                   1926:       min=1.;
                   1927:       max=0.;
                   1928:       for(i=1; i<=nlstate; i++) {
                   1929:        sumnew=0;
                   1930:        for(k=1; k<=ndeath; k++) sumnew+=newm[i][nlstate+k];
                   1931:        prlim[i][j]= newm[i][j]/(1-sumnew);
1.145     brouard  1932:         /*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  1933:        max=FMAX(max,prlim[i][j]);
                   1934:        min=FMIN(min,prlim[i][j]);
                   1935:       }
                   1936:       maxmin=max-min;
                   1937:       maxmax=FMAX(maxmax,maxmin);
1.169     brouard  1938:     } /* j loop */
1.126     brouard  1939:     if(maxmax < ftolpl){
                   1940:       return prlim;
                   1941:     }
1.169     brouard  1942:   } /* age loop */
                   1943:   return prlim; /* should not reach here */
1.126     brouard  1944: }
                   1945: 
                   1946: /*************** transition probabilities ***************/ 
                   1947: 
                   1948: double **pmij(double **ps, double *cov, int ncovmodel, double *x, int nlstate )
                   1949: {
1.138     brouard  1950:   /* According to parameters values stored in x and the covariate's values stored in cov,
                   1951:      computes the probability to be observed in state j being in state i by appying the
                   1952:      model to the ncovmodel covariates (including constant and age).
                   1953:      lnpijopii=ln(pij/pii)= aij+bij*age+cij*v1+dij*v2+... = sum_nc=1^ncovmodel xij(nc)*cov[nc]
                   1954:      and, according on how parameters are entered, the position of the coefficient xij(nc) of the
                   1955:      ncth covariate in the global vector x is given by the formula:
                   1956:      j<i nc+((i-1)*(nlstate+ndeath-1)+j-1)*ncovmodel
                   1957:      j>=i nc + ((i-1)*(nlstate+ndeath-1)+(j-2))*ncovmodel
                   1958:      Computes ln(pij/pii) (lnpijopii), deduces pij/pii by exponentiation,
                   1959:      sums on j different of i to get 1-pii/pii, deduces pii, and then all pij.
                   1960:      Outputs ps[i][j] the probability to be observed in j being in j according to
                   1961:      the values of the covariates cov[nc] and corresponding parameter values x[nc+shiftij]
                   1962:   */
                   1963:   double s1, lnpijopii;
1.126     brouard  1964:   /*double t34;*/
1.164     brouard  1965:   int i,j, nc, ii, jj;
1.126     brouard  1966: 
                   1967:     for(i=1; i<= nlstate; i++){
                   1968:       for(j=1; j<i;j++){
1.138     brouard  1969:        for (nc=1, lnpijopii=0.;nc <=ncovmodel; nc++){
                   1970:          /*lnpijopii += param[i][j][nc]*cov[nc];*/
                   1971:          lnpijopii += x[nc+((i-1)*(nlstate+ndeath-1)+j-1)*ncovmodel]*cov[nc];
                   1972: /*      printf("Int j<i s1=%.17e, lnpijopii=%.17e\n",s1,lnpijopii); */
1.126     brouard  1973:        }
1.138     brouard  1974:        ps[i][j]=lnpijopii; /* In fact ln(pij/pii) */
                   1975: /*     printf("s1=%.17e, lnpijopii=%.17e\n",s1,lnpijopii); */
1.126     brouard  1976:       }
                   1977:       for(j=i+1; j<=nlstate+ndeath;j++){
1.138     brouard  1978:        for (nc=1, lnpijopii=0.;nc <=ncovmodel; nc++){
                   1979:          /*lnpijopii += x[(i-1)*nlstate*ncovmodel+(j-2)*ncovmodel+nc+(i-1)*(ndeath-1)*ncovmodel]*cov[nc];*/
                   1980:          lnpijopii += x[nc + ((i-1)*(nlstate+ndeath-1)+(j-2))*ncovmodel]*cov[nc];
                   1981: /*       printf("Int j>i s1=%.17e, lnpijopii=%.17e %lx %lx\n",s1,lnpijopii,s1,lnpijopii); */
1.126     brouard  1982:        }
1.138     brouard  1983:        ps[i][j]=lnpijopii; /* In fact ln(pij/pii) */
1.126     brouard  1984:       }
                   1985:     }
                   1986:     
                   1987:     for(i=1; i<= nlstate; i++){
                   1988:       s1=0;
1.131     brouard  1989:       for(j=1; j<i; j++){
1.138     brouard  1990:        s1+=exp(ps[i][j]); /* In fact sums pij/pii */
1.131     brouard  1991:        /*printf("debug1 %d %d ps=%lf exp(ps)=%lf s1+=%lf\n",i,j,ps[i][j],exp(ps[i][j]),s1); */
                   1992:       }
                   1993:       for(j=i+1; j<=nlstate+ndeath; j++){
1.138     brouard  1994:        s1+=exp(ps[i][j]); /* In fact sums pij/pii */
1.131     brouard  1995:        /*printf("debug2 %d %d ps=%lf exp(ps)=%lf s1+=%lf\n",i,j,ps[i][j],exp(ps[i][j]),s1); */
                   1996:       }
1.138     brouard  1997:       /* s1= sum_{j<>i} pij/pii=(1-pii)/pii and thus pii is known from s1 */
1.126     brouard  1998:       ps[i][i]=1./(s1+1.);
1.138     brouard  1999:       /* Computing other pijs */
1.126     brouard  2000:       for(j=1; j<i; j++)
                   2001:        ps[i][j]= exp(ps[i][j])*ps[i][i];
                   2002:       for(j=i+1; j<=nlstate+ndeath; j++)
                   2003:        ps[i][j]= exp(ps[i][j])*ps[i][i];
                   2004:       /* ps[i][nlstate+1]=1.-s1- ps[i][i];*/ /* Sum should be 1 */
                   2005:     } /* end i */
                   2006:     
                   2007:     for(ii=nlstate+1; ii<= nlstate+ndeath; ii++){
                   2008:       for(jj=1; jj<= nlstate+ndeath; jj++){
                   2009:        ps[ii][jj]=0;
                   2010:        ps[ii][ii]=1;
                   2011:       }
                   2012:     }
                   2013:     
1.145     brouard  2014:     
                   2015:     /* for(ii=1; ii<= nlstate+ndeath; ii++){ */
                   2016:     /*   for(jj=1; jj<= nlstate+ndeath; jj++){ */
                   2017:     /*         printf(" pmij  ps[%d][%d]=%lf ",ii,jj,ps[ii][jj]); */
                   2018:     /*   } */
                   2019:     /*   printf("\n "); */
                   2020:     /* } */
                   2021:     /* printf("\n ");printf("%lf ",cov[2]);*/
                   2022:     /*
1.126     brouard  2023:       for(i=1; i<= npar; i++) printf("%f ",x[i]);
                   2024:       goto end;*/
                   2025:     return ps;
                   2026: }
                   2027: 
                   2028: /**************** Product of 2 matrices ******************/
                   2029: 
1.145     brouard  2030: double **matprod2(double **out, double **in,int nrl, int nrh, int ncl, int nch, int ncolol, int ncoloh, double **b)
1.126     brouard  2031: {
                   2032:   /* Computes the matrix product of in(1,nrh-nrl+1)(1,nch-ncl+1) times
                   2033:      b(1,nch-ncl+1)(1,ncoloh-ncolol+1) into out(...) */
                   2034:   /* in, b, out are matrice of pointers which should have been initialized 
                   2035:      before: only the contents of out is modified. The function returns
                   2036:      a pointer to pointers identical to out */
1.145     brouard  2037:   int i, j, k;
1.126     brouard  2038:   for(i=nrl; i<= nrh; i++)
1.145     brouard  2039:     for(k=ncolol; k<=ncoloh; k++){
                   2040:       out[i][k]=0.;
                   2041:       for(j=ncl; j<=nch; j++)
                   2042:        out[i][k] +=in[i][j]*b[j][k];
                   2043:     }
1.126     brouard  2044:   return out;
                   2045: }
                   2046: 
                   2047: 
                   2048: /************* Higher Matrix Product ***************/
                   2049: 
                   2050: double ***hpxij(double ***po, int nhstepm, double age, int hstepm, double *x, int nlstate, int stepm, double **oldm, double **savm, int ij )
                   2051: {
                   2052:   /* Computes the transition matrix starting at age 'age' over 
                   2053:      'nhstepm*hstepm*stepm' months (i.e. until
                   2054:      age (in years)  age+nhstepm*hstepm*stepm/12) by multiplying 
                   2055:      nhstepm*hstepm matrices. 
                   2056:      Output is stored in matrix po[i][j][h] for h every 'hstepm' step 
                   2057:      (typically every 2 years instead of every month which is too big 
                   2058:      for the memory).
                   2059:      Model is determined by parameters x and covariates have to be 
                   2060:      included manually here. 
                   2061: 
                   2062:      */
                   2063: 
                   2064:   int i, j, d, h, k;
1.131     brouard  2065:   double **out, cov[NCOVMAX+1];
1.126     brouard  2066:   double **newm;
1.187     brouard  2067:   double agexact;
1.126     brouard  2068: 
                   2069:   /* Hstepm could be zero and should return the unit matrix */
                   2070:   for (i=1;i<=nlstate+ndeath;i++)
                   2071:     for (j=1;j<=nlstate+ndeath;j++){
                   2072:       oldm[i][j]=(i==j ? 1.0 : 0.0);
                   2073:       po[i][j][0]=(i==j ? 1.0 : 0.0);
                   2074:     }
                   2075:   /* Even if hstepm = 1, at least one multiplication by the unit matrix */
                   2076:   for(h=1; h <=nhstepm; h++){
                   2077:     for(d=1; d <=hstepm; d++){
                   2078:       newm=savm;
                   2079:       /* Covariates have to be included here again */
                   2080:       cov[1]=1.;
1.187     brouard  2081:       agexact=age+((h-1)*hstepm + (d-1))*stepm/YEARM;
                   2082:       cov[2]=agexact;
                   2083:       if(nagesqr==1)
                   2084:        cov[3]= agexact*agexact;
1.131     brouard  2085:       for (k=1; k<=cptcovn;k++) 
1.187     brouard  2086:        cov[2+nagesqr+k]=nbcode[Tvar[k]][codtab[ij][Tvar[k]]];
1.186     brouard  2087:       for (k=1; k<=cptcovage;k++) /* Should start at cptcovn+1 */
                   2088:        /* cov[2+Tage[k]]=cov[2+Tage[k]]*cov[2]; */
1.187     brouard  2089:        cov[2+nagesqr+Tage[k]]=nbcode[Tvar[Tage[k]]][codtab[ij][Tvar[Tage[k]]]]*cov[2];
1.145     brouard  2090:       for (k=1; k<=cptcovprod;k++) /* Useless because included in cptcovn */
1.187     brouard  2091:        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  2092: 
                   2093: 
                   2094:       /*printf("hxi cptcov=%d cptcode=%d\n",cptcov,cptcode);*/
                   2095:       /*printf("h=%d d=%d age=%f cov=%f\n",h,d,age,cov[2]);*/
                   2096:       out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, 
                   2097:                   pmij(pmmij,cov,ncovmodel,x,nlstate));
                   2098:       savm=oldm;
                   2099:       oldm=newm;
                   2100:     }
                   2101:     for(i=1; i<=nlstate+ndeath; i++)
                   2102:       for(j=1;j<=nlstate+ndeath;j++) {
                   2103:        po[i][j][h]=newm[i][j];
1.128     brouard  2104:        /*if(h==nhstepm) printf("po[%d][%d][%d]=%f ",i,j,h,po[i][j][h]);*/
1.126     brouard  2105:       }
1.128     brouard  2106:     /*printf("h=%d ",h);*/
1.126     brouard  2107:   } /* end h */
1.128     brouard  2108: /*     printf("\n H=%d \n",h); */
1.126     brouard  2109:   return po;
                   2110: }
                   2111: 
1.162     brouard  2112: #ifdef NLOPT
                   2113:   double  myfunc(unsigned n, const double *p1, double *grad, void *pd){
                   2114:   double fret;
                   2115:   double *xt;
                   2116:   int j;
                   2117:   myfunc_data *d2 = (myfunc_data *) pd;
                   2118: /* xt = (p1-1); */
                   2119:   xt=vector(1,n); 
                   2120:   for (j=1;j<=n;j++)   xt[j]=p1[j-1]; /* xt[1]=p1[0] */
                   2121: 
                   2122:   fret=(d2->function)(xt); /*  p xt[1]@8 is fine */
                   2123:   /* fret=(*func)(xt); /\*  p xt[1]@8 is fine *\/ */
                   2124:   printf("Function = %.12lf ",fret);
                   2125:   for (j=1;j<=n;j++) printf(" %d %.8lf", j, xt[j]); 
                   2126:   printf("\n");
                   2127:  free_vector(xt,1,n);
                   2128:   return fret;
                   2129: }
                   2130: #endif
1.126     brouard  2131: 
                   2132: /*************** log-likelihood *************/
                   2133: double func( double *x)
                   2134: {
                   2135:   int i, ii, j, k, mi, d, kk;
1.131     brouard  2136:   double l, ll[NLSTATEMAX+1], cov[NCOVMAX+1];
1.126     brouard  2137:   double **out;
                   2138:   double sw; /* Sum of weights */
                   2139:   double lli; /* Individual log likelihood */
                   2140:   int s1, s2;
                   2141:   double bbh, survp;
                   2142:   long ipmx;
1.187     brouard  2143:   double agexact;
1.126     brouard  2144:   /*extern weight */
                   2145:   /* We are differentiating ll according to initial status */
                   2146:   /*  for (i=1;i<=npar;i++) printf("%f ", x[i]);*/
                   2147:   /*for(i=1;i<imx;i++) 
                   2148:     printf(" %d\n",s[4][i]);
                   2149:   */
1.162     brouard  2150: 
                   2151:   ++countcallfunc;
                   2152: 
1.126     brouard  2153:   cov[1]=1.;
                   2154: 
                   2155:   for(k=1; k<=nlstate; k++) ll[k]=0.;
                   2156: 
                   2157:   if(mle==1){
                   2158:     for (i=1,ipmx=0, sw=0.; i<=imx; i++){
1.138     brouard  2159:       /* Computes the values of the ncovmodel covariates of the model
                   2160:         depending if the covariates are fixed or variying (age dependent) and stores them in cov[]
                   2161:         Then computes with function pmij which return a matrix p[i][j] giving the elementary probability
                   2162:         to be observed in j being in i according to the model.
                   2163:        */
1.145     brouard  2164:       for (k=1; k<=cptcovn;k++){ /* Simple and product covariates without age* products */
1.187     brouard  2165:          cov[2+nagesqr+k]=covar[Tvar[k]][i];
1.145     brouard  2166:       }
1.137     brouard  2167:       /* In model V2+V1*V4+age*V3+V3*V2 Tvar[1] is V2, Tvar[2=V1*V4] 
1.138     brouard  2168:         is 6, Tvar[3=age*V3] should not be computed because of age Tvar[4=V3*V2] 
1.137     brouard  2169:         has been calculated etc */
1.126     brouard  2170:       for(mi=1; mi<= wav[i]-1; mi++){
                   2171:        for (ii=1;ii<=nlstate+ndeath;ii++)
                   2172:          for (j=1;j<=nlstate+ndeath;j++){
                   2173:            oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   2174:            savm[ii][j]=(ii==j ? 1.0 : 0.0);
                   2175:          }
                   2176:        for(d=0; d<dh[mi][i]; d++){
                   2177:          newm=savm;
1.187     brouard  2178:          agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;
                   2179:          cov[2]=agexact;
                   2180:          if(nagesqr==1)
                   2181:            cov[3]= agexact*agexact;
1.126     brouard  2182:          for (kk=1; kk<=cptcovage;kk++) {
1.187     brouard  2183:            cov[Tage[kk]+2+nagesqr]=covar[Tvar[Tage[kk]]][i]*agexact; /* Tage[kk] gives the data-covariate associated with age */
1.126     brouard  2184:          }
                   2185:          out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
                   2186:                       1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
                   2187:          savm=oldm;
                   2188:          oldm=newm;
                   2189:        } /* end mult */
                   2190:       
                   2191:        /*lli=log(out[s[mw[mi][i]][i]][s[mw[mi+1][i]][i]]);*/ /* Original formula */
                   2192:        /* But now since version 0.9 we anticipate for bias at large stepm.
                   2193:         * If stepm is larger than one month (smallest stepm) and if the exact delay 
                   2194:         * (in months) between two waves is not a multiple of stepm, we rounded to 
                   2195:         * the nearest (and in case of equal distance, to the lowest) interval but now
                   2196:         * we keep into memory the bias bh[mi][i] and also the previous matrix product
                   2197:         * (i.e to dh[mi][i]-1) saved in 'savm'. Then we inter(extra)polate the
                   2198:         * probability in order to take into account the bias as a fraction of the way
                   2199:         * from savm to out if bh is negative or even beyond if bh is positive. bh varies
                   2200:         * -stepm/2 to stepm/2 .
                   2201:         * For stepm=1 the results are the same as for previous versions of Imach.
                   2202:         * For stepm > 1 the results are less biased than in previous versions. 
                   2203:         */
                   2204:        s1=s[mw[mi][i]][i];
                   2205:        s2=s[mw[mi+1][i]][i];
                   2206:        bbh=(double)bh[mi][i]/(double)stepm; 
                   2207:        /* bias bh is positive if real duration
                   2208:         * is higher than the multiple of stepm and negative otherwise.
                   2209:         */
                   2210:        /* lli= (savm[s1][s2]>1.e-8 ?(1.+bbh)*log(out[s1][s2])- bbh*log(savm[s1][s2]):log((1.+bbh)*out[s1][s2]));*/
                   2211:        if( s2 > nlstate){ 
                   2212:          /* i.e. if s2 is a death state and if the date of death is known 
                   2213:             then the contribution to the likelihood is the probability to 
                   2214:             die between last step unit time and current  step unit time, 
                   2215:             which is also equal to probability to die before dh 
                   2216:             minus probability to die before dh-stepm . 
                   2217:             In version up to 0.92 likelihood was computed
                   2218:        as if date of death was unknown. Death was treated as any other
                   2219:        health state: the date of the interview describes the actual state
                   2220:        and not the date of a change in health state. The former idea was
                   2221:        to consider that at each interview the state was recorded
                   2222:        (healthy, disable or death) and IMaCh was corrected; but when we
                   2223:        introduced the exact date of death then we should have modified
                   2224:        the contribution of an exact death to the likelihood. This new
                   2225:        contribution is smaller and very dependent of the step unit
                   2226:        stepm. It is no more the probability to die between last interview
                   2227:        and month of death but the probability to survive from last
                   2228:        interview up to one month before death multiplied by the
                   2229:        probability to die within a month. Thanks to Chris
                   2230:        Jackson for correcting this bug.  Former versions increased
                   2231:        mortality artificially. The bad side is that we add another loop
                   2232:        which slows down the processing. The difference can be up to 10%
                   2233:        lower mortality.
                   2234:          */
1.183     brouard  2235:        /* If, at the beginning of the maximization mostly, the
                   2236:           cumulative probability or probability to be dead is
                   2237:           constant (ie = 1) over time d, the difference is equal to
                   2238:           0.  out[s1][3] = savm[s1][3]: probability, being at state
                   2239:           s1 at precedent wave, to be dead a month before current
                   2240:           wave is equal to probability, being at state s1 at
                   2241:           precedent wave, to be dead at mont of the current
                   2242:           wave. Then the observed probability (that this person died)
                   2243:           is null according to current estimated parameter. In fact,
                   2244:           it should be very low but not zero otherwise the log go to
                   2245:           infinity.
                   2246:        */
                   2247: /* #ifdef INFINITYORIGINAL */
                   2248: /*         lli=log(out[s1][s2] - savm[s1][s2]); */
                   2249: /* #else */
                   2250: /*       if ((out[s1][s2] - savm[s1][s2]) < mytinydouble)  */
                   2251: /*         lli=log(mytinydouble); */
                   2252: /*       else */
                   2253: /*         lli=log(out[s1][s2] - savm[s1][s2]); */
                   2254: /* #endif */
                   2255:            lli=log(out[s1][s2] - savm[s1][s2]);
1.126     brouard  2256: 
                   2257:        } else if  (s2==-2) {
                   2258:          for (j=1,survp=0. ; j<=nlstate; j++) 
                   2259:            survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j];
                   2260:          /*survp += out[s1][j]; */
                   2261:          lli= log(survp);
                   2262:        }
                   2263:        
                   2264:        else if  (s2==-4) { 
                   2265:          for (j=3,survp=0. ; j<=nlstate; j++)  
                   2266:            survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j];
                   2267:          lli= log(survp); 
                   2268:        } 
                   2269: 
                   2270:        else if  (s2==-5) { 
                   2271:          for (j=1,survp=0. ; j<=2; j++)  
                   2272:            survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j];
                   2273:          lli= log(survp); 
                   2274:        } 
                   2275:        
                   2276:        else{
                   2277:          lli= log((1.+bbh)*out[s1][s2]- bbh*savm[s1][s2]); /* linear interpolation */
                   2278:          /*  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 */
                   2279:        } 
                   2280:        /*lli=(1.+bbh)*log(out[s1][s2])- bbh*log(savm[s1][s2]);*/
                   2281:        /*if(lli ==000.0)*/
                   2282:        /*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); */
                   2283:        ipmx +=1;
                   2284:        sw += weight[i];
                   2285:        ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
1.183     brouard  2286:        /* if (lli < log(mytinydouble)){ */
                   2287:        /*   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); */
                   2288:        /*   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]); */
                   2289:        /* } */
1.126     brouard  2290:       } /* end of wave */
                   2291:     } /* end of individual */
                   2292:   }  else if(mle==2){
                   2293:     for (i=1,ipmx=0, sw=0.; i<=imx; i++){
1.187     brouard  2294:       for (k=1; k<=cptcovn;k++) cov[2+nagesqr+k]=covar[Tvar[k]][i];
1.126     brouard  2295:       for(mi=1; mi<= wav[i]-1; mi++){
                   2296:        for (ii=1;ii<=nlstate+ndeath;ii++)
                   2297:          for (j=1;j<=nlstate+ndeath;j++){
                   2298:            oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   2299:            savm[ii][j]=(ii==j ? 1.0 : 0.0);
                   2300:          }
                   2301:        for(d=0; d<=dh[mi][i]; d++){
                   2302:          newm=savm;
1.187     brouard  2303:          agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;
                   2304:          cov[2]=agexact;
                   2305:          if(nagesqr==1)
                   2306:            cov[3]= agexact*agexact;
1.126     brouard  2307:          for (kk=1; kk<=cptcovage;kk++) {
1.187     brouard  2308:            cov[Tage[kk]+2+nagesqr]=covar[Tvar[Tage[kk]]][i]*agexact;
1.126     brouard  2309:          }
                   2310:          out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
                   2311:                       1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
                   2312:          savm=oldm;
                   2313:          oldm=newm;
                   2314:        } /* end mult */
                   2315:       
                   2316:        s1=s[mw[mi][i]][i];
                   2317:        s2=s[mw[mi+1][i]][i];
                   2318:        bbh=(double)bh[mi][i]/(double)stepm; 
                   2319:        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 */
                   2320:        ipmx +=1;
                   2321:        sw += weight[i];
                   2322:        ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
                   2323:       } /* end of wave */
                   2324:     } /* end of individual */
                   2325:   }  else if(mle==3){  /* exponential inter-extrapolation */
                   2326:     for (i=1,ipmx=0, sw=0.; i<=imx; i++){
1.187     brouard  2327:       for (k=1; k<=cptcovn;k++) cov[2+nagesqr+k]=covar[Tvar[k]][i];
1.126     brouard  2328:       for(mi=1; mi<= wav[i]-1; mi++){
                   2329:        for (ii=1;ii<=nlstate+ndeath;ii++)
                   2330:          for (j=1;j<=nlstate+ndeath;j++){
                   2331:            oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   2332:            savm[ii][j]=(ii==j ? 1.0 : 0.0);
                   2333:          }
                   2334:        for(d=0; d<dh[mi][i]; d++){
                   2335:          newm=savm;
1.187     brouard  2336:          agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;
                   2337:          cov[2]=agexact;
                   2338:          if(nagesqr==1)
                   2339:            cov[3]= agexact*agexact;
1.126     brouard  2340:          for (kk=1; kk<=cptcovage;kk++) {
1.187     brouard  2341:            cov[Tage[kk]+2+nagesqr]=covar[Tvar[Tage[kk]]][i]*agexact;
1.126     brouard  2342:          }
                   2343:          out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
                   2344:                       1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
                   2345:          savm=oldm;
                   2346:          oldm=newm;
                   2347:        } /* end mult */
                   2348:       
                   2349:        s1=s[mw[mi][i]][i];
                   2350:        s2=s[mw[mi+1][i]][i];
                   2351:        bbh=(double)bh[mi][i]/(double)stepm; 
                   2352:        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 */
                   2353:        ipmx +=1;
                   2354:        sw += weight[i];
                   2355:        ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
                   2356:       } /* end of wave */
                   2357:     } /* end of individual */
                   2358:   }else if (mle==4){  /* ml=4 no inter-extrapolation */
                   2359:     for (i=1,ipmx=0, sw=0.; i<=imx; i++){
1.187     brouard  2360:       for (k=1; k<=cptcovn;k++) cov[2+nagesqr+k]=covar[Tvar[k]][i];
1.126     brouard  2361:       for(mi=1; mi<= wav[i]-1; mi++){
                   2362:        for (ii=1;ii<=nlstate+ndeath;ii++)
                   2363:          for (j=1;j<=nlstate+ndeath;j++){
                   2364:            oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   2365:            savm[ii][j]=(ii==j ? 1.0 : 0.0);
                   2366:          }
                   2367:        for(d=0; d<dh[mi][i]; d++){
                   2368:          newm=savm;
1.187     brouard  2369:          agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;
                   2370:          cov[2]=agexact;
                   2371:          if(nagesqr==1)
                   2372:            cov[3]= agexact*agexact;
1.126     brouard  2373:          for (kk=1; kk<=cptcovage;kk++) {
1.187     brouard  2374:            cov[Tage[kk]+2+nagesqr]=covar[Tvar[Tage[kk]]][i]*agexact;
1.126     brouard  2375:          }
                   2376:        
                   2377:          out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
                   2378:                       1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
                   2379:          savm=oldm;
                   2380:          oldm=newm;
                   2381:        } /* end mult */
                   2382:       
                   2383:        s1=s[mw[mi][i]][i];
                   2384:        s2=s[mw[mi+1][i]][i];
                   2385:        if( s2 > nlstate){ 
                   2386:          lli=log(out[s1][s2] - savm[s1][s2]);
                   2387:        }else{
                   2388:          lli=log(out[s[mw[mi][i]][i]][s[mw[mi+1][i]][i]]); /* Original formula */
                   2389:        }
                   2390:        ipmx +=1;
                   2391:        sw += weight[i];
                   2392:        ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
                   2393: /*     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]); */
                   2394:       } /* end of wave */
                   2395:     } /* end of individual */
                   2396:   }else{  /* ml=5 no inter-extrapolation no jackson =0.8a */
                   2397:     for (i=1,ipmx=0, sw=0.; i<=imx; i++){
1.187     brouard  2398:       for (k=1; k<=cptcovn;k++) cov[2+nagesqr+k]=covar[Tvar[k]][i];
1.126     brouard  2399:       for(mi=1; mi<= wav[i]-1; mi++){
                   2400:        for (ii=1;ii<=nlstate+ndeath;ii++)
                   2401:          for (j=1;j<=nlstate+ndeath;j++){
                   2402:            oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   2403:            savm[ii][j]=(ii==j ? 1.0 : 0.0);
                   2404:          }
                   2405:        for(d=0; d<dh[mi][i]; d++){
                   2406:          newm=savm;
1.187     brouard  2407:          agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;
                   2408:          cov[2]=agexact;
                   2409:          if(nagesqr==1)
                   2410:            cov[3]= agexact*agexact;
1.126     brouard  2411:          for (kk=1; kk<=cptcovage;kk++) {
1.187     brouard  2412:            cov[Tage[kk]+2+nagesqr]=covar[Tvar[Tage[kk]]][i]*agexact;
1.126     brouard  2413:          }
                   2414:        
                   2415:          out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
                   2416:                       1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
                   2417:          savm=oldm;
                   2418:          oldm=newm;
                   2419:        } /* end mult */
                   2420:       
                   2421:        s1=s[mw[mi][i]][i];
                   2422:        s2=s[mw[mi+1][i]][i];
                   2423:        lli=log(out[s[mw[mi][i]][i]][s[mw[mi+1][i]][i]]); /* Original formula */
                   2424:        ipmx +=1;
                   2425:        sw += weight[i];
                   2426:        ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
                   2427:        /*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]);*/
                   2428:       } /* end of wave */
                   2429:     } /* end of individual */
                   2430:   } /* End of if */
                   2431:   for(k=1,l=0.; k<=nlstate; k++) l += ll[k];
                   2432:   /* printf("l1=%f l2=%f ",ll[1],ll[2]); */
                   2433:   l= l*ipmx/sw; /* To get the same order of magnitude as if weight=1 for every body */
                   2434:   return -l;
                   2435: }
                   2436: 
                   2437: /*************** log-likelihood *************/
                   2438: double funcone( double *x)
                   2439: {
                   2440:   /* Same as likeli but slower because of a lot of printf and if */
                   2441:   int i, ii, j, k, mi, d, kk;
1.131     brouard  2442:   double l, ll[NLSTATEMAX+1], cov[NCOVMAX+1];
1.126     brouard  2443:   double **out;
                   2444:   double lli; /* Individual log likelihood */
                   2445:   double llt;
                   2446:   int s1, s2;
                   2447:   double bbh, survp;
1.187     brouard  2448:   double agexact;
1.126     brouard  2449:   /*extern weight */
                   2450:   /* We are differentiating ll according to initial status */
                   2451:   /*  for (i=1;i<=npar;i++) printf("%f ", x[i]);*/
                   2452:   /*for(i=1;i<imx;i++) 
                   2453:     printf(" %d\n",s[4][i]);
                   2454:   */
                   2455:   cov[1]=1.;
                   2456: 
                   2457:   for(k=1; k<=nlstate; k++) ll[k]=0.;
                   2458: 
                   2459:   for (i=1,ipmx=0, sw=0.; i<=imx; i++){
1.187     brouard  2460:     for (k=1; k<=cptcovn;k++) cov[2+nagesqr+k]=covar[Tvar[k]][i];
1.126     brouard  2461:     for(mi=1; mi<= wav[i]-1; mi++){
                   2462:       for (ii=1;ii<=nlstate+ndeath;ii++)
                   2463:        for (j=1;j<=nlstate+ndeath;j++){
                   2464:          oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   2465:          savm[ii][j]=(ii==j ? 1.0 : 0.0);
                   2466:        }
                   2467:       for(d=0; d<dh[mi][i]; d++){
                   2468:        newm=savm;
1.187     brouard  2469:        agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;
                   2470:        cov[2]=agexact;
                   2471:        if(nagesqr==1)
                   2472:          cov[3]= agexact*agexact;
1.126     brouard  2473:        for (kk=1; kk<=cptcovage;kk++) {
1.187     brouard  2474:          cov[Tage[kk]+2+nagesqr]=covar[Tvar[Tage[kk]]][i]*agexact;
1.126     brouard  2475:        }
1.187     brouard  2476: 
1.145     brouard  2477:        /* savm=pmij(pmmij,cov,ncovmodel,x,nlstate); */
1.126     brouard  2478:        out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
                   2479:                     1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
1.145     brouard  2480:        /* out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath, */
                   2481:        /*           1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate)); */
1.126     brouard  2482:        savm=oldm;
                   2483:        oldm=newm;
                   2484:       } /* end mult */
                   2485:       
                   2486:       s1=s[mw[mi][i]][i];
                   2487:       s2=s[mw[mi+1][i]][i];
                   2488:       bbh=(double)bh[mi][i]/(double)stepm; 
                   2489:       /* bias is positive if real duration
                   2490:        * is higher than the multiple of stepm and negative otherwise.
                   2491:        */
                   2492:       if( s2 > nlstate && (mle <5) ){  /* Jackson */
                   2493:        lli=log(out[s1][s2] - savm[s1][s2]);
                   2494:       } else if  (s2==-2) {
                   2495:        for (j=1,survp=0. ; j<=nlstate; j++) 
                   2496:          survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j];
                   2497:        lli= log(survp);
                   2498:       }else if (mle==1){
                   2499:        lli= log((1.+bbh)*out[s1][s2]- bbh*savm[s1][s2]); /* linear interpolation */
                   2500:       } else if(mle==2){
                   2501:        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 */
                   2502:       } else if(mle==3){  /* exponential inter-extrapolation */
                   2503:        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 */
                   2504:       } else if (mle==4){  /* mle=4 no inter-extrapolation */
                   2505:        lli=log(out[s1][s2]); /* Original formula */
1.136     brouard  2506:       } else{  /* mle=0 back to 1 */
                   2507:        lli= log((1.+bbh)*out[s1][s2]- bbh*savm[s1][s2]); /* linear interpolation */
                   2508:        /*lli=log(out[s1][s2]); */ /* Original formula */
1.126     brouard  2509:       } /* End of if */
                   2510:       ipmx +=1;
                   2511:       sw += weight[i];
                   2512:       ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
1.132     brouard  2513:       /*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  2514:       if(globpr){
1.141     brouard  2515:        fprintf(ficresilk,"%9ld %6d %2d %2d %1d %1d %3d %11.6f %8.4f\
1.126     brouard  2516:  %11.6f %11.6f %11.6f ", \
                   2517:                num[i],i,s1,s2,mi,mw[mi][i],dh[mi][i],exp(lli),weight[i],
                   2518:                2*weight[i]*lli,out[s1][s2],savm[s1][s2]);
                   2519:        for(k=1,llt=0.,l=0.; k<=nlstate; k++){
                   2520:          llt +=ll[k]*gipmx/gsw;
                   2521:          fprintf(ficresilk," %10.6f",-ll[k]*gipmx/gsw);
                   2522:        }
                   2523:        fprintf(ficresilk," %10.6f\n", -llt);
                   2524:       }
                   2525:     } /* end of wave */
                   2526:   } /* end of individual */
                   2527:   for(k=1,l=0.; k<=nlstate; k++) l += ll[k];
                   2528:   /* printf("l1=%f l2=%f ",ll[1],ll[2]); */
                   2529:   l= l*ipmx/sw; /* To get the same order of magnitude as if weight=1 for every body */
                   2530:   if(globpr==0){ /* First time we count the contributions and weights */
                   2531:     gipmx=ipmx;
                   2532:     gsw=sw;
                   2533:   }
                   2534:   return -l;
                   2535: }
                   2536: 
                   2537: 
                   2538: /*************** function likelione ***********/
                   2539: void likelione(FILE *ficres,double p[], int npar, int nlstate, int *globpri, long *ipmx, double *sw, double *fretone, double (*funcone)(double []))
                   2540: {
                   2541:   /* This routine should help understanding what is done with 
                   2542:      the selection of individuals/waves and
                   2543:      to check the exact contribution to the likelihood.
                   2544:      Plotting could be done.
                   2545:    */
                   2546:   int k;
                   2547: 
                   2548:   if(*globpri !=0){ /* Just counts and sums, no printings */
                   2549:     strcpy(fileresilk,"ilk"); 
                   2550:     strcat(fileresilk,fileres);
                   2551:     if((ficresilk=fopen(fileresilk,"w"))==NULL) {
                   2552:       printf("Problem with resultfile: %s\n", fileresilk);
                   2553:       fprintf(ficlog,"Problem with resultfile: %s\n", fileresilk);
                   2554:     }
                   2555:     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");
                   2556:     fprintf(ficresilk, "#num_i i s1 s2 mi mw dh likeli weight 2wlli out sav ");
                   2557:     /*         i,s1,s2,mi,mw[mi][i],dh[mi][i],exp(lli),weight[i],2*weight[i]*lli,out[s1][s2],savm[s1][s2]); */
                   2558:     for(k=1; k<=nlstate; k++) 
                   2559:       fprintf(ficresilk," -2*gipw/gsw*weight*ll[%d]++",k);
                   2560:     fprintf(ficresilk," -2*gipw/gsw*weight*ll(total)\n");
                   2561:   }
                   2562: 
                   2563:   *fretone=(*funcone)(p);
                   2564:   if(*globpri !=0){
                   2565:     fclose(ficresilk);
                   2566:     fprintf(fichtm,"\n<br>File of contributions to the likelihood: <a href=\"%s\">%s</a><br>\n",subdirf(fileresilk),subdirf(fileresilk));
                   2567:     fflush(fichtm); 
                   2568:   } 
                   2569:   return;
                   2570: }
                   2571: 
                   2572: 
                   2573: /*********** Maximum Likelihood Estimation ***************/
                   2574: 
                   2575: void mlikeli(FILE *ficres,double p[], int npar, int ncovmodel, int nlstate, double ftol, double (*func)(double []))
                   2576: {
1.165     brouard  2577:   int i,j, iter=0;
1.126     brouard  2578:   double **xi;
                   2579:   double fret;
                   2580:   double fretone; /* Only one call to likelihood */
                   2581:   /*  char filerespow[FILENAMELENGTH];*/
1.162     brouard  2582: 
                   2583: #ifdef NLOPT
                   2584:   int creturn;
                   2585:   nlopt_opt opt;
                   2586:   /* double lb[9] = { -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL }; /\* lower bounds *\/ */
                   2587:   double *lb;
                   2588:   double minf; /* the minimum objective value, upon return */
                   2589:   double * p1; /* Shifted parameters from 0 instead of 1 */
                   2590:   myfunc_data dinst, *d = &dinst;
                   2591: #endif
                   2592: 
                   2593: 
1.126     brouard  2594:   xi=matrix(1,npar,1,npar);
                   2595:   for (i=1;i<=npar;i++)
                   2596:     for (j=1;j<=npar;j++)
                   2597:       xi[i][j]=(i==j ? 1.0 : 0.0);
                   2598:   printf("Powell\n");  fprintf(ficlog,"Powell\n");
                   2599:   strcpy(filerespow,"pow"); 
                   2600:   strcat(filerespow,fileres);
                   2601:   if((ficrespow=fopen(filerespow,"w"))==NULL) {
                   2602:     printf("Problem with resultfile: %s\n", filerespow);
                   2603:     fprintf(ficlog,"Problem with resultfile: %s\n", filerespow);
                   2604:   }
                   2605:   fprintf(ficrespow,"# Powell\n# iter -2*LL");
                   2606:   for (i=1;i<=nlstate;i++)
                   2607:     for(j=1;j<=nlstate+ndeath;j++)
                   2608:       if(j!=i)fprintf(ficrespow," p%1d%1d",i,j);
                   2609:   fprintf(ficrespow,"\n");
1.162     brouard  2610: #ifdef POWELL
1.126     brouard  2611:   powell(p,xi,npar,ftol,&iter,&fret,func);
1.162     brouard  2612: #endif
1.126     brouard  2613: 
1.162     brouard  2614: #ifdef NLOPT
                   2615: #ifdef NEWUOA
                   2616:   opt = nlopt_create(NLOPT_LN_NEWUOA,npar);
                   2617: #else
                   2618:   opt = nlopt_create(NLOPT_LN_BOBYQA,npar);
                   2619: #endif
                   2620:   lb=vector(0,npar-1);
                   2621:   for (i=0;i<npar;i++) lb[i]= -HUGE_VAL;
                   2622:   nlopt_set_lower_bounds(opt, lb);
                   2623:   nlopt_set_initial_step1(opt, 0.1);
                   2624:   
                   2625:   p1= (p+1); /*  p *(p+1)@8 and p *(p1)@8 are equal p1[0]=p[1] */
                   2626:   d->function = func;
                   2627:   printf(" Func %.12lf \n",myfunc(npar,p1,NULL,d));
                   2628:   nlopt_set_min_objective(opt, myfunc, d);
                   2629:   nlopt_set_xtol_rel(opt, ftol);
                   2630:   if ((creturn=nlopt_optimize(opt, p1, &minf)) < 0) {
                   2631:     printf("nlopt failed! %d\n",creturn); 
                   2632:   }
                   2633:   else {
                   2634:     printf("found minimum after %d evaluations (NLOPT=%d)\n", countcallfunc ,NLOPT);
                   2635:     printf("found minimum at f(%g,%g) = %0.10g\n", p[0], p[1], minf);
                   2636:     iter=1; /* not equal */
                   2637:   }
                   2638:   nlopt_destroy(opt);
                   2639: #endif
1.126     brouard  2640:   free_matrix(xi,1,npar,1,npar);
                   2641:   fclose(ficrespow);
1.180     brouard  2642:   printf("#Number of iterations & function calls = %d & %d, -2 Log likelihood = %.12f\n",iter, countcallfunc,func(p));
                   2643:   fprintf(ficlog,"#Number of iterations & function calls = %d & %d, -2 Log likelihood = %.12f\n",iter, countcallfunc,func(p));
                   2644:   fprintf(ficres,"#Number of iterations & function calls = %d & %d, -2 Log likelihood = %.12f\n",iter, countcallfunc,func(p));
1.126     brouard  2645: 
                   2646: }
                   2647: 
                   2648: /**** Computes Hessian and covariance matrix ***/
                   2649: void hesscov(double **matcov, double p[], int npar, double delti[], double ftolhess, double (*func)(double []))
                   2650: {
                   2651:   double  **a,**y,*x,pd;
                   2652:   double **hess;
1.164     brouard  2653:   int i, j;
1.126     brouard  2654:   int *indx;
                   2655: 
                   2656:   double hessii(double p[], double delta, int theta, double delti[],double (*func)(double []),int npar);
                   2657:   double hessij(double p[], double delti[], int i, int j,double (*func)(double []),int npar);
                   2658:   void lubksb(double **a, int npar, int *indx, double b[]) ;
                   2659:   void ludcmp(double **a, int npar, int *indx, double *d) ;
                   2660:   double gompertz(double p[]);
                   2661:   hess=matrix(1,npar,1,npar);
                   2662: 
                   2663:   printf("\nCalculation of the hessian matrix. Wait...\n");
                   2664:   fprintf(ficlog,"\nCalculation of the hessian matrix. Wait...\n");
                   2665:   for (i=1;i<=npar;i++){
                   2666:     printf("%d",i);fflush(stdout);
                   2667:     fprintf(ficlog,"%d",i);fflush(ficlog);
                   2668:    
                   2669:      hess[i][i]=hessii(p,ftolhess,i,delti,func,npar);
                   2670:     
                   2671:     /*  printf(" %f ",p[i]);
                   2672:        printf(" %lf %lf %lf",hess[i][i],ftolhess,delti[i]);*/
                   2673:   }
                   2674:   
                   2675:   for (i=1;i<=npar;i++) {
                   2676:     for (j=1;j<=npar;j++)  {
                   2677:       if (j>i) { 
                   2678:        printf(".%d%d",i,j);fflush(stdout);
                   2679:        fprintf(ficlog,".%d%d",i,j);fflush(ficlog);
                   2680:        hess[i][j]=hessij(p,delti,i,j,func,npar);
                   2681:        
                   2682:        hess[j][i]=hess[i][j];    
                   2683:        /*printf(" %lf ",hess[i][j]);*/
                   2684:       }
                   2685:     }
                   2686:   }
                   2687:   printf("\n");
                   2688:   fprintf(ficlog,"\n");
                   2689: 
                   2690:   printf("\nInverting the hessian to get the covariance matrix. Wait...\n");
                   2691:   fprintf(ficlog,"\nInverting the hessian to get the covariance matrix. Wait...\n");
                   2692:   
                   2693:   a=matrix(1,npar,1,npar);
                   2694:   y=matrix(1,npar,1,npar);
                   2695:   x=vector(1,npar);
                   2696:   indx=ivector(1,npar);
                   2697:   for (i=1;i<=npar;i++)
                   2698:     for (j=1;j<=npar;j++) a[i][j]=hess[i][j];
                   2699:   ludcmp(a,npar,indx,&pd);
                   2700: 
                   2701:   for (j=1;j<=npar;j++) {
                   2702:     for (i=1;i<=npar;i++) x[i]=0;
                   2703:     x[j]=1;
                   2704:     lubksb(a,npar,indx,x);
                   2705:     for (i=1;i<=npar;i++){ 
                   2706:       matcov[i][j]=x[i];
                   2707:     }
                   2708:   }
                   2709: 
                   2710:   printf("\n#Hessian matrix#\n");
                   2711:   fprintf(ficlog,"\n#Hessian matrix#\n");
                   2712:   for (i=1;i<=npar;i++) { 
                   2713:     for (j=1;j<=npar;j++) { 
                   2714:       printf("%.3e ",hess[i][j]);
                   2715:       fprintf(ficlog,"%.3e ",hess[i][j]);
                   2716:     }
                   2717:     printf("\n");
                   2718:     fprintf(ficlog,"\n");
                   2719:   }
                   2720: 
                   2721:   /* Recompute Inverse */
                   2722:   for (i=1;i<=npar;i++)
                   2723:     for (j=1;j<=npar;j++) a[i][j]=matcov[i][j];
                   2724:   ludcmp(a,npar,indx,&pd);
                   2725: 
                   2726:   /*  printf("\n#Hessian matrix recomputed#\n");
                   2727: 
                   2728:   for (j=1;j<=npar;j++) {
                   2729:     for (i=1;i<=npar;i++) x[i]=0;
                   2730:     x[j]=1;
                   2731:     lubksb(a,npar,indx,x);
                   2732:     for (i=1;i<=npar;i++){ 
                   2733:       y[i][j]=x[i];
                   2734:       printf("%.3e ",y[i][j]);
                   2735:       fprintf(ficlog,"%.3e ",y[i][j]);
                   2736:     }
                   2737:     printf("\n");
                   2738:     fprintf(ficlog,"\n");
                   2739:   }
                   2740:   */
                   2741: 
                   2742:   free_matrix(a,1,npar,1,npar);
                   2743:   free_matrix(y,1,npar,1,npar);
                   2744:   free_vector(x,1,npar);
                   2745:   free_ivector(indx,1,npar);
                   2746:   free_matrix(hess,1,npar,1,npar);
                   2747: 
                   2748: 
                   2749: }
                   2750: 
                   2751: /*************** hessian matrix ****************/
                   2752: double hessii(double x[], double delta, int theta, double delti[], double (*func)(double []), int npar)
                   2753: {
                   2754:   int i;
                   2755:   int l=1, lmax=20;
                   2756:   double k1,k2;
1.132     brouard  2757:   double p2[MAXPARM+1]; /* identical to x */
1.126     brouard  2758:   double res;
                   2759:   double delt=0.0001, delts, nkhi=10.,nkhif=1., khi=1.e-4;
                   2760:   double fx;
                   2761:   int k=0,kmax=10;
                   2762:   double l1;
                   2763: 
                   2764:   fx=func(x);
                   2765:   for (i=1;i<=npar;i++) p2[i]=x[i];
1.145     brouard  2766:   for(l=0 ; l <=lmax; l++){  /* Enlarging the zone around the Maximum */
1.126     brouard  2767:     l1=pow(10,l);
                   2768:     delts=delt;
                   2769:     for(k=1 ; k <kmax; k=k+1){
                   2770:       delt = delta*(l1*k);
                   2771:       p2[theta]=x[theta] +delt;
1.145     brouard  2772:       k1=func(p2)-fx;   /* Might be negative if too close to the theoretical maximum */
1.126     brouard  2773:       p2[theta]=x[theta]-delt;
                   2774:       k2=func(p2)-fx;
                   2775:       /*res= (k1-2.0*fx+k2)/delt/delt; */
                   2776:       res= (k1+k2)/delt/delt/2.; /* Divided by because L and not 2*L */
                   2777:       
1.132     brouard  2778: #ifdef DEBUGHESS
1.126     brouard  2779:       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);
                   2780:       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);
                   2781: #endif
                   2782:       /*if(fabs(k1-2.0*fx+k2) <1.e-13){ */
                   2783:       if((k1 <khi/nkhi/2.) || (k2 <khi/nkhi/2.)){
                   2784:        k=kmax;
                   2785:       }
                   2786:       else if((k1 >khi/nkhif) || (k2 >khi/nkhif)){ /* Keeps lastvalue before 3.84/2 KHI2 5% 1d.f. */
1.164     brouard  2787:        k=kmax; l=lmax*10;
1.126     brouard  2788:       }
                   2789:       else if((k1 >khi/nkhi) || (k2 >khi/nkhi)){ 
                   2790:        delts=delt;
                   2791:       }
                   2792:     }
                   2793:   }
                   2794:   delti[theta]=delts;
                   2795:   return res; 
                   2796:   
                   2797: }
                   2798: 
                   2799: double hessij( double x[], double delti[], int thetai,int thetaj,double (*func)(double []),int npar)
                   2800: {
                   2801:   int i;
1.164     brouard  2802:   int l=1, lmax=20;
1.126     brouard  2803:   double k1,k2,k3,k4,res,fx;
1.132     brouard  2804:   double p2[MAXPARM+1];
1.126     brouard  2805:   int k;
                   2806: 
                   2807:   fx=func(x);
                   2808:   for (k=1; k<=2; k++) {
                   2809:     for (i=1;i<=npar;i++) p2[i]=x[i];
                   2810:     p2[thetai]=x[thetai]+delti[thetai]/k;
                   2811:     p2[thetaj]=x[thetaj]+delti[thetaj]/k;
                   2812:     k1=func(p2)-fx;
                   2813:   
                   2814:     p2[thetai]=x[thetai]+delti[thetai]/k;
                   2815:     p2[thetaj]=x[thetaj]-delti[thetaj]/k;
                   2816:     k2=func(p2)-fx;
                   2817:   
                   2818:     p2[thetai]=x[thetai]-delti[thetai]/k;
                   2819:     p2[thetaj]=x[thetaj]+delti[thetaj]/k;
                   2820:     k3=func(p2)-fx;
                   2821:   
                   2822:     p2[thetai]=x[thetai]-delti[thetai]/k;
                   2823:     p2[thetaj]=x[thetaj]-delti[thetaj]/k;
                   2824:     k4=func(p2)-fx;
                   2825:     res=(k1-k2-k3+k4)/4.0/delti[thetai]*k/delti[thetaj]*k/2.; /* Because of L not 2*L */
                   2826: #ifdef DEBUG
                   2827:     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);
                   2828:     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);
                   2829: #endif
                   2830:   }
                   2831:   return res;
                   2832: }
                   2833: 
                   2834: /************** Inverse of matrix **************/
                   2835: void ludcmp(double **a, int n, int *indx, double *d) 
                   2836: { 
                   2837:   int i,imax,j,k; 
                   2838:   double big,dum,sum,temp; 
                   2839:   double *vv; 
                   2840:  
                   2841:   vv=vector(1,n); 
                   2842:   *d=1.0; 
                   2843:   for (i=1;i<=n;i++) { 
                   2844:     big=0.0; 
                   2845:     for (j=1;j<=n;j++) 
                   2846:       if ((temp=fabs(a[i][j])) > big) big=temp; 
                   2847:     if (big == 0.0) nrerror("Singular matrix in routine ludcmp"); 
                   2848:     vv[i]=1.0/big; 
                   2849:   } 
                   2850:   for (j=1;j<=n;j++) { 
                   2851:     for (i=1;i<j;i++) { 
                   2852:       sum=a[i][j]; 
                   2853:       for (k=1;k<i;k++) sum -= a[i][k]*a[k][j]; 
                   2854:       a[i][j]=sum; 
                   2855:     } 
                   2856:     big=0.0; 
                   2857:     for (i=j;i<=n;i++) { 
                   2858:       sum=a[i][j]; 
                   2859:       for (k=1;k<j;k++) 
                   2860:        sum -= a[i][k]*a[k][j]; 
                   2861:       a[i][j]=sum; 
                   2862:       if ( (dum=vv[i]*fabs(sum)) >= big) { 
                   2863:        big=dum; 
                   2864:        imax=i; 
                   2865:       } 
                   2866:     } 
                   2867:     if (j != imax) { 
                   2868:       for (k=1;k<=n;k++) { 
                   2869:        dum=a[imax][k]; 
                   2870:        a[imax][k]=a[j][k]; 
                   2871:        a[j][k]=dum; 
                   2872:       } 
                   2873:       *d = -(*d); 
                   2874:       vv[imax]=vv[j]; 
                   2875:     } 
                   2876:     indx[j]=imax; 
                   2877:     if (a[j][j] == 0.0) a[j][j]=TINY; 
                   2878:     if (j != n) { 
                   2879:       dum=1.0/(a[j][j]); 
                   2880:       for (i=j+1;i<=n;i++) a[i][j] *= dum; 
                   2881:     } 
                   2882:   } 
                   2883:   free_vector(vv,1,n);  /* Doesn't work */
                   2884: ;
                   2885: } 
                   2886: 
                   2887: void lubksb(double **a, int n, int *indx, double b[]) 
                   2888: { 
                   2889:   int i,ii=0,ip,j; 
                   2890:   double sum; 
                   2891:  
                   2892:   for (i=1;i<=n;i++) { 
                   2893:     ip=indx[i]; 
                   2894:     sum=b[ip]; 
                   2895:     b[ip]=b[i]; 
                   2896:     if (ii) 
                   2897:       for (j=ii;j<=i-1;j++) sum -= a[i][j]*b[j]; 
                   2898:     else if (sum) ii=i; 
                   2899:     b[i]=sum; 
                   2900:   } 
                   2901:   for (i=n;i>=1;i--) { 
                   2902:     sum=b[i]; 
                   2903:     for (j=i+1;j<=n;j++) sum -= a[i][j]*b[j]; 
                   2904:     b[i]=sum/a[i][i]; 
                   2905:   } 
                   2906: } 
                   2907: 
                   2908: void pstamp(FILE *fichier)
                   2909: {
1.196   ! brouard  2910:   fprintf(fichier,"# %s.%s\n#IMaCh version %s, %s\n#%s\n# %s", optionfilefiname,optionfilext,version,copyright, fullversion, strstart);
1.126     brouard  2911: }
                   2912: 
                   2913: /************ Frequencies ********************/
                   2914: 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[])
                   2915: {  /* Some frequencies */
                   2916:   
1.164     brouard  2917:   int i, m, jk, j1, bool, z1,j;
1.126     brouard  2918:   int first;
                   2919:   double ***freq; /* Frequencies */
                   2920:   double *pp, **prop;
                   2921:   double pos,posprop, k2, dateintsum=0,k2cpt=0;
                   2922:   char fileresp[FILENAMELENGTH];
                   2923:   
                   2924:   pp=vector(1,nlstate);
                   2925:   prop=matrix(1,nlstate,iagemin,iagemax+3);
                   2926:   strcpy(fileresp,"p");
                   2927:   strcat(fileresp,fileres);
                   2928:   if((ficresp=fopen(fileresp,"w"))==NULL) {
                   2929:     printf("Problem with prevalence resultfile: %s\n", fileresp);
                   2930:     fprintf(ficlog,"Problem with prevalence resultfile: %s\n", fileresp);
                   2931:     exit(0);
                   2932:   }
                   2933:   freq= ma3x(-5,nlstate+ndeath,-5,nlstate+ndeath,iagemin,iagemax+3);
                   2934:   j1=0;
                   2935:   
                   2936:   j=cptcoveff;
                   2937:   if (cptcovn<1) {j=1;ncodemax[1]=1;}
                   2938: 
                   2939:   first=1;
                   2940: 
1.169     brouard  2941:   /* for(k1=1; k1<=j ; k1++){ */  /* Loop on covariates */
                   2942:   /*  for(i1=1; i1<=ncodemax[k1];i1++){ */ /* Now it is 2 */
                   2943:   /*    j1++; */
1.145     brouard  2944:   for (j1 = 1; j1 <= (int) pow(2,cptcoveff); j1++){
1.126     brouard  2945:       /*printf("cptcoveff=%d Tvaraff=%d", cptcoveff,Tvaraff[1]);
                   2946:        scanf("%d", i);*/
                   2947:       for (i=-5; i<=nlstate+ndeath; i++)  
                   2948:        for (jk=-5; jk<=nlstate+ndeath; jk++)  
                   2949:          for(m=iagemin; m <= iagemax+3; m++)
                   2950:            freq[i][jk][m]=0;
1.143     brouard  2951:       
                   2952:       for (i=1; i<=nlstate; i++)  
                   2953:        for(m=iagemin; m <= iagemax+3; m++)
                   2954:          prop[i][m]=0;
1.126     brouard  2955:       
                   2956:       dateintsum=0;
                   2957:       k2cpt=0;
                   2958:       for (i=1; i<=imx; i++) {
                   2959:        bool=1;
1.144     brouard  2960:        if  (cptcovn>0) { /* Filter is here: Must be looked at for model=V1+V2+V3+V4 */
                   2961:          for (z1=1; z1<=cptcoveff; z1++)       
                   2962:             if (covar[Tvaraff[z1]][i]!= nbcode[Tvaraff[z1]][codtab[j1][z1]]){
1.145     brouard  2963:                 /* Tests if the value of each of the covariates of i is equal to filter j1 */
1.144     brouard  2964:               bool=0;
1.145     brouard  2965:               /* 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", 
                   2966:                 bool,i,z1, z1, Tvaraff[z1],i,covar[Tvaraff[z1]][i],j1,z1,codtab[j1][z1],
                   2967:                 j1,z1,nbcode[Tvaraff[z1]][codtab[j1][z1]],j1);*/
1.144     brouard  2968:               /* For j1=7 in V1+V2+V3+V4 = 0 1 1 0 and codtab[7][3]=1 and nbcde[3][?]=1*/
                   2969:             } 
1.126     brouard  2970:        }
1.144     brouard  2971:  
1.126     brouard  2972:        if (bool==1){
                   2973:          for(m=firstpass; m<=lastpass; m++){
                   2974:            k2=anint[m][i]+(mint[m][i]/12.);
                   2975:            /*if ((k2>=dateprev1) && (k2<=dateprev2)) {*/
                   2976:              if(agev[m][i]==0) agev[m][i]=iagemax+1;
                   2977:              if(agev[m][i]==1) agev[m][i]=iagemax+2;
                   2978:              if (s[m][i]>0 && s[m][i]<=nlstate) prop[s[m][i]][(int)agev[m][i]] += weight[i];
                   2979:              if (m<lastpass) {
                   2980:                freq[s[m][i]][s[m+1][i]][(int)agev[m][i]] += weight[i];
                   2981:                freq[s[m][i]][s[m+1][i]][iagemax+3] += weight[i];
                   2982:              }
                   2983:              
                   2984:              if ((agev[m][i]>1) && (agev[m][i]< (iagemax+3))) {
                   2985:                dateintsum=dateintsum+k2;
                   2986:                k2cpt++;
                   2987:              }
                   2988:              /*}*/
                   2989:          }
                   2990:        }
1.145     brouard  2991:       } /* end i */
1.126     brouard  2992:        
                   2993:       /*      fprintf(ficresp, "#Count between %.lf/%.lf/%.lf and %.lf/%.lf/%.lf\n",jprev1, mprev1,anprev1,jprev2, mprev2,anprev2);*/
                   2994:       pstamp(ficresp);
                   2995:       if  (cptcovn>0) {
                   2996:        fprintf(ficresp, "\n#********** Variable "); 
                   2997:        for (z1=1; z1<=cptcoveff; z1++) fprintf(ficresp, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtab[j1][z1]]);
                   2998:        fprintf(ficresp, "**********\n#");
1.143     brouard  2999:        fprintf(ficlog, "\n#********** Variable "); 
                   3000:        for (z1=1; z1<=cptcoveff; z1++) fprintf(ficlog, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtab[j1][z1]]);
                   3001:        fprintf(ficlog, "**********\n#");
1.126     brouard  3002:       }
                   3003:       for(i=1; i<=nlstate;i++) 
                   3004:        fprintf(ficresp, " Age Prev(%d) N(%d) N",i,i);
                   3005:       fprintf(ficresp, "\n");
                   3006:       
                   3007:       for(i=iagemin; i <= iagemax+3; i++){
                   3008:        if(i==iagemax+3){
                   3009:          fprintf(ficlog,"Total");
                   3010:        }else{
                   3011:          if(first==1){
                   3012:            first=0;
                   3013:            printf("See log file for details...\n");
                   3014:          }
                   3015:          fprintf(ficlog,"Age %d", i);
                   3016:        }
                   3017:        for(jk=1; jk <=nlstate ; jk++){
                   3018:          for(m=-1, pp[jk]=0; m <=nlstate+ndeath ; m++)
                   3019:            pp[jk] += freq[jk][m][i]; 
                   3020:        }
                   3021:        for(jk=1; jk <=nlstate ; jk++){
                   3022:          for(m=-1, pos=0; m <=0 ; m++)
                   3023:            pos += freq[jk][m][i];
                   3024:          if(pp[jk]>=1.e-10){
                   3025:            if(first==1){
1.132     brouard  3026:              printf(" %d.=%.0f loss[%d]=%.1f%%",jk,pp[jk],jk,100*pos/pp[jk]);
1.126     brouard  3027:            }
                   3028:            fprintf(ficlog," %d.=%.0f loss[%d]=%.1f%%",jk,pp[jk],jk,100*pos/pp[jk]);
                   3029:          }else{
                   3030:            if(first==1)
                   3031:              printf(" %d.=%.0f loss[%d]=NaNQ%%",jk,pp[jk],jk);
                   3032:            fprintf(ficlog," %d.=%.0f loss[%d]=NaNQ%%",jk,pp[jk],jk);
                   3033:          }
                   3034:        }
                   3035: 
                   3036:        for(jk=1; jk <=nlstate ; jk++){
                   3037:          for(m=0, pp[jk]=0; m <=nlstate+ndeath; m++)
                   3038:            pp[jk] += freq[jk][m][i];
                   3039:        }       
                   3040:        for(jk=1,pos=0,posprop=0; jk <=nlstate ; jk++){
                   3041:          pos += pp[jk];
                   3042:          posprop += prop[jk][i];
                   3043:        }
                   3044:        for(jk=1; jk <=nlstate ; jk++){
                   3045:          if(pos>=1.e-5){
                   3046:            if(first==1)
                   3047:              printf(" %d.=%.0f prev[%d]=%.1f%%",jk,pp[jk],jk,100*pp[jk]/pos);
                   3048:            fprintf(ficlog," %d.=%.0f prev[%d]=%.1f%%",jk,pp[jk],jk,100*pp[jk]/pos);
                   3049:          }else{
                   3050:            if(first==1)
                   3051:              printf(" %d.=%.0f prev[%d]=NaNQ%%",jk,pp[jk],jk);
                   3052:            fprintf(ficlog," %d.=%.0f prev[%d]=NaNQ%%",jk,pp[jk],jk);
                   3053:          }
                   3054:          if( i <= iagemax){
                   3055:            if(pos>=1.e-5){
                   3056:              fprintf(ficresp," %d %.5f %.0f %.0f",i,prop[jk][i]/posprop, prop[jk][i],posprop);
                   3057:              /*probs[i][jk][j1]= pp[jk]/pos;*/
                   3058:              /*printf("\ni=%d jk=%d j1=%d %.5f %.0f %.0f %f",i,jk,j1,pp[jk]/pos, pp[jk],pos,probs[i][jk][j1]);*/
                   3059:            }
                   3060:            else
                   3061:              fprintf(ficresp," %d NaNq %.0f %.0f",i,prop[jk][i],posprop);
                   3062:          }
                   3063:        }
                   3064:        
                   3065:        for(jk=-1; jk <=nlstate+ndeath; jk++)
                   3066:          for(m=-1; m <=nlstate+ndeath; m++)
                   3067:            if(freq[jk][m][i] !=0 ) {
                   3068:            if(first==1)
                   3069:              printf(" %d%d=%.0f",jk,m,freq[jk][m][i]);
                   3070:              fprintf(ficlog," %d%d=%.0f",jk,m,freq[jk][m][i]);
                   3071:            }
                   3072:        if(i <= iagemax)
                   3073:          fprintf(ficresp,"\n");
                   3074:        if(first==1)
                   3075:          printf("Others in log...\n");
                   3076:        fprintf(ficlog,"\n");
                   3077:       }
1.145     brouard  3078:       /*}*/
1.126     brouard  3079:   }
                   3080:   dateintmean=dateintsum/k2cpt; 
                   3081:  
                   3082:   fclose(ficresp);
                   3083:   free_ma3x(freq,-5,nlstate+ndeath,-5,nlstate+ndeath, iagemin, iagemax+3);
                   3084:   free_vector(pp,1,nlstate);
                   3085:   free_matrix(prop,1,nlstate,iagemin, iagemax+3);
                   3086:   /* End of Freq */
                   3087: }
                   3088: 
                   3089: /************ Prevalence ********************/
                   3090: 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)
                   3091: {  
                   3092:   /* Compute observed prevalence between dateprev1 and dateprev2 by counting the number of people
                   3093:      in each health status at the date of interview (if between dateprev1 and dateprev2).
                   3094:      We still use firstpass and lastpass as another selection.
                   3095:   */
                   3096:  
1.164     brouard  3097:   int i, m, jk, j1, bool, z1,j;
                   3098: 
                   3099:   double **prop;
                   3100:   double posprop; 
1.126     brouard  3101:   double  y2; /* in fractional years */
                   3102:   int iagemin, iagemax;
1.145     brouard  3103:   int first; /** to stop verbosity which is redirected to log file */
1.126     brouard  3104: 
                   3105:   iagemin= (int) agemin;
                   3106:   iagemax= (int) agemax;
                   3107:   /*pp=vector(1,nlstate);*/
                   3108:   prop=matrix(1,nlstate,iagemin,iagemax+3); 
                   3109:   /*  freq=ma3x(-1,nlstate+ndeath,-1,nlstate+ndeath,iagemin,iagemax+3);*/
                   3110:   j1=0;
                   3111:   
1.145     brouard  3112:   /*j=cptcoveff;*/
1.126     brouard  3113:   if (cptcovn<1) {j=1;ncodemax[1]=1;}
                   3114:   
1.145     brouard  3115:   first=1;
                   3116:   for(j1=1; j1<= (int) pow(2,cptcoveff);j1++){
                   3117:     /*for(i1=1; i1<=ncodemax[k1];i1++){
                   3118:       j1++;*/
1.126     brouard  3119:       
                   3120:       for (i=1; i<=nlstate; i++)  
                   3121:        for(m=iagemin; m <= iagemax+3; m++)
                   3122:          prop[i][m]=0.0;
                   3123:      
                   3124:       for (i=1; i<=imx; i++) { /* Each individual */
                   3125:        bool=1;
                   3126:        if  (cptcovn>0) {
                   3127:          for (z1=1; z1<=cptcoveff; z1++) 
                   3128:            if (covar[Tvaraff[z1]][i]!= nbcode[Tvaraff[z1]][codtab[j1][z1]]) 
                   3129:              bool=0;
                   3130:        } 
                   3131:        if (bool==1) { 
                   3132:          for(m=firstpass; m<=lastpass; m++){/* Other selection (we can limit to certain interviews*/
                   3133:            y2=anint[m][i]+(mint[m][i]/12.); /* Fractional date in year */
                   3134:            if ((y2>=dateprev1) && (y2<=dateprev2)) { /* Here is the main selection (fractional years) */
                   3135:              if(agev[m][i]==0) agev[m][i]=iagemax+1;
                   3136:              if(agev[m][i]==1) agev[m][i]=iagemax+2;
                   3137:              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); 
                   3138:              if (s[m][i]>0 && s[m][i]<=nlstate) { 
                   3139:                /*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]]);*/
                   3140:                prop[s[m][i]][(int)agev[m][i]] += weight[i];
                   3141:                prop[s[m][i]][iagemax+3] += weight[i]; 
                   3142:              } 
                   3143:            }
                   3144:          } /* end selection of waves */
                   3145:        }
                   3146:       }
                   3147:       for(i=iagemin; i <= iagemax+3; i++){  
                   3148:        for(jk=1,posprop=0; jk <=nlstate ; jk++) { 
                   3149:          posprop += prop[jk][i]; 
                   3150:        } 
1.145     brouard  3151:        
1.126     brouard  3152:        for(jk=1; jk <=nlstate ; jk++){     
                   3153:          if( i <=  iagemax){ 
                   3154:            if(posprop>=1.e-5){ 
                   3155:              probs[i][jk][j1]= prop[jk][i]/posprop;
1.145     brouard  3156:            } else{
                   3157:              if(first==1){
                   3158:                first=0;
                   3159:                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]);
                   3160:              }
                   3161:            }
1.126     brouard  3162:          } 
                   3163:        }/* end jk */ 
                   3164:       }/* end i */ 
1.145     brouard  3165:     /*} *//* end i1 */
                   3166:   } /* end j1 */
1.126     brouard  3167:   
                   3168:   /*  free_ma3x(freq,-1,nlstate+ndeath,-1,nlstate+ndeath, iagemin, iagemax+3);*/
                   3169:   /*free_vector(pp,1,nlstate);*/
                   3170:   free_matrix(prop,1,nlstate, iagemin,iagemax+3);
                   3171: }  /* End of prevalence */
                   3172: 
                   3173: /************* Waves Concatenation ***************/
                   3174: 
                   3175: 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)
                   3176: {
                   3177:   /* Concatenates waves: wav[i] is the number of effective (useful waves) of individual i.
                   3178:      Death is a valid wave (if date is known).
                   3179:      mw[mi][i] is the mi (mi=1 to wav[i])  effective wave of individual i
                   3180:      dh[m][i] or dh[mw[mi][i]][i] is the delay between two effective waves m=mw[mi][i]
                   3181:      and mw[mi+1][i]. dh depends on stepm.
                   3182:      */
                   3183: 
                   3184:   int i, mi, m;
                   3185:   /* int j, k=0,jk, ju, jl,jmin=1e+5, jmax=-1;
                   3186:      double sum=0., jmean=0.;*/
                   3187:   int first;
                   3188:   int j, k=0,jk, ju, jl;
                   3189:   double sum=0.;
                   3190:   first=0;
1.164     brouard  3191:   jmin=100000;
1.126     brouard  3192:   jmax=-1;
                   3193:   jmean=0.;
                   3194:   for(i=1; i<=imx; i++){
                   3195:     mi=0;
                   3196:     m=firstpass;
                   3197:     while(s[m][i] <= nlstate){
                   3198:       if(s[m][i]>=1 || s[m][i]==-2 || s[m][i]==-4 || s[m][i]==-5)
                   3199:        mw[++mi][i]=m;
                   3200:       if(m >=lastpass)
                   3201:        break;
                   3202:       else
                   3203:        m++;
                   3204:     }/* end while */
                   3205:     if (s[m][i] > nlstate){
                   3206:       mi++;    /* Death is another wave */
                   3207:       /* if(mi==0)  never been interviewed correctly before death */
                   3208:         /* Only death is a correct wave */
                   3209:       mw[mi][i]=m;
                   3210:     }
                   3211: 
                   3212:     wav[i]=mi;
                   3213:     if(mi==0){
                   3214:       nbwarn++;
                   3215:       if(first==0){
                   3216:        printf("Warning! No valid information for individual %ld line=%d (skipped) and may be others, see log file\n",num[i],i);
                   3217:        first=1;
                   3218:       }
                   3219:       if(first==1){
                   3220:        fprintf(ficlog,"Warning! No valid information for individual %ld line=%d (skipped)\n",num[i],i);
                   3221:       }
                   3222:     } /* end mi==0 */
                   3223:   } /* End individuals */
                   3224: 
                   3225:   for(i=1; i<=imx; i++){
                   3226:     for(mi=1; mi<wav[i];mi++){
                   3227:       if (stepm <=0)
                   3228:        dh[mi][i]=1;
                   3229:       else{
                   3230:        if (s[mw[mi+1][i]][i] > nlstate) { /* A death */
                   3231:          if (agedc[i] < 2*AGESUP) {
                   3232:            j= rint(agedc[i]*12-agev[mw[mi][i]][i]*12); 
                   3233:            if(j==0) j=1;  /* Survives at least one month after exam */
                   3234:            else if(j<0){
                   3235:              nberr++;
                   3236:              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]);
                   3237:              j=1; /* Temporary Dangerous patch */
                   3238:              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);
                   3239:              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]);
                   3240:              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);
                   3241:            }
                   3242:            k=k+1;
                   3243:            if (j >= jmax){
                   3244:              jmax=j;
                   3245:              ijmax=i;
                   3246:            }
                   3247:            if (j <= jmin){
                   3248:              jmin=j;
                   3249:              ijmin=i;
                   3250:            }
                   3251:            sum=sum+j;
                   3252:            /*if (j<0) printf("j=%d num=%d \n",j,i);*/
                   3253:            /*    printf("%d %d %d %d\n", s[mw[mi][i]][i] ,s[mw[mi+1][i]][i],j,i);*/
                   3254:          }
                   3255:        }
                   3256:        else{
                   3257:          j= rint( (agev[mw[mi+1][i]][i]*12 - agev[mw[mi][i]][i]*12));
                   3258: /*       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]); */
                   3259: 
                   3260:          k=k+1;
                   3261:          if (j >= jmax) {
                   3262:            jmax=j;
                   3263:            ijmax=i;
                   3264:          }
                   3265:          else if (j <= jmin){
                   3266:            jmin=j;
                   3267:            ijmin=i;
                   3268:          }
                   3269:          /*        if (j<10) printf("j=%d jmin=%d num=%d ",j,jmin,i); */
                   3270:          /*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]);*/
                   3271:          if(j<0){
                   3272:            nberr++;
                   3273:            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]);
                   3274:            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]);
                   3275:          }
                   3276:          sum=sum+j;
                   3277:        }
                   3278:        jk= j/stepm;
                   3279:        jl= j -jk*stepm;
                   3280:        ju= j -(jk+1)*stepm;
                   3281:        if(mle <=1){ /* only if we use a the linear-interpoloation pseudo-likelihood */
                   3282:          if(jl==0){
                   3283:            dh[mi][i]=jk;
                   3284:            bh[mi][i]=0;
                   3285:          }else{ /* We want a negative bias in order to only have interpolation ie
1.136     brouard  3286:                  * to avoid the price of an extra matrix product in likelihood */
1.126     brouard  3287:            dh[mi][i]=jk+1;
                   3288:            bh[mi][i]=ju;
                   3289:          }
                   3290:        }else{
                   3291:          if(jl <= -ju){
                   3292:            dh[mi][i]=jk;
                   3293:            bh[mi][i]=jl;       /* bias is positive if real duration
                   3294:                                 * is higher than the multiple of stepm and negative otherwise.
                   3295:                                 */
                   3296:          }
                   3297:          else{
                   3298:            dh[mi][i]=jk+1;
                   3299:            bh[mi][i]=ju;
                   3300:          }
                   3301:          if(dh[mi][i]==0){
                   3302:            dh[mi][i]=1; /* At least one step */
                   3303:            bh[mi][i]=ju; /* At least one step */
                   3304:            /*  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);*/
                   3305:          }
                   3306:        } /* end if mle */
                   3307:       }
                   3308:     } /* end wave */
                   3309:   }
                   3310:   jmean=sum/k;
                   3311:   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  3312:   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  3313:  }
                   3314: 
                   3315: /*********** Tricode ****************************/
1.145     brouard  3316: void tricode(int *Tvar, int **nbcode, int imx, int *Ndum)
1.126     brouard  3317: {
1.144     brouard  3318:   /**< Uses cptcovn+2*cptcovprod as the number of covariates */
                   3319:   /*     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  3320:    * Boring subroutine which should only output nbcode[Tvar[j]][k]
1.145     brouard  3321:    * Tvar[5] in V2+V1+V3*age+V2*V4 is 2 (V2)
1.169     brouard  3322:    * nbcode[Tvar[j]][1]= 
1.144     brouard  3323:   */
1.130     brouard  3324: 
1.145     brouard  3325:   int ij=1, k=0, j=0, i=0, maxncov=NCOVMAX;
1.136     brouard  3326:   int modmaxcovj=0; /* Modality max of covariates j */
1.145     brouard  3327:   int cptcode=0; /* Modality max of covariates j */
                   3328:   int modmincovj=0; /* Modality min of covariates j */
                   3329: 
                   3330: 
1.126     brouard  3331:   cptcoveff=0; 
                   3332:  
1.144     brouard  3333:   for (k=1; k <= maxncov; k++) ncodemax[k]=0; /* Horrible constant again replaced by NCOVMAX */
1.126     brouard  3334: 
1.145     brouard  3335:   /* Loop on covariates without age and products */
1.186     brouard  3336:   for (j=1; j<=(cptcovs); j++) { /* From model V1 + V2*age+ V3 + V3*V4 keeps V1 + V3 = 2 only */
1.192     brouard  3337:     for (k=-1; k < maxncov; k++) Ndum[k]=0;
1.186     brouard  3338:     for (i=1; i<=imx; i++) { /* Loop on individuals: reads the data file to get the maximum value of the 
1.136     brouard  3339:                               modality of this covariate Vj*/ 
1.145     brouard  3340:       ij=(int)(covar[Tvar[j]][i]); /* ij=0 or 1 or -1. Value of the covariate Tvar[j] for individual i
                   3341:                                    * If product of Vn*Vm, still boolean *:
                   3342:                                    * If it was coded 1, 2, 3, 4 should be splitted into 3 boolean variables
                   3343:                                    * 1 => 0 0 0, 2 => 0 0 1, 3 => 0 1 1, 4=1 0 0   */
                   3344:       /* Finds for covariate j, n=Tvar[j] of Vn . ij is the
1.136     brouard  3345:                                      modality of the nth covariate of individual i. */
1.145     brouard  3346:       if (ij > modmaxcovj)
                   3347:         modmaxcovj=ij; 
                   3348:       else if (ij < modmincovj) 
                   3349:        modmincovj=ij; 
                   3350:       if ((ij < -1) && (ij > NCOVMAX)){
                   3351:        printf( "Error: minimal is less than -1 or maximal is bigger than %d. Exiting. \n", NCOVMAX );
                   3352:        exit(1);
                   3353:       }else
1.136     brouard  3354:       Ndum[ij]++; /*counts and stores the occurence of this modality 0, 1, -1*/
1.145     brouard  3355:       /*  If coded 1, 2, 3 , counts the number of 1 Ndum[1], number of 2, Ndum[2], etc */
1.126     brouard  3356:       /*printf("i=%d ij=%d Ndum[ij]=%d imx=%d",i,ij,Ndum[ij],imx);*/
1.136     brouard  3357:       /* getting the maximum value of the modality of the covariate
                   3358:         (should be 0 or 1 now) Tvar[j]. If V=sex and male is coded 0 and
                   3359:         female is 1, then modmaxcovj=1.*/
1.192     brouard  3360:     } /* end for loop on individuals i */
1.145     brouard  3361:     printf(" Minimal and maximal values of %d th covariate V%d: min=%d max=%d \n", j, Tvar[j], modmincovj, modmaxcovj);
1.192     brouard  3362:     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  3363:     cptcode=modmaxcovj;
1.137     brouard  3364:     /* Ndum[0] = frequency of 0 for model-covariate j, Ndum[1] frequency of 1 etc. */
1.145     brouard  3365:    /*for (i=0; i<=cptcode; i++) {*/
1.192     brouard  3366:     for (k=modmincovj;  k<=modmaxcovj; k++) { /* k=-1 ? 0 and 1*//* For each value k of the modality of model-cov j */
                   3367:       printf("Frequencies of covariates %d ie V%d with value %d: %d\n", j, Tvar[j], k, Ndum[k]);
                   3368:       fprintf(ficlog, "Frequencies of covariates %d ie V%d with value %d: %d\n", j, Tvar[j], k, Ndum[k]);
                   3369:       if( Ndum[k] != 0 ){ /* Counts if nobody answered modality k ie empty modality, we skip it and reorder */
                   3370:        if( k != -1){
                   3371:          ncodemax[j]++;  /* ncodemax[j]= Number of modalities of the j th
                   3372:                             covariate for which somebody answered excluding 
                   3373:                             undefined. Usually 2: 0 and 1. */
                   3374:        }
                   3375:        ncodemaxwundef[j]++; /* ncodemax[j]= Number of modalities of the j th
                   3376:                             covariate for which somebody answered including 
                   3377:                             undefined. Usually 3: -1, 0 and 1. */
1.145     brouard  3378:       }
                   3379:       /* In fact  ncodemax[j]=2 (dichotom. variables only) but it could be more for
                   3380:         historical reasons: 3 if coded 1, 2, 3 and 4 and Ndum[2]=0 */
1.131     brouard  3381:     } /* Ndum[-1] number of undefined modalities */
1.126     brouard  3382: 
1.136     brouard  3383:     /* j is a covariate, n=Tvar[j] of Vn; Fills nbcode */
1.186     brouard  3384:     /* For covariate j, modalities could be 1, 2, 3, 4, 5, 6, 7. 
                   3385:        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  3386:        modmincovj=3; modmaxcovj = 7;
1.186     brouard  3387:        There are only 3 modalities non empty 3, 6, 7 (or 2 if 27 is too few) : ncodemax[j]=3;
                   3388:        which will be coded 0, 1, 2 which in binary on 2=3-1 digits are 0=00 1=01, 2=10;
                   3389:        defining two dummy variables: variables V1_1 and V1_2.
1.145     brouard  3390:        nbcode[Tvar[j]][ij]=k;
                   3391:        nbcode[Tvar[j]][1]=0;
                   3392:        nbcode[Tvar[j]][2]=1;
                   3393:        nbcode[Tvar[j]][3]=2;
                   3394:     */
1.192     brouard  3395:     ij=0; /* ij is similar to i but can jumps over null modalities */
                   3396:     for (i=modmincovj; i<=modmaxcovj; i++) { /* i= 1 to 2 for dichotomous, or from 1 to 3 or from -1 to 1*/
                   3397:        if (Ndum[i] == 0) { /* If at least one individual responded to this modality k */
                   3398:          break;
                   3399:        }
                   3400:        ij++;
                   3401:        nbcode[Tvar[j]][ij]=i;  /* stores the original modality i in an array nbcode, ij modality from 1 to last non-nul modality.*/
                   3402:        cptcode = ij; /* New max modality for covar j */
                   3403:     } /* end of loop on modality i=-1 to 1 or more */
                   3404:       
                   3405:     /*   for (k=0; k<= cptcode; k++) { /\* k=-1 ? k=0 to 1 *\//\* Could be 1 to 4 *\//\* cptcode=modmaxcovj *\/ */
                   3406:     /*         /\*recode from 0 *\/ */
                   3407:     /*                                      k is a modality. If we have model=V1+V1*sex  */
                   3408:     /*                                      then: nbcode[1][1]=0 ; nbcode[1][2]=1; nbcode[2][1]=0 ; nbcode[2][2]=1; */
                   3409:     /*                                   But if some modality were not used, it is recoded from 0 to a newer modmaxcovj=cptcode *\/ */
                   3410:     /*         } */
                   3411:     /*         /\* cptcode = ij; *\/ /\* New max modality for covar j *\/ */
                   3412:     /*         if (ij > ncodemax[j]) { */
                   3413:     /*           printf( " Error ij=%d > ncodemax[%d]=%d\n", ij, j, ncodemax[j]);  */
                   3414:     /*           fprintf(ficlog, " Error ij=%d > ncodemax[%d]=%d\n", ij, j, ncodemax[j]); */
                   3415:     /*           break; */
                   3416:     /*         } */
                   3417:     /*   }  /\* end of loop on modality k *\/ */
1.137     brouard  3418:   } /* end of loop on model-covariate j. nbcode[Tvarj][1]=0 and nbcode[Tvarj][2]=1 sets the value of covariate j*/  
                   3419:   
1.145     brouard  3420:  for (k=-1; k< maxncov; k++) Ndum[k]=0; 
1.137     brouard  3421:   
1.187     brouard  3422:   for (i=1; i<=ncovmodel-2-nagesqr; i++) { /* -2, cste and age and eventually age*age */ 
1.145     brouard  3423:    /* Listing of all covariables in statement model to see if some covariates appear twice. For example, V1 appears twice in V1+V1*V2.*/ 
                   3424:    ij=Tvar[i]; /* Tvar might be -1 if status was unknown */ 
1.187     brouard  3425:    Ndum[ij]++; /* Might be supersed V1 + V1*age */
1.145     brouard  3426:  } 
1.126     brouard  3427: 
1.192     brouard  3428:  ij=0;
1.145     brouard  3429:  for (i=0; i<=  maxncov-1; i++) { /* modmaxcovj is unknown here. Only Ndum[2(V2),3(age*V3), 5(V3*V2) 6(V1*V4) */
                   3430:    /*printf("Ndum[%d]=%d\n",i, Ndum[i]);*/
1.126     brouard  3431:    if((Ndum[i]!=0) && (i<=ncovcol)){
1.192     brouard  3432:      ij++;
1.145     brouard  3433:      /*printf("diff Ndum[%d]=%d\n",i, Ndum[i]);*/
                   3434:      Tvaraff[ij]=i; /*For printing (unclear) */
1.192     brouard  3435:    }else{
                   3436:        /* Tvaraff[ij]=0; */
                   3437:    }
1.126     brouard  3438:  }
1.192     brouard  3439:  /* ij--; */
1.144     brouard  3440:  cptcoveff=ij; /*Number of total covariates*/
1.145     brouard  3441: 
1.126     brouard  3442: }
                   3443: 
1.145     brouard  3444: 
1.126     brouard  3445: /*********** Health Expectancies ****************/
                   3446: 
1.127     brouard  3447: 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  3448: 
                   3449: {
                   3450:   /* Health expectancies, no variances */
1.164     brouard  3451:   int i, j, nhstepm, hstepm, h, nstepm;
1.126     brouard  3452:   int nhstepma, nstepma; /* Decreasing with age */
                   3453:   double age, agelim, hf;
                   3454:   double ***p3mat;
                   3455:   double eip;
                   3456: 
                   3457:   pstamp(ficreseij);
                   3458:   fprintf(ficreseij,"# (a) Life expectancies by health status at initial age and (b) health expectancies by health status at initial age\n");
                   3459:   fprintf(ficreseij,"# Age");
                   3460:   for(i=1; i<=nlstate;i++){
                   3461:     for(j=1; j<=nlstate;j++){
                   3462:       fprintf(ficreseij," e%1d%1d ",i,j);
                   3463:     }
                   3464:     fprintf(ficreseij," e%1d. ",i);
                   3465:   }
                   3466:   fprintf(ficreseij,"\n");
                   3467: 
                   3468:   
                   3469:   if(estepm < stepm){
                   3470:     printf ("Problem %d lower than %d\n",estepm, stepm);
                   3471:   }
                   3472:   else  hstepm=estepm;   
                   3473:   /* We compute the life expectancy from trapezoids spaced every estepm months
                   3474:    * This is mainly to measure the difference between two models: for example
                   3475:    * if stepm=24 months pijx are given only every 2 years and by summing them
                   3476:    * we are calculating an estimate of the Life Expectancy assuming a linear 
                   3477:    * progression in between and thus overestimating or underestimating according
                   3478:    * to the curvature of the survival function. If, for the same date, we 
                   3479:    * estimate the model with stepm=1 month, we can keep estepm to 24 months
                   3480:    * to compare the new estimate of Life expectancy with the same linear 
                   3481:    * hypothesis. A more precise result, taking into account a more precise
                   3482:    * curvature will be obtained if estepm is as small as stepm. */
                   3483: 
                   3484:   /* For example we decided to compute the life expectancy with the smallest unit */
                   3485:   /* hstepm beeing the number of stepms, if hstepm=1 the length of hstepm is stepm. 
                   3486:      nhstepm is the number of hstepm from age to agelim 
                   3487:      nstepm is the number of stepm from age to agelin. 
                   3488:      Look at hpijx to understand the reason of that which relies in memory size
                   3489:      and note for a fixed period like estepm months */
                   3490:   /* We decided (b) to get a life expectancy respecting the most precise curvature of the
                   3491:      survival function given by stepm (the optimization length). Unfortunately it
                   3492:      means that if the survival funtion is printed only each two years of age and if
                   3493:      you sum them up and add 1 year (area under the trapezoids) you won't get the same 
                   3494:      results. So we changed our mind and took the option of the best precision.
                   3495:   */
                   3496:   hstepm=hstepm/stepm; /* Typically in stepm units, if stepm=6 & estepm=24 , = 24/6 months = 4 */ 
                   3497: 
                   3498:   agelim=AGESUP;
                   3499:   /* If stepm=6 months */
                   3500:     /* Computed by stepm unit matrices, product of hstepm matrices, stored
                   3501:        in an array of nhstepm length: nhstepm=10, hstepm=4, stepm=6 months */
                   3502:     
                   3503: /* nhstepm age range expressed in number of stepm */
                   3504:   nstepm=(int) rint((agelim-bage)*YEARM/stepm); /* Biggest nstepm */
                   3505:   /* Typically if 20 years nstepm = 20*12/6=40 stepm */ 
                   3506:   /* if (stepm >= YEARM) hstepm=1;*/
                   3507:   nhstepm = nstepm/hstepm;/* Expressed in hstepm, typically nhstepm=40/4=10 */
                   3508:   p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   3509: 
                   3510:   for (age=bage; age<=fage; age ++){ 
                   3511:     nstepma=(int) rint((agelim-bage)*YEARM/stepm); /* Biggest nstepm */
                   3512:     /* Typically if 20 years nstepm = 20*12/6=40 stepm */ 
                   3513:     /* if (stepm >= YEARM) hstepm=1;*/
                   3514:     nhstepma = nstepma/hstepm;/* Expressed in hstepm, typically nhstepma=40/4=10 */
                   3515: 
                   3516:     /* If stepm=6 months */
                   3517:     /* Computed by stepm unit matrices, product of hstepma matrices, stored
                   3518:        in an array of nhstepma length: nhstepma=10, hstepm=4, stepm=6 months */
                   3519:     
                   3520:     hpxij(p3mat,nhstepma,age,hstepm,x,nlstate,stepm,oldm, savm, cij);  
                   3521:     
                   3522:     hf=hstepm*stepm/YEARM;  /* Duration of hstepm expressed in year unit. */
                   3523:     
                   3524:     printf("%d|",(int)age);fflush(stdout);
                   3525:     fprintf(ficlog,"%d|",(int)age);fflush(ficlog);
                   3526:     
                   3527:     /* Computing expectancies */
                   3528:     for(i=1; i<=nlstate;i++)
                   3529:       for(j=1; j<=nlstate;j++)
                   3530:        for (h=0, eij[i][j][(int)age]=0; h<=nhstepm-1; h++){
                   3531:          eij[i][j][(int)age] += (p3mat[i][j][h]+p3mat[i][j][h+1])/2.0*hf;
                   3532:          
                   3533:          /* 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]);*/
                   3534: 
                   3535:        }
                   3536: 
                   3537:     fprintf(ficreseij,"%3.0f",age );
                   3538:     for(i=1; i<=nlstate;i++){
                   3539:       eip=0;
                   3540:       for(j=1; j<=nlstate;j++){
                   3541:        eip +=eij[i][j][(int)age];
                   3542:        fprintf(ficreseij,"%9.4f", eij[i][j][(int)age] );
                   3543:       }
                   3544:       fprintf(ficreseij,"%9.4f", eip );
                   3545:     }
                   3546:     fprintf(ficreseij,"\n");
                   3547:     
                   3548:   }
                   3549:   free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   3550:   printf("\n");
                   3551:   fprintf(ficlog,"\n");
                   3552:   
                   3553: }
                   3554: 
1.127     brouard  3555: 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  3556: 
                   3557: {
                   3558:   /* Covariances of health expectancies eij and of total life expectancies according
                   3559:    to initial status i, ei. .
                   3560:   */
                   3561:   int i, j, nhstepm, hstepm, h, nstepm, k, cptj, cptj2, i2, j2, ij, ji;
                   3562:   int nhstepma, nstepma; /* Decreasing with age */
                   3563:   double age, agelim, hf;
                   3564:   double ***p3matp, ***p3matm, ***varhe;
                   3565:   double **dnewm,**doldm;
                   3566:   double *xp, *xm;
                   3567:   double **gp, **gm;
                   3568:   double ***gradg, ***trgradg;
                   3569:   int theta;
                   3570: 
                   3571:   double eip, vip;
                   3572: 
                   3573:   varhe=ma3x(1,nlstate*nlstate,1,nlstate*nlstate,(int) bage, (int) fage);
                   3574:   xp=vector(1,npar);
                   3575:   xm=vector(1,npar);
                   3576:   dnewm=matrix(1,nlstate*nlstate,1,npar);
                   3577:   doldm=matrix(1,nlstate*nlstate,1,nlstate*nlstate);
                   3578:   
                   3579:   pstamp(ficresstdeij);
                   3580:   fprintf(ficresstdeij,"# Health expectancies with standard errors\n");
                   3581:   fprintf(ficresstdeij,"# Age");
                   3582:   for(i=1; i<=nlstate;i++){
                   3583:     for(j=1; j<=nlstate;j++)
                   3584:       fprintf(ficresstdeij," e%1d%1d (SE)",i,j);
                   3585:     fprintf(ficresstdeij," e%1d. ",i);
                   3586:   }
                   3587:   fprintf(ficresstdeij,"\n");
                   3588: 
                   3589:   pstamp(ficrescveij);
                   3590:   fprintf(ficrescveij,"# Subdiagonal matrix of covariances of health expectancies by age: cov(eij,ekl)\n");
                   3591:   fprintf(ficrescveij,"# Age");
                   3592:   for(i=1; i<=nlstate;i++)
                   3593:     for(j=1; j<=nlstate;j++){
                   3594:       cptj= (j-1)*nlstate+i;
                   3595:       for(i2=1; i2<=nlstate;i2++)
                   3596:        for(j2=1; j2<=nlstate;j2++){
                   3597:          cptj2= (j2-1)*nlstate+i2;
                   3598:          if(cptj2 <= cptj)
                   3599:            fprintf(ficrescveij,"  %1d%1d,%1d%1d",i,j,i2,j2);
                   3600:        }
                   3601:     }
                   3602:   fprintf(ficrescveij,"\n");
                   3603:   
                   3604:   if(estepm < stepm){
                   3605:     printf ("Problem %d lower than %d\n",estepm, stepm);
                   3606:   }
                   3607:   else  hstepm=estepm;   
                   3608:   /* We compute the life expectancy from trapezoids spaced every estepm months
                   3609:    * This is mainly to measure the difference between two models: for example
                   3610:    * if stepm=24 months pijx are given only every 2 years and by summing them
                   3611:    * we are calculating an estimate of the Life Expectancy assuming a linear 
                   3612:    * progression in between and thus overestimating or underestimating according
                   3613:    * to the curvature of the survival function. If, for the same date, we 
                   3614:    * estimate the model with stepm=1 month, we can keep estepm to 24 months
                   3615:    * to compare the new estimate of Life expectancy with the same linear 
                   3616:    * hypothesis. A more precise result, taking into account a more precise
                   3617:    * curvature will be obtained if estepm is as small as stepm. */
                   3618: 
                   3619:   /* For example we decided to compute the life expectancy with the smallest unit */
                   3620:   /* hstepm beeing the number of stepms, if hstepm=1 the length of hstepm is stepm. 
                   3621:      nhstepm is the number of hstepm from age to agelim 
                   3622:      nstepm is the number of stepm from age to agelin. 
                   3623:      Look at hpijx to understand the reason of that which relies in memory size
                   3624:      and note for a fixed period like estepm months */
                   3625:   /* We decided (b) to get a life expectancy respecting the most precise curvature of the
                   3626:      survival function given by stepm (the optimization length). Unfortunately it
                   3627:      means that if the survival funtion is printed only each two years of age and if
                   3628:      you sum them up and add 1 year (area under the trapezoids) you won't get the same 
                   3629:      results. So we changed our mind and took the option of the best precision.
                   3630:   */
                   3631:   hstepm=hstepm/stepm; /* Typically in stepm units, if stepm=6 & estepm=24 , = 24/6 months = 4 */ 
                   3632: 
                   3633:   /* If stepm=6 months */
                   3634:   /* nhstepm age range expressed in number of stepm */
                   3635:   agelim=AGESUP;
                   3636:   nstepm=(int) rint((agelim-bage)*YEARM/stepm); 
                   3637:   /* Typically if 20 years nstepm = 20*12/6=40 stepm */ 
                   3638:   /* if (stepm >= YEARM) hstepm=1;*/
                   3639:   nhstepm = nstepm/hstepm;/* Expressed in hstepm, typically nhstepm=40/4=10 */
                   3640:   
                   3641:   p3matp=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   3642:   p3matm=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   3643:   gradg=ma3x(0,nhstepm,1,npar,1,nlstate*nlstate);
                   3644:   trgradg =ma3x(0,nhstepm,1,nlstate*nlstate,1,npar);
                   3645:   gp=matrix(0,nhstepm,1,nlstate*nlstate);
                   3646:   gm=matrix(0,nhstepm,1,nlstate*nlstate);
                   3647: 
                   3648:   for (age=bage; age<=fage; age ++){ 
                   3649:     nstepma=(int) rint((agelim-bage)*YEARM/stepm); /* Biggest nstepm */
                   3650:     /* Typically if 20 years nstepm = 20*12/6=40 stepm */ 
                   3651:     /* if (stepm >= YEARM) hstepm=1;*/
                   3652:     nhstepma = nstepma/hstepm;/* Expressed in hstepm, typically nhstepma=40/4=10 */
                   3653: 
                   3654:     /* If stepm=6 months */
                   3655:     /* Computed by stepm unit matrices, product of hstepma matrices, stored
                   3656:        in an array of nhstepma length: nhstepma=10, hstepm=4, stepm=6 months */
                   3657:     
                   3658:     hf=hstepm*stepm/YEARM;  /* Duration of hstepm expressed in year unit. */
                   3659: 
                   3660:     /* Computing  Variances of health expectancies */
                   3661:     /* Gradient is computed with plus gp and minus gm. Code is duplicated in order to
                   3662:        decrease memory allocation */
                   3663:     for(theta=1; theta <=npar; theta++){
                   3664:       for(i=1; i<=npar; i++){ 
                   3665:        xp[i] = x[i] + (i==theta ?delti[theta]:0);
                   3666:        xm[i] = x[i] - (i==theta ?delti[theta]:0);
                   3667:       }
                   3668:       hpxij(p3matp,nhstepm,age,hstepm,xp,nlstate,stepm,oldm,savm, cij);  
                   3669:       hpxij(p3matm,nhstepm,age,hstepm,xm,nlstate,stepm,oldm,savm, cij);  
                   3670:   
                   3671:       for(j=1; j<= nlstate; j++){
                   3672:        for(i=1; i<=nlstate; i++){
                   3673:          for(h=0; h<=nhstepm-1; h++){
                   3674:            gp[h][(j-1)*nlstate + i] = (p3matp[i][j][h]+p3matp[i][j][h+1])/2.;
                   3675:            gm[h][(j-1)*nlstate + i] = (p3matm[i][j][h]+p3matm[i][j][h+1])/2.;
                   3676:          }
                   3677:        }
                   3678:       }
                   3679:      
                   3680:       for(ij=1; ij<= nlstate*nlstate; ij++)
                   3681:        for(h=0; h<=nhstepm-1; h++){
                   3682:          gradg[h][theta][ij]= (gp[h][ij]-gm[h][ij])/2./delti[theta];
                   3683:        }
                   3684:     }/* End theta */
                   3685:     
                   3686:     
                   3687:     for(h=0; h<=nhstepm-1; h++)
                   3688:       for(j=1; j<=nlstate*nlstate;j++)
                   3689:        for(theta=1; theta <=npar; theta++)
                   3690:          trgradg[h][j][theta]=gradg[h][theta][j];
                   3691:     
                   3692: 
                   3693:      for(ij=1;ij<=nlstate*nlstate;ij++)
                   3694:       for(ji=1;ji<=nlstate*nlstate;ji++)
                   3695:        varhe[ij][ji][(int)age] =0.;
                   3696: 
                   3697:      printf("%d|",(int)age);fflush(stdout);
                   3698:      fprintf(ficlog,"%d|",(int)age);fflush(ficlog);
                   3699:      for(h=0;h<=nhstepm-1;h++){
                   3700:       for(k=0;k<=nhstepm-1;k++){
                   3701:        matprod2(dnewm,trgradg[h],1,nlstate*nlstate,1,npar,1,npar,matcov);
                   3702:        matprod2(doldm,dnewm,1,nlstate*nlstate,1,npar,1,nlstate*nlstate,gradg[k]);
                   3703:        for(ij=1;ij<=nlstate*nlstate;ij++)
                   3704:          for(ji=1;ji<=nlstate*nlstate;ji++)
                   3705:            varhe[ij][ji][(int)age] += doldm[ij][ji]*hf*hf;
                   3706:       }
                   3707:     }
                   3708: 
                   3709:     /* Computing expectancies */
                   3710:     hpxij(p3matm,nhstepm,age,hstepm,x,nlstate,stepm,oldm, savm, cij);  
                   3711:     for(i=1; i<=nlstate;i++)
                   3712:       for(j=1; j<=nlstate;j++)
                   3713:        for (h=0, eij[i][j][(int)age]=0; h<=nhstepm-1; h++){
                   3714:          eij[i][j][(int)age] += (p3matm[i][j][h]+p3matm[i][j][h+1])/2.0*hf;
                   3715:          
                   3716:          /* 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]);*/
                   3717: 
                   3718:        }
                   3719: 
                   3720:     fprintf(ficresstdeij,"%3.0f",age );
                   3721:     for(i=1; i<=nlstate;i++){
                   3722:       eip=0.;
                   3723:       vip=0.;
                   3724:       for(j=1; j<=nlstate;j++){
                   3725:        eip += eij[i][j][(int)age];
                   3726:        for(k=1; k<=nlstate;k++) /* Sum on j and k of cov(eij,eik) */
                   3727:          vip += varhe[(j-1)*nlstate+i][(k-1)*nlstate+i][(int)age];
                   3728:        fprintf(ficresstdeij," %9.4f (%.4f)", eij[i][j][(int)age], sqrt(varhe[(j-1)*nlstate+i][(j-1)*nlstate+i][(int)age]) );
                   3729:       }
                   3730:       fprintf(ficresstdeij," %9.4f (%.4f)", eip, sqrt(vip));
                   3731:     }
                   3732:     fprintf(ficresstdeij,"\n");
                   3733: 
                   3734:     fprintf(ficrescveij,"%3.0f",age );
                   3735:     for(i=1; i<=nlstate;i++)
                   3736:       for(j=1; j<=nlstate;j++){
                   3737:        cptj= (j-1)*nlstate+i;
                   3738:        for(i2=1; i2<=nlstate;i2++)
                   3739:          for(j2=1; j2<=nlstate;j2++){
                   3740:            cptj2= (j2-1)*nlstate+i2;
                   3741:            if(cptj2 <= cptj)
                   3742:              fprintf(ficrescveij," %.4f", varhe[cptj][cptj2][(int)age]);
                   3743:          }
                   3744:       }
                   3745:     fprintf(ficrescveij,"\n");
                   3746:    
                   3747:   }
                   3748:   free_matrix(gm,0,nhstepm,1,nlstate*nlstate);
                   3749:   free_matrix(gp,0,nhstepm,1,nlstate*nlstate);
                   3750:   free_ma3x(gradg,0,nhstepm,1,npar,1,nlstate*nlstate);
                   3751:   free_ma3x(trgradg,0,nhstepm,1,nlstate*nlstate,1,npar);
                   3752:   free_ma3x(p3matm,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   3753:   free_ma3x(p3matp,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   3754:   printf("\n");
                   3755:   fprintf(ficlog,"\n");
                   3756: 
                   3757:   free_vector(xm,1,npar);
                   3758:   free_vector(xp,1,npar);
                   3759:   free_matrix(dnewm,1,nlstate*nlstate,1,npar);
                   3760:   free_matrix(doldm,1,nlstate*nlstate,1,nlstate*nlstate);
                   3761:   free_ma3x(varhe,1,nlstate*nlstate,1,nlstate*nlstate,(int) bage, (int)fage);
                   3762: }
                   3763: 
                   3764: /************ Variance ******************/
                   3765: 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[])
                   3766: {
                   3767:   /* Variance of health expectancies */
                   3768:   /*  double **prevalim(double **prlim, int nlstate, double *xp, double age, double **oldm, double ** savm,double ftolpl);*/
                   3769:   /* double **newm;*/
1.169     brouard  3770:   /* int movingaverage(double ***probs, double bage,double fage, double ***mobaverage, int mobilav)*/
                   3771:   
                   3772:   int movingaverage();
1.126     brouard  3773:   double **dnewm,**doldm;
                   3774:   double **dnewmp,**doldmp;
                   3775:   int i, j, nhstepm, hstepm, h, nstepm ;
1.164     brouard  3776:   int k;
1.126     brouard  3777:   double *xp;
                   3778:   double **gp, **gm;  /* for var eij */
                   3779:   double ***gradg, ***trgradg; /*for var eij */
                   3780:   double **gradgp, **trgradgp; /* for var p point j */
                   3781:   double *gpp, *gmp; /* for var p point j */
                   3782:   double **varppt; /* for var p point j nlstate to nlstate+ndeath */
                   3783:   double ***p3mat;
                   3784:   double age,agelim, hf;
                   3785:   double ***mobaverage;
                   3786:   int theta;
                   3787:   char digit[4];
                   3788:   char digitp[25];
                   3789: 
                   3790:   char fileresprobmorprev[FILENAMELENGTH];
                   3791: 
                   3792:   if(popbased==1){
                   3793:     if(mobilav!=0)
                   3794:       strcpy(digitp,"-populbased-mobilav-");
                   3795:     else strcpy(digitp,"-populbased-nomobil-");
                   3796:   }
                   3797:   else 
                   3798:     strcpy(digitp,"-stablbased-");
                   3799: 
                   3800:   if (mobilav!=0) {
                   3801:     mobaverage= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
                   3802:     if (movingaverage(probs, bage, fage, mobaverage,mobilav)!=0){
                   3803:       fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav);
                   3804:       printf(" Error in movingaverage mobilav=%d\n",mobilav);
                   3805:     }
                   3806:   }
                   3807: 
                   3808:   strcpy(fileresprobmorprev,"prmorprev"); 
                   3809:   sprintf(digit,"%-d",ij);
                   3810:   /*printf("DIGIT=%s, ij=%d ijr=%-d|\n",digit, ij,ij);*/
                   3811:   strcat(fileresprobmorprev,digit); /* Tvar to be done */
                   3812:   strcat(fileresprobmorprev,digitp); /* Popbased or not, mobilav or not */
                   3813:   strcat(fileresprobmorprev,fileres);
                   3814:   if((ficresprobmorprev=fopen(fileresprobmorprev,"w"))==NULL) {
                   3815:     printf("Problem with resultfile: %s\n", fileresprobmorprev);
                   3816:     fprintf(ficlog,"Problem with resultfile: %s\n", fileresprobmorprev);
                   3817:   }
                   3818:   printf("Computing total mortality p.j=w1*p1j+w2*p2j+..: result on file '%s' \n",fileresprobmorprev);
                   3819:  
                   3820:   fprintf(ficlog,"Computing total mortality p.j=w1*p1j+w2*p2j+..: result on file '%s' \n",fileresprobmorprev);
                   3821:   pstamp(ficresprobmorprev);
                   3822:   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);
                   3823:   fprintf(ficresprobmorprev,"# Age cov=%-d",ij);
                   3824:   for(j=nlstate+1; j<=(nlstate+ndeath);j++){
                   3825:     fprintf(ficresprobmorprev," p.%-d SE",j);
                   3826:     for(i=1; i<=nlstate;i++)
                   3827:       fprintf(ficresprobmorprev," w%1d p%-d%-d",i,i,j);
                   3828:   }  
                   3829:   fprintf(ficresprobmorprev,"\n");
                   3830:   fprintf(ficgp,"\n# Routine varevsij");
                   3831:   /* fprintf(fichtm, "#Local time at start: %s", strstart);*/
                   3832:   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");
                   3833:   fprintf(fichtm,"\n<br>%s  <br>\n",digitp);
                   3834: /*   } */
                   3835:   varppt = matrix(nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);
                   3836:   pstamp(ficresvij);
                   3837:   fprintf(ficresvij,"# Variance and covariance of health expectancies e.j \n#  (weighted average of eij where weights are ");
                   3838:   if(popbased==1)
1.128     brouard  3839:     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  3840:   else
                   3841:     fprintf(ficresvij,"the age specific period (stable) prevalences in each health state \n");
                   3842:   fprintf(ficresvij,"# Age");
                   3843:   for(i=1; i<=nlstate;i++)
                   3844:     for(j=1; j<=nlstate;j++)
                   3845:       fprintf(ficresvij," Cov(e.%1d, e.%1d)",i,j);
                   3846:   fprintf(ficresvij,"\n");
                   3847: 
                   3848:   xp=vector(1,npar);
                   3849:   dnewm=matrix(1,nlstate,1,npar);
                   3850:   doldm=matrix(1,nlstate,1,nlstate);
                   3851:   dnewmp= matrix(nlstate+1,nlstate+ndeath,1,npar);
                   3852:   doldmp= matrix(nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);
                   3853: 
                   3854:   gradgp=matrix(1,npar,nlstate+1,nlstate+ndeath);
                   3855:   gpp=vector(nlstate+1,nlstate+ndeath);
                   3856:   gmp=vector(nlstate+1,nlstate+ndeath);
                   3857:   trgradgp =matrix(nlstate+1,nlstate+ndeath,1,npar); /* mu or p point j*/
                   3858:   
                   3859:   if(estepm < stepm){
                   3860:     printf ("Problem %d lower than %d\n",estepm, stepm);
                   3861:   }
                   3862:   else  hstepm=estepm;   
                   3863:   /* For example we decided to compute the life expectancy with the smallest unit */
                   3864:   /* hstepm beeing the number of stepms, if hstepm=1 the length of hstepm is stepm. 
                   3865:      nhstepm is the number of hstepm from age to agelim 
                   3866:      nstepm is the number of stepm from age to agelin. 
1.128     brouard  3867:      Look at function hpijx to understand why (it is linked to memory size questions) */
1.126     brouard  3868:   /* We decided (b) to get a life expectancy respecting the most precise curvature of the
                   3869:      survival function given by stepm (the optimization length). Unfortunately it
                   3870:      means that if the survival funtion is printed every two years of age and if
                   3871:      you sum them up and add 1 year (area under the trapezoids) you won't get the same 
                   3872:      results. So we changed our mind and took the option of the best precision.
                   3873:   */
                   3874:   hstepm=hstepm/stepm; /* Typically in stepm units, if stepm=6 & estepm=24 , = 24/6 months = 4 */ 
                   3875:   agelim = AGESUP;
                   3876:   for (age=bage; age<=fage; age ++){ /* If stepm=6 months */
                   3877:     nstepm=(int) rint((agelim-age)*YEARM/stepm); /* Typically 20 years = 20*12/6=40 */ 
                   3878:     nhstepm = nstepm/hstepm;/* Expressed in hstepm, typically nhstepm=40/4=10 */
                   3879:     p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   3880:     gradg=ma3x(0,nhstepm,1,npar,1,nlstate);
                   3881:     gp=matrix(0,nhstepm,1,nlstate);
                   3882:     gm=matrix(0,nhstepm,1,nlstate);
                   3883: 
                   3884: 
                   3885:     for(theta=1; theta <=npar; theta++){
                   3886:       for(i=1; i<=npar; i++){ /* Computes gradient x + delta*/
                   3887:        xp[i] = x[i] + (i==theta ?delti[theta]:0);
                   3888:       }
                   3889:       hpxij(p3mat,nhstepm,age,hstepm,xp,nlstate,stepm,oldm,savm, ij);  
                   3890:       prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ij);
                   3891: 
                   3892:       if (popbased==1) {
                   3893:        if(mobilav ==0){
                   3894:          for(i=1; i<=nlstate;i++)
                   3895:            prlim[i][i]=probs[(int)age][i][ij];
                   3896:        }else{ /* mobilav */ 
                   3897:          for(i=1; i<=nlstate;i++)
                   3898:            prlim[i][i]=mobaverage[(int)age][i][ij];
                   3899:        }
                   3900:       }
                   3901:   
                   3902:       for(j=1; j<= nlstate; j++){
                   3903:        for(h=0; h<=nhstepm; h++){
                   3904:          for(i=1, gp[h][j]=0.;i<=nlstate;i++)
                   3905:            gp[h][j] += prlim[i][i]*p3mat[i][j][h];
                   3906:        }
                   3907:       }
                   3908:       /* This for computing probability of death (h=1 means
                   3909:          computed over hstepm matrices product = hstepm*stepm months) 
                   3910:          as a weighted average of prlim.
                   3911:       */
                   3912:       for(j=nlstate+1;j<=nlstate+ndeath;j++){
                   3913:        for(i=1,gpp[j]=0.; i<= nlstate; i++)
                   3914:          gpp[j] += prlim[i][i]*p3mat[i][j][1];
                   3915:       }    
                   3916:       /* end probability of death */
                   3917: 
                   3918:       for(i=1; i<=npar; i++) /* Computes gradient x - delta */
                   3919:        xp[i] = x[i] - (i==theta ?delti[theta]:0);
                   3920:       hpxij(p3mat,nhstepm,age,hstepm,xp,nlstate,stepm,oldm,savm, ij);  
                   3921:       prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ij);
                   3922:  
                   3923:       if (popbased==1) {
                   3924:        if(mobilav ==0){
                   3925:          for(i=1; i<=nlstate;i++)
                   3926:            prlim[i][i]=probs[(int)age][i][ij];
                   3927:        }else{ /* mobilav */ 
                   3928:          for(i=1; i<=nlstate;i++)
                   3929:            prlim[i][i]=mobaverage[(int)age][i][ij];
                   3930:        }
                   3931:       }
                   3932: 
1.128     brouard  3933:       for(j=1; j<= nlstate; j++){  /* Sum of wi * eij = e.j */
1.126     brouard  3934:        for(h=0; h<=nhstepm; h++){
                   3935:          for(i=1, gm[h][j]=0.;i<=nlstate;i++)
                   3936:            gm[h][j] += prlim[i][i]*p3mat[i][j][h];
                   3937:        }
                   3938:       }
                   3939:       /* This for computing probability of death (h=1 means
                   3940:          computed over hstepm matrices product = hstepm*stepm months) 
                   3941:          as a weighted average of prlim.
                   3942:       */
                   3943:       for(j=nlstate+1;j<=nlstate+ndeath;j++){
                   3944:        for(i=1,gmp[j]=0.; i<= nlstate; i++)
                   3945:          gmp[j] += prlim[i][i]*p3mat[i][j][1];
                   3946:       }    
                   3947:       /* end probability of death */
                   3948: 
                   3949:       for(j=1; j<= nlstate; j++) /* vareij */
                   3950:        for(h=0; h<=nhstepm; h++){
                   3951:          gradg[h][theta][j]= (gp[h][j]-gm[h][j])/2./delti[theta];
                   3952:        }
                   3953: 
                   3954:       for(j=nlstate+1; j<= nlstate+ndeath; j++){ /* var mu */
                   3955:        gradgp[theta][j]= (gpp[j]-gmp[j])/2./delti[theta];
                   3956:       }
                   3957: 
                   3958:     } /* End theta */
                   3959: 
                   3960:     trgradg =ma3x(0,nhstepm,1,nlstate,1,npar); /* veij */
                   3961: 
                   3962:     for(h=0; h<=nhstepm; h++) /* veij */
                   3963:       for(j=1; j<=nlstate;j++)
                   3964:        for(theta=1; theta <=npar; theta++)
                   3965:          trgradg[h][j][theta]=gradg[h][theta][j];
                   3966: 
                   3967:     for(j=nlstate+1; j<=nlstate+ndeath;j++) /* mu */
                   3968:       for(theta=1; theta <=npar; theta++)
                   3969:        trgradgp[j][theta]=gradgp[theta][j];
                   3970:   
                   3971: 
                   3972:     hf=hstepm*stepm/YEARM;  /* Duration of hstepm expressed in year unit. */
                   3973:     for(i=1;i<=nlstate;i++)
                   3974:       for(j=1;j<=nlstate;j++)
                   3975:        vareij[i][j][(int)age] =0.;
                   3976: 
                   3977:     for(h=0;h<=nhstepm;h++){
                   3978:       for(k=0;k<=nhstepm;k++){
                   3979:        matprod2(dnewm,trgradg[h],1,nlstate,1,npar,1,npar,matcov);
                   3980:        matprod2(doldm,dnewm,1,nlstate,1,npar,1,nlstate,gradg[k]);
                   3981:        for(i=1;i<=nlstate;i++)
                   3982:          for(j=1;j<=nlstate;j++)
                   3983:            vareij[i][j][(int)age] += doldm[i][j]*hf*hf;
                   3984:       }
                   3985:     }
                   3986:   
                   3987:     /* pptj */
                   3988:     matprod2(dnewmp,trgradgp,nlstate+1,nlstate+ndeath,1,npar,1,npar,matcov);
                   3989:     matprod2(doldmp,dnewmp,nlstate+1,nlstate+ndeath,1,npar,nlstate+1,nlstate+ndeath,gradgp);
                   3990:     for(j=nlstate+1;j<=nlstate+ndeath;j++)
                   3991:       for(i=nlstate+1;i<=nlstate+ndeath;i++)
                   3992:        varppt[j][i]=doldmp[j][i];
                   3993:     /* end ppptj */
                   3994:     /*  x centered again */
                   3995:     hpxij(p3mat,nhstepm,age,hstepm,x,nlstate,stepm,oldm,savm, ij);  
                   3996:     prevalim(prlim,nlstate,x,age,oldm,savm,ftolpl,ij);
                   3997:  
                   3998:     if (popbased==1) {
                   3999:       if(mobilav ==0){
                   4000:        for(i=1; i<=nlstate;i++)
                   4001:          prlim[i][i]=probs[(int)age][i][ij];
                   4002:       }else{ /* mobilav */ 
                   4003:        for(i=1; i<=nlstate;i++)
                   4004:          prlim[i][i]=mobaverage[(int)age][i][ij];
                   4005:       }
                   4006:     }
                   4007:              
                   4008:     /* This for computing probability of death (h=1 means
                   4009:        computed over hstepm (estepm) matrices product = hstepm*stepm months) 
                   4010:        as a weighted average of prlim.
                   4011:     */
                   4012:     for(j=nlstate+1;j<=nlstate+ndeath;j++){
                   4013:       for(i=1,gmp[j]=0.;i<= nlstate; i++) 
                   4014:        gmp[j] += prlim[i][i]*p3mat[i][j][1]; 
                   4015:     }    
                   4016:     /* end probability of death */
                   4017: 
                   4018:     fprintf(ficresprobmorprev,"%3d %d ",(int) age, ij);
                   4019:     for(j=nlstate+1; j<=(nlstate+ndeath);j++){
                   4020:       fprintf(ficresprobmorprev," %11.3e %11.3e",gmp[j], sqrt(varppt[j][j]));
                   4021:       for(i=1; i<=nlstate;i++){
                   4022:        fprintf(ficresprobmorprev," %11.3e %11.3e ",prlim[i][i],p3mat[i][j][1]);
                   4023:       }
                   4024:     } 
                   4025:     fprintf(ficresprobmorprev,"\n");
                   4026: 
                   4027:     fprintf(ficresvij,"%.0f ",age );
                   4028:     for(i=1; i<=nlstate;i++)
                   4029:       for(j=1; j<=nlstate;j++){
                   4030:        fprintf(ficresvij," %.4f", vareij[i][j][(int)age]);
                   4031:       }
                   4032:     fprintf(ficresvij,"\n");
                   4033:     free_matrix(gp,0,nhstepm,1,nlstate);
                   4034:     free_matrix(gm,0,nhstepm,1,nlstate);
                   4035:     free_ma3x(gradg,0,nhstepm,1,npar,1,nlstate);
                   4036:     free_ma3x(trgradg,0,nhstepm,1,nlstate,1,npar);
                   4037:     free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   4038:   } /* End age */
                   4039:   free_vector(gpp,nlstate+1,nlstate+ndeath);
                   4040:   free_vector(gmp,nlstate+1,nlstate+ndeath);
                   4041:   free_matrix(gradgp,1,npar,nlstate+1,nlstate+ndeath);
                   4042:   free_matrix(trgradgp,nlstate+1,nlstate+ndeath,1,npar); /* mu or p point j*/
1.145     brouard  4043:   fprintf(ficgp,"\nunset parametric;unset label; set ter png small size 320, 240");
1.126     brouard  4044:   /* for(j=nlstate+1; j<= nlstate+ndeath; j++){ *//* Only the first actually */
1.131     brouard  4045:   fprintf(ficgp,"\n set log y; unset log x;set xlabel \"Age\"; set ylabel \"Force of mortality (year-1)\";");
1.126     brouard  4046: /*   fprintf(ficgp,"\n plot \"%s\"  u 1:($3*%6.3f) not w l 1 ",fileresprobmorprev,YEARM/estepm); */
                   4047: /*   fprintf(ficgp,"\n replot \"%s\"  u 1:(($3+1.96*$4)*%6.3f) t \"95\%% interval\" w l 2 ",fileresprobmorprev,YEARM/estepm); */
                   4048: /*   fprintf(ficgp,"\n replot \"%s\"  u 1:(($3-1.96*$4)*%6.3f) not w l 2 ",fileresprobmorprev,YEARM/estepm); */
1.145     brouard  4049:   fprintf(ficgp,"\n plot \"%s\"  u 1:($3) not w l lt 1 ",subdirf(fileresprobmorprev));
1.170     brouard  4050:   fprintf(ficgp,"\n replot \"%s\"  u 1:(($3+1.96*$4)) t \"95%% interval\" w l lt 2 ",subdirf(fileresprobmorprev));
1.145     brouard  4051:   fprintf(ficgp,"\n replot \"%s\"  u 1:(($3-1.96*$4)) not w l lt 2 ",subdirf(fileresprobmorprev));
1.126     brouard  4052:   fprintf(fichtm,"\n<br> File (multiple files are possible if covariates are present): <A href=\"%s\">%s</a>\n",subdirf(fileresprobmorprev),subdirf(fileresprobmorprev));
                   4053:   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);
                   4054:   /*  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);
                   4055: */
                   4056: /*   fprintf(ficgp,"\nset out \"varmuptjgr%s%s%s.png\";replot;",digitp,optionfilefiname,digit); */
                   4057:   fprintf(ficgp,"\nset out \"%s%s.png\";replot;\n",subdirf3(optionfilefiname,"varmuptjgr",digitp),digit);
                   4058: 
                   4059:   free_vector(xp,1,npar);
                   4060:   free_matrix(doldm,1,nlstate,1,nlstate);
                   4061:   free_matrix(dnewm,1,nlstate,1,npar);
                   4062:   free_matrix(doldmp,nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);
                   4063:   free_matrix(dnewmp,nlstate+1,nlstate+ndeath,1,npar);
                   4064:   free_matrix(varppt,nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);
                   4065:   if (mobilav!=0) free_ma3x(mobaverage,1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
                   4066:   fclose(ficresprobmorprev);
                   4067:   fflush(ficgp);
                   4068:   fflush(fichtm); 
                   4069: }  /* end varevsij */
                   4070: 
                   4071: /************ Variance of prevlim ******************/
                   4072: 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[])
                   4073: {
                   4074:   /* Variance of prevalence limit */
                   4075:   /*  double **prevalim(double **prlim, int nlstate, double *xp, double age, double **oldm, double **savm,double ftolpl);*/
1.164     brouard  4076: 
1.126     brouard  4077:   double **dnewm,**doldm;
                   4078:   int i, j, nhstepm, hstepm;
                   4079:   double *xp;
                   4080:   double *gp, *gm;
                   4081:   double **gradg, **trgradg;
                   4082:   double age,agelim;
                   4083:   int theta;
                   4084:   
                   4085:   pstamp(ficresvpl);
                   4086:   fprintf(ficresvpl,"# Standard deviation of period (stable) prevalences \n");
                   4087:   fprintf(ficresvpl,"# Age");
                   4088:   for(i=1; i<=nlstate;i++)
                   4089:       fprintf(ficresvpl," %1d-%1d",i,i);
                   4090:   fprintf(ficresvpl,"\n");
                   4091: 
                   4092:   xp=vector(1,npar);
                   4093:   dnewm=matrix(1,nlstate,1,npar);
                   4094:   doldm=matrix(1,nlstate,1,nlstate);
                   4095:   
                   4096:   hstepm=1*YEARM; /* Every year of age */
                   4097:   hstepm=hstepm/stepm; /* Typically in stepm units, if j= 2 years, = 2/6 months = 4 */ 
                   4098:   agelim = AGESUP;
                   4099:   for (age=bage; age<=fage; age ++){ /* If stepm=6 months */
                   4100:     nhstepm=(int) rint((agelim-age)*YEARM/stepm); /* Typically 20 years = 20*12/6=40 */ 
                   4101:     if (stepm >= YEARM) hstepm=1;
                   4102:     nhstepm = nhstepm/hstepm; /* Typically 40/4=10 */
                   4103:     gradg=matrix(1,npar,1,nlstate);
                   4104:     gp=vector(1,nlstate);
                   4105:     gm=vector(1,nlstate);
                   4106: 
                   4107:     for(theta=1; theta <=npar; theta++){
                   4108:       for(i=1; i<=npar; i++){ /* Computes gradient */
                   4109:        xp[i] = x[i] + (i==theta ?delti[theta]:0);
                   4110:       }
                   4111:       prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ij);
                   4112:       for(i=1;i<=nlstate;i++)
                   4113:        gp[i] = prlim[i][i];
                   4114:     
                   4115:       for(i=1; i<=npar; i++) /* Computes gradient */
                   4116:        xp[i] = x[i] - (i==theta ?delti[theta]:0);
                   4117:       prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ij);
                   4118:       for(i=1;i<=nlstate;i++)
                   4119:        gm[i] = prlim[i][i];
                   4120: 
                   4121:       for(i=1;i<=nlstate;i++)
                   4122:        gradg[theta][i]= (gp[i]-gm[i])/2./delti[theta];
                   4123:     } /* End theta */
                   4124: 
                   4125:     trgradg =matrix(1,nlstate,1,npar);
                   4126: 
                   4127:     for(j=1; j<=nlstate;j++)
                   4128:       for(theta=1; theta <=npar; theta++)
                   4129:        trgradg[j][theta]=gradg[theta][j];
                   4130: 
                   4131:     for(i=1;i<=nlstate;i++)
                   4132:       varpl[i][(int)age] =0.;
                   4133:     matprod2(dnewm,trgradg,1,nlstate,1,npar,1,npar,matcov);
                   4134:     matprod2(doldm,dnewm,1,nlstate,1,npar,1,nlstate,gradg);
                   4135:     for(i=1;i<=nlstate;i++)
                   4136:       varpl[i][(int)age] = doldm[i][i]; /* Covariances are useless */
                   4137: 
                   4138:     fprintf(ficresvpl,"%.0f ",age );
                   4139:     for(i=1; i<=nlstate;i++)
                   4140:       fprintf(ficresvpl," %.5f (%.5f)",prlim[i][i],sqrt(varpl[i][(int)age]));
                   4141:     fprintf(ficresvpl,"\n");
                   4142:     free_vector(gp,1,nlstate);
                   4143:     free_vector(gm,1,nlstate);
                   4144:     free_matrix(gradg,1,npar,1,nlstate);
                   4145:     free_matrix(trgradg,1,nlstate,1,npar);
                   4146:   } /* End age */
                   4147: 
                   4148:   free_vector(xp,1,npar);
                   4149:   free_matrix(doldm,1,nlstate,1,npar);
                   4150:   free_matrix(dnewm,1,nlstate,1,nlstate);
                   4151: 
                   4152: }
                   4153: 
                   4154: /************ Variance of one-step probabilities  ******************/
                   4155: 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[])
                   4156: {
1.164     brouard  4157:   int i, j=0,  k1, l1, tj;
1.126     brouard  4158:   int k2, l2, j1,  z1;
1.164     brouard  4159:   int k=0, l;
1.145     brouard  4160:   int first=1, first1, first2;
1.126     brouard  4161:   double cv12, mu1, mu2, lc1, lc2, v12, v21, v11, v22,v1,v2, c12, tnalp;
                   4162:   double **dnewm,**doldm;
                   4163:   double *xp;
                   4164:   double *gp, *gm;
                   4165:   double **gradg, **trgradg;
                   4166:   double **mu;
1.164     brouard  4167:   double age, cov[NCOVMAX+1];
1.126     brouard  4168:   double std=2.0; /* Number of standard deviation wide of confidence ellipsoids */
                   4169:   int theta;
                   4170:   char fileresprob[FILENAMELENGTH];
                   4171:   char fileresprobcov[FILENAMELENGTH];
                   4172:   char fileresprobcor[FILENAMELENGTH];
                   4173:   double ***varpij;
                   4174: 
                   4175:   strcpy(fileresprob,"prob"); 
                   4176:   strcat(fileresprob,fileres);
                   4177:   if((ficresprob=fopen(fileresprob,"w"))==NULL) {
                   4178:     printf("Problem with resultfile: %s\n", fileresprob);
                   4179:     fprintf(ficlog,"Problem with resultfile: %s\n", fileresprob);
                   4180:   }
                   4181:   strcpy(fileresprobcov,"probcov"); 
                   4182:   strcat(fileresprobcov,fileres);
                   4183:   if((ficresprobcov=fopen(fileresprobcov,"w"))==NULL) {
                   4184:     printf("Problem with resultfile: %s\n", fileresprobcov);
                   4185:     fprintf(ficlog,"Problem with resultfile: %s\n", fileresprobcov);
                   4186:   }
                   4187:   strcpy(fileresprobcor,"probcor"); 
                   4188:   strcat(fileresprobcor,fileres);
                   4189:   if((ficresprobcor=fopen(fileresprobcor,"w"))==NULL) {
                   4190:     printf("Problem with resultfile: %s\n", fileresprobcor);
                   4191:     fprintf(ficlog,"Problem with resultfile: %s\n", fileresprobcor);
                   4192:   }
                   4193:   printf("Computing standard deviation of one-step probabilities: result on file '%s' \n",fileresprob);
                   4194:   fprintf(ficlog,"Computing standard deviation of one-step probabilities: result on file '%s' \n",fileresprob);
                   4195:   printf("Computing matrix of variance covariance of one-step probabilities: result on file '%s' \n",fileresprobcov);
                   4196:   fprintf(ficlog,"Computing matrix of variance covariance of one-step probabilities: result on file '%s' \n",fileresprobcov);
                   4197:   printf("and correlation matrix of one-step probabilities: result on file '%s' \n",fileresprobcor);
                   4198:   fprintf(ficlog,"and correlation matrix of one-step probabilities: result on file '%s' \n",fileresprobcor);
                   4199:   pstamp(ficresprob);
                   4200:   fprintf(ficresprob,"#One-step probabilities and stand. devi in ()\n");
                   4201:   fprintf(ficresprob,"# Age");
                   4202:   pstamp(ficresprobcov);
                   4203:   fprintf(ficresprobcov,"#One-step probabilities and covariance matrix\n");
                   4204:   fprintf(ficresprobcov,"# Age");
                   4205:   pstamp(ficresprobcor);
                   4206:   fprintf(ficresprobcor,"#One-step probabilities and correlation matrix\n");
                   4207:   fprintf(ficresprobcor,"# Age");
                   4208: 
                   4209: 
                   4210:   for(i=1; i<=nlstate;i++)
                   4211:     for(j=1; j<=(nlstate+ndeath);j++){
                   4212:       fprintf(ficresprob," p%1d-%1d (SE)",i,j);
                   4213:       fprintf(ficresprobcov," p%1d-%1d ",i,j);
                   4214:       fprintf(ficresprobcor," p%1d-%1d ",i,j);
                   4215:     }  
                   4216:  /* fprintf(ficresprob,"\n");
                   4217:   fprintf(ficresprobcov,"\n");
                   4218:   fprintf(ficresprobcor,"\n");
                   4219:  */
1.131     brouard  4220:   xp=vector(1,npar);
1.126     brouard  4221:   dnewm=matrix(1,(nlstate)*(nlstate+ndeath),1,npar);
                   4222:   doldm=matrix(1,(nlstate)*(nlstate+ndeath),1,(nlstate)*(nlstate+ndeath));
                   4223:   mu=matrix(1,(nlstate)*(nlstate+ndeath), (int) bage, (int)fage);
                   4224:   varpij=ma3x(1,nlstate*(nlstate+ndeath),1,nlstate*(nlstate+ndeath),(int) bage, (int) fage);
                   4225:   first=1;
                   4226:   fprintf(ficgp,"\n# Routine varprob");
                   4227:   fprintf(fichtm,"\n<li><h4> Computing and drawing one step probabilities with their confidence intervals</h4></li>\n");
                   4228:   fprintf(fichtm,"\n");
                   4229: 
                   4230:   fprintf(fichtm,"\n<li><h4> <a href=\"%s\">Matrix of variance-covariance of pairs of step probabilities (drawings)</a></h4></li>\n",optionfilehtmcov);
                   4231:   fprintf(fichtmcov,"\n<h4>Matrix of variance-covariance of pairs of step probabilities</h4>\n\
                   4232:   file %s<br>\n",optionfilehtmcov);
                   4233:   fprintf(fichtmcov,"\nEllipsoids of confidence centered on point (p<inf>ij</inf>, p<inf>kl</inf>) are estimated\
                   4234: and drawn. It helps understanding how is the covariance between two incidences.\
                   4235:  They are expressed in year<sup>-1</sup> in order to be less dependent of stepm.<br>\n");
                   4236:   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. \
                   4237: It can be understood this way: if pij and pkl where uncorrelated the (2x2) matrix of covariance \
                   4238: would have been (1/(var pij), 0 , 0, 1/(var pkl)), and the confidence interval would be 2 \
                   4239: standard deviations wide on each axis. <br>\
                   4240:  Now, if both incidences are correlated (usual case) we diagonalised the inverse of the covariance matrix\
                   4241:  and made the appropriate rotation to look at the uncorrelated principal directions.<br>\
                   4242: To be simple, these graphs help to understand the significativity of each parameter in relation to a second other one.<br> \n");
                   4243: 
                   4244:   cov[1]=1;
1.145     brouard  4245:   /* tj=cptcoveff; */
                   4246:   tj = (int) pow(2,cptcoveff);
1.126     brouard  4247:   if (cptcovn<1) {tj=1;ncodemax[1]=1;}
                   4248:   j1=0;
1.145     brouard  4249:   for(j1=1; j1<=tj;j1++){
                   4250:     /*for(i1=1; i1<=ncodemax[t];i1++){ */
                   4251:     /*j1++;*/
1.126     brouard  4252:       if  (cptcovn>0) {
                   4253:        fprintf(ficresprob, "\n#********** Variable "); 
                   4254:        for (z1=1; z1<=cptcoveff; z1++) fprintf(ficresprob, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtab[j1][z1]]);
                   4255:        fprintf(ficresprob, "**********\n#\n");
                   4256:        fprintf(ficresprobcov, "\n#********** Variable "); 
                   4257:        for (z1=1; z1<=cptcoveff; z1++) fprintf(ficresprobcov, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtab[j1][z1]]);
                   4258:        fprintf(ficresprobcov, "**********\n#\n");
                   4259:        
                   4260:        fprintf(ficgp, "\n#********** Variable "); 
                   4261:        for (z1=1; z1<=cptcoveff; z1++) fprintf(ficgp, " V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtab[j1][z1]]);
                   4262:        fprintf(ficgp, "**********\n#\n");
                   4263:        
                   4264:        
                   4265:        fprintf(fichtmcov, "\n<hr  size=\"2\" color=\"#EC5E5E\">********** Variable "); 
                   4266:        for (z1=1; z1<=cptcoveff; z1++) fprintf(fichtm, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtab[j1][z1]]);
                   4267:        fprintf(fichtmcov, "**********\n<hr size=\"2\" color=\"#EC5E5E\">");
                   4268:        
                   4269:        fprintf(ficresprobcor, "\n#********** Variable ");    
                   4270:        for (z1=1; z1<=cptcoveff; z1++) fprintf(ficresprobcor, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtab[j1][z1]]);
                   4271:        fprintf(ficresprobcor, "**********\n#");    
                   4272:       }
                   4273:       
1.145     brouard  4274:       gradg=matrix(1,npar,1,(nlstate)*(nlstate+ndeath));
                   4275:       trgradg=matrix(1,(nlstate)*(nlstate+ndeath),1,npar);
                   4276:       gp=vector(1,(nlstate)*(nlstate+ndeath));
                   4277:       gm=vector(1,(nlstate)*(nlstate+ndeath));
1.126     brouard  4278:       for (age=bage; age<=fage; age ++){ 
                   4279:        cov[2]=age;
1.187     brouard  4280:        if(nagesqr==1)
                   4281:          cov[3]= age*age;
1.126     brouard  4282:        for (k=1; k<=cptcovn;k++) {
1.187     brouard  4283:          cov[2+nagesqr+k]=nbcode[Tvar[k]][codtab[j1][Tvar[k]]];/* j1 1 2 3 4
1.145     brouard  4284:                                                         * 1  1 1 1 1
                   4285:                                                         * 2  2 1 1 1
                   4286:                                                         * 3  1 2 1 1
                   4287:                                                         */
                   4288:          /* nbcode[1][1]=0 nbcode[1][2]=1;*/
1.126     brouard  4289:        }
1.186     brouard  4290:        /* for (k=1; k<=cptcovage;k++) cov[2+Tage[k]]=cov[2+Tage[k]]*cov[2]; */
                   4291:        for (k=1; k<=cptcovage;k++) cov[2+Tage[k]]=nbcode[Tvar[Tage[k]]][codtab[ij][Tvar[Tage[k]]]]*cov[2];
1.126     brouard  4292:        for (k=1; k<=cptcovprod;k++)
1.187     brouard  4293:          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  4294:        
                   4295:     
                   4296:        for(theta=1; theta <=npar; theta++){
                   4297:          for(i=1; i<=npar; i++)
                   4298:            xp[i] = x[i] + (i==theta ?delti[theta]:(double)0);
                   4299:          
                   4300:          pmij(pmmij,cov,ncovmodel,xp,nlstate);
                   4301:          
                   4302:          k=0;
                   4303:          for(i=1; i<= (nlstate); i++){
                   4304:            for(j=1; j<=(nlstate+ndeath);j++){
                   4305:              k=k+1;
                   4306:              gp[k]=pmmij[i][j];
                   4307:            }
                   4308:          }
                   4309:          
                   4310:          for(i=1; i<=npar; i++)
                   4311:            xp[i] = x[i] - (i==theta ?delti[theta]:(double)0);
                   4312:     
                   4313:          pmij(pmmij,cov,ncovmodel,xp,nlstate);
                   4314:          k=0;
                   4315:          for(i=1; i<=(nlstate); i++){
                   4316:            for(j=1; j<=(nlstate+ndeath);j++){
                   4317:              k=k+1;
                   4318:              gm[k]=pmmij[i][j];
                   4319:            }
                   4320:          }
                   4321:      
                   4322:          for(i=1; i<= (nlstate)*(nlstate+ndeath); i++) 
                   4323:            gradg[theta][i]=(gp[i]-gm[i])/(double)2./delti[theta];  
                   4324:        }
                   4325: 
                   4326:        for(j=1; j<=(nlstate)*(nlstate+ndeath);j++)
                   4327:          for(theta=1; theta <=npar; theta++)
                   4328:            trgradg[j][theta]=gradg[theta][j];
                   4329:        
                   4330:        matprod2(dnewm,trgradg,1,(nlstate)*(nlstate+ndeath),1,npar,1,npar,matcov); 
                   4331:        matprod2(doldm,dnewm,1,(nlstate)*(nlstate+ndeath),1,npar,1,(nlstate)*(nlstate+ndeath),gradg);
                   4332: 
                   4333:        pmij(pmmij,cov,ncovmodel,x,nlstate);
                   4334:        
                   4335:        k=0;
                   4336:        for(i=1; i<=(nlstate); i++){
                   4337:          for(j=1; j<=(nlstate+ndeath);j++){
                   4338:            k=k+1;
                   4339:            mu[k][(int) age]=pmmij[i][j];
                   4340:          }
                   4341:        }
                   4342:        for(i=1;i<=(nlstate)*(nlstate+ndeath);i++)
                   4343:          for(j=1;j<=(nlstate)*(nlstate+ndeath);j++)
                   4344:            varpij[i][j][(int)age] = doldm[i][j];
                   4345: 
                   4346:        /*printf("\n%d ",(int)age);
                   4347:          for (i=1; i<=(nlstate)*(nlstate+ndeath);i++){
                   4348:          printf("%e [%e ;%e] ",gm[i],gm[i]-2*sqrt(doldm[i][i]),gm[i]+2*sqrt(doldm[i][i]));
                   4349:          fprintf(ficlog,"%e [%e ;%e] ",gm[i],gm[i]-2*sqrt(doldm[i][i]),gm[i]+2*sqrt(doldm[i][i]));
                   4350:          }*/
                   4351: 
                   4352:        fprintf(ficresprob,"\n%d ",(int)age);
                   4353:        fprintf(ficresprobcov,"\n%d ",(int)age);
                   4354:        fprintf(ficresprobcor,"\n%d ",(int)age);
                   4355: 
                   4356:        for (i=1; i<=(nlstate)*(nlstate+ndeath);i++)
                   4357:          fprintf(ficresprob,"%11.3e (%11.3e) ",mu[i][(int) age],sqrt(varpij[i][i][(int)age]));
                   4358:        for (i=1; i<=(nlstate)*(nlstate+ndeath);i++){
                   4359:          fprintf(ficresprobcov,"%11.3e ",mu[i][(int) age]);
                   4360:          fprintf(ficresprobcor,"%11.3e ",mu[i][(int) age]);
                   4361:        }
                   4362:        i=0;
                   4363:        for (k=1; k<=(nlstate);k++){
                   4364:          for (l=1; l<=(nlstate+ndeath);l++){ 
1.145     brouard  4365:            i++;
1.126     brouard  4366:            fprintf(ficresprobcov,"\n%d %d-%d",(int)age,k,l);
                   4367:            fprintf(ficresprobcor,"\n%d %d-%d",(int)age,k,l);
                   4368:            for (j=1; j<=i;j++){
1.145     brouard  4369:              /* printf(" k=%d l=%d i=%d j=%d\n",k,l,i,j);fflush(stdout); */
1.126     brouard  4370:              fprintf(ficresprobcov," %11.3e",varpij[i][j][(int)age]);
                   4371:              fprintf(ficresprobcor," %11.3e",varpij[i][j][(int) age]/sqrt(varpij[i][i][(int) age])/sqrt(varpij[j][j][(int)age]));
                   4372:            }
                   4373:          }
                   4374:        }/* end of loop for state */
                   4375:       } /* end of loop for age */
1.145     brouard  4376:       free_vector(gp,1,(nlstate+ndeath)*(nlstate+ndeath));
                   4377:       free_vector(gm,1,(nlstate+ndeath)*(nlstate+ndeath));
                   4378:       free_matrix(trgradg,1,(nlstate+ndeath)*(nlstate+ndeath),1,npar);
                   4379:       free_matrix(gradg,1,(nlstate+ndeath)*(nlstate+ndeath),1,npar);
                   4380:       
1.126     brouard  4381:       /* Confidence intervalle of pij  */
                   4382:       /*
1.131     brouard  4383:        fprintf(ficgp,"\nunset parametric;unset label");
1.126     brouard  4384:        fprintf(ficgp,"\nset log y;unset log x; set xlabel \"Age\";set ylabel \"probability (year-1)\"");
                   4385:        fprintf(ficgp,"\nset ter png small\nset size 0.65,0.65");
                   4386:        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);
                   4387:        fprintf(fichtm,"\n<br><img src=\"pijgr%s.png\"> ",optionfilefiname);
                   4388:        fprintf(ficgp,"\nset out \"pijgr%s.png\"",optionfilefiname);
                   4389:        fprintf(ficgp,"\nplot \"%s\" every :::%d::%d u 1:2 \"\%%lf",k1,k2,xfilevarprob);
                   4390:       */
                   4391: 
                   4392:       /* Drawing ellipsoids of confidence of two variables p(k1-l1,k2-l2)*/
1.145     brouard  4393:       first1=1;first2=2;
1.126     brouard  4394:       for (k2=1; k2<=(nlstate);k2++){
                   4395:        for (l2=1; l2<=(nlstate+ndeath);l2++){ 
                   4396:          if(l2==k2) continue;
                   4397:          j=(k2-1)*(nlstate+ndeath)+l2;
                   4398:          for (k1=1; k1<=(nlstate);k1++){
                   4399:            for (l1=1; l1<=(nlstate+ndeath);l1++){ 
                   4400:              if(l1==k1) continue;
                   4401:              i=(k1-1)*(nlstate+ndeath)+l1;
                   4402:              if(i<=j) continue;
                   4403:              for (age=bage; age<=fage; age ++){ 
                   4404:                if ((int)age %5==0){
                   4405:                  v1=varpij[i][i][(int)age]/stepm*YEARM/stepm*YEARM;
                   4406:                  v2=varpij[j][j][(int)age]/stepm*YEARM/stepm*YEARM;
                   4407:                  cv12=varpij[i][j][(int)age]/stepm*YEARM/stepm*YEARM;
                   4408:                  mu1=mu[i][(int) age]/stepm*YEARM ;
                   4409:                  mu2=mu[j][(int) age]/stepm*YEARM;
                   4410:                  c12=cv12/sqrt(v1*v2);
                   4411:                  /* Computing eigen value of matrix of covariance */
                   4412:                  lc1=((v1+v2)+sqrt((v1+v2)*(v1+v2) - 4*(v1*v2-cv12*cv12)))/2.;
                   4413:                  lc2=((v1+v2)-sqrt((v1+v2)*(v1+v2) - 4*(v1*v2-cv12*cv12)))/2.;
1.135     brouard  4414:                  if ((lc2 <0) || (lc1 <0) ){
1.145     brouard  4415:                    if(first2==1){
                   4416:                      first1=0;
                   4417:                    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);
                   4418:                    }
                   4419:                    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);
                   4420:                    /* lc1=fabs(lc1); */ /* If we want to have them positive */
                   4421:                    /* lc2=fabs(lc2); */
1.135     brouard  4422:                  }
                   4423: 
1.126     brouard  4424:                  /* Eigen vectors */
                   4425:                  v11=(1./sqrt(1+(v1-lc1)*(v1-lc1)/cv12/cv12));
                   4426:                  /*v21=sqrt(1.-v11*v11); *//* error */
                   4427:                  v21=(lc1-v1)/cv12*v11;
                   4428:                  v12=-v21;
                   4429:                  v22=v11;
                   4430:                  tnalp=v21/v11;
                   4431:                  if(first1==1){
                   4432:                    first1=0;
                   4433:                    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);
                   4434:                  }
                   4435:                  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);
                   4436:                  /*printf(fignu*/
                   4437:                  /* mu1+ v11*lc1*cost + v12*lc2*sin(t) */
                   4438:                  /* mu2+ v21*lc1*cost + v22*lc2*sin(t) */
                   4439:                  if(first==1){
                   4440:                    first=0;
                   4441:                    fprintf(ficgp,"\nset parametric;unset label");
                   4442:                    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  4443:                    fprintf(ficgp,"\nset ter png small size 320, 240");
1.126     brouard  4444:                    fprintf(fichtmcov,"\n<br>Ellipsoids of confidence cov(p%1d%1d,p%1d%1d) expressed in year<sup>-1</sup>\
                   4445:  :<a href=\"%s%d%1d%1d-%1d%1d.png\">\
                   4446: %s%d%1d%1d-%1d%1d.png</A>, ",k1,l1,k2,l2,\
                   4447:                            subdirf2(optionfilefiname,"varpijgr"), j1,k1,l1,k2,l2,\
                   4448:                            subdirf2(optionfilefiname,"varpijgr"), j1,k1,l1,k2,l2);
                   4449:                    fprintf(fichtmcov,"\n<br><img src=\"%s%d%1d%1d-%1d%1d.png\"> ",subdirf2(optionfilefiname,"varpijgr"), j1,k1,l1,k2,l2);
                   4450:                    fprintf(fichtmcov,"\n<br> Correlation at age %d (%.3f),",(int) age, c12);
                   4451:                    fprintf(ficgp,"\nset out \"%s%d%1d%1d-%1d%1d.png\"",subdirf2(optionfilefiname,"varpijgr"), j1,k1,l1,k2,l2);
                   4452:                    fprintf(ficgp,"\nset label \"%d\" at %11.3e,%11.3e center",(int) age, mu1,mu2);
                   4453:                    fprintf(ficgp,"\n# Age %d, p%1d%1d - p%1d%1d",(int) age, k1,l1,k2,l2);
                   4454:                    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",\
                   4455:                            mu1,std,v11,sqrt(lc1),v12,sqrt(lc2),\
                   4456:                            mu2,std,v21,sqrt(lc1),v22,sqrt(lc2));
                   4457:                  }else{
                   4458:                    first=0;
                   4459:                    fprintf(fichtmcov," %d (%.3f),",(int) age, c12);
                   4460:                    fprintf(ficgp,"\n# Age %d, p%1d%1d - p%1d%1d",(int) age, k1,l1,k2,l2);
                   4461:                    fprintf(ficgp,"\nset label \"%d\" at %11.3e,%11.3e center",(int) age, mu1,mu2);
                   4462:                    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",\
                   4463:                            mu1,std,v11,sqrt(lc1),v12,sqrt(lc2),\
                   4464:                            mu2,std,v21,sqrt(lc1),v22,sqrt(lc2));
                   4465:                  }/* if first */
                   4466:                } /* age mod 5 */
                   4467:              } /* end loop age */
                   4468:              fprintf(ficgp,"\nset out \"%s%d%1d%1d-%1d%1d.png\";replot;",subdirf2(optionfilefiname,"varpijgr"), j1,k1,l1,k2,l2);
                   4469:              first=1;
                   4470:            } /*l12 */
                   4471:          } /* k12 */
                   4472:        } /*l1 */
                   4473:       }/* k1 */
1.169     brouard  4474:       /* } */ /* loop covariates */
1.126     brouard  4475:   }
                   4476:   free_ma3x(varpij,1,nlstate,1,nlstate+ndeath,(int) bage, (int)fage);
                   4477:   free_matrix(mu,1,(nlstate+ndeath)*(nlstate+ndeath),(int) bage, (int)fage);
                   4478:   free_matrix(doldm,1,(nlstate)*(nlstate+ndeath),1,(nlstate)*(nlstate+ndeath));
                   4479:   free_matrix(dnewm,1,(nlstate)*(nlstate+ndeath),1,npar);
                   4480:   free_vector(xp,1,npar);
                   4481:   fclose(ficresprob);
                   4482:   fclose(ficresprobcov);
                   4483:   fclose(ficresprobcor);
                   4484:   fflush(ficgp);
                   4485:   fflush(fichtmcov);
                   4486: }
                   4487: 
                   4488: 
                   4489: /******************* Printing html file ***********/
                   4490: void printinghtml(char fileres[], char title[], char datafile[], int firstpass, \
                   4491:                  int lastpass, int stepm, int weightopt, char model[],\
                   4492:                  int imx,int jmin, int jmax, double jmeanint,char rfileres[],\
                   4493:                  int popforecast, int estepm ,\
                   4494:                  double jprev1, double mprev1,double anprev1, \
                   4495:                  double jprev2, double mprev2,double anprev2){
                   4496:   int jj1, k1, i1, cpt;
                   4497: 
                   4498:    fprintf(fichtm,"<ul><li><a href='#firstorder'>Result files (first order: no variance)</a>\n \
                   4499:    <li><a href='#secondorder'>Result files (second order (variance)</a>\n \
                   4500: </ul>");
                   4501:    fprintf(fichtm,"<ul><li><h4><a name='firstorder'>Result files (first order: no variance)</a></h4>\n \
                   4502:  - Observed prevalence in each state (during the period defined between %.lf/%.lf/%.lf and %.lf/%.lf/%.lf): <a href=\"%s\">%s</a> <br>\n ",
                   4503:           jprev1, mprev1,anprev1,jprev2, mprev2,anprev2,subdirf2(fileres,"p"),subdirf2(fileres,"p"));
                   4504:    fprintf(fichtm,"\
                   4505:  - Estimated transition probabilities over %d (stepm) months: <a href=\"%s\">%s</a><br>\n ",
                   4506:           stepm,subdirf2(fileres,"pij"),subdirf2(fileres,"pij"));
                   4507:    fprintf(fichtm,"\
                   4508:  - Period (stable) prevalence in each health state: <a href=\"%s\">%s</a> <br>\n",
                   4509:           subdirf2(fileres,"pl"),subdirf2(fileres,"pl"));
                   4510:    fprintf(fichtm,"\
1.128     brouard  4511:  - (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  4512:    <a href=\"%s\">%s</a> <br>\n",
                   4513:           estepm,subdirf2(fileres,"e"),subdirf2(fileres,"e"));
                   4514:    fprintf(fichtm,"\
                   4515:  - Population projections by age and states: \
                   4516:    <a href=\"%s\">%s</a> <br>\n</li>", subdirf2(fileres,"f"),subdirf2(fileres,"f"));
                   4517: 
                   4518: fprintf(fichtm," \n<ul><li><b>Graphs</b></li><p>");
                   4519: 
1.145     brouard  4520:  m=pow(2,cptcoveff);
1.126     brouard  4521:  if (cptcovn < 1) {m=1;ncodemax[1]=1;}
                   4522: 
                   4523:  jj1=0;
                   4524:  for(k1=1; k1<=m;k1++){
1.192     brouard  4525:    /* for(i1=1; i1<=ncodemax[k1];i1++){ */
1.126     brouard  4526:      jj1++;
                   4527:      if (cptcovn > 0) {
                   4528:        fprintf(fichtm,"<hr  size=\"2\" color=\"#EC5E5E\">************ Results for covariates");
1.192     brouard  4529:        for (cpt=1; cpt<=cptcoveff;cpt++){ 
1.126     brouard  4530:         fprintf(fichtm," V%d=%d ",Tvaraff[cpt],nbcode[Tvaraff[cpt]][codtab[jj1][cpt]]);
1.192     brouard  4531:         printf(" V%d=%d ",Tvaraff[cpt],nbcode[Tvaraff[cpt]][codtab[jj1][cpt]]);fflush(stdout);
                   4532:        }
1.126     brouard  4533:        fprintf(fichtm," ************\n<hr size=\"2\" color=\"#EC5E5E\">");
                   4534:      }
                   4535:      /* Pij */
1.145     brouard  4536:      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> \
                   4537: <img src=\"%s%d_1.png\">",stepm,subdirf2(optionfilefiname,"pe"),jj1,subdirf2(optionfilefiname,"pe"),jj1,subdirf2(optionfilefiname,"pe"),jj1);     
1.126     brouard  4538:      /* Quasi-incidences */
                   4539:      fprintf(fichtm,"<br>- Pij or Conditional probabilities to be observed in state j being in state i %d (stepm) months\
1.145     brouard  4540:  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> \
                   4541: <img src=\"%s%d_2.png\">",stepm,subdirf2(optionfilefiname,"pe"),jj1,subdirf2(optionfilefiname,"pe"),jj1,subdirf2(optionfilefiname,"pe"),jj1); 
1.126     brouard  4542:        /* Period (stable) prevalence in each health state */
1.154     brouard  4543:        for(cpt=1; cpt<=nlstate;cpt++){
1.166     brouard  4544:         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> \
                   4545: <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  4546:        }
                   4547:      for(cpt=1; cpt<=nlstate;cpt++) {
1.154     brouard  4548:         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> \
                   4549: <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  4550:      }
1.192     brouard  4551:    /* } /\* end i1 *\/ */
1.126     brouard  4552:  }/* End k1 */
                   4553:  fprintf(fichtm,"</ul>");
                   4554: 
                   4555:  fprintf(fichtm,"\
                   4556: \n<br><li><h4> <a name='secondorder'>Result files (second order: variances)</a></h4>\n\
1.193     brouard  4557:  - Parameter file with estimated parameters and covariance matrix: <a href=\"%s\">%s</a> <br> \
                   4558:  - 95%% confidence intervals and T statistics are in the log file.<br>\n", rfileres,rfileres);
1.126     brouard  4559: 
1.193     brouard  4560:  fprintf(fichtm," - Standard deviation of one-step probabilities: <a href=\"%s\">%s</a> <br>\n",
1.126     brouard  4561:         subdirf2(fileres,"prob"),subdirf2(fileres,"prob"));
                   4562:  fprintf(fichtm,"\
                   4563:  - Variance-covariance of one-step probabilities: <a href=\"%s\">%s</a> <br>\n",
                   4564:         subdirf2(fileres,"probcov"),subdirf2(fileres,"probcov"));
                   4565: 
                   4566:  fprintf(fichtm,"\
                   4567:  - Correlation matrix of one-step probabilities: <a href=\"%s\">%s</a> <br>\n",
                   4568:         subdirf2(fileres,"probcor"),subdirf2(fileres,"probcor"));
                   4569:  fprintf(fichtm,"\
                   4570:  - 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): \
                   4571:    <a href=\"%s\">%s</a> <br>\n</li>",
                   4572:           estepm,subdirf2(fileres,"cve"),subdirf2(fileres,"cve"));
                   4573:  fprintf(fichtm,"\
                   4574:  - (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): \
                   4575:    <a href=\"%s\">%s</a> <br>\n</li>",
                   4576:           estepm,subdirf2(fileres,"stde"),subdirf2(fileres,"stde"));
                   4577:  fprintf(fichtm,"\
1.128     brouard  4578:  - 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  4579:         estepm, subdirf2(fileres,"v"),subdirf2(fileres,"v"));
                   4580:  fprintf(fichtm,"\
1.128     brouard  4581:  - 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",
                   4582:         estepm, subdirf2(fileres,"t"),subdirf2(fileres,"t"));
1.126     brouard  4583:  fprintf(fichtm,"\
                   4584:  - Standard deviation of period (stable) prevalences: <a href=\"%s\">%s</a> <br>\n",\
                   4585:         subdirf2(fileres,"vpl"),subdirf2(fileres,"vpl"));
                   4586: 
                   4587: /*  if(popforecast==1) fprintf(fichtm,"\n */
                   4588: /*  - Prevalences forecasting: <a href=\"f%s\">f%s</a> <br>\n */
                   4589: /*  - Population forecasting (if popforecast=1): <a href=\"pop%s\">pop%s</a> <br>\n */
                   4590: /*     <br>",fileres,fileres,fileres,fileres); */
                   4591: /*  else  */
                   4592: /*    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); */
                   4593:  fflush(fichtm);
                   4594:  fprintf(fichtm," <ul><li><b>Graphs</b></li><p>");
                   4595: 
1.145     brouard  4596:  m=pow(2,cptcoveff);
1.126     brouard  4597:  if (cptcovn < 1) {m=1;ncodemax[1]=1;}
                   4598: 
                   4599:  jj1=0;
                   4600:  for(k1=1; k1<=m;k1++){
1.192     brouard  4601:    /* for(i1=1; i1<=ncodemax[k1];i1++){ */
1.126     brouard  4602:      jj1++;
                   4603:      if (cptcovn > 0) {
                   4604:        fprintf(fichtm,"<hr  size=\"2\" color=\"#EC5E5E\">************ Results for covariates");
                   4605:        for (cpt=1; cpt<=cptcoveff;cpt++) 
                   4606:         fprintf(fichtm," V%d=%d ",Tvaraff[cpt],nbcode[Tvaraff[cpt]][codtab[jj1][cpt]]);
                   4607:        fprintf(fichtm," ************\n<hr size=\"2\" color=\"#EC5E5E\">");
                   4608:      }
                   4609:      for(cpt=1; cpt<=nlstate;cpt++) {
                   4610:        fprintf(fichtm,"<br>- Observed (cross-sectional) and period (incidence based) \
1.145     brouard  4611: prevalence (with 95%% confidence interval) in state (%d): %s%d_%d.png <br>\
                   4612: <img src=\"%s%d_%d.png\">",cpt,subdirf2(optionfilefiname,"v"),cpt,jj1,subdirf2(optionfilefiname,"v"),cpt,jj1);  
1.126     brouard  4613:      }
                   4614:      fprintf(fichtm,"\n<br>- Total life expectancy by age and \
1.128     brouard  4615: health expectancies in states (1) and (2). If popbased=1 the smooth (due to the model) \
                   4616: true period expectancies (those weighted with period prevalences are also\
                   4617:  drawn in addition to the population based expectancies computed using\
                   4618:  observed and cahotic prevalences: %s%d.png<br>\
1.126     brouard  4619: <img src=\"%s%d.png\">",subdirf2(optionfilefiname,"e"),jj1,subdirf2(optionfilefiname,"e"),jj1);
1.192     brouard  4620:    /* } /\* end i1 *\/ */
1.126     brouard  4621:  }/* End k1 */
                   4622:  fprintf(fichtm,"</ul>");
                   4623:  fflush(fichtm);
                   4624: }
                   4625: 
                   4626: /******************* Gnuplot file **************/
                   4627: void printinggnuplot(char fileres[], char optionfilefiname[], double ageminpar, double agemaxpar, double fage , char pathc[], double p[]){
                   4628: 
                   4629:   char dirfileres[132],optfileres[132];
1.164     brouard  4630:   int cpt=0,k1=0,i=0,k=0,j=0,jk=0,k2=0,k3=0,ij=0,l=0;
1.130     brouard  4631:   int ng=0;
1.126     brouard  4632: /*   if((ficgp=fopen(optionfilegnuplot,"a"))==NULL) { */
                   4633: /*     printf("Problem with file %s",optionfilegnuplot); */
                   4634: /*     fprintf(ficlog,"Problem with file %s",optionfilegnuplot); */
                   4635: /*   } */
                   4636: 
                   4637:   /*#ifdef windows */
                   4638:   fprintf(ficgp,"cd \"%s\" \n",pathc);
                   4639:     /*#endif */
                   4640:   m=pow(2,cptcoveff);
                   4641: 
                   4642:   strcpy(dirfileres,optionfilefiname);
                   4643:   strcpy(optfileres,"vpl");
                   4644:  /* 1eme*/
1.153     brouard  4645:   fprintf(ficgp,"\n# 1st: Period (stable) prevalence with CI: 'vpl' files\n");
1.126     brouard  4646:   for (cpt=1; cpt<= nlstate ; cpt ++) {
1.145     brouard  4647:     for (k1=1; k1<= m ; k1 ++) { /* plot [100000000000000000000:-100000000000000000000] "mysbiaspar/vplrmysbiaspar.txt to check */
                   4648:      fprintf(ficgp,"\nset out \"%s%d_%d.png\" \n",subdirf2(optionfilefiname,"v"),cpt,k1);
                   4649:      fprintf(ficgp,"\n#set out \"v%s%d_%d.png\" \n",optionfilefiname,cpt,k1);
1.126     brouard  4650:      fprintf(ficgp,"set xlabel \"Age\" \n\
                   4651: set ylabel \"Probability\" \n\
1.145     brouard  4652: set ter png small size 320, 240\n\
1.170     brouard  4653: plot [%.f:%.f] \"%s\" every :::%d::%d u 1:2 \"%%lf",ageminpar,fage,subdirf2(fileres,"vpl"),k1-1,k1-1);
1.126     brouard  4654: 
                   4655:      for (i=1; i<= nlstate ; i ++) {
1.170     brouard  4656:        if (i==cpt) fprintf(ficgp," %%lf (%%lf)");
                   4657:        else        fprintf(ficgp," %%*lf (%%*lf)");
1.126     brouard  4658:      }
1.170     brouard  4659:      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  4660:      for (i=1; i<= nlstate ; i ++) {
1.170     brouard  4661:        if (i==cpt) fprintf(ficgp," %%lf (%%lf)");
                   4662:        else fprintf(ficgp," %%*lf (%%*lf)");
1.126     brouard  4663:      } 
1.170     brouard  4664:      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  4665:      for (i=1; i<= nlstate ; i ++) {
1.170     brouard  4666:        if (i==cpt) fprintf(ficgp," %%lf (%%lf)");
                   4667:        else fprintf(ficgp," %%*lf (%%*lf)");
1.126     brouard  4668:      }  
1.145     brouard  4669:      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  4670:    }
                   4671:   }
                   4672:   /*2 eme*/
1.153     brouard  4673:   fprintf(ficgp,"\n# 2nd: Total life expectancy with CI: 't' files\n");
1.126     brouard  4674:   for (k1=1; k1<= m ; k1 ++) { 
                   4675:     fprintf(ficgp,"\nset out \"%s%d.png\" \n",subdirf2(optionfilefiname,"e"),k1);
1.145     brouard  4676:     fprintf(ficgp,"set ylabel \"Years\" \nset ter png small size 320, 240\nplot [%.f:%.f] ",ageminpar,fage);
1.126     brouard  4677:     
                   4678:     for (i=1; i<= nlstate+1 ; i ++) {
                   4679:       k=2*i;
1.170     brouard  4680:       fprintf(ficgp,"\"%s\" every :::%d::%d u 1:2 \"%%lf",subdirf2(fileres,"t"),k1-1,k1-1);
1.126     brouard  4681:       for (j=1; j<= nlstate+1 ; j ++) {
1.170     brouard  4682:        if (j==i) fprintf(ficgp," %%lf (%%lf)");
                   4683:        else fprintf(ficgp," %%*lf (%%*lf)");
1.126     brouard  4684:       }   
                   4685:       if (i== 1) fprintf(ficgp,"\" t\"TLE\" w l ,");
                   4686:       else fprintf(ficgp,"\" t\"LE in state (%d)\" w l ,",i-1);
1.170     brouard  4687:       fprintf(ficgp,"\"%s\" every :::%d::%d u 1:($2-$3*2) \"%%lf",subdirf2(fileres,"t"),k1-1,k1-1);
1.126     brouard  4688:       for (j=1; j<= nlstate+1 ; j ++) {
1.170     brouard  4689:        if (j==i) fprintf(ficgp," %%lf (%%lf)");
                   4690:        else fprintf(ficgp," %%*lf (%%*lf)");
1.126     brouard  4691:       }   
1.145     brouard  4692:       fprintf(ficgp,"\" t\"\" w l lt 0,");
1.170     brouard  4693:       fprintf(ficgp,"\"%s\" every :::%d::%d u 1:($2+$3*2) \"%%lf",subdirf2(fileres,"t"),k1-1,k1-1);
1.126     brouard  4694:       for (j=1; j<= nlstate+1 ; j ++) {
1.170     brouard  4695:        if (j==i) fprintf(ficgp," %%lf (%%lf)");
                   4696:        else fprintf(ficgp," %%*lf (%%*lf)");
1.126     brouard  4697:       }   
1.145     brouard  4698:       if (i== (nlstate+1)) fprintf(ficgp,"\" t\"\" w l lt 0");
                   4699:       else fprintf(ficgp,"\" t\"\" w l lt 0,");
1.126     brouard  4700:     }
                   4701:   }
                   4702:   
                   4703:   /*3eme*/
                   4704:   
                   4705:   for (k1=1; k1<= m ; k1 ++) { 
                   4706:     for (cpt=1; cpt<= nlstate ; cpt ++) {
                   4707:       /*       k=2+nlstate*(2*cpt-2); */
                   4708:       k=2+(nlstate+1)*(cpt-1);
                   4709:       fprintf(ficgp,"\nset out \"%s%d%d.png\" \n",subdirf2(optionfilefiname,"exp"),cpt,k1);
1.145     brouard  4710:       fprintf(ficgp,"set ter png small size 320, 240\n\
1.126     brouard  4711: 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);
                   4712:       /*fprintf(ficgp,",\"e%s\" every :::%d::%d u 1:($%d-2*$%d) \"\%%lf ",fileres,k1-1,k1-1,k,k+1);
                   4713:        for (i=1; i<= nlstate*2 ; i ++) fprintf(ficgp,"\%%lf (\%%lf) ");
                   4714:        fprintf(ficgp,"\" t \"e%d1\" w l",cpt);
                   4715:        fprintf(ficgp,",\"e%s\" every :::%d::%d u 1:($%d+2*$%d) \"\%%lf ",fileres,k1-1,k1-1,k,k+1);
                   4716:        for (i=1; i<= nlstate*2 ; i ++) fprintf(ficgp,"\%%lf (\%%lf) ");
                   4717:        fprintf(ficgp,"\" t \"e%d1\" w l",cpt);
                   4718:        
                   4719:       */
                   4720:       for (i=1; i< nlstate ; i ++) {
                   4721:        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);
                   4722:        /*      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);*/
                   4723:        
                   4724:       } 
                   4725:       fprintf(ficgp," ,\"%s\" every :::%d::%d u 1:%d t \"e%d.\" w l",subdirf2(fileres,"e"),k1-1,k1-1,k+nlstate,cpt);
                   4726:     }
                   4727:   }
                   4728:   
                   4729:   /* CV preval stable (period) */
1.153     brouard  4730:   for (k1=1; k1<= m ; k1 ++) { /* For each multivariate if any */
                   4731:     for (cpt=1; cpt<=nlstate ; cpt ++) { /* For each life state */
1.126     brouard  4732:       k=3;
1.153     brouard  4733:       fprintf(ficgp,"\n#\n#\n#CV preval stable (period): 'pij' files, cov=%d state=%d",k1, cpt);
1.145     brouard  4734:       fprintf(ficgp,"\nset out \"%s%d_%d.png\" \n",subdirf2(optionfilefiname,"p"),cpt,k1);
1.126     brouard  4735:       fprintf(ficgp,"set xlabel \"Age\" \nset ylabel \"Probability\" \n\
1.145     brouard  4736: set ter png small size 320, 240\n\
1.126     brouard  4737: unset log y\n\
1.153     brouard  4738: plot [%.f:%.f]  ", ageminpar, agemaxpar);
                   4739:       for (i=1; i<= nlstate ; i ++){
                   4740:        if(i==1)
                   4741:          fprintf(ficgp,"\"%s\"",subdirf2(fileres,"pij"));
                   4742:        else
                   4743:          fprintf(ficgp,", '' ");
1.154     brouard  4744:        l=(nlstate+ndeath)*(i-1)+1;
                   4745:        fprintf(ficgp," u ($1==%d ? ($3):1/0):($%d/($%d",k1,k+l+(cpt-1),k+l);
1.153     brouard  4746:        for (j=1; j<= (nlstate-1) ; j ++)
                   4747:          fprintf(ficgp,"+$%d",k+l+j);
                   4748:        fprintf(ficgp,")) t \"prev(%d,%d)\" w l",i,cpt);
                   4749:       } /* nlstate */
                   4750:       fprintf(ficgp,"\n");
                   4751:     } /* end cpt state*/ 
                   4752:   } /* end covariate */  
1.126     brouard  4753:   
                   4754:   /* proba elementaires */
1.187     brouard  4755:   fprintf(ficgp,"\n##############\n#MLE estimated parameters\n#############\n");
1.126     brouard  4756:   for(i=1,jk=1; i <=nlstate; i++){
1.187     brouard  4757:     fprintf(ficgp,"# initial state %d\n",i);
1.126     brouard  4758:     for(k=1; k <=(nlstate+ndeath); k++){
                   4759:       if (k != i) {
1.187     brouard  4760:        fprintf(ficgp,"#   current state %d\n",k);
1.126     brouard  4761:        for(j=1; j <=ncovmodel; j++){
1.187     brouard  4762:          fprintf(ficgp,"p%d=%f; ",jk,p[jk]);
1.126     brouard  4763:          jk++; 
                   4764:        }
1.187     brouard  4765:        fprintf(ficgp,"\n");
1.126     brouard  4766:       }
                   4767:     }
                   4768:    }
1.187     brouard  4769:   fprintf(ficgp,"##############\n#\n");
                   4770: 
1.145     brouard  4771:   /*goto avoid;*/
1.187     brouard  4772:   fprintf(ficgp,"\n##############\n#Graphics of of probabilities or incidences\n#############\n");
                   4773:   fprintf(ficgp,"# logi(p12/p11)=a12+b12*age+c12age*age+d12*V1+e12*V1*age\n");
                   4774:   fprintf(ficgp,"# logi(p12/p11)=p1 +p2*age +p3*age*age+ p4*V1+ p5*V1*age\n");
                   4775:   fprintf(ficgp,"# logi(p13/p11)=a13+b13*age+c13age*age+d13*V1+e13*V1*age\n");
                   4776:   fprintf(ficgp,"# logi(p13/p11)=p6 +p7*age +p8*age*age+ p9*V1+ p10*V1*age\n");
                   4777:   fprintf(ficgp,"# p12+p13+p14+p11=1=p11(1+exp(a12+b12*age+c12age*age+d12*V1+e12*V1*age)\n");
                   4778:   fprintf(ficgp,"#                      +exp(a13+b13*age+c13age*age+d13*V1+e13*V1*age)+...)\n");
                   4779:   fprintf(ficgp,"# p11=1/(1+exp(a12+b12*age+c12age*age+d12*V1+e12*V1*age)\n");
                   4780:   fprintf(ficgp,"#                      +exp(a13+b13*age+c13age*age+d13*V1+e13*V1*age)+...)\n");
                   4781:   fprintf(ficgp,"# p12=exp(a12+b12*age+c12age*age+d12*V1+e12*V1*age)/\n");
                   4782:   fprintf(ficgp,"#     (1+exp(a12+b12*age+c12age*age+d12*V1+e12*V1*age)\n");
                   4783:   fprintf(ficgp,"#       +exp(a13+b13*age+c13age*age+d13*V1+e13*V1*age))\n");
                   4784:   fprintf(ficgp,"#       +exp(a14+b14*age+c14age*age+d14*V1+e14*V1*age)+...)\n");
                   4785:   fprintf(ficgp,"#\n");
1.126     brouard  4786:    for(ng=1; ng<=2;ng++){ /* Number of graphics: first is probabilities second is incidence per year*/
1.187     brouard  4787:      fprintf(ficgp,"# ng=%d\n",ng);
                   4788:      fprintf(ficgp,"#   jk=1 to 2^%d=%d\n",cptcoveff,m);
1.126     brouard  4789:      for(jk=1; jk <=m; jk++) {
1.187     brouard  4790:        fprintf(ficgp,"#    jk=%d\n",jk);
1.145     brouard  4791:        fprintf(ficgp,"\nset out \"%s%d_%d.png\" \n",subdirf2(optionfilefiname,"pe"),jk,ng); 
1.126     brouard  4792:        if (ng==2)
                   4793:         fprintf(ficgp,"\nset ylabel \"Quasi-incidence per year\"\n");
                   4794:        else
                   4795:         fprintf(ficgp,"\nset title \"Probability\"\n");
1.145     brouard  4796:        fprintf(ficgp,"\nset ter png small size 320, 240\nset log y\nplot  [%.f:%.f] ",ageminpar,agemaxpar);
1.126     brouard  4797:        i=1;
                   4798:        for(k2=1; k2<=nlstate; k2++) {
                   4799:         k3=i;
                   4800:         for(k=1; k<=(nlstate+ndeath); k++) {
                   4801:           if (k != k2){
                   4802:             if(ng==2)
1.187     brouard  4803:               if(nagesqr==0)
                   4804:                 fprintf(ficgp," %f*exp(p%d+p%d*x",YEARM/stepm,i,i+1);
                   4805:               else /* nagesqr =1 */
                   4806:                 fprintf(ficgp," %f*exp(p%d+p%d*x+p%d*x*x",YEARM/stepm,i,i+1,i+1+nagesqr);
1.126     brouard  4807:             else
1.187     brouard  4808:               if(nagesqr==0)
                   4809:                 fprintf(ficgp," exp(p%d+p%d*x",i,i+1);
                   4810:               else /* nagesqr =1 */
                   4811:                 fprintf(ficgp," exp(p%d+p%d*x+p%d*x*x",i,i+1,i+1+nagesqr);
1.141     brouard  4812:             ij=1;/* To be checked else nbcode[0][0] wrong */
1.187     brouard  4813:             for(j=3; j <=ncovmodel-nagesqr; j++) {
1.186     brouard  4814:               if(((j-2)==Tage[ij]) &&(ij <=cptcovage)) { /* Bug valgrind */
1.187     brouard  4815:                 fprintf(ficgp,"+p%d*%d*x",i+j+nagesqr-1,nbcode[Tvar[j-2]][codtab[jk][Tvar[j-2]]]);
1.186     brouard  4816:                 ij++;
                   4817:               }
                   4818:               else
1.187     brouard  4819:                 fprintf(ficgp,"+p%d*%d",i+j+nagesqr-1,nbcode[Tvar[j-2]][codtab[jk][j-2]]);
1.126     brouard  4820:             }
                   4821:             fprintf(ficgp,")/(1");
                   4822:             
1.187     brouard  4823:             for(k1=1; k1 <=nlstate; k1++){ 
                   4824:               if(nagesqr==0)
                   4825:                 fprintf(ficgp,"+exp(p%d+p%d*x",k3+(k1-1)*ncovmodel,k3+(k1-1)*ncovmodel+1);
                   4826:               else /* nagesqr =1 */
                   4827:                 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);
                   4828:   
1.126     brouard  4829:               ij=1;
1.187     brouard  4830:               for(j=3; j <=ncovmodel-nagesqr; j++){
1.186     brouard  4831:                 if(((j-2)==Tage[ij]) &&(ij <=cptcovage)) {
1.187     brouard  4832:                   fprintf(ficgp,"+p%d*%d*x",k3+(k1-1)*ncovmodel+1+j-2+nagesqr,nbcode[Tvar[j-2]][codtab[jk][Tvar[j-2]]]);
1.186     brouard  4833:                   ij++;
                   4834:                 }
                   4835:                 else
1.187     brouard  4836:                   fprintf(ficgp,"+p%d*%d",k3+(k1-1)*ncovmodel+1+j-2+nagesqr,nbcode[Tvar[j-2]][codtab[jk][j-2]]);
1.126     brouard  4837:               }
                   4838:               fprintf(ficgp,")");
                   4839:             }
                   4840:             fprintf(ficgp,") t \"p%d%d\" ", k2,k);
                   4841:             if ((k+k2)!= (nlstate*2+ndeath)) fprintf(ficgp,",");
                   4842:             i=i+ncovmodel;
                   4843:           }
                   4844:         } /* end k */
                   4845:        } /* end k2 */
                   4846:      } /* end jk */
                   4847:    } /* end ng */
1.164     brouard  4848:  /* avoid: */
1.126     brouard  4849:    fflush(ficgp); 
                   4850: }  /* end gnuplot */
                   4851: 
                   4852: 
                   4853: /*************** Moving average **************/
                   4854: int movingaverage(double ***probs, double bage,double fage, double ***mobaverage, int mobilav){
                   4855: 
                   4856:   int i, cpt, cptcod;
                   4857:   int modcovmax =1;
                   4858:   int mobilavrange, mob;
                   4859:   double age;
                   4860: 
                   4861:   modcovmax=2*cptcoveff;/* Max number of modalities. We suppose 
                   4862:                           a covariate has 2 modalities */
                   4863:   if (cptcovn<1) modcovmax=1; /* At least 1 pass */
                   4864: 
                   4865:   if(mobilav==1||mobilav ==3 ||mobilav==5 ||mobilav== 7){
                   4866:     if(mobilav==1) mobilavrange=5; /* default */
                   4867:     else mobilavrange=mobilav;
                   4868:     for (age=bage; age<=fage; age++)
                   4869:       for (i=1; i<=nlstate;i++)
                   4870:        for (cptcod=1;cptcod<=modcovmax;cptcod++)
                   4871:          mobaverage[(int)age][i][cptcod]=probs[(int)age][i][cptcod];
                   4872:     /* We keep the original values on the extreme ages bage, fage and for 
                   4873:        fage+1 and bage-1 we use a 3 terms moving average; for fage+2 bage+2
                   4874:        we use a 5 terms etc. until the borders are no more concerned. 
                   4875:     */ 
                   4876:     for (mob=3;mob <=mobilavrange;mob=mob+2){
                   4877:       for (age=bage+(mob-1)/2; age<=fage-(mob-1)/2; age++){
                   4878:        for (i=1; i<=nlstate;i++){
                   4879:          for (cptcod=1;cptcod<=modcovmax;cptcod++){
                   4880:            mobaverage[(int)age][i][cptcod] =probs[(int)age][i][cptcod];
                   4881:              for (cpt=1;cpt<=(mob-1)/2;cpt++){
                   4882:                mobaverage[(int)age][i][cptcod] +=probs[(int)age-cpt][i][cptcod];
                   4883:                mobaverage[(int)age][i][cptcod] +=probs[(int)age+cpt][i][cptcod];
                   4884:              }
                   4885:            mobaverage[(int)age][i][cptcod]=mobaverage[(int)age][i][cptcod]/mob;
                   4886:          }
                   4887:        }
                   4888:       }/* end age */
                   4889:     }/* end mob */
                   4890:   }else return -1;
                   4891:   return 0;
                   4892: }/* End movingaverage */
                   4893: 
                   4894: 
                   4895: /************** Forecasting ******************/
1.169     brouard  4896: 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  4897:   /* proj1, year, month, day of starting projection 
                   4898:      agemin, agemax range of age
                   4899:      dateprev1 dateprev2 range of dates during which prevalence is computed
                   4900:      anproj2 year of en of projection (same day and month as proj1).
                   4901:   */
1.164     brouard  4902:   int yearp, stepsize, hstepm, nhstepm, j, k, cptcod, i, h, i1;
1.126     brouard  4903:   double agec; /* generic age */
                   4904:   double agelim, ppij, yp,yp1,yp2,jprojmean,mprojmean,anprojmean;
                   4905:   double *popeffectif,*popcount;
                   4906:   double ***p3mat;
                   4907:   double ***mobaverage;
                   4908:   char fileresf[FILENAMELENGTH];
                   4909: 
                   4910:   agelim=AGESUP;
                   4911:   prevalence(probs, ageminpar, agemax, s, agev, nlstate, imx, Tvar, nbcode, ncodemax, mint, anint, dateprev1, dateprev2, firstpass, lastpass);
                   4912:  
                   4913:   strcpy(fileresf,"f"); 
                   4914:   strcat(fileresf,fileres);
                   4915:   if((ficresf=fopen(fileresf,"w"))==NULL) {
                   4916:     printf("Problem with forecast resultfile: %s\n", fileresf);
                   4917:     fprintf(ficlog,"Problem with forecast resultfile: %s\n", fileresf);
                   4918:   }
                   4919:   printf("Computing forecasting: result on file '%s' \n", fileresf);
                   4920:   fprintf(ficlog,"Computing forecasting: result on file '%s' \n", fileresf);
                   4921: 
                   4922:   if (cptcoveff==0) ncodemax[cptcoveff]=1;
                   4923: 
                   4924:   if (mobilav!=0) {
                   4925:     mobaverage= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
                   4926:     if (movingaverage(probs, ageminpar, fage, mobaverage,mobilav)!=0){
                   4927:       fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav);
                   4928:       printf(" Error in movingaverage mobilav=%d\n",mobilav);
                   4929:     }
                   4930:   }
                   4931: 
                   4932:   stepsize=(int) (stepm+YEARM-1)/YEARM;
                   4933:   if (stepm<=12) stepsize=1;
                   4934:   if(estepm < stepm){
                   4935:     printf ("Problem %d lower than %d\n",estepm, stepm);
                   4936:   }
                   4937:   else  hstepm=estepm;   
                   4938: 
                   4939:   hstepm=hstepm/stepm; 
                   4940:   yp1=modf(dateintmean,&yp);/* extracts integral of datemean in yp  and
                   4941:                                fractional in yp1 */
                   4942:   anprojmean=yp;
                   4943:   yp2=modf((yp1*12),&yp);
                   4944:   mprojmean=yp;
                   4945:   yp1=modf((yp2*30.5),&yp);
                   4946:   jprojmean=yp;
                   4947:   if(jprojmean==0) jprojmean=1;
                   4948:   if(mprojmean==0) jprojmean=1;
                   4949: 
                   4950:   i1=cptcoveff;
                   4951:   if (cptcovn < 1){i1=1;}
                   4952:   
                   4953:   fprintf(ficresf,"# Mean day of interviews %.lf/%.lf/%.lf (%.2f) between %.2f and %.2f \n",jprojmean,mprojmean,anprojmean,dateintmean,dateprev1,dateprev2); 
                   4954:   
                   4955:   fprintf(ficresf,"#****** Routine prevforecast **\n");
                   4956: 
                   4957: /*           if (h==(int)(YEARM*yearp)){ */
                   4958:   for(cptcov=1, k=0;cptcov<=i1;cptcov++){
                   4959:     for(cptcod=1;cptcod<=ncodemax[cptcoveff];cptcod++){
                   4960:       k=k+1;
                   4961:       fprintf(ficresf,"\n#******");
                   4962:       for(j=1;j<=cptcoveff;j++) {
                   4963:        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]]);
                   4964:       }
                   4965:       fprintf(ficresf,"******\n");
                   4966:       fprintf(ficresf,"# Covariate valuofcovar yearproj age");
                   4967:       for(j=1; j<=nlstate+ndeath;j++){ 
                   4968:        for(i=1; i<=nlstate;i++)              
                   4969:           fprintf(ficresf," p%d%d",i,j);
                   4970:        fprintf(ficresf," p.%d",j);
                   4971:       }
                   4972:       for (yearp=0; yearp<=(anproj2-anproj1);yearp +=stepsize) { 
                   4973:        fprintf(ficresf,"\n");
                   4974:        fprintf(ficresf,"\n# Forecasting at date %.lf/%.lf/%.lf ",jproj1,mproj1,anproj1+yearp);   
                   4975: 
                   4976:        for (agec=fage; agec>=(ageminpar-1); agec--){ 
                   4977:          nhstepm=(int) rint((agelim-agec)*YEARM/stepm); 
                   4978:          nhstepm = nhstepm/hstepm; 
                   4979:          p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   4980:          oldm=oldms;savm=savms;
                   4981:          hpxij(p3mat,nhstepm,agec,hstepm,p,nlstate,stepm,oldm,savm, k);  
                   4982:        
                   4983:          for (h=0; h<=nhstepm; h++){
                   4984:            if (h*hstepm/YEARM*stepm ==yearp) {
                   4985:               fprintf(ficresf,"\n");
                   4986:               for(j=1;j<=cptcoveff;j++) 
                   4987:                 fprintf(ficresf,"%d %d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
                   4988:              fprintf(ficresf,"%.f %.f ",anproj1+yearp,agec+h*hstepm/YEARM*stepm);
                   4989:            } 
                   4990:            for(j=1; j<=nlstate+ndeath;j++) {
                   4991:              ppij=0.;
                   4992:              for(i=1; i<=nlstate;i++) {
                   4993:                if (mobilav==1) 
                   4994:                  ppij=ppij+p3mat[i][j][h]*mobaverage[(int)agec][i][cptcod];
                   4995:                else {
                   4996:                  ppij=ppij+p3mat[i][j][h]*probs[(int)(agec)][i][cptcod];
                   4997:                }
                   4998:                if (h*hstepm/YEARM*stepm== yearp) {
                   4999:                  fprintf(ficresf," %.3f", p3mat[i][j][h]);
                   5000:                }
                   5001:              } /* end i */
                   5002:              if (h*hstepm/YEARM*stepm==yearp) {
                   5003:                fprintf(ficresf," %.3f", ppij);
                   5004:              }
                   5005:            }/* end j */
                   5006:          } /* end h */
                   5007:          free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   5008:        } /* end agec */
                   5009:       } /* end yearp */
                   5010:     } /* end cptcod */
                   5011:   } /* end  cptcov */
                   5012:        
                   5013:   if (mobilav!=0) free_ma3x(mobaverage,1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
                   5014: 
                   5015:   fclose(ficresf);
                   5016: }
                   5017: 
                   5018: /************** Forecasting *****not tested NB*************/
1.169     brouard  5019: 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  5020:   
                   5021:   int cpt, stepsize, hstepm, nhstepm, j,k,c, cptcod, i,h;
                   5022:   int *popage;
                   5023:   double calagedatem, agelim, kk1, kk2;
                   5024:   double *popeffectif,*popcount;
                   5025:   double ***p3mat,***tabpop,***tabpopprev;
                   5026:   double ***mobaverage;
                   5027:   char filerespop[FILENAMELENGTH];
                   5028: 
                   5029:   tabpop= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
                   5030:   tabpopprev= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
                   5031:   agelim=AGESUP;
                   5032:   calagedatem=(anpyram+mpyram/12.+jpyram/365.-dateintmean)*YEARM;
                   5033:   
                   5034:   prevalence(probs, ageminpar, agemax, s, agev, nlstate, imx, Tvar, nbcode, ncodemax, mint, anint, dateprev1, dateprev2, firstpass, lastpass);
                   5035:   
                   5036:   
                   5037:   strcpy(filerespop,"pop"); 
                   5038:   strcat(filerespop,fileres);
                   5039:   if((ficrespop=fopen(filerespop,"w"))==NULL) {
                   5040:     printf("Problem with forecast resultfile: %s\n", filerespop);
                   5041:     fprintf(ficlog,"Problem with forecast resultfile: %s\n", filerespop);
                   5042:   }
                   5043:   printf("Computing forecasting: result on file '%s' \n", filerespop);
                   5044:   fprintf(ficlog,"Computing forecasting: result on file '%s' \n", filerespop);
                   5045: 
                   5046:   if (cptcoveff==0) ncodemax[cptcoveff]=1;
                   5047: 
                   5048:   if (mobilav!=0) {
                   5049:     mobaverage= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
                   5050:     if (movingaverage(probs, ageminpar, fage, mobaverage,mobilav)!=0){
                   5051:       fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav);
                   5052:       printf(" Error in movingaverage mobilav=%d\n",mobilav);
                   5053:     }
                   5054:   }
                   5055: 
                   5056:   stepsize=(int) (stepm+YEARM-1)/YEARM;
                   5057:   if (stepm<=12) stepsize=1;
                   5058:   
                   5059:   agelim=AGESUP;
                   5060:   
                   5061:   hstepm=1;
                   5062:   hstepm=hstepm/stepm; 
                   5063:   
                   5064:   if (popforecast==1) {
                   5065:     if((ficpop=fopen(popfile,"r"))==NULL) {
                   5066:       printf("Problem with population file : %s\n",popfile);exit(0);
                   5067:       fprintf(ficlog,"Problem with population file : %s\n",popfile);exit(0);
                   5068:     } 
                   5069:     popage=ivector(0,AGESUP);
                   5070:     popeffectif=vector(0,AGESUP);
                   5071:     popcount=vector(0,AGESUP);
                   5072:     
                   5073:     i=1;   
                   5074:     while ((c=fscanf(ficpop,"%d %lf\n",&popage[i],&popcount[i])) != EOF) i=i+1;
                   5075:    
                   5076:     imx=i;
                   5077:     for (i=1; i<imx;i++) popeffectif[popage[i]]=popcount[i];
                   5078:   }
                   5079: 
                   5080:   for(cptcov=1,k=0;cptcov<=i2;cptcov++){
                   5081:    for(cptcod=1;cptcod<=ncodemax[cptcoveff];cptcod++){
                   5082:       k=k+1;
                   5083:       fprintf(ficrespop,"\n#******");
                   5084:       for(j=1;j<=cptcoveff;j++) {
                   5085:        fprintf(ficrespop," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
                   5086:       }
                   5087:       fprintf(ficrespop,"******\n");
                   5088:       fprintf(ficrespop,"# Age");
                   5089:       for(j=1; j<=nlstate+ndeath;j++) fprintf(ficrespop," P.%d",j);
                   5090:       if (popforecast==1)  fprintf(ficrespop," [Population]");
                   5091:       
                   5092:       for (cpt=0; cpt<=0;cpt++) { 
                   5093:        fprintf(ficrespop,"\n\n# Forecasting at date %.lf/%.lf/%.lf ",jpyram,mpyram,anpyram+cpt);   
                   5094:        
                   5095:        for (agedeb=(fage-((int)calagedatem %12/12.)); agedeb>=(ageminpar-((int)calagedatem %12)/12.); agedeb--){ 
                   5096:          nhstepm=(int) rint((agelim-agedeb)*YEARM/stepm); 
                   5097:          nhstepm = nhstepm/hstepm; 
                   5098:          
                   5099:          p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   5100:          oldm=oldms;savm=savms;
                   5101:          hpxij(p3mat,nhstepm,agedeb,hstepm,p,nlstate,stepm,oldm,savm, k);  
                   5102:        
                   5103:          for (h=0; h<=nhstepm; h++){
                   5104:            if (h==(int) (calagedatem+YEARM*cpt)) {
                   5105:              fprintf(ficrespop,"\n %3.f ",agedeb+h*hstepm/YEARM*stepm);
                   5106:            } 
                   5107:            for(j=1; j<=nlstate+ndeath;j++) {
                   5108:              kk1=0.;kk2=0;
                   5109:              for(i=1; i<=nlstate;i++) {              
                   5110:                if (mobilav==1) 
                   5111:                  kk1=kk1+p3mat[i][j][h]*mobaverage[(int)agedeb+1][i][cptcod];
                   5112:                else {
                   5113:                  kk1=kk1+p3mat[i][j][h]*probs[(int)(agedeb+1)][i][cptcod];
                   5114:                }
                   5115:              }
                   5116:              if (h==(int)(calagedatem+12*cpt)){
                   5117:                tabpop[(int)(agedeb)][j][cptcod]=kk1;
                   5118:                  /*fprintf(ficrespop," %.3f", kk1);
                   5119:                    if (popforecast==1) fprintf(ficrespop," [%.f]", kk1*popeffectif[(int)agedeb+1]);*/
                   5120:              }
                   5121:            }
                   5122:            for(i=1; i<=nlstate;i++){
                   5123:              kk1=0.;
                   5124:                for(j=1; j<=nlstate;j++){
                   5125:                  kk1= kk1+tabpop[(int)(agedeb)][j][cptcod]; 
                   5126:                }
                   5127:                  tabpopprev[(int)(agedeb)][i][cptcod]=tabpop[(int)(agedeb)][i][cptcod]/kk1*popeffectif[(int)(agedeb+(calagedatem+12*cpt)*hstepm/YEARM*stepm-1)];
                   5128:            }
                   5129: 
                   5130:            if (h==(int)(calagedatem+12*cpt)) for(j=1; j<=nlstate;j++) 
                   5131:              fprintf(ficrespop," %15.2f",tabpopprev[(int)(agedeb+1)][j][cptcod]);
                   5132:          }
                   5133:          free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   5134:        }
                   5135:       }
                   5136:  
                   5137:   /******/
                   5138: 
                   5139:       for (cpt=1; cpt<=(anpyram1-anpyram);cpt++) { 
                   5140:        fprintf(ficrespop,"\n\n# Forecasting at date %.lf/%.lf/%.lf ",jpyram,mpyram,anpyram+cpt);   
                   5141:        for (agedeb=(fage-((int)calagedatem %12/12.)); agedeb>=(ageminpar-((int)calagedatem %12)/12.); agedeb--){ 
                   5142:          nhstepm=(int) rint((agelim-agedeb)*YEARM/stepm); 
                   5143:          nhstepm = nhstepm/hstepm; 
                   5144:          
                   5145:          p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   5146:          oldm=oldms;savm=savms;
                   5147:          hpxij(p3mat,nhstepm,agedeb,hstepm,p,nlstate,stepm,oldm,savm, k);  
                   5148:          for (h=0; h<=nhstepm; h++){
                   5149:            if (h==(int) (calagedatem+YEARM*cpt)) {
                   5150:              fprintf(ficresf,"\n %3.f ",agedeb+h*hstepm/YEARM*stepm);
                   5151:            } 
                   5152:            for(j=1; j<=nlstate+ndeath;j++) {
                   5153:              kk1=0.;kk2=0;
                   5154:              for(i=1; i<=nlstate;i++) {              
                   5155:                kk1=kk1+p3mat[i][j][h]*tabpopprev[(int)agedeb+1][i][cptcod];    
                   5156:              }
                   5157:              if (h==(int)(calagedatem+12*cpt)) fprintf(ficresf," %15.2f", kk1);        
                   5158:            }
                   5159:          }
                   5160:          free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   5161:        }
                   5162:       }
                   5163:    } 
                   5164:   }
                   5165:  
                   5166:   if (mobilav!=0) free_ma3x(mobaverage,1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
                   5167: 
                   5168:   if (popforecast==1) {
                   5169:     free_ivector(popage,0,AGESUP);
                   5170:     free_vector(popeffectif,0,AGESUP);
                   5171:     free_vector(popcount,0,AGESUP);
                   5172:   }
                   5173:   free_ma3x(tabpop,1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
                   5174:   free_ma3x(tabpopprev,1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
                   5175:   fclose(ficrespop);
                   5176: } /* End of popforecast */
                   5177: 
                   5178: int fileappend(FILE *fichier, char *optionfich)
                   5179: {
                   5180:   if((fichier=fopen(optionfich,"a"))==NULL) {
                   5181:     printf("Problem with file: %s\n", optionfich);
                   5182:     fprintf(ficlog,"Problem with file: %s\n", optionfich);
                   5183:     return (0);
                   5184:   }
                   5185:   fflush(fichier);
                   5186:   return (1);
                   5187: }
                   5188: 
                   5189: 
                   5190: /**************** function prwizard **********************/
                   5191: void prwizard(int ncovmodel, int nlstate, int ndeath,  char model[], FILE *ficparo)
                   5192: {
                   5193: 
                   5194:   /* Wizard to print covariance matrix template */
                   5195: 
1.164     brouard  5196:   char ca[32], cb[32];
                   5197:   int i,j, k, li, lj, lk, ll, jj, npar, itimes;
1.126     brouard  5198:   int numlinepar;
                   5199: 
                   5200:   printf("# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
                   5201:   fprintf(ficparo,"# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
                   5202:   for(i=1; i <=nlstate; i++){
                   5203:     jj=0;
                   5204:     for(j=1; j <=nlstate+ndeath; j++){
                   5205:       if(j==i) continue;
                   5206:       jj++;
                   5207:       /*ca[0]= k+'a'-1;ca[1]='\0';*/
                   5208:       printf("%1d%1d",i,j);
                   5209:       fprintf(ficparo,"%1d%1d",i,j);
                   5210:       for(k=1; k<=ncovmodel;k++){
                   5211:        /*        printf(" %lf",param[i][j][k]); */
                   5212:        /*        fprintf(ficparo," %lf",param[i][j][k]); */
                   5213:        printf(" 0.");
                   5214:        fprintf(ficparo," 0.");
                   5215:       }
                   5216:       printf("\n");
                   5217:       fprintf(ficparo,"\n");
                   5218:     }
                   5219:   }
                   5220:   printf("# Scales (for hessian or gradient estimation)\n");
                   5221:   fprintf(ficparo,"# Scales (for hessian or gradient estimation)\n");
                   5222:   npar= (nlstate+ndeath-1)*nlstate*ncovmodel; /* Number of parameters*/ 
                   5223:   for(i=1; i <=nlstate; i++){
                   5224:     jj=0;
                   5225:     for(j=1; j <=nlstate+ndeath; j++){
                   5226:       if(j==i) continue;
                   5227:       jj++;
                   5228:       fprintf(ficparo,"%1d%1d",i,j);
                   5229:       printf("%1d%1d",i,j);
                   5230:       fflush(stdout);
                   5231:       for(k=1; k<=ncovmodel;k++){
                   5232:        /*      printf(" %le",delti3[i][j][k]); */
                   5233:        /*      fprintf(ficparo," %le",delti3[i][j][k]); */
                   5234:        printf(" 0.");
                   5235:        fprintf(ficparo," 0.");
                   5236:       }
                   5237:       numlinepar++;
                   5238:       printf("\n");
                   5239:       fprintf(ficparo,"\n");
                   5240:     }
                   5241:   }
                   5242:   printf("# Covariance matrix\n");
                   5243: /* # 121 Var(a12)\n\ */
                   5244: /* # 122 Cov(b12,a12) Var(b12)\n\ */
                   5245: /* # 131 Cov(a13,a12) Cov(a13,b12, Var(a13)\n\ */
                   5246: /* # 132 Cov(b13,a12) Cov(b13,b12, Cov(b13,a13) Var(b13)\n\ */
                   5247: /* # 212 Cov(a21,a12) Cov(a21,b12, Cov(a21,a13) Cov(a21,b13) Var(a21)\n\ */
                   5248: /* # 212 Cov(b21,a12) Cov(b21,b12, Cov(b21,a13) Cov(b21,b13) Cov(b21,a21) Var(b21)\n\ */
                   5249: /* # 232 Cov(a23,a12) Cov(a23,b12, Cov(a23,a13) Cov(a23,b13) Cov(a23,a21) Cov(a23,b21) Var(a23)\n\ */
                   5250: /* # 232 Cov(b23,a12) Cov(b23,b12) ... Var (b23)\n" */
                   5251:   fflush(stdout);
                   5252:   fprintf(ficparo,"# Covariance matrix\n");
                   5253:   /* # 121 Var(a12)\n\ */
                   5254:   /* # 122 Cov(b12,a12) Var(b12)\n\ */
                   5255:   /* #   ...\n\ */
                   5256:   /* # 232 Cov(b23,a12)  Cov(b23,b12) ... Var (b23)\n" */
                   5257:   
                   5258:   for(itimes=1;itimes<=2;itimes++){
                   5259:     jj=0;
                   5260:     for(i=1; i <=nlstate; i++){
                   5261:       for(j=1; j <=nlstate+ndeath; j++){
                   5262:        if(j==i) continue;
                   5263:        for(k=1; k<=ncovmodel;k++){
                   5264:          jj++;
                   5265:          ca[0]= k+'a'-1;ca[1]='\0';
                   5266:          if(itimes==1){
                   5267:            printf("#%1d%1d%d",i,j,k);
                   5268:            fprintf(ficparo,"#%1d%1d%d",i,j,k);
                   5269:          }else{
                   5270:            printf("%1d%1d%d",i,j,k);
                   5271:            fprintf(ficparo,"%1d%1d%d",i,j,k);
                   5272:            /*  printf(" %.5le",matcov[i][j]); */
                   5273:          }
                   5274:          ll=0;
                   5275:          for(li=1;li <=nlstate; li++){
                   5276:            for(lj=1;lj <=nlstate+ndeath; lj++){
                   5277:              if(lj==li) continue;
                   5278:              for(lk=1;lk<=ncovmodel;lk++){
                   5279:                ll++;
                   5280:                if(ll<=jj){
                   5281:                  cb[0]= lk +'a'-1;cb[1]='\0';
                   5282:                  if(ll<jj){
                   5283:                    if(itimes==1){
                   5284:                      printf(" Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
                   5285:                      fprintf(ficparo," Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
                   5286:                    }else{
                   5287:                      printf(" 0.");
                   5288:                      fprintf(ficparo," 0.");
                   5289:                    }
                   5290:                  }else{
                   5291:                    if(itimes==1){
                   5292:                      printf(" Var(%s%1d%1d)",ca,i,j);
                   5293:                      fprintf(ficparo," Var(%s%1d%1d)",ca,i,j);
                   5294:                    }else{
                   5295:                      printf(" 0.");
                   5296:                      fprintf(ficparo," 0.");
                   5297:                    }
                   5298:                  }
                   5299:                }
                   5300:              } /* end lk */
                   5301:            } /* end lj */
                   5302:          } /* end li */
                   5303:          printf("\n");
                   5304:          fprintf(ficparo,"\n");
                   5305:          numlinepar++;
                   5306:        } /* end k*/
                   5307:       } /*end j */
                   5308:     } /* end i */
                   5309:   } /* end itimes */
                   5310: 
                   5311: } /* end of prwizard */
                   5312: /******************* Gompertz Likelihood ******************************/
                   5313: double gompertz(double x[])
                   5314: { 
                   5315:   double A,B,L=0.0,sump=0.,num=0.;
                   5316:   int i,n=0; /* n is the size of the sample */
                   5317: 
                   5318:   for (i=0;i<=imx-1 ; i++) {
                   5319:     sump=sump+weight[i];
                   5320:     /*    sump=sump+1;*/
                   5321:     num=num+1;
                   5322:   }
                   5323:  
                   5324:  
                   5325:   /* for (i=0; i<=imx; i++) 
                   5326:      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]);*/
                   5327: 
                   5328:   for (i=1;i<=imx ; i++)
                   5329:     {
                   5330:       if (cens[i] == 1 && wav[i]>1)
                   5331:        A=-x[1]/(x[2])*(exp(x[2]*(agecens[i]-agegomp))-exp(x[2]*(ageexmed[i]-agegomp)));
                   5332:       
                   5333:       if (cens[i] == 0 && wav[i]>1)
                   5334:        A=-x[1]/(x[2])*(exp(x[2]*(agedc[i]-agegomp))-exp(x[2]*(ageexmed[i]-agegomp)))
                   5335:             +log(x[1]/YEARM)+x[2]*(agedc[i]-agegomp)+log(YEARM);  
                   5336:       
                   5337:       /*if (wav[i] > 1 && agecens[i] > 15) {*/ /* ??? */
                   5338:       if (wav[i] > 1 ) { /* ??? */
                   5339:        L=L+A*weight[i];
                   5340:        /*      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]);*/
                   5341:       }
                   5342:     }
                   5343: 
                   5344:  /*printf("x1=%2.9f x2=%2.9f x3=%2.9f L=%f\n",x[1],x[2],x[3],L);*/
                   5345:  
                   5346:   return -2*L*num/sump;
                   5347: }
                   5348: 
1.136     brouard  5349: #ifdef GSL
                   5350: /******************* Gompertz_f Likelihood ******************************/
                   5351: double gompertz_f(const gsl_vector *v, void *params)
                   5352: { 
                   5353:   double A,B,LL=0.0,sump=0.,num=0.;
                   5354:   double *x= (double *) v->data;
                   5355:   int i,n=0; /* n is the size of the sample */
                   5356: 
                   5357:   for (i=0;i<=imx-1 ; i++) {
                   5358:     sump=sump+weight[i];
                   5359:     /*    sump=sump+1;*/
                   5360:     num=num+1;
                   5361:   }
                   5362:  
                   5363:  
                   5364:   /* for (i=0; i<=imx; i++) 
                   5365:      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]);*/
                   5366:   printf("x[0]=%lf x[1]=%lf\n",x[0],x[1]);
                   5367:   for (i=1;i<=imx ; i++)
                   5368:     {
                   5369:       if (cens[i] == 1 && wav[i]>1)
                   5370:        A=-x[0]/(x[1])*(exp(x[1]*(agecens[i]-agegomp))-exp(x[1]*(ageexmed[i]-agegomp)));
                   5371:       
                   5372:       if (cens[i] == 0 && wav[i]>1)
                   5373:        A=-x[0]/(x[1])*(exp(x[1]*(agedc[i]-agegomp))-exp(x[1]*(ageexmed[i]-agegomp)))
                   5374:             +log(x[0]/YEARM)+x[1]*(agedc[i]-agegomp)+log(YEARM);  
                   5375:       
                   5376:       /*if (wav[i] > 1 && agecens[i] > 15) {*/ /* ??? */
                   5377:       if (wav[i] > 1 ) { /* ??? */
                   5378:        LL=LL+A*weight[i];
                   5379:        /*      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]);*/
                   5380:       }
                   5381:     }
                   5382: 
                   5383:  /*printf("x1=%2.9f x2=%2.9f x3=%2.9f L=%f\n",x[1],x[2],x[3],L);*/
                   5384:   printf("x[0]=%lf x[1]=%lf -2*LL*num/sump=%lf\n",x[0],x[1],-2*LL*num/sump);
                   5385:  
                   5386:   return -2*LL*num/sump;
                   5387: }
                   5388: #endif
                   5389: 
1.126     brouard  5390: /******************* Printing html file ***********/
                   5391: void printinghtmlmort(char fileres[], char title[], char datafile[], int firstpass, \
                   5392:                  int lastpass, int stepm, int weightopt, char model[],\
                   5393:                  int imx,  double p[],double **matcov,double agemortsup){
                   5394:   int i,k;
                   5395: 
                   5396:   fprintf(fichtm,"<ul><li><h4>Result files </h4>\n Force of mortality. Parameters of the Gompertz fit (with confidence interval in brackets):<br>");
                   5397:   fprintf(fichtm,"  mu(age) =%lf*exp(%lf*(age-%d)) per year<br><br>",p[1],p[2],agegomp);
                   5398:   for (i=1;i<=2;i++) 
                   5399:     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]));
                   5400:   fprintf(fichtm,"<br><br><img src=\"graphmort.png\">");
                   5401:   fprintf(fichtm,"</ul>");
                   5402: 
                   5403: fprintf(fichtm,"<ul><li><h4>Life table</h4>\n <br>");
                   5404: 
                   5405:  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>");
                   5406: 
                   5407:  for (k=agegomp;k<(agemortsup-2);k++) 
                   5408:    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]);
                   5409: 
                   5410:  
                   5411:   fflush(fichtm);
                   5412: }
                   5413: 
                   5414: /******************* Gnuplot file **************/
                   5415: void printinggnuplotmort(char fileres[], char optionfilefiname[], double ageminpar, double agemaxpar, double fage , char pathc[], double p[]){
                   5416: 
                   5417:   char dirfileres[132],optfileres[132];
1.164     brouard  5418: 
1.126     brouard  5419:   int ng;
                   5420: 
                   5421: 
                   5422:   /*#ifdef windows */
                   5423:   fprintf(ficgp,"cd \"%s\" \n",pathc);
                   5424:     /*#endif */
                   5425: 
                   5426: 
                   5427:   strcpy(dirfileres,optionfilefiname);
                   5428:   strcpy(optfileres,"vpl");
                   5429:   fprintf(ficgp,"set out \"graphmort.png\"\n "); 
                   5430:   fprintf(ficgp,"set xlabel \"Age\"\n set ylabel \"Force of mortality (per year)\" \n "); 
1.145     brouard  5431:   fprintf(ficgp, "set ter png small size 320, 240\n set log y\n"); 
                   5432:   /* fprintf(ficgp, "set size 0.65,0.65\n"); */
1.126     brouard  5433:   fprintf(ficgp,"plot [%d:100] %lf*exp(%lf*(x-%d))",agegomp,p[1],p[2],agegomp);
                   5434: 
                   5435: } 
                   5436: 
1.136     brouard  5437: int readdata(char datafile[], int firstobs, int lastobs, int *imax)
                   5438: {
1.126     brouard  5439: 
1.136     brouard  5440:   /*-------- data file ----------*/
                   5441:   FILE *fic;
                   5442:   char dummy[]="                         ";
1.164     brouard  5443:   int i=0, j=0, n=0;
1.136     brouard  5444:   int linei, month, year,iout;
                   5445:   char line[MAXLINE], linetmp[MAXLINE];
1.164     brouard  5446:   char stra[MAXLINE], strb[MAXLINE];
1.136     brouard  5447:   char *stratrunc;
                   5448:   int lstra;
1.126     brouard  5449: 
                   5450: 
1.136     brouard  5451:   if((fic=fopen(datafile,"r"))==NULL)    {
1.195     brouard  5452:     printf("Problem while opening datafile: %s\n", datafile);fflush(stdout);
                   5453:     fprintf(ficlog,"Problem while opening datafile: %s\n", datafile);fflush(ficlog);return 1;
1.136     brouard  5454:   }
1.126     brouard  5455: 
1.136     brouard  5456:   i=1;
                   5457:   linei=0;
                   5458:   while ((fgets(line, MAXLINE, fic) != NULL) &&((i >= firstobs) && (i <=lastobs))) {
                   5459:     linei=linei+1;
                   5460:     for(j=strlen(line); j>=0;j--){  /* Untabifies line */
                   5461:       if(line[j] == '\t')
                   5462:        line[j] = ' ';
                   5463:     }
                   5464:     for(j=strlen(line)-1; (line[j]==' ')||(line[j]==10)||(line[j]==13);j--){
                   5465:       ;
                   5466:     };
                   5467:     line[j+1]=0;  /* Trims blanks at end of line */
                   5468:     if(line[0]=='#'){
                   5469:       fprintf(ficlog,"Comment line\n%s\n",line);
                   5470:       printf("Comment line\n%s\n",line);
                   5471:       continue;
                   5472:     }
                   5473:     trimbb(linetmp,line); /* Trims multiple blanks in line */
1.164     brouard  5474:     strcpy(line, linetmp);
1.136     brouard  5475:   
1.126     brouard  5476: 
1.136     brouard  5477:     for (j=maxwav;j>=1;j--){
1.137     brouard  5478:       cutv(stra, strb, line, ' '); 
1.136     brouard  5479:       if(strb[0]=='.') { /* Missing status */
                   5480:        lval=-1;
                   5481:       }else{
                   5482:        errno=0;
                   5483:        lval=strtol(strb,&endptr,10); 
                   5484:       /*       if (errno == ERANGE && (lval == LONG_MAX || lval == LONG_MIN))*/
                   5485:        if( strb[0]=='\0' || (*endptr != '\0')){
1.141     brouard  5486:          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);
                   5487:          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  5488:          return 1;
                   5489:        }
                   5490:       }
                   5491:       s[j][i]=lval;
                   5492:       
                   5493:       strcpy(line,stra);
                   5494:       cutv(stra, strb,line,' ');
1.169     brouard  5495:       if( (iout=sscanf(strb,"%d/%d",&month, &year)) != 0){
1.136     brouard  5496:       }
1.169     brouard  5497:       else  if( (iout=sscanf(strb,"%s.",dummy)) != 0){
1.136     brouard  5498:        month=99;
                   5499:        year=9999;
                   5500:       }else{
1.141     brouard  5501:        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);
                   5502:        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  5503:        return 1;
                   5504:       }
                   5505:       anint[j][i]= (double) year; 
                   5506:       mint[j][i]= (double)month; 
                   5507:       strcpy(line,stra);
                   5508:     } /* ENd Waves */
                   5509:     
                   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 death (mm/yyyy or .).  Exiting.\n",strb, linei,i,line);
                   5518:        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  5519:        return 1;
                   5520:     }
                   5521:     andc[i]=(double) year; 
                   5522:     moisdc[i]=(double) month; 
                   5523:     strcpy(line,stra);
                   5524:     
                   5525:     cutv(stra, strb,line,' '); 
1.169     brouard  5526:     if( (iout=sscanf(strb,"%d/%d",&month, &year)) != 0){
1.136     brouard  5527:     }
1.169     brouard  5528:     else  if( (iout=sscanf(strb,"%s.", dummy)) != 0){
1.136     brouard  5529:       month=99;
                   5530:       year=9999;
                   5531:     }else{
1.141     brouard  5532:       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);
                   5533:       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  5534:        return 1;
                   5535:     }
                   5536:     if (year==9999) {
1.141     brouard  5537:       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);
                   5538:       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  5539:        return 1;
1.126     brouard  5540: 
1.136     brouard  5541:     }
                   5542:     annais[i]=(double)(year);
                   5543:     moisnais[i]=(double)(month); 
                   5544:     strcpy(line,stra);
                   5545:     
                   5546:     cutv(stra, strb,line,' '); 
                   5547:     errno=0;
                   5548:     dval=strtod(strb,&endptr); 
                   5549:     if( strb[0]=='\0' || (*endptr != '\0')){
1.141     brouard  5550:       printf("Error reading data around '%f' at line number %d, \"%s\" for individual %d\nShould be a weight.  Exiting.\n",dval, i,line,linei);
                   5551:       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  5552:       fflush(ficlog);
                   5553:       return 1;
                   5554:     }
                   5555:     weight[i]=dval; 
                   5556:     strcpy(line,stra);
                   5557:     
                   5558:     for (j=ncovcol;j>=1;j--){
                   5559:       cutv(stra, strb,line,' '); 
                   5560:       if(strb[0]=='.') { /* Missing status */
                   5561:        lval=-1;
                   5562:       }else{
                   5563:        errno=0;
                   5564:        lval=strtol(strb,&endptr,10); 
                   5565:        if( strb[0]=='\0' || (*endptr != '\0')){
1.141     brouard  5566:          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);
                   5567:          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  5568:          return 1;
                   5569:        }
                   5570:       }
                   5571:       if(lval <-1 || lval >1){
1.141     brouard  5572:        printf("Error reading data around '%ld' at line number %d for individual %d, '%s'\n \
1.136     brouard  5573:  Should be a value of %d(nth) covariate (0 should be the value for the reference and 1\n \
                   5574:  for the alternative. IMaCh does not build design variables automatically, do it yourself.\n \
                   5575:  For example, for multinomial values like 1, 2 and 3,\n \
                   5576:  build V1=0 V2=0 for the reference value (1),\n \
                   5577:         V1=1 V2=0 for (2) \n \
                   5578:  and V1=0 V2=1 for (3). V1=1 V2=1 should not exist and the corresponding\n \
                   5579:  output of IMaCh is often meaningless.\n \
                   5580:  Exiting.\n",lval,linei, i,line,j);
1.141     brouard  5581:        fprintf(ficlog,"Error reading data around '%ld' at line number %d for individual %d, '%s'\n \
1.136     brouard  5582:  Should be a value of %d(nth) covariate (0 should be the value for the reference and 1\n \
                   5583:  for the alternative. IMaCh does not build design variables automatically, do it yourself.\n \
                   5584:  For example, for multinomial values like 1, 2 and 3,\n \
                   5585:  build V1=0 V2=0 for the reference value (1),\n \
                   5586:         V1=1 V2=0 for (2) \n \
                   5587:  and V1=0 V2=1 for (3). V1=1 V2=1 should not exist and the corresponding\n \
                   5588:  output of IMaCh is often meaningless.\n \
                   5589:  Exiting.\n",lval,linei, i,line,j);fflush(ficlog);
                   5590:        return 1;
                   5591:       }
                   5592:       covar[j][i]=(double)(lval);
                   5593:       strcpy(line,stra);
                   5594:     }  
                   5595:     lstra=strlen(stra);
                   5596:      
                   5597:     if(lstra > 9){ /* More than 2**32 or max of what printf can write with %ld */
                   5598:       stratrunc = &(stra[lstra-9]);
                   5599:       num[i]=atol(stratrunc);
                   5600:     }
                   5601:     else
                   5602:       num[i]=atol(stra);
                   5603:     /*if((s[2][i]==2) && (s[3][i]==-1)&&(s[4][i]==9)){
                   5604:       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;}*/
                   5605:     
                   5606:     i=i+1;
                   5607:   } /* End loop reading  data */
1.126     brouard  5608: 
1.136     brouard  5609:   *imax=i-1; /* Number of individuals */
                   5610:   fclose(fic);
                   5611:  
                   5612:   return (0);
1.164     brouard  5613:   /* endread: */
1.136     brouard  5614:     printf("Exiting readdata: ");
                   5615:     fclose(fic);
                   5616:     return (1);
1.126     brouard  5617: 
                   5618: 
                   5619: 
1.136     brouard  5620: }
1.145     brouard  5621: void removespace(char *str) {
                   5622:   char *p1 = str, *p2 = str;
                   5623:   do
                   5624:     while (*p2 == ' ')
                   5625:       p2++;
1.169     brouard  5626:   while (*p1++ == *p2++);
1.145     brouard  5627: }
                   5628: 
                   5629: int decodemodel ( char model[], int lastobs) /**< This routine decode the model and returns:
1.187     brouard  5630:    * Model  V1+V2+V3+V8+V7*V8+V5*V6+V8*age+V3*age+age*age
                   5631:    * - nagesqr = 1 if age*age in the model, otherwise 0.
                   5632:    * - cptcovt total number of covariates of the model nbocc(+)+1 = 8 excepting constant and age and age*age
                   5633:    * - cptcovn or number of covariates k of the models excluding age*products =6 and age*age
1.145     brouard  5634:    * - cptcovage number of covariates with age*products =2
                   5635:    * - cptcovs number of simple covariates
                   5636:    * - 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
                   5637:    *     which is a new column after the 9 (ncovcol) variables. 
                   5638:    * - if k is a product Vn*Vm covar[k][i] is filled with correct values for each individual
                   5639:    * - Tprod[l] gives the kth covariates of the product Vn*Vm l=1 to cptcovprod-cptcovage
                   5640:    *    Tprod[1]@2 {5, 6}: position of first product V7*V8 is 5, and second V5*V6 is 6.
                   5641:    * - Tvard[k]  p Tvard[1][1]@4 {7, 8, 5, 6} for V7*V8 and V5*V6 .
                   5642:  */
1.136     brouard  5643: {
1.145     brouard  5644:   int i, j, k, ks;
1.164     brouard  5645:   int  j1, k1, k2;
1.136     brouard  5646:   char modelsav[80];
1.145     brouard  5647:   char stra[80], strb[80], strc[80], strd[80],stre[80];
1.187     brouard  5648:   char *strpt;
1.136     brouard  5649: 
1.145     brouard  5650:   /*removespace(model);*/
1.136     brouard  5651:   if (strlen(model) >1){ /* If there is at least 1 covariate */
1.145     brouard  5652:     j=0, j1=0, k1=0, k2=-1, ks=0, cptcovn=0;
1.137     brouard  5653:     if (strstr(model,"AGE") !=0){
1.192     brouard  5654:       printf("Error. AGE must be in lower case 'age' model=1+age+%s. ",model);
                   5655:       fprintf(ficlog,"Error. AGE must be in lower case model=1+age+%s. ",model);fflush(ficlog);
1.136     brouard  5656:       return 1;
                   5657:     }
1.141     brouard  5658:     if (strstr(model,"v") !=0){
                   5659:       printf("Error. 'v' must be in upper case 'V' model=%s ",model);
                   5660:       fprintf(ficlog,"Error. 'v' must be in upper case model=%s ",model);fflush(ficlog);
                   5661:       return 1;
                   5662:     }
1.187     brouard  5663:     strcpy(modelsav,model); 
                   5664:     if ((strpt=strstr(model,"age*age")) !=0){
                   5665:       printf(" strpt=%s, model=%s\n",strpt, model);
                   5666:       if(strpt != model){
                   5667:       printf("Error in model: 'model=%s'; 'age*age' should in first place before other covariates\n \
1.192     brouard  5668:  'model=1+age+age*age+V1.' or 'model=1+age+age*age+V1+V1*age.', please swap as well as \n \
1.187     brouard  5669:  corresponding column of parameters.\n",model);
                   5670:       fprintf(ficlog,"Error in model: 'model=%s'; 'age*age' should in first place before other covariates\n \
1.192     brouard  5671:  'model=1+age+age*age+V1.' or 'model=1+age+age*age+V1+V1*age.', please swap as well as \n \
1.187     brouard  5672:  corresponding column of parameters.\n",model); fflush(ficlog);
                   5673:       return 1;
                   5674:     }
                   5675: 
                   5676:       nagesqr=1;
                   5677:       if (strstr(model,"+age*age") !=0)
                   5678:        substrchaine(modelsav, model, "+age*age");
                   5679:       else if (strstr(model,"age*age+") !=0)
                   5680:        substrchaine(modelsav, model, "age*age+");
                   5681:       else 
                   5682:        substrchaine(modelsav, model, "age*age");
                   5683:     }else
                   5684:       nagesqr=0;
                   5685:     if (strlen(modelsav) >1){
                   5686:       j=nbocc(modelsav,'+'); /**< j=Number of '+' */
                   5687:       j1=nbocc(modelsav,'*'); /**< j1=Number of '*' */
                   5688:       cptcovs=j+1-j1; /**<  Number of simple covariates V1+V1*age+V3 +V3*V4+age*age=> V1 + V3 =2  */
                   5689:       cptcovt= j+1; /* Number of total covariates in the model, not including
                   5690:                   * cst, age and age*age 
                   5691:                   * V1+V1*age+ V3 + V3*V4+age*age=> 4*/
                   5692:                   /* including age products which are counted in cptcovage.
                   5693:                  * but the covariates which are products must be treated 
                   5694:                  * separately: ncovn=4- 2=2 (V1+V3). */
                   5695:       cptcovprod=j1; /**< Number of products  V1*V2 +v3*age = 2 */
                   5696:       cptcovprodnoage=0; /**< Number of covariate products without age: V3*V4 =1  */
                   5697: 
                   5698:     
                   5699:       /*   Design
                   5700:        *  V1   V2   V3   V4  V5  V6  V7  V8  V9 Weight
                   5701:        *  <          ncovcol=8                >
                   5702:        * Model V2 + V1 + V3*age + V3 + V5*V6 + V7*V8 + V8*age + V8
                   5703:        *   k=  1    2      3       4     5       6      7        8
                   5704:        *  cptcovn number of covariates (not including constant and age ) = # of + plus 1 = 7+1=8
                   5705:        *  covar[k,i], value of kth covariate if not including age for individual i:
                   5706:        *       covar[1][i]= (V2), covar[4][i]=(V3), covar[8][i]=(V8)
                   5707:        *  Tvar[k] # of the kth covariate:  Tvar[1]=2  Tvar[4]=3 Tvar[8]=8
                   5708:        *       if multiplied by age: V3*age Tvar[3=V3*age]=3 (V3) Tvar[7]=8 and 
                   5709:        *  Tage[++cptcovage]=k
                   5710:        *       if products, new covar are created after ncovcol with k1
                   5711:        *  Tvar[k]=ncovcol+k1; # of the kth covariate product:  Tvar[5]=ncovcol+1=10  Tvar[6]=ncovcol+1=11
                   5712:        *  Tprod[k1]=k; Tprod[1]=5 Tprod[2]= 6; gives the position of the k1th product
                   5713:        *  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
                   5714:        *  Tvar[cptcovn+k2]=Tvard[k1][1];Tvar[cptcovn+k2+1]=Tvard[k1][2];
                   5715:        *  Tvar[8+1]=5;Tvar[8+2]=6;Tvar[8+3]=7;Tvar[8+4]=8 inverted
                   5716:        *  V1   V2   V3   V4  V5  V6  V7  V8  V9  V10  V11
                   5717:        *  <          ncovcol=8                >
                   5718:        *       Model V2 + V1 + V3*age + V3 + V5*V6 + V7*V8 + V8*age + V8    d1   d1   d2  d2
                   5719:        *          k=  1    2      3       4     5       6      7        8    9   10   11  12
                   5720:        *     Tvar[k]= 2    1      3       3    10      11      8        8    5    6    7   8
                   5721:        * p Tvar[1]@12={2,   1,     3,      3,   11,     10,     8,       8,   7,   8,   5,  6}
                   5722:        * p Tprod[1]@2={                         6, 5}
                   5723:        *p Tvard[1][1]@4= {7, 8, 5, 6}
                   5724:        * covar[k][i]= V2   V1      ?      V3    V5*V6?   V7*V8?  ?       V8   
                   5725:        *  cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*cov[2];
                   5726:        *How to reorganize?
                   5727:        * Model V1 + V2 + V3 + V8 + V5*V6 + V7*V8 + V3*age + V8*age
                   5728:        * Tvars {2,   1,     3,      3,   11,     10,     8,       8,   7,   8,   5,  6}
                   5729:        *       {2,   1,     4,      8,    5,      6,     3,       7}
                   5730:        * Struct []
                   5731:        */
1.145     brouard  5732: 
1.187     brouard  5733:       /* This loop fills the array Tvar from the string 'model'.*/
                   5734:       /* j is the number of + signs in the model V1+V2+V3 j=2 i=3 to 1 */
                   5735:       /*   modelsav=V2+V1+V4+age*V3 strb=age*V3 stra=V2+V1+V4  */
                   5736:       /*       k=4 (age*V3) Tvar[k=4]= 3 (from V3) Tage[cptcovage=1]=4 */
                   5737:       /*       k=3 V4 Tvar[k=3]= 4 (from V4) */
                   5738:       /*       k=2 V1 Tvar[k=2]= 1 (from V1) */
                   5739:       /*       k=1 Tvar[1]=2 (from V2) */
                   5740:       /*       k=5 Tvar[5] */
                   5741:       /* for (k=1; k<=cptcovn;k++) { */
                   5742:       /*       cov[2+k]=nbcode[Tvar[k]][codtab[ij][Tvar[k]]]; */
                   5743:       /*       } */
                   5744:       /* for (k=1; k<=cptcovage;k++) cov[2+Tage[k]]=nbcode[Tvar[Tage[k]]][codtab[ij][Tvar[Tage[k]]]]*cov[2]; */
                   5745:       /*
                   5746:        * Treating invertedly V2+V1+V3*age+V2*V4 is as if written V2*V4 +V3*age + V1 + V2 */
                   5747:       for(k=cptcovt; k>=1;k--) /**< Number of covariates */
1.145     brouard  5748:         Tvar[k]=0;
1.187     brouard  5749:       cptcovage=0;
                   5750:       for(k=1; k<=cptcovt;k++){ /* Loop on total covariates of the model */
                   5751:        cutl(stra,strb,modelsav,'+'); /* keeps in strb after the first '+' 
                   5752:                                         modelsav==V2+V1+V4+V3*age strb=V3*age stra=V2+V1+V4 */ 
                   5753:        if (nbocc(modelsav,'+')==0) strcpy(strb,modelsav); /* and analyzes it */
                   5754:        /*      printf("i=%d a=%s b=%s sav=%s\n",i, stra,strb,modelsav);*/
                   5755:        /*scanf("%d",i);*/
                   5756:        if (strchr(strb,'*')) {  /**< Model includes a product V2+V1+V4+V3*age strb=V3*age */
                   5757:          cutl(strc,strd,strb,'*'); /**< strd*strc  Vm*Vn: strb=V3*age(input) strc=age strd=V3 ; V3*V2 strc=V2, strd=V3 */
                   5758:          if (strcmp(strc,"age")==0) { /**< Model includes age: Vn*age */
                   5759:            /* covar is not filled and then is empty */
                   5760:            cptcovprod--;
                   5761:            cutl(stre,strb,strd,'V'); /* strd=V3(input): stre="3" */
                   5762:            Tvar[k]=atoi(stre);  /* V2+V1+V4+V3*age Tvar[4]=3 ; V1+V2*age Tvar[2]=2; V1+V1*age Tvar[2]=1 */
                   5763:            cptcovage++; /* Sums the number of covariates which include age as a product */
                   5764:            Tage[cptcovage]=k;  /* Tvar[4]=3, Tage[1] = 4 or V1+V1*age Tvar[2]=1, Tage[1]=2 */
                   5765:            /*printf("stre=%s ", stre);*/
                   5766:          } else if (strcmp(strd,"age")==0) { /* or age*Vn */
                   5767:            cptcovprod--;
                   5768:            cutl(stre,strb,strc,'V');
                   5769:            Tvar[k]=atoi(stre);
                   5770:            cptcovage++;
                   5771:            Tage[cptcovage]=k;
                   5772:          } else {  /* Age is not in the model product V2+V1+V1*V4+V3*age+V3*V2  strb=V3*V2*/
                   5773:            /* loops on k1=1 (V3*V2) and k1=2 V4*V3 */
                   5774:            cptcovn++;
                   5775:            cptcovprodnoage++;k1++;
                   5776:            cutl(stre,strb,strc,'V'); /* strc= Vn, stre is n; strb=V3*V2 stre=3 strc=*/
                   5777:            Tvar[k]=ncovcol+k1; /* For model-covariate k tells which data-covariate to use but
                   5778:                                   because this model-covariate is a construction we invent a new column
                   5779:                                   ncovcol + k1
                   5780:                                   If already ncovcol=4 and model=V2+V1+V1*V4+age*V3+V3*V2
                   5781:                                   Tvar[3=V1*V4]=4+1 Tvar[5=V3*V2]=4 + 2= 6, etc */
                   5782:            cutl(strc,strb,strd,'V'); /* strd was Vm, strc is m */
                   5783:            Tprod[k1]=k;  /* Tprod[1]=3(=V1*V4) for V2+V1+V1*V4+age*V3+V3*V2  */
                   5784:            Tvard[k1][1] =atoi(strc); /* m 1 for V1*/
                   5785:            Tvard[k1][2] =atoi(stre); /* n 4 for V4*/
                   5786:            k2=k2+2;
                   5787:            Tvar[cptcovt+k2]=Tvard[k1][1]; /* Tvar[(cptcovt=4+k2=1)=5]= 1 (V1) */
                   5788:            Tvar[cptcovt+k2+1]=Tvard[k1][2];  /* Tvar[(cptcovt=4+(k2=1)+1)=6]= 4 (V4) */
                   5789:            for (i=1; i<=lastobs;i++){
                   5790:              /* Computes the new covariate which is a product of
                   5791:                 covar[n][i]* covar[m][i] and stores it at ncovol+k1 May not be defined */
                   5792:              covar[ncovcol+k1][i]=covar[atoi(stre)][i]*covar[atoi(strc)][i];
                   5793:            }
                   5794:          } /* End age is not in the model */
                   5795:        } /* End if model includes a product */
                   5796:        else { /* no more sum */
                   5797:          /*printf("d=%s c=%s b=%s\n", strd,strc,strb);*/
                   5798:          /*  scanf("%d",i);*/
                   5799:          cutl(strd,strc,strb,'V');
                   5800:          ks++; /**< Number of simple covariates */
1.145     brouard  5801:          cptcovn++;
1.187     brouard  5802:          Tvar[k]=atoi(strd);
                   5803:        }
                   5804:        strcpy(modelsav,stra);  /* modelsav=V2+V1+V4 stra=V2+V1+V4 */ 
                   5805:        /*printf("a=%s b=%s sav=%s\n", stra,strb,modelsav);
                   5806:          scanf("%d",i);*/
                   5807:       } /* end of loop + on total covariates */
                   5808:     } /* end if strlen(modelsave == 0) age*age might exist */
                   5809:   } /* end if strlen(model == 0) */
1.136     brouard  5810:   
                   5811:   /*The number n of Vn is stored in Tvar. cptcovage =number of age covariate. Tage gives the position of age. cptcovprod= number of products.
                   5812:     If model=V1+V1*age then Tvar[1]=1 Tvar[2]=1 cptcovage=1 Tage[1]=2 cptcovprod=0*/
                   5813: 
                   5814:   /* printf("tvar1=%d tvar2=%d tvar3=%d cptcovage=%d Tage=%d",Tvar[1],Tvar[2],Tvar[3],cptcovage,Tage[1]);
                   5815:   printf("cptcovprod=%d ", cptcovprod);
                   5816:   fprintf(ficlog,"cptcovprod=%d ", cptcovprod);
                   5817: 
                   5818:   scanf("%d ",i);*/
                   5819: 
                   5820: 
1.137     brouard  5821:   return (0); /* with covar[new additional covariate if product] and Tage if age */ 
1.164     brouard  5822:   /*endread:*/
1.136     brouard  5823:     printf("Exiting decodemodel: ");
                   5824:     return (1);
                   5825: }
                   5826: 
1.169     brouard  5827: int calandcheckages(int imx, int maxwav, double *agemin, double *agemax, int *nberr, int *nbwarn )
1.136     brouard  5828: {
                   5829:   int i, m;
                   5830: 
                   5831:   for (i=1; i<=imx; i++) {
                   5832:     for(m=2; (m<= maxwav); m++) {
                   5833:       if (((int)mint[m][i]== 99) && (s[m][i] <= nlstate)){
                   5834:        anint[m][i]=9999;
                   5835:        s[m][i]=-1;
                   5836:       }
                   5837:       if((int)moisdc[i]==99 && (int)andc[i]==9999 && s[m][i]>nlstate){
1.169     brouard  5838:        *nberr = *nberr + 1;
                   5839:        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);
                   5840:        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  5841:        s[m][i]=-1;
                   5842:       }
                   5843:       if((int)moisdc[i]==99 && (int)andc[i]!=9999 && s[m][i]>nlstate){
1.169     brouard  5844:        (*nberr)++;
1.136     brouard  5845:        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]); 
                   5846:        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]); 
                   5847:        s[m][i]=-1; /* We prefer to skip it (and to skip it in version 0.8a1 too */
                   5848:       }
                   5849:     }
                   5850:   }
                   5851: 
                   5852:   for (i=1; i<=imx; i++)  {
                   5853:     agedc[i]=(moisdc[i]/12.+andc[i])-(moisnais[i]/12.+annais[i]);
                   5854:     for(m=firstpass; (m<= lastpass); m++){
                   5855:       if(s[m][i] >0 || s[m][i]==-2 || s[m][i]==-4 || s[m][i]==-5){
                   5856:        if (s[m][i] >= nlstate+1) {
1.169     brouard  5857:          if(agedc[i]>0){
                   5858:            if((int)moisdc[i]!=99 && (int)andc[i]!=9999){
1.136     brouard  5859:              agev[m][i]=agedc[i];
                   5860:          /*if(moisdc[i]==99 && andc[i]==9999) s[m][i]=-1;*/
1.169     brouard  5861:            }else {
1.136     brouard  5862:              if ((int)andc[i]!=9999){
                   5863:                nbwarn++;
                   5864:                printf("Warning negative age at death: %ld line:%d\n",num[i],i);
                   5865:                fprintf(ficlog,"Warning negative age at death: %ld line:%d\n",num[i],i);
                   5866:                agev[m][i]=-1;
                   5867:              }
                   5868:            }
1.169     brouard  5869:          } /* agedc > 0 */
1.136     brouard  5870:        }
                   5871:        else if(s[m][i] !=9){ /* Standard case, age in fractional
                   5872:                                 years but with the precision of a month */
                   5873:          agev[m][i]=(mint[m][i]/12.+1./24.+anint[m][i])-(moisnais[i]/12.+1./24.+annais[i]);
                   5874:          if((int)mint[m][i]==99 || (int)anint[m][i]==9999)
                   5875:            agev[m][i]=1;
                   5876:          else if(agev[m][i] < *agemin){ 
                   5877:            *agemin=agev[m][i];
                   5878:            printf(" Min anint[%d][%d]=%.2f annais[%d]=%.2f, agemin=%.2f\n",m,i,anint[m][i], i,annais[i], *agemin);
                   5879:          }
                   5880:          else if(agev[m][i] >*agemax){
                   5881:            *agemax=agev[m][i];
1.156     brouard  5882:            /* printf(" Max anint[%d][%d]=%.0f annais[%d]=%.0f, agemax=%.2f\n",m,i,anint[m][i], i,annais[i], *agemax);*/
1.136     brouard  5883:          }
                   5884:          /*agev[m][i]=anint[m][i]-annais[i];*/
                   5885:          /*     agev[m][i] = age[i]+2*m;*/
                   5886:        }
                   5887:        else { /* =9 */
                   5888:          agev[m][i]=1;
                   5889:          s[m][i]=-1;
                   5890:        }
                   5891:       }
                   5892:       else /*= 0 Unknown */
                   5893:        agev[m][i]=1;
                   5894:     }
                   5895:     
                   5896:   }
                   5897:   for (i=1; i<=imx; i++)  {
                   5898:     for(m=firstpass; (m<=lastpass); m++){
                   5899:       if (s[m][i] > (nlstate+ndeath)) {
1.169     brouard  5900:        (*nberr)++;
1.136     brouard  5901:        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);     
                   5902:        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);     
                   5903:        return 1;
                   5904:       }
                   5905:     }
                   5906:   }
                   5907: 
                   5908:   /*for (i=1; i<=imx; i++){
                   5909:   for (m=firstpass; (m<lastpass); m++){
                   5910:      printf("%ld %d %.lf %d %d\n", num[i],(covar[1][i]),agev[m][i],s[m][i],s[m+1][i]);
                   5911: }
                   5912: 
                   5913: }*/
                   5914: 
                   5915: 
1.139     brouard  5916:   printf("Total number of individuals= %d, Agemin = %.2f, Agemax= %.2f\n\n", imx, *agemin, *agemax);
                   5917:   fprintf(ficlog,"Total number of individuals= %d, Agemin = %.2f, Agemax= %.2f\n\n", imx, *agemin, *agemax); 
1.136     brouard  5918: 
                   5919:   return (0);
1.164     brouard  5920:  /* endread:*/
1.136     brouard  5921:     printf("Exiting calandcheckages: ");
                   5922:     return (1);
                   5923: }
                   5924: 
1.172     brouard  5925: #if defined(_MSC_VER)
                   5926: /*printf("Visual C++ compiler: %s \n;", _MSC_FULL_VER);*/
                   5927: /*fprintf(ficlog, "Visual C++ compiler: %s \n;", _MSC_FULL_VER);*/
                   5928: //#include "stdafx.h"
                   5929: //#include <stdio.h>
                   5930: //#include <tchar.h>
                   5931: //#include <windows.h>
                   5932: //#include <iostream>
                   5933: typedef BOOL(WINAPI *LPFN_ISWOW64PROCESS) (HANDLE, PBOOL);
                   5934: 
                   5935: LPFN_ISWOW64PROCESS fnIsWow64Process;
                   5936: 
                   5937: BOOL IsWow64()
                   5938: {
                   5939:        BOOL bIsWow64 = FALSE;
                   5940: 
                   5941:        //typedef BOOL (APIENTRY *LPFN_ISWOW64PROCESS)
                   5942:        //  (HANDLE, PBOOL);
                   5943: 
                   5944:        //LPFN_ISWOW64PROCESS fnIsWow64Process;
                   5945: 
                   5946:        HMODULE module = GetModuleHandle(_T("kernel32"));
                   5947:        const char funcName[] = "IsWow64Process";
                   5948:        fnIsWow64Process = (LPFN_ISWOW64PROCESS)
                   5949:                GetProcAddress(module, funcName);
                   5950: 
                   5951:        if (NULL != fnIsWow64Process)
                   5952:        {
                   5953:                if (!fnIsWow64Process(GetCurrentProcess(),
                   5954:                        &bIsWow64))
                   5955:                        //throw std::exception("Unknown error");
                   5956:                        printf("Unknown error\n");
                   5957:        }
                   5958:        return bIsWow64 != FALSE;
                   5959: }
                   5960: #endif
1.177     brouard  5961: 
1.191     brouard  5962: void syscompilerinfo(int logged)
1.167     brouard  5963:  {
                   5964:    /* #include "syscompilerinfo.h"*/
1.185     brouard  5965:    /* command line Intel compiler 32bit windows, XP compatible:*/
                   5966:    /* /GS /W3 /Gy
                   5967:       /Zc:wchar_t /Zi /O2 /Fd"Release\vc120.pdb" /D "WIN32" /D "NDEBUG" /D
                   5968:       "_CONSOLE" /D "_LIB" /D "_USING_V110_SDK71_" /D "_UNICODE" /D
                   5969:       "UNICODE" /Qipo /Zc:forScope /Gd /Oi /MT /Fa"Release\" /EHsc /nologo
1.186     brouard  5970:       /Fo"Release\" /Qprof-dir "Release\" /Fp"Release\IMaCh.pch"
                   5971:    */ 
                   5972:    /* 64 bits */
1.185     brouard  5973:    /*
                   5974:      /GS /W3 /Gy
                   5975:      /Zc:wchar_t /Zi /O2 /Fd"x64\Release\vc120.pdb" /D "WIN32" /D "NDEBUG"
                   5976:      /D "_CONSOLE" /D "_LIB" /D "_UNICODE" /D "UNICODE" /Qipo /Zc:forScope
                   5977:      /Oi /MD /Fa"x64\Release\" /EHsc /nologo /Fo"x64\Release\" /Qprof-dir
                   5978:      "x64\Release\" /Fp"x64\Release\IMaCh.pch" */
                   5979:    /* Optimization are useless and O3 is slower than O2 */
                   5980:    /*
                   5981:      /GS /W3 /Gy /Zc:wchar_t /Zi /O3 /Fd"x64\Release\vc120.pdb" /D "WIN32" 
                   5982:      /D "NDEBUG" /D "_CONSOLE" /D "_LIB" /D "_UNICODE" /D "UNICODE" /Qipo 
                   5983:      /Zc:forScope /Oi /MD /Fa"x64\Release\" /EHsc /nologo /Qparallel 
                   5984:      /Fo"x64\Release\" /Qprof-dir "x64\Release\" /Fp"x64\Release\IMaCh.pch" 
                   5985:    */
1.186     brouard  5986:    /* Link is */ /* /OUT:"visual studio
1.185     brouard  5987:       2013\Projects\IMaCh\Release\IMaCh.exe" /MANIFEST /NXCOMPAT
                   5988:       /PDB:"visual studio
                   5989:       2013\Projects\IMaCh\Release\IMaCh.pdb" /DYNAMICBASE
                   5990:       "kernel32.lib" "user32.lib" "gdi32.lib" "winspool.lib"
                   5991:       "comdlg32.lib" "advapi32.lib" "shell32.lib" "ole32.lib"
                   5992:       "oleaut32.lib" "uuid.lib" "odbc32.lib" "odbccp32.lib"
                   5993:       /MACHINE:X86 /OPT:REF /SAFESEH /INCREMENTAL:NO
                   5994:       /SUBSYSTEM:CONSOLE",5.01" /MANIFESTUAC:"level='asInvoker'
                   5995:       uiAccess='false'"
                   5996:       /ManifestFile:"Release\IMaCh.exe.intermediate.manifest" /OPT:ICF
                   5997:       /NOLOGO /TLBID:1
                   5998:    */
1.177     brouard  5999: #if defined __INTEL_COMPILER
1.178     brouard  6000: #if defined(__GNUC__)
                   6001:        struct utsname sysInfo;  /* For Intel on Linux and OS/X */
                   6002: #endif
1.177     brouard  6003: #elif defined(__GNUC__) 
1.179     brouard  6004: #ifndef  __APPLE__
1.174     brouard  6005: #include <gnu/libc-version.h>  /* Only on gnu */
1.179     brouard  6006: #endif
1.177     brouard  6007:    struct utsname sysInfo;
1.178     brouard  6008:    int cross = CROSS;
                   6009:    if (cross){
                   6010:           printf("Cross-");
1.191     brouard  6011:           if(logged) fprintf(ficlog, "Cross-");
1.178     brouard  6012:    }
1.174     brouard  6013: #endif
                   6014: 
1.171     brouard  6015: #include <stdint.h>
1.178     brouard  6016: 
1.191     brouard  6017:    printf("Compiled with:");if(logged)fprintf(ficlog,"Compiled with:");
1.169     brouard  6018: #if defined(__clang__)
1.191     brouard  6019:    printf(" Clang/LLVM");if(logged)fprintf(ficlog," Clang/LLVM");      /* Clang/LLVM. ---------------------------------------------- */
1.169     brouard  6020: #endif
                   6021: #if defined(__ICC) || defined(__INTEL_COMPILER)
1.191     brouard  6022:    printf(" Intel ICC/ICPC");if(logged)fprintf(ficlog," Intel ICC/ICPC");/* Intel ICC/ICPC. ------------------------------------------ */
1.169     brouard  6023: #endif
                   6024: #if defined(__GNUC__) || defined(__GNUG__)
1.191     brouard  6025:    printf(" GNU GCC/G++");if(logged)fprintf(ficlog," GNU GCC/G++");/* GNU GCC/G++. --------------------------------------------- */
1.169     brouard  6026: #endif
                   6027: #if defined(__HP_cc) || defined(__HP_aCC)
1.191     brouard  6028:    printf(" Hewlett-Packard C/aC++");if(logged)fprintf(fcilog," Hewlett-Packard C/aC++"); /* Hewlett-Packard C/aC++. ---------------------------------- */
1.169     brouard  6029: #endif
                   6030: #if defined(__IBMC__) || defined(__IBMCPP__)
1.191     brouard  6031:    printf(" IBM XL C/C++"); if(logged) fprintf(ficlog," IBM XL C/C++");/* IBM XL C/C++. -------------------------------------------- */
1.169     brouard  6032: #endif
                   6033: #if defined(_MSC_VER)
1.191     brouard  6034:    printf(" Microsoft Visual Studio");if(logged)fprintf(ficlog," Microsoft Visual Studio");/* Microsoft Visual Studio. --------------------------------- */
1.169     brouard  6035: #endif
                   6036: #if defined(__PGI)
1.191     brouard  6037:    printf(" Portland Group PGCC/PGCPP");if(logged) fprintf(ficlog," Portland Group PGCC/PGCPP");/* Portland Group PGCC/PGCPP. ------------------------------- */
1.169     brouard  6038: #endif
                   6039: #if defined(__SUNPRO_C) || defined(__SUNPRO_CC)
1.191     brouard  6040:    printf(" Oracle Solaris Studio");if(logged)fprintf(ficlog," Oracle Solaris Studio\n");/* Oracle Solaris Studio. ----------------------------------- */
1.167     brouard  6041: #endif
1.191     brouard  6042:    printf(" for "); if (logged) fprintf(ficlog, " for ");
1.169     brouard  6043:    
1.167     brouard  6044: // http://stackoverflow.com/questions/4605842/how-to-identify-platform-compiler-from-preprocessor-macros
                   6045: #ifdef _WIN32 // note the underscore: without it, it's not msdn official!
                   6046:     // Windows (x64 and x86)
1.191     brouard  6047:    printf("Windows (x64 and x86) ");if(logged) fprintf(ficlog,"Windows (x64 and x86) ");
1.167     brouard  6048: #elif __unix__ // all unices, not all compilers
                   6049:     // Unix
1.191     brouard  6050:    printf("Unix ");if(logged) fprintf(ficlog,"Unix ");
1.167     brouard  6051: #elif __linux__
                   6052:     // linux
1.191     brouard  6053:    printf("linux ");if(logged) fprintf(ficlog,"linux ");
1.167     brouard  6054: #elif __APPLE__
1.174     brouard  6055:     // Mac OS, not sure if this is covered by __posix__ and/or __unix__ though..
1.191     brouard  6056:    printf("Mac OS ");if(logged) fprintf(ficlog,"Mac OS ");
1.167     brouard  6057: #endif
                   6058: 
                   6059: /*  __MINGW32__          */
                   6060: /*  __CYGWIN__  */
                   6061: /* __MINGW64__  */
                   6062: // http://msdn.microsoft.com/en-us/library/b0084kay.aspx
                   6063: /* _MSC_VER  //the Visual C++ compiler is 17.00.51106.1, the _MSC_VER macro evaluates to 1700. Type cl /?  */
                   6064: /* _MSC_FULL_VER //the Visual C++ compiler is 15.00.20706.01, the _MSC_FULL_VER macro evaluates to 150020706 */
                   6065: /* _WIN64  // Defined for applications for Win64. */
                   6066: /* _M_X64 // Defined for compilations that target x64 processors. */
                   6067: /* _DEBUG // Defined when you compile with /LDd, /MDd, and /MTd. */
1.171     brouard  6068: 
1.167     brouard  6069: #if UINTPTR_MAX == 0xffffffff
1.191     brouard  6070:    printf(" 32-bit"); if(logged) fprintf(ficlog," 32-bit");/* 32-bit */
1.167     brouard  6071: #elif UINTPTR_MAX == 0xffffffffffffffff
1.191     brouard  6072:    printf(" 64-bit"); if(logged) fprintf(ficlog," 64-bit");/* 64-bit */
1.167     brouard  6073: #else
1.191     brouard  6074:    printf(" wtf-bit"); if(logged) fprintf(ficlog," wtf-bit");/* wtf */
1.167     brouard  6075: #endif
                   6076: 
1.169     brouard  6077: #if defined(__GNUC__)
                   6078: # if defined(__GNUC_PATCHLEVEL__)
                   6079: #  define __GNUC_VERSION__ (__GNUC__ * 10000 \
                   6080:                             + __GNUC_MINOR__ * 100 \
                   6081:                             + __GNUC_PATCHLEVEL__)
                   6082: # else
                   6083: #  define __GNUC_VERSION__ (__GNUC__ * 10000 \
                   6084:                             + __GNUC_MINOR__ * 100)
                   6085: # endif
1.174     brouard  6086:    printf(" using GNU C version %d.\n", __GNUC_VERSION__);
1.191     brouard  6087:    if(logged) fprintf(ficlog, " using GNU C version %d.\n", __GNUC_VERSION__);
1.176     brouard  6088: 
                   6089:    if (uname(&sysInfo) != -1) {
                   6090:      printf("Running on: %s %s %s %s %s\n",sysInfo.sysname, sysInfo.nodename, sysInfo.release, sysInfo.version, sysInfo.machine);
1.191     brouard  6091:         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  6092:    }
                   6093:    else
                   6094:       perror("uname() error");
1.179     brouard  6095:    //#ifndef __INTEL_COMPILER 
                   6096: #if !defined (__INTEL_COMPILER) && !defined(__APPLE__)
1.174     brouard  6097:    printf("GNU libc version: %s\n", gnu_get_libc_version()); 
1.191     brouard  6098:    if(logged) fprintf(ficlog,"GNU libc version: %s\n", gnu_get_libc_version());
1.177     brouard  6099: #endif
1.169     brouard  6100: #endif
1.172     brouard  6101: 
                   6102:    //   void main()
                   6103:    //   {
1.169     brouard  6104: #if defined(_MSC_VER)
1.174     brouard  6105:    if (IsWow64()){
1.191     brouard  6106:           printf("\nThe program (probably compiled for 32bit) is running under WOW64 (64bit) emulation.\n");
                   6107:           if (logged) fprintf(ficlog, "\nThe program (probably compiled for 32bit) is running under WOW64 (64bit) emulation.\n");
1.174     brouard  6108:    }
                   6109:    else{
1.191     brouard  6110:           printf("\nThe program is not running under WOW64 (i.e probably on a 64bit Windows).\n");
                   6111:           if (logged) fprintf(ficlog, "\nThe programm is not running under WOW64 (i.e probably on a 64bit Windows).\n");
1.174     brouard  6112:    }
1.172     brouard  6113:    //     printf("\nPress Enter to continue...");
                   6114:    //     getchar();
                   6115:    //   }
                   6116: 
1.169     brouard  6117: #endif
                   6118:    
1.167     brouard  6119: 
                   6120:  }
1.136     brouard  6121: 
1.180     brouard  6122: int prevalence_limit(double *p, double **prlim, double ageminpar, double agemaxpar){
                   6123:   /*--------------- Prevalence limit  (period or stable prevalence) --------------*/
                   6124:   int i, j, k, i1 ;
                   6125:   double ftolpl = 1.e-10;
                   6126:   double age, agebase, agelim;
                   6127: 
                   6128:     strcpy(filerespl,"pl");
                   6129:     strcat(filerespl,fileres);
                   6130:     if((ficrespl=fopen(filerespl,"w"))==NULL) {
                   6131:       printf("Problem with period (stable) prevalence resultfile: %s\n", filerespl);return 1;
                   6132:       fprintf(ficlog,"Problem with period (stable) prevalence resultfile: %s\n", filerespl);return 1;
                   6133:     }
                   6134:     printf("Computing period (stable) prevalence: result on file '%s' \n", filerespl);
                   6135:     fprintf(ficlog,"Computing period (stable) prevalence: result on file '%s' \n", filerespl);
                   6136:     pstamp(ficrespl);
                   6137:     fprintf(ficrespl,"# Period (stable) prevalence \n");
                   6138:     fprintf(ficrespl,"#Age ");
                   6139:     for(i=1; i<=nlstate;i++) fprintf(ficrespl,"%d-%d ",i,i);
                   6140:     fprintf(ficrespl,"\n");
                   6141:   
                   6142:     /* prlim=matrix(1,nlstate,1,nlstate);*/ /* back in main */
                   6143: 
                   6144:     agebase=ageminpar;
                   6145:     agelim=agemaxpar;
                   6146: 
                   6147:     i1=pow(2,cptcoveff);
                   6148:     if (cptcovn < 1){i1=1;}
                   6149: 
                   6150:     for(cptcov=1,k=0;cptcov<=i1;cptcov++){
                   6151:     /* for(cptcov=1,k=0;cptcov<=1;cptcov++){ */
                   6152:       //for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){
                   6153:        k=k+1;
                   6154:        /* to clean */
                   6155:        //printf("cptcov=%d cptcod=%d codtab=%d\n",cptcov, cptcod,codtab[cptcod][cptcov]);
                   6156:        fprintf(ficrespl,"\n#******");
                   6157:        printf("\n#******");
                   6158:        fprintf(ficlog,"\n#******");
                   6159:        for(j=1;j<=cptcoveff;j++) {
                   6160:          fprintf(ficrespl," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
                   6161:          printf(" V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
                   6162:          fprintf(ficlog," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
                   6163:        }
                   6164:        fprintf(ficrespl,"******\n");
                   6165:        printf("******\n");
                   6166:        fprintf(ficlog,"******\n");
                   6167: 
                   6168:        fprintf(ficrespl,"#Age ");
                   6169:        for(j=1;j<=cptcoveff;j++) {
                   6170:          fprintf(ficrespl,"V%d %d",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
                   6171:        }
                   6172:        for(i=1; i<=nlstate;i++) fprintf(ficrespl,"%d-%d ",i,i);
                   6173:        fprintf(ficrespl,"\n");
                   6174:        
                   6175:        for (age=agebase; age<=agelim; age++){
                   6176:        /* for (age=agebase; age<=agebase; age++){ */
                   6177:          prevalim(prlim, nlstate, p, age, oldm, savm,ftolpl,k);
                   6178:          fprintf(ficrespl,"%.0f ",age );
                   6179:          for(j=1;j<=cptcoveff;j++)
                   6180:            fprintf(ficrespl,"%d %d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
                   6181:          for(i=1; i<=nlstate;i++)
                   6182:            fprintf(ficrespl," %.5f", prlim[i][i]);
                   6183:          fprintf(ficrespl,"\n");
                   6184:        } /* Age */
                   6185:        /* was end of cptcod */
                   6186:     } /* cptcov */
1.184     brouard  6187:        return 0;
1.180     brouard  6188: }
                   6189: 
                   6190: int hPijx(double *p, int bage, int fage){
                   6191:     /*------------- h Pij x at various ages ------------*/
                   6192: 
                   6193:   int stepsize;
                   6194:   int agelim;
                   6195:   int hstepm;
                   6196:   int nhstepm;
                   6197:   int h, i, i1, j, k;
                   6198: 
                   6199:   double agedeb;
                   6200:   double ***p3mat;
                   6201: 
                   6202:     strcpy(filerespij,"pij");  strcat(filerespij,fileres);
                   6203:     if((ficrespij=fopen(filerespij,"w"))==NULL) {
                   6204:       printf("Problem with Pij resultfile: %s\n", filerespij); return 1;
                   6205:       fprintf(ficlog,"Problem with Pij resultfile: %s\n", filerespij); return 1;
                   6206:     }
                   6207:     printf("Computing pij: result on file '%s' \n", filerespij);
                   6208:     fprintf(ficlog,"Computing pij: result on file '%s' \n", filerespij);
                   6209:   
                   6210:     stepsize=(int) (stepm+YEARM-1)/YEARM;
                   6211:     /*if (stepm<=24) stepsize=2;*/
                   6212: 
                   6213:     agelim=AGESUP;
                   6214:     hstepm=stepsize*YEARM; /* Every year of age */
                   6215:     hstepm=hstepm/stepm; /* Typically 2 years, = 2/6 months = 4 */ 
                   6216: 
                   6217:     /* hstepm=1;   aff par mois*/
                   6218:     pstamp(ficrespij);
                   6219:     fprintf(ficrespij,"#****** h Pij x Probability to be in state j at age x+h being in i at x ");
                   6220:     i1= pow(2,cptcoveff);
1.183     brouard  6221:    /* for(cptcov=1,k=0;cptcov<=i1;cptcov++){ */
                   6222:    /*    /\*for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){*\/ */
                   6223:    /*          k=k+1;  */
                   6224:     for (k=1; k <= (int) pow(2,cptcoveff); k++){
                   6225:       fprintf(ficrespij,"\n#****** ");
                   6226:       for(j=1;j<=cptcoveff;j++) 
                   6227:        fprintf(ficrespij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
                   6228:       fprintf(ficrespij,"******\n");
                   6229:       
                   6230:       for (agedeb=fage; agedeb>=bage; agedeb--){ /* If stepm=6 months */
                   6231:        nhstepm=(int) rint((agelim-agedeb)*YEARM/stepm); /* Typically 20 years = 20*12/6=40 */ 
                   6232:        nhstepm = nhstepm/hstepm; /* Typically 40/4=10 */
                   6233:        
                   6234:        /*        nhstepm=nhstepm*YEARM; aff par mois*/
1.180     brouard  6235:        
1.183     brouard  6236:        p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   6237:        oldm=oldms;savm=savms;
                   6238:        hpxij(p3mat,nhstepm,agedeb,hstepm,p,nlstate,stepm,oldm,savm, k);  
                   6239:        fprintf(ficrespij,"# Cov Agex agex+h hpijx with i,j=");
                   6240:        for(i=1; i<=nlstate;i++)
                   6241:          for(j=1; j<=nlstate+ndeath;j++)
                   6242:            fprintf(ficrespij," %1d-%1d",i,j);
                   6243:        fprintf(ficrespij,"\n");
                   6244:        for (h=0; h<=nhstepm; h++){
                   6245:          /*agedebphstep = agedeb + h*hstepm/YEARM*stepm;*/
                   6246:          fprintf(ficrespij,"%d %3.f %3.f",k, agedeb, agedeb + h*hstepm/YEARM*stepm );
1.180     brouard  6247:          for(i=1; i<=nlstate;i++)
                   6248:            for(j=1; j<=nlstate+ndeath;j++)
1.183     brouard  6249:              fprintf(ficrespij," %.5f", p3mat[i][j][h]);
1.180     brouard  6250:          fprintf(ficrespij,"\n");
                   6251:        }
1.183     brouard  6252:        free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   6253:        fprintf(ficrespij,"\n");
                   6254:       }
1.180     brouard  6255:       /*}*/
                   6256:     }
1.184     brouard  6257:        return 0;
1.180     brouard  6258: }
                   6259: 
                   6260: 
1.136     brouard  6261: /***********************************************/
                   6262: /**************** Main Program *****************/
                   6263: /***********************************************/
                   6264: 
                   6265: int main(int argc, char *argv[])
                   6266: {
                   6267: #ifdef GSL
                   6268:   const gsl_multimin_fminimizer_type *T;
                   6269:   size_t iteri = 0, it;
                   6270:   int rval = GSL_CONTINUE;
                   6271:   int status = GSL_SUCCESS;
                   6272:   double ssval;
                   6273: #endif
                   6274:   int movingaverage(double ***probs, double bage,double fage, double ***mobaverage, int mobilav);
1.164     brouard  6275:   int i,j, k, n=MAXN,iter=0,m,size=100, cptcod;
                   6276: 
                   6277:   int jj, ll, li, lj, lk;
1.136     brouard  6278:   int numlinepar=0; /* Current linenumber of parameter file */
                   6279:   int itimes;
                   6280:   int NDIM=2;
                   6281:   int vpopbased=0;
                   6282: 
1.164     brouard  6283:   char ca[32], cb[32];
1.136     brouard  6284:   /*  FILE *fichtm; *//* Html File */
                   6285:   /* FILE *ficgp;*/ /*Gnuplot File */
                   6286:   struct stat info;
1.191     brouard  6287:   double agedeb=0.;
1.194     brouard  6288: 
                   6289:   double ageminpar=AGEOVERFLOW,agemin=AGEOVERFLOW, agemaxpar=-AGEOVERFLOW, agemax=-AGEOVERFLOW;
1.136     brouard  6290: 
1.165     brouard  6291:   double fret;
1.191     brouard  6292:   double dum=0.; /* Dummy variable */
1.136     brouard  6293:   double ***p3mat;
                   6294:   double ***mobaverage;
1.164     brouard  6295: 
                   6296:   char line[MAXLINE];
1.136     brouard  6297:   char path[MAXLINE],pathc[MAXLINE],pathcd[MAXLINE],pathtot[MAXLINE],model[MAXLINE];
                   6298:   char pathr[MAXLINE], pathimach[MAXLINE]; 
1.164     brouard  6299:   char *tok, *val; /* pathtot */
1.136     brouard  6300:   int firstobs=1, lastobs=10;
1.195     brouard  6301:   int c,  h , cpt, c2;
1.191     brouard  6302:   int jl=0;
                   6303:   int i1, j1, jk, stepsize=0;
1.194     brouard  6304:   int count=0;
                   6305: 
1.164     brouard  6306:   int *tab; 
1.136     brouard  6307:   int mobilavproj=0 , prevfcast=0 ; /* moving average of prev, If prevfcast=1 prevalence projection */
                   6308:   int mobilav=0,popforecast=0;
1.191     brouard  6309:   int hstepm=0, nhstepm=0;
1.136     brouard  6310:   int agemortsup;
                   6311:   float  sumlpop=0.;
                   6312:   double jprev1=1, mprev1=1,anprev1=2000,jprev2=1, mprev2=1,anprev2=2000;
                   6313:   double jpyram=1, mpyram=1,anpyram=2000,jpyram1=1, mpyram1=1,anpyram1=2000;
                   6314: 
1.191     brouard  6315:   double bage=0, fage=110., age, agelim=0., agebase=0.;
1.136     brouard  6316:   double ftolpl=FTOL;
                   6317:   double **prlim;
                   6318:   double ***param; /* Matrix of parameters */
                   6319:   double  *p;
                   6320:   double **matcov; /* Matrix of covariance */
                   6321:   double ***delti3; /* Scale */
                   6322:   double *delti; /* Scale */
                   6323:   double ***eij, ***vareij;
                   6324:   double **varpl; /* Variances of prevalence limits by age */
                   6325:   double *epj, vepp;
1.164     brouard  6326: 
1.136     brouard  6327:   double dateprev1, dateprev2,jproj1=1,mproj1=1,anproj1=2000,jproj2=1,mproj2=1,anproj2=2000;
                   6328:   double **ximort;
1.145     brouard  6329:   char *alph[]={"a","a","b","c","d","e"}, str[4]="1234";
1.136     brouard  6330:   int *dcwave;
                   6331: 
1.164     brouard  6332:   char z[1]="c";
1.136     brouard  6333: 
                   6334:   /*char  *strt;*/
                   6335:   char strtend[80];
1.126     brouard  6336: 
1.164     brouard  6337: 
1.126     brouard  6338: /*   setlocale (LC_ALL, ""); */
                   6339: /*   bindtextdomain (PACKAGE, LOCALEDIR); */
                   6340: /*   textdomain (PACKAGE); */
                   6341: /*   setlocale (LC_CTYPE, ""); */
                   6342: /*   setlocale (LC_MESSAGES, ""); */
                   6343: 
                   6344:   /*   gettimeofday(&start_time, (struct timezone*)0); */ /* at first time */
1.157     brouard  6345:   rstart_time = time(NULL);  
                   6346:   /*  (void) gettimeofday(&start_time,&tzp);*/
                   6347:   start_time = *localtime(&rstart_time);
1.126     brouard  6348:   curr_time=start_time;
1.157     brouard  6349:   /*tml = *localtime(&start_time.tm_sec);*/
                   6350:   /* strcpy(strstart,asctime(&tml)); */
                   6351:   strcpy(strstart,asctime(&start_time));
1.126     brouard  6352: 
                   6353: /*  printf("Localtime (at start)=%s",strstart); */
1.157     brouard  6354: /*  tp.tm_sec = tp.tm_sec +86400; */
                   6355: /*  tm = *localtime(&start_time.tm_sec); */
1.126     brouard  6356: /*   tmg.tm_year=tmg.tm_year +dsign*dyear; */
                   6357: /*   tmg.tm_mon=tmg.tm_mon +dsign*dmonth; */
                   6358: /*   tmg.tm_hour=tmg.tm_hour + 1; */
1.157     brouard  6359: /*   tp.tm_sec = mktime(&tmg); */
1.126     brouard  6360: /*   strt=asctime(&tmg); */
                   6361: /*   printf("Time(after) =%s",strstart);  */
                   6362: /*  (void) time (&time_value);
                   6363: *  printf("time=%d,t-=%d\n",time_value,time_value-86400);
                   6364: *  tm = *localtime(&time_value);
                   6365: *  strstart=asctime(&tm);
                   6366: *  printf("tim_value=%d,asctime=%s\n",time_value,strstart); 
                   6367: */
                   6368: 
                   6369:   nberr=0; /* Number of errors and warnings */
                   6370:   nbwarn=0;
1.184     brouard  6371: #ifdef WIN32
                   6372:   _getcwd(pathcd, size);
                   6373: #else
1.126     brouard  6374:   getcwd(pathcd, size);
1.184     brouard  6375: #endif
1.191     brouard  6376:   syscompilerinfo(0);
1.196   ! brouard  6377:   printf("\nIMaCh version %s, %s\n%s",version, copyright, fullversion);
1.126     brouard  6378:   if(argc <=1){
                   6379:     printf("\nEnter the parameter file name: ");
                   6380:     fgets(pathr,FILENAMELENGTH,stdin);
                   6381:     i=strlen(pathr);
                   6382:     if(pathr[i-1]=='\n')
                   6383:       pathr[i-1]='\0';
1.156     brouard  6384:     i=strlen(pathr);
                   6385:     if(pathr[i-1]==' ') /* This may happen when dragging on oS/X! */
                   6386:       pathr[i-1]='\0';
1.126     brouard  6387:    for (tok = pathr; tok != NULL; ){
                   6388:       printf("Pathr |%s|\n",pathr);
                   6389:       while ((val = strsep(&tok, "\"" )) != NULL && *val == '\0');
                   6390:       printf("val= |%s| pathr=%s\n",val,pathr);
                   6391:       strcpy (pathtot, val);
                   6392:       if(pathr[0] == '\0') break; /* Dirty */
                   6393:     }
                   6394:   }
                   6395:   else{
                   6396:     strcpy(pathtot,argv[1]);
                   6397:   }
                   6398:   /*if(getcwd(pathcd, MAXLINE)!= NULL)printf ("Error pathcd\n");*/
                   6399:   /*cygwin_split_path(pathtot,path,optionfile);
                   6400:     printf("pathtot=%s, path=%s, optionfile=%s\n",pathtot,path,optionfile);*/
                   6401:   /* cutv(path,optionfile,pathtot,'\\');*/
                   6402: 
                   6403:   /* Split argv[0], imach program to get pathimach */
                   6404:   printf("\nargv[0]=%s argv[1]=%s, \n",argv[0],argv[1]);
                   6405:   split(argv[0],pathimach,optionfile,optionfilext,optionfilefiname);
                   6406:   printf("\nargv[0]=%s pathimach=%s, \noptionfile=%s \noptionfilext=%s \noptionfilefiname=%s\n",argv[0],pathimach,optionfile,optionfilext,optionfilefiname);
                   6407:  /*   strcpy(pathimach,argv[0]); */
                   6408:   /* Split argv[1]=pathtot, parameter file name to get path, optionfile, extension and name */
                   6409:   split(pathtot,path,optionfile,optionfilext,optionfilefiname);
                   6410:   printf("\npathtot=%s,\npath=%s,\noptionfile=%s \noptionfilext=%s \noptionfilefiname=%s\n",pathtot,path,optionfile,optionfilext,optionfilefiname);
1.184     brouard  6411: #ifdef WIN32
                   6412:   _chdir(path); /* Can be a relative path */
                   6413:   if(_getcwd(pathcd,MAXLINE) > 0) /* So pathcd is the full path */
                   6414: #else
1.126     brouard  6415:   chdir(path); /* Can be a relative path */
1.184     brouard  6416:   if (getcwd(pathcd, MAXLINE) > 0) /* So pathcd is the full path */
                   6417: #endif
                   6418:   printf("Current directory %s!\n",pathcd);
1.126     brouard  6419:   strcpy(command,"mkdir ");
                   6420:   strcat(command,optionfilefiname);
                   6421:   if((outcmd=system(command)) != 0){
1.169     brouard  6422:     printf("Directory already exists (or can't create it) %s%s, err=%d\n",path,optionfilefiname,outcmd);
1.126     brouard  6423:     /* fprintf(ficlog,"Problem creating directory %s%s\n",path,optionfilefiname); */
                   6424:     /* fclose(ficlog); */
                   6425: /*     exit(1); */
                   6426:   }
                   6427: /*   if((imk=mkdir(optionfilefiname))<0){ */
                   6428: /*     perror("mkdir"); */
                   6429: /*   } */
                   6430: 
                   6431:   /*-------- arguments in the command line --------*/
                   6432: 
1.186     brouard  6433:   /* Main Log file */
1.126     brouard  6434:   strcat(filelog, optionfilefiname);
                   6435:   strcat(filelog,".log");    /* */
                   6436:   if((ficlog=fopen(filelog,"w"))==NULL)    {
                   6437:     printf("Problem with logfile %s\n",filelog);
                   6438:     goto end;
                   6439:   }
                   6440:   fprintf(ficlog,"Log filename:%s\n",filelog);
                   6441:   fprintf(ficlog,"\n%s\n%s",version,fullversion);
                   6442:   fprintf(ficlog,"\nEnter the parameter file name: \n");
                   6443:   fprintf(ficlog,"pathimach=%s\npathtot=%s\n\
                   6444:  path=%s \n\
                   6445:  optionfile=%s\n\
                   6446:  optionfilext=%s\n\
1.156     brouard  6447:  optionfilefiname='%s'\n",pathimach,pathtot,path,optionfile,optionfilext,optionfilefiname);
1.126     brouard  6448: 
1.191     brouard  6449:   syscompilerinfo(0);
1.167     brouard  6450: 
1.126     brouard  6451:   printf("Local time (at start):%s",strstart);
                   6452:   fprintf(ficlog,"Local time (at start): %s",strstart);
                   6453:   fflush(ficlog);
                   6454: /*   (void) gettimeofday(&curr_time,&tzp); */
1.157     brouard  6455: /*   printf("Elapsed time %d\n", asc_diff_time(curr_time.tm_sec-start_time.tm_sec,tmpout)); */
1.126     brouard  6456: 
                   6457:   /* */
                   6458:   strcpy(fileres,"r");
                   6459:   strcat(fileres, optionfilefiname);
                   6460:   strcat(fileres,".txt");    /* Other files have txt extension */
                   6461: 
1.186     brouard  6462:   /* Main ---------arguments file --------*/
1.126     brouard  6463: 
                   6464:   if((ficpar=fopen(optionfile,"r"))==NULL)    {
1.155     brouard  6465:     printf("Problem with optionfile '%s' with errno='%s'\n",optionfile,strerror(errno));
                   6466:     fprintf(ficlog,"Problem with optionfile '%s' with errno='%s'\n",optionfile,strerror(errno));
1.126     brouard  6467:     fflush(ficlog);
1.149     brouard  6468:     /* goto end; */
                   6469:     exit(70); 
1.126     brouard  6470:   }
                   6471: 
                   6472: 
                   6473: 
                   6474:   strcpy(filereso,"o");
                   6475:   strcat(filereso,fileres);
                   6476:   if((ficparo=fopen(filereso,"w"))==NULL) { /* opened on subdirectory */
                   6477:     printf("Problem with Output resultfile: %s\n", filereso);
                   6478:     fprintf(ficlog,"Problem with Output resultfile: %s\n", filereso);
                   6479:     fflush(ficlog);
                   6480:     goto end;
                   6481:   }
                   6482: 
                   6483:   /* Reads comments: lines beginning with '#' */
                   6484:   numlinepar=0;
                   6485:   while((c=getc(ficpar))=='#' && c!= EOF){
                   6486:     ungetc(c,ficpar);
                   6487:     fgets(line, MAXLINE, ficpar);
                   6488:     numlinepar++;
1.141     brouard  6489:     fputs(line,stdout);
1.126     brouard  6490:     fputs(line,ficparo);
                   6491:     fputs(line,ficlog);
                   6492:   }
                   6493:   ungetc(c,ficpar);
                   6494: 
1.187     brouard  6495:   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);
1.194     brouard  6496:   numlinepar=numlinepar+3; /* In general */
1.187     brouard  6497:   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);
                   6498:   if(model[strlen(model)-1]=='.') /* Suppressing leading dot in the model */
                   6499:     model[strlen(model)-1]='\0';
                   6500:   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);
                   6501:   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  6502:   fflush(ficlog);
1.190     brouard  6503:   /* if(model[0]=='#'|| model[0]== '\0'){ */
                   6504:   if(model[0]=='#'){
1.187     brouard  6505:     printf("Error in 'model' line: model should start with 'model=1+age+' and end with '.' \n \
                   6506:  'model=1+age+.' or 'model=1+age+V1.' or 'model=1+age+age*age+V1+V1*age.' or \n \
                   6507:  'model=1+age+V1+V2.' or 'model=1+age+V1+V2+V1*V2.' etc. \n");         \
                   6508:     if(mle != -1){
                   6509:       printf("Fix the model line and run imach with mle=-1 to get a correct template of the parameter file.\n");
                   6510:       exit(1);
                   6511:     }
                   6512:   }
1.126     brouard  6513:   while((c=getc(ficpar))=='#' && c!= EOF){
                   6514:     ungetc(c,ficpar);
                   6515:     fgets(line, MAXLINE, ficpar);
                   6516:     numlinepar++;
1.195     brouard  6517:     if(line[1]=='q'){ /* This #q will quit imach (the answer is q) */
                   6518:       z[0]=line[1];
                   6519:     }
                   6520:     /* printf("****line [1] = %c \n",line[1]); */
1.141     brouard  6521:     fputs(line, stdout);
                   6522:     //puts(line);
1.126     brouard  6523:     fputs(line,ficparo);
                   6524:     fputs(line,ficlog);
                   6525:   }
                   6526:   ungetc(c,ficpar);
                   6527: 
                   6528:    
1.145     brouard  6529:   covar=matrix(0,NCOVMAX,1,n);  /**< used in readdata */
1.136     brouard  6530:   cptcovn=0; /*Number of covariates, i.e. number of '+' in model statement plus one, indepently of n in Vn*/
                   6531:   /* v1+v2+v3+v2*v4+v5*age makes cptcovn = 5
                   6532:      v1+v2*age+v2*v3 makes cptcovn = 3
                   6533:   */
                   6534:   if (strlen(model)>1) 
1.187     brouard  6535:     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  6536:   else
1.187     brouard  6537:     ncovmodel=2; /* Constant and age */
1.133     brouard  6538:   nforce= (nlstate+ndeath-1)*nlstate; /* Number of forces ij from state i to j */
                   6539:   npar= nforce*ncovmodel; /* Number of parameters like aij*/
1.131     brouard  6540:   if(npar >MAXPARM || nlstate >NLSTATEMAX || ndeath >NDEATHMAX || ncovmodel>NCOVMAX){
                   6541:     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);
                   6542:     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);
                   6543:     fflush(stdout);
                   6544:     fclose (ficlog);
                   6545:     goto end;
                   6546:   }
1.126     brouard  6547:   delti3= ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel);
                   6548:   delti=delti3[1][1];
                   6549:   /*delti=vector(1,npar); *//* Scale of each paramater (output from hesscov)*/
                   6550:   if(mle==-1){ /* Print a wizard for help writing covariance matrix */
                   6551:     prwizard(ncovmodel, nlstate, ndeath, model, ficparo);
1.191     brouard  6552:     printf(" You chose mle=-1, look at file %s for a template of covariance matrix \n",filereso);
                   6553:     fprintf(ficlog," You chose mle=-1, look at file %s for a template of covariance matrix \n",filereso);
1.126     brouard  6554:     free_ma3x(delti3,1,nlstate,1, nlstate+ndeath-1,1,ncovmodel); 
                   6555:     fclose (ficparo);
                   6556:     fclose (ficlog);
                   6557:     goto end;
                   6558:     exit(0);
                   6559:   }
1.186     brouard  6560:   else if(mle==-3) { /* Main Wizard */
1.126     brouard  6561:     prwizard(ncovmodel, nlstate, ndeath, model, ficparo);
1.192     brouard  6562:     printf(" You chose mle=-3, look at file %s for a template of covariance matrix \n",filereso);
                   6563:     fprintf(ficlog," You chose mle=-3, look at file %s for a template of covariance matrix \n",filereso);
1.126     brouard  6564:     param= ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel);
                   6565:     matcov=matrix(1,npar,1,npar);
                   6566:   }
                   6567:   else{
1.145     brouard  6568:     /* Read guessed parameters */
1.126     brouard  6569:     /* Reads comments: lines beginning with '#' */
                   6570:     while((c=getc(ficpar))=='#' && c!= EOF){
                   6571:       ungetc(c,ficpar);
                   6572:       fgets(line, MAXLINE, ficpar);
                   6573:       numlinepar++;
1.141     brouard  6574:       fputs(line,stdout);
1.126     brouard  6575:       fputs(line,ficparo);
                   6576:       fputs(line,ficlog);
                   6577:     }
                   6578:     ungetc(c,ficpar);
                   6579:     
                   6580:     param= ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel);
                   6581:     for(i=1; i <=nlstate; i++){
                   6582:       j=0;
                   6583:       for(jj=1; jj <=nlstate+ndeath; jj++){
                   6584:        if(jj==i) continue;
                   6585:        j++;
                   6586:        fscanf(ficpar,"%1d%1d",&i1,&j1);
1.193     brouard  6587:        if ((i1 != i) || (j1 != jj)){
1.126     brouard  6588:          printf("Error in line parameters number %d, %1d%1d instead of %1d%1d \n \
                   6589: It might be a problem of design; if ncovcol and the model are correct\n \
                   6590: run imach with mle=-1 to get a correct template of the parameter file.\n",numlinepar, i,j, i1, j1);
                   6591:          exit(1);
                   6592:        }
                   6593:        fprintf(ficparo,"%1d%1d",i1,j1);
                   6594:        if(mle==1)
1.193     brouard  6595:          printf("%1d%1d",i,jj);
                   6596:        fprintf(ficlog,"%1d%1d",i,jj);
1.126     brouard  6597:        for(k=1; k<=ncovmodel;k++){
                   6598:          fscanf(ficpar," %lf",&param[i][j][k]);
                   6599:          if(mle==1){
                   6600:            printf(" %lf",param[i][j][k]);
                   6601:            fprintf(ficlog," %lf",param[i][j][k]);
                   6602:          }
                   6603:          else
                   6604:            fprintf(ficlog," %lf",param[i][j][k]);
                   6605:          fprintf(ficparo," %lf",param[i][j][k]);
                   6606:        }
                   6607:        fscanf(ficpar,"\n");
                   6608:        numlinepar++;
                   6609:        if(mle==1)
                   6610:          printf("\n");
                   6611:        fprintf(ficlog,"\n");
                   6612:        fprintf(ficparo,"\n");
                   6613:       }
                   6614:     }  
                   6615:     fflush(ficlog);
                   6616: 
1.145     brouard  6617:     /* Reads scales values */
1.126     brouard  6618:     p=param[1][1];
                   6619:     
                   6620:     /* Reads comments: lines beginning with '#' */
                   6621:     while((c=getc(ficpar))=='#' && c!= EOF){
                   6622:       ungetc(c,ficpar);
                   6623:       fgets(line, MAXLINE, ficpar);
                   6624:       numlinepar++;
1.141     brouard  6625:       fputs(line,stdout);
1.126     brouard  6626:       fputs(line,ficparo);
                   6627:       fputs(line,ficlog);
                   6628:     }
                   6629:     ungetc(c,ficpar);
                   6630: 
                   6631:     for(i=1; i <=nlstate; i++){
                   6632:       for(j=1; j <=nlstate+ndeath-1; j++){
                   6633:        fscanf(ficpar,"%1d%1d",&i1,&j1);
1.164     brouard  6634:        if ( (i1-i) * (j1-j) != 0){
1.126     brouard  6635:          printf("Error in line parameters number %d, %1d%1d instead of %1d%1d \n",numlinepar, i,j, i1, j1);
                   6636:          exit(1);
                   6637:        }
                   6638:        printf("%1d%1d",i,j);
                   6639:        fprintf(ficparo,"%1d%1d",i1,j1);
                   6640:        fprintf(ficlog,"%1d%1d",i1,j1);
                   6641:        for(k=1; k<=ncovmodel;k++){
                   6642:          fscanf(ficpar,"%le",&delti3[i][j][k]);
                   6643:          printf(" %le",delti3[i][j][k]);
                   6644:          fprintf(ficparo," %le",delti3[i][j][k]);
                   6645:          fprintf(ficlog," %le",delti3[i][j][k]);
                   6646:        }
                   6647:        fscanf(ficpar,"\n");
                   6648:        numlinepar++;
                   6649:        printf("\n");
                   6650:        fprintf(ficparo,"\n");
                   6651:        fprintf(ficlog,"\n");
                   6652:       }
                   6653:     }
                   6654:     fflush(ficlog);
                   6655: 
1.145     brouard  6656:     /* Reads covariance matrix */
1.126     brouard  6657:     delti=delti3[1][1];
                   6658: 
                   6659: 
                   6660:     /* free_ma3x(delti3,1,nlstate,1,nlstate+ndeath-1,1,ncovmodel); */ /* Hasn't to to freed here otherwise delti is no more allocated */
                   6661:   
                   6662:     /* Reads comments: lines beginning with '#' */
                   6663:     while((c=getc(ficpar))=='#' && c!= EOF){
                   6664:       ungetc(c,ficpar);
                   6665:       fgets(line, MAXLINE, ficpar);
                   6666:       numlinepar++;
1.141     brouard  6667:       fputs(line,stdout);
1.126     brouard  6668:       fputs(line,ficparo);
                   6669:       fputs(line,ficlog);
                   6670:     }
                   6671:     ungetc(c,ficpar);
                   6672:   
                   6673:     matcov=matrix(1,npar,1,npar);
1.131     brouard  6674:     for(i=1; i <=npar; i++)
                   6675:       for(j=1; j <=npar; j++) matcov[i][j]=0.;
                   6676:       
1.194     brouard  6677:     /* Scans npar lines */
1.126     brouard  6678:     for(i=1; i <=npar; i++){
1.194     brouard  6679:       count=fscanf(ficpar,"%1d%1d%1d",&i1,&j1,&jk);
                   6680:       if(count != 3){
                   6681:        printf("Error! Error in parameter file %s at line %d after line starting with %1d%1d%1d\n\
                   6682: This is probably because your covariance matrix doesn't \n  contain exactly %d lines corresponding to your model line '1+age+%s'.\n\
                   6683: Please run with mle=-1 to get a correct covariance matrix.\n",optionfile,numlinepar, i1,j1,jk, npar, model);
                   6684:        fprintf(ficlog,"Error! Error in parameter file %s at line %d after line starting with %1d%1d%1d\n\
                   6685: This is probably because your covariance matrix doesn't \n  contain exactly %d lines corresponding to your model line '1+age+%s'.\n\
                   6686: Please run with mle=-1 to get a correct covariance matrix.\n",optionfile,numlinepar, i1,j1,jk, npar, model);
                   6687:        exit(1);
                   6688:       }else
1.126     brouard  6689:       if(mle==1)
1.194     brouard  6690:        printf("%1d%1d%1d",i1,j1,jk);
                   6691:       fprintf(ficlog,"%1d%1d%1d",i1,j1,jk);
                   6692:       fprintf(ficparo,"%1d%1d%1d",i1,j1,jk);
1.126     brouard  6693:       for(j=1; j <=i; j++){
                   6694:        fscanf(ficpar," %le",&matcov[i][j]);
                   6695:        if(mle==1){
                   6696:          printf(" %.5le",matcov[i][j]);
                   6697:        }
                   6698:        fprintf(ficlog," %.5le",matcov[i][j]);
                   6699:        fprintf(ficparo," %.5le",matcov[i][j]);
                   6700:       }
                   6701:       fscanf(ficpar,"\n");
                   6702:       numlinepar++;
                   6703:       if(mle==1)
                   6704:        printf("\n");
                   6705:       fprintf(ficlog,"\n");
                   6706:       fprintf(ficparo,"\n");
                   6707:     }
1.194     brouard  6708:     /* End of read covariance matrix npar lines */
1.126     brouard  6709:     for(i=1; i <=npar; i++)
                   6710:       for(j=i+1;j<=npar;j++)
                   6711:        matcov[i][j]=matcov[j][i];
                   6712:     
                   6713:     if(mle==1)
                   6714:       printf("\n");
                   6715:     fprintf(ficlog,"\n");
                   6716:     
                   6717:     fflush(ficlog);
                   6718:     
                   6719:     /*-------- Rewriting parameter file ----------*/
                   6720:     strcpy(rfileres,"r");    /* "Rparameterfile */
                   6721:     strcat(rfileres,optionfilefiname);    /* Parameter file first name*/
                   6722:     strcat(rfileres,".");    /* */
                   6723:     strcat(rfileres,optionfilext);    /* Other files have txt extension */
                   6724:     if((ficres =fopen(rfileres,"w"))==NULL) {
                   6725:       printf("Problem writing new parameter file: %s\n", fileres);goto end;
                   6726:       fprintf(ficlog,"Problem writing new parameter file: %s\n", fileres);goto end;
                   6727:     }
                   6728:     fprintf(ficres,"#%s\n",version);
                   6729:   }    /* End of mle != -3 */
                   6730: 
1.186     brouard  6731:   /*  Main data
                   6732:    */
1.126     brouard  6733:   n= lastobs;
                   6734:   num=lvector(1,n);
                   6735:   moisnais=vector(1,n);
                   6736:   annais=vector(1,n);
                   6737:   moisdc=vector(1,n);
                   6738:   andc=vector(1,n);
                   6739:   agedc=vector(1,n);
                   6740:   cod=ivector(1,n);
                   6741:   weight=vector(1,n);
                   6742:   for(i=1;i<=n;i++) weight[i]=1.0; /* Equal weights, 1 by default */
                   6743:   mint=matrix(1,maxwav,1,n);
                   6744:   anint=matrix(1,maxwav,1,n);
1.131     brouard  6745:   s=imatrix(1,maxwav+1,1,n); /* s[i][j] health state for wave i and individual j */ 
1.126     brouard  6746:   tab=ivector(1,NCOVMAX);
1.144     brouard  6747:   ncodemax=ivector(1,NCOVMAX); /* Number of code per covariate; if O and 1 only, 2**ncov; V1+V2+V3+V4=>16 */
1.192     brouard  6748:   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  6749: 
1.136     brouard  6750:   /* Reads data from file datafile */
                   6751:   if (readdata(datafile, firstobs, lastobs, &imx)==1)
                   6752:     goto end;
                   6753: 
                   6754:   /* Calculation of the number of parameters from char model */
1.137     brouard  6755:     /*    modelsav=V2+V1+V4+age*V3 strb=age*V3 stra=V2+V1+V4 
                   6756:        k=4 (age*V3) Tvar[k=4]= 3 (from V3) Tag[cptcovage=1]=4
                   6757:        k=3 V4 Tvar[k=3]= 4 (from V4)
                   6758:        k=2 V1 Tvar[k=2]= 1 (from V1)
                   6759:        k=1 Tvar[1]=2 (from V2)
                   6760:     */
                   6761:   Tvar=ivector(1,NCOVMAX); /* Was 15 changed to NCOVMAX. */
                   6762:   /*  V2+V1+V4+age*V3 is a model with 4 covariates (3 plus signs). 
                   6763:       For each model-covariate stores the data-covariate id. Tvar[1]=2, Tvar[2]=1, Tvar[3]=4, 
                   6764:       Tvar[4=age*V3] is 3 and 'age' is recorded in Tage.
                   6765:   */
                   6766:   /* For model-covariate k tells which data-covariate to use but
                   6767:     because this model-covariate is a construction we invent a new column
                   6768:     ncovcol + k1
                   6769:     If already ncovcol=4 and model=V2+V1+V1*V4+age*V3
                   6770:     Tvar[3=V1*V4]=4+1 etc */
1.145     brouard  6771:   Tprod=ivector(1,NCOVMAX); /* Gives the position of a product */
1.137     brouard  6772:   /* Tprod[k1=1]=3(=V1*V4) for V2+V1+V1*V4+age*V3
                   6773:      if  V2+V1+V1*V4+age*V3+V3*V2   TProd[k1=2]=5 (V3*V2)
                   6774:   */
1.145     brouard  6775:   Tvaraff=ivector(1,NCOVMAX); /* Unclear */
                   6776:   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  6777:                            * For V3*V2 (in V2+V1+V1*V4+age*V3+V3*V2), V3*V2 position is 2nd. 
                   6778:                            * Tvard[k1=2][1]=3 (V3) Tvard[k1=2][2]=2(V2) */
1.145     brouard  6779:   Tage=ivector(1,NCOVMAX); /* Gives the covariate id of covariates associated with age: V2 + V1 + age*V4 + V3*age
1.137     brouard  6780:                         4 covariates (3 plus signs)
                   6781:                         Tage[1=V3*age]= 4; Tage[2=age*V4] = 3
                   6782:                      */  
1.136     brouard  6783: 
1.186     brouard  6784: /* Main decodemodel */
                   6785: 
1.187     brouard  6786: 
1.136     brouard  6787:   if(decodemodel(model, lastobs) == 1)
                   6788:     goto end;
                   6789: 
1.137     brouard  6790:   if((double)(lastobs-imx)/(double)imx > 1.10){
                   6791:     nbwarn++;
                   6792:     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); 
                   6793:     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); 
                   6794:   }
1.136     brouard  6795:     /*  if(mle==1){*/
1.137     brouard  6796:   if (weightopt != 1) { /* Maximisation without weights. We can have weights different from 1 but want no weight*/
                   6797:     for(i=1;i<=imx;i++) weight[i]=1.0; /* changed to imx */
1.136     brouard  6798:   }
                   6799: 
                   6800:     /*-calculation of age at interview from date of interview and age at death -*/
                   6801:   agev=matrix(1,maxwav,1,imx);
                   6802: 
                   6803:   if(calandcheckages(imx, maxwav, &agemin, &agemax, &nberr, &nbwarn) == 1)
                   6804:     goto end;
                   6805: 
1.126     brouard  6806: 
1.136     brouard  6807:   agegomp=(int)agemin;
                   6808:   free_vector(moisnais,1,n);
                   6809:   free_vector(annais,1,n);
1.126     brouard  6810:   /* free_matrix(mint,1,maxwav,1,n);
                   6811:      free_matrix(anint,1,maxwav,1,n);*/
                   6812:   free_vector(moisdc,1,n);
                   6813:   free_vector(andc,1,n);
1.145     brouard  6814:   /* */
                   6815:   
1.126     brouard  6816:   wav=ivector(1,imx);
                   6817:   dh=imatrix(1,lastpass-firstpass+1,1,imx);
                   6818:   bh=imatrix(1,lastpass-firstpass+1,1,imx);
                   6819:   mw=imatrix(1,lastpass-firstpass+1,1,imx);
                   6820:    
                   6821:   /* Concatenates waves */
                   6822:   concatwav(wav, dh, bh, mw, s, agedc, agev,  firstpass, lastpass, imx, nlstate, stepm);
1.145     brouard  6823:   /* */
                   6824:  
1.126     brouard  6825:   /* Routine tricode is to calculate cptcoveff (real number of unique covariates) and to associate covariable number and modality */
                   6826: 
                   6827:   nbcode=imatrix(0,NCOVMAX,0,NCOVMAX); 
                   6828:   ncodemax[1]=1;
1.145     brouard  6829:   Ndum =ivector(-1,NCOVMAX);  
1.187     brouard  6830:   if (ncovmodel-nagesqr > 2 ) /* That is if covariate other than cst, age and age*age */
1.145     brouard  6831:     tricode(Tvar,nbcode,imx, Ndum); /**< Fills nbcode[Tvar[j]][l]; */
1.186     brouard  6832:   /* Nbcode gives the value of the lth modality of jth covariate, in
                   6833:      V2+V1*age, there are 3 covariates Tvar[2]=1 (V1).*/
                   6834:   /* 1 to ncodemax[j] is the maximum value of this jth covariate */
1.145     brouard  6835: 
                   6836:   codtab=imatrix(1,100,1,10); /* codtab[h,k]=( (h-1) - mod(k-1,2**(k-1) )/2**(k-1) */
                   6837:   /*printf(" codtab[1,1],codtab[100,10]=%d,%d\n", codtab[1][1],codtab[100][10]);*/
1.186     brouard  6838:   /* codtab gives the value 1 or 2 of the hth combination of k covariates (1 or 2).*/
1.145     brouard  6839:   h=0;
                   6840: 
                   6841: 
                   6842:   /*if (cptcovn > 0) */
1.126     brouard  6843:       
1.145     brouard  6844:  
1.126     brouard  6845:   m=pow(2,cptcoveff);
                   6846:  
1.131     brouard  6847:   for(k=1;k<=cptcoveff; k++){ /* scans any effective covariate */
1.143     brouard  6848:     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 */ 
                   6849:       for(j=1; j <= ncodemax[k]; j++){ /* For each modality of this covariate ncodemax=2*/
                   6850:        for(cpt=1; cpt <=pow(2,k-1); cpt++){  /* cpt=1 to 8/2**(3+1-1 or 3+1-3) =1 or 4 */ 
1.126     brouard  6851:          h++;
1.141     brouard  6852:          if (h>m) 
1.136     brouard  6853:            h=1;
1.144     brouard  6854:          /**< codtab(h,k)  k   = codtab[h,k]=( (h-1) - mod(k-1,2**(k-1) )/2**(k-1) + 1
1.186     brouard  6855:           * For k=4 covariates, h goes from 1 to 2**k
                   6856:           * codtabm(h,k)=  1 & (h-1) >> (k-1) ;
                   6857:           *     h\k   1     2     3     4
1.143     brouard  6858:           *______________________________  
                   6859:           *     1 i=1 1 i=1 1 i=1 1 i=1 1
                   6860:           *     2     2     1     1     1
                   6861:           *     3 i=2 1     2     1     1
                   6862:           *     4     2     2     1     1
                   6863:           *     5 i=3 1 i=2 1     2     1
                   6864:           *     6     2     1     2     1
                   6865:           *     7 i=4 1     2     2     1
                   6866:           *     8     2     2     2     1
                   6867:           *     9 i=5 1 i=3 1 i=2 1     1
                   6868:           *    10     2     1     1     1
                   6869:           *    11 i=6 1     2     1     1
                   6870:           *    12     2     2     1     1
                   6871:           *    13 i=7 1 i=4 1     2     1    
                   6872:           *    14     2     1     2     1
                   6873:           *    15 i=8 1     2     2     1
                   6874:           *    16     2     2     2     1
                   6875:           */
1.141     brouard  6876:          codtab[h][k]=j;
1.186     brouard  6877:          /* codtab[12][3]=1; */
1.145     brouard  6878:          /*codtab[h][Tvar[k]]=j;*/
1.130     brouard  6879:          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]]);
1.126     brouard  6880:        } 
                   6881:       }
                   6882:     }
                   6883:   } 
                   6884:   /* printf("codtab[1][2]=%d codtab[2][2]=%d",codtab[1][2],codtab[2][2]); 
                   6885:      codtab[1][2]=1;codtab[2][2]=2; */
                   6886:   /* for(i=1; i <=m ;i++){ 
                   6887:      for(k=1; k <=cptcovn; k++){
1.131     brouard  6888:        printf("i=%d k=%d %d %d ",i,k,codtab[i][k], cptcoveff);
1.126     brouard  6889:      }
                   6890:      printf("\n");
                   6891:      }
                   6892:      scanf("%d",i);*/
1.145     brouard  6893: 
                   6894:  free_ivector(Ndum,-1,NCOVMAX);
                   6895: 
                   6896: 
1.126     brouard  6897:     
1.186     brouard  6898:   /* Initialisation of ----------- gnuplot -------------*/
1.126     brouard  6899:   strcpy(optionfilegnuplot,optionfilefiname);
                   6900:   if(mle==-3)
                   6901:     strcat(optionfilegnuplot,"-mort");
                   6902:   strcat(optionfilegnuplot,".gp");
                   6903: 
                   6904:   if((ficgp=fopen(optionfilegnuplot,"w"))==NULL) {
                   6905:     printf("Problem with file %s",optionfilegnuplot);
                   6906:   }
                   6907:   else{
                   6908:     fprintf(ficgp,"\n# %s\n", version); 
                   6909:     fprintf(ficgp,"# %s\n", optionfilegnuplot); 
1.141     brouard  6910:     //fprintf(ficgp,"set missing 'NaNq'\n");
                   6911:     fprintf(ficgp,"set datafile missing 'NaNq'\n");
1.126     brouard  6912:   }
                   6913:   /*  fclose(ficgp);*/
1.186     brouard  6914: 
                   6915: 
                   6916:   /* Initialisation of --------- index.htm --------*/
1.126     brouard  6917: 
                   6918:   strcpy(optionfilehtm,optionfilefiname); /* Main html file */
                   6919:   if(mle==-3)
                   6920:     strcat(optionfilehtm,"-mort");
                   6921:   strcat(optionfilehtm,".htm");
                   6922:   if((fichtm=fopen(optionfilehtm,"w"))==NULL)    {
1.131     brouard  6923:     printf("Problem with %s \n",optionfilehtm);
                   6924:     exit(0);
1.126     brouard  6925:   }
                   6926: 
                   6927:   strcpy(optionfilehtmcov,optionfilefiname); /* Only for matrix of covariance */
                   6928:   strcat(optionfilehtmcov,"-cov.htm");
                   6929:   if((fichtmcov=fopen(optionfilehtmcov,"w"))==NULL)    {
                   6930:     printf("Problem with %s \n",optionfilehtmcov), exit(0);
                   6931:   }
                   6932:   else{
                   6933:   fprintf(fichtmcov,"<html><head>\n<title>IMaCh Cov %s</title></head>\n <body><font size=\"2\">%s <br> %s</font> \
                   6934: <hr size=\"2\" color=\"#EC5E5E\"> \n\
                   6935: Title=%s <br>Datafile=%s Firstpass=%d Lastpass=%d Stepm=%d Weight=%d Model=%s<br>\n",\
                   6936:          optionfilehtmcov,version,fullversion,title,datafile,firstpass,lastpass,stepm, weightopt, model);
                   6937:   }
                   6938: 
                   6939:   fprintf(fichtm,"<html><head>\n<title>IMaCh %s</title></head>\n <body><font size=\"2\">%s <br> %s</font> \
                   6940: <hr size=\"2\" color=\"#EC5E5E\"> \n\
                   6941: Title=%s <br>Datafile=%s Firstpass=%d Lastpass=%d Stepm=%d Weight=%d Model=%s<br>\n\
                   6942: \n\
                   6943: <hr  size=\"2\" color=\"#EC5E5E\">\
                   6944:  <ul><li><h4>Parameter files</h4>\n\
                   6945:  - Parameter file: <a href=\"%s.%s\">%s.%s</a><br>\n\
                   6946:  - Copy of the parameter file: <a href=\"o%s\">o%s</a><br>\n\
                   6947:  - Log file of the run: <a href=\"%s\">%s</a><br>\n\
                   6948:  - Gnuplot file name: <a href=\"%s\">%s</a><br>\n\
                   6949:  - Date and time at start: %s</ul>\n",\
                   6950:          optionfilehtm,version,fullversion,title,datafile,firstpass,lastpass,stepm, weightopt, model,\
                   6951:          optionfilefiname,optionfilext,optionfilefiname,optionfilext,\
                   6952:          fileres,fileres,\
                   6953:          filelog,filelog,optionfilegnuplot,optionfilegnuplot,strstart);
                   6954:   fflush(fichtm);
                   6955: 
                   6956:   strcpy(pathr,path);
                   6957:   strcat(pathr,optionfilefiname);
1.184     brouard  6958: #ifdef WIN32
                   6959:   _chdir(optionfilefiname); /* Move to directory named optionfile */
                   6960: #else
1.126     brouard  6961:   chdir(optionfilefiname); /* Move to directory named optionfile */
1.184     brouard  6962: #endif
                   6963:          
1.126     brouard  6964:   
                   6965:   /* Calculates basic frequencies. Computes observed prevalence at single age
                   6966:      and prints on file fileres'p'. */
                   6967:   freqsummary(fileres, agemin, agemax, s, agev, nlstate, imx,Tvaraff,nbcode, ncodemax,mint,anint,strstart);
                   6968: 
                   6969:   fprintf(fichtm,"\n");
                   6970:   fprintf(fichtm,"<br>Total number of observations=%d <br>\n\
                   6971: Youngest age at first (selected) pass %.2f, oldest age %.2f<br>\n\
                   6972: Interval (in months) between two waves: Min=%d Max=%d Mean=%.2lf<br>\n",\
                   6973:          imx,agemin,agemax,jmin,jmax,jmean);
                   6974:   pmmij= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
                   6975:     oldms= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
                   6976:     newms= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
                   6977:     savms= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
                   6978:     oldm=oldms; newm=newms; savm=savms; /* Keeps fixed addresses to free */
                   6979:     
                   6980:    
                   6981:   /* For Powell, parameters are in a vector p[] starting at p[1]
                   6982:      so we point p on param[1][1] so that p[1] maps on param[1][1][1] */
                   6983:   p=param[1][1]; /* *(*(*(param +1)+1)+0) */
                   6984: 
                   6985:   globpr=0; /* To get the number ipmx of contributions and the sum of weights*/
1.186     brouard  6986:   /* For mortality only */
1.126     brouard  6987:   if (mle==-3){
1.136     brouard  6988:     ximort=matrix(1,NDIM,1,NDIM); 
1.186     brouard  6989:     /*     ximort=gsl_matrix_alloc(1,NDIM,1,NDIM); */
1.126     brouard  6990:     cens=ivector(1,n);
                   6991:     ageexmed=vector(1,n);
                   6992:     agecens=vector(1,n);
                   6993:     dcwave=ivector(1,n);
                   6994:  
                   6995:     for (i=1; i<=imx; i++){
                   6996:       dcwave[i]=-1;
                   6997:       for (m=firstpass; m<=lastpass; m++)
                   6998:        if (s[m][i]>nlstate) {
                   6999:          dcwave[i]=m;
                   7000:          /*    printf("i=%d j=%d s=%d dcwave=%d\n",i,j, s[j][i],dcwave[i]);*/
                   7001:          break;
                   7002:        }
                   7003:     }
                   7004: 
                   7005:     for (i=1; i<=imx; i++) {
                   7006:       if (wav[i]>0){
                   7007:        ageexmed[i]=agev[mw[1][i]][i];
                   7008:        j=wav[i];
                   7009:        agecens[i]=1.; 
                   7010: 
                   7011:        if (ageexmed[i]> 1 && wav[i] > 0){
                   7012:          agecens[i]=agev[mw[j][i]][i];
                   7013:          cens[i]= 1;
                   7014:        }else if (ageexmed[i]< 1) 
                   7015:          cens[i]= -1;
                   7016:        if (agedc[i]< AGESUP && agedc[i]>1 && dcwave[i]>firstpass && dcwave[i]<=lastpass)
                   7017:          cens[i]=0 ;
                   7018:       }
                   7019:       else cens[i]=-1;
                   7020:     }
                   7021:     
                   7022:     for (i=1;i<=NDIM;i++) {
                   7023:       for (j=1;j<=NDIM;j++)
                   7024:        ximort[i][j]=(i == j ? 1.0 : 0.0);
                   7025:     }
                   7026:     
1.145     brouard  7027:     /*p[1]=0.0268; p[NDIM]=0.083;*/
1.126     brouard  7028:     /*printf("%lf %lf", p[1], p[2]);*/
                   7029:     
                   7030:     
1.136     brouard  7031: #ifdef GSL
                   7032:     printf("GSL optimization\n");  fprintf(ficlog,"Powell\n");
1.162     brouard  7033: #else
1.126     brouard  7034:     printf("Powell\n");  fprintf(ficlog,"Powell\n");
1.136     brouard  7035: #endif
1.126     brouard  7036:     strcpy(filerespow,"pow-mort"); 
                   7037:     strcat(filerespow,fileres);
                   7038:     if((ficrespow=fopen(filerespow,"w"))==NULL) {
                   7039:       printf("Problem with resultfile: %s\n", filerespow);
                   7040:       fprintf(ficlog,"Problem with resultfile: %s\n", filerespow);
                   7041:     }
1.136     brouard  7042: #ifdef GSL
                   7043:     fprintf(ficrespow,"# GSL optimization\n# iter -2*LL");
1.162     brouard  7044: #else
1.126     brouard  7045:     fprintf(ficrespow,"# Powell\n# iter -2*LL");
1.136     brouard  7046: #endif
1.126     brouard  7047:     /*  for (i=1;i<=nlstate;i++)
                   7048:        for(j=1;j<=nlstate+ndeath;j++)
                   7049:        if(j!=i)fprintf(ficrespow," p%1d%1d",i,j);
                   7050:     */
                   7051:     fprintf(ficrespow,"\n");
1.136     brouard  7052: #ifdef GSL
                   7053:     /* gsl starts here */ 
                   7054:     T = gsl_multimin_fminimizer_nmsimplex;
                   7055:     gsl_multimin_fminimizer *sfm = NULL;
                   7056:     gsl_vector *ss, *x;
                   7057:     gsl_multimin_function minex_func;
                   7058: 
                   7059:     /* Initial vertex size vector */
                   7060:     ss = gsl_vector_alloc (NDIM);
                   7061:     
                   7062:     if (ss == NULL){
                   7063:       GSL_ERROR_VAL ("failed to allocate space for ss", GSL_ENOMEM, 0);
                   7064:     }
                   7065:     /* Set all step sizes to 1 */
                   7066:     gsl_vector_set_all (ss, 0.001);
                   7067: 
                   7068:     /* Starting point */
1.126     brouard  7069:     
1.136     brouard  7070:     x = gsl_vector_alloc (NDIM);
                   7071:     
                   7072:     if (x == NULL){
                   7073:       gsl_vector_free(ss);
                   7074:       GSL_ERROR_VAL ("failed to allocate space for x", GSL_ENOMEM, 0);
                   7075:     }
                   7076:   
                   7077:     /* Initialize method and iterate */
                   7078:     /*     p[1]=0.0268; p[NDIM]=0.083; */
1.186     brouard  7079:     /*     gsl_vector_set(x, 0, 0.0268); */
                   7080:     /*     gsl_vector_set(x, 1, 0.083); */
1.136     brouard  7081:     gsl_vector_set(x, 0, p[1]);
                   7082:     gsl_vector_set(x, 1, p[2]);
                   7083: 
                   7084:     minex_func.f = &gompertz_f;
                   7085:     minex_func.n = NDIM;
                   7086:     minex_func.params = (void *)&p; /* ??? */
                   7087:     
                   7088:     sfm = gsl_multimin_fminimizer_alloc (T, NDIM);
                   7089:     gsl_multimin_fminimizer_set (sfm, &minex_func, x, ss);
                   7090:     
                   7091:     printf("Iterations beginning .....\n\n");
                   7092:     printf("Iter. #    Intercept       Slope     -Log Likelihood     Simplex size\n");
                   7093: 
                   7094:     iteri=0;
                   7095:     while (rval == GSL_CONTINUE){
                   7096:       iteri++;
                   7097:       status = gsl_multimin_fminimizer_iterate(sfm);
                   7098:       
                   7099:       if (status) printf("error: %s\n", gsl_strerror (status));
                   7100:       fflush(0);
                   7101:       
                   7102:       if (status) 
                   7103:         break;
                   7104:       
                   7105:       rval = gsl_multimin_test_size (gsl_multimin_fminimizer_size (sfm), 1e-6);
                   7106:       ssval = gsl_multimin_fminimizer_size (sfm);
                   7107:       
                   7108:       if (rval == GSL_SUCCESS)
                   7109:         printf ("converged to a local maximum at\n");
                   7110:       
                   7111:       printf("%5d ", iteri);
                   7112:       for (it = 0; it < NDIM; it++){
                   7113:        printf ("%10.5f ", gsl_vector_get (sfm->x, it));
                   7114:       }
                   7115:       printf("f() = %-10.5f ssize = %.7f\n", sfm->fval, ssval);
                   7116:     }
                   7117:     
                   7118:     printf("\n\n Please note: Program should be run many times with varying starting points to detemine global maximum\n\n");
                   7119:     
                   7120:     gsl_vector_free(x); /* initial values */
                   7121:     gsl_vector_free(ss); /* inital step size */
                   7122:     for (it=0; it<NDIM; it++){
                   7123:       p[it+1]=gsl_vector_get(sfm->x,it);
                   7124:       fprintf(ficrespow," %.12lf", p[it]);
                   7125:     }
                   7126:     gsl_multimin_fminimizer_free (sfm); /* p *(sfm.x.data) et p *(sfm.x.data+1)  */
                   7127: #endif
                   7128: #ifdef POWELL
                   7129:      powell(p,ximort,NDIM,ftol,&iter,&fret,gompertz);
                   7130: #endif  
1.126     brouard  7131:     fclose(ficrespow);
                   7132:     
                   7133:     hesscov(matcov, p, NDIM, delti, 1e-4, gompertz); 
                   7134: 
                   7135:     for(i=1; i <=NDIM; i++)
                   7136:       for(j=i+1;j<=NDIM;j++)
                   7137:        matcov[i][j]=matcov[j][i];
                   7138:     
                   7139:     printf("\nCovariance matrix\n ");
                   7140:     for(i=1; i <=NDIM; i++) {
                   7141:       for(j=1;j<=NDIM;j++){ 
                   7142:        printf("%f ",matcov[i][j]);
                   7143:       }
                   7144:       printf("\n ");
                   7145:     }
                   7146:     
                   7147:     printf("iter=%d MLE=%f Eq=%lf*exp(%lf*(age-%d))\n",iter,-gompertz(p),p[1],p[2],agegomp);
1.193     brouard  7148:     for (i=1;i<=NDIM;i++) {
1.126     brouard  7149:       printf("%f [%f ; %f]\n",p[i],p[i]-2*sqrt(matcov[i][i]),p[i]+2*sqrt(matcov[i][i]));
1.193     brouard  7150:       fprintf(ficlog,"%f [%f ; %f]\n",p[i],p[i]-2*sqrt(matcov[i][i]),p[i]+2*sqrt(matcov[i][i]));
                   7151:     }
1.126     brouard  7152:     lsurv=vector(1,AGESUP);
                   7153:     lpop=vector(1,AGESUP);
                   7154:     tpop=vector(1,AGESUP);
                   7155:     lsurv[agegomp]=100000;
                   7156:     
                   7157:     for (k=agegomp;k<=AGESUP;k++) {
                   7158:       agemortsup=k;
                   7159:       if (p[1]*exp(p[2]*(k-agegomp))>1) break;
                   7160:     }
                   7161:     
                   7162:     for (k=agegomp;k<agemortsup;k++)
                   7163:       lsurv[k+1]=lsurv[k]-lsurv[k]*(p[1]*exp(p[2]*(k-agegomp)));
                   7164:     
                   7165:     for (k=agegomp;k<agemortsup;k++){
                   7166:       lpop[k]=(lsurv[k]+lsurv[k+1])/2.;
                   7167:       sumlpop=sumlpop+lpop[k];
                   7168:     }
                   7169:     
                   7170:     tpop[agegomp]=sumlpop;
                   7171:     for (k=agegomp;k<(agemortsup-3);k++){
                   7172:       /*  tpop[k+1]=2;*/
                   7173:       tpop[k+1]=tpop[k]-lpop[k];
                   7174:     }
                   7175:     
                   7176:     
                   7177:     printf("\nAge   lx     qx    dx    Lx     Tx     e(x)\n");
                   7178:     for (k=agegomp;k<(agemortsup-2);k++) 
                   7179:       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]);
                   7180:     
                   7181:     
                   7182:     replace_back_to_slash(pathc,pathcd); /* Even gnuplot wants a / */
1.194     brouard  7183:     if(ageminpar == AGEOVERFLOW ||agemaxpar == AGEOVERFLOW){
                   7184:        printf("Warning! Error in gnuplot file with ageminpar %f or agemaxpar %f overflow\n\
                   7185: This is probably because your parameter file doesn't \n  contain the exact number of lines (or columns) corresponding to your model line.\n\
                   7186: Please run with mle=-1 to get a correct covariance matrix.\n",ageminpar,agemaxpar);
                   7187:        fprintf(ficlog,"Warning! Error in gnuplot file with ageminpar %f or agemaxpar %f overflow\n\
                   7188: This is probably because your parameter file doesn't \n  contain the exact number of lines (or columns) corresponding to your model line.\n\
                   7189: Please run with mle=-1 to get a correct covariance matrix.\n",ageminpar,agemaxpar);
                   7190:     }else
                   7191:       printinggnuplotmort(fileres, optionfilefiname,ageminpar,agemaxpar,fage, pathc,p);
1.126     brouard  7192:     printinghtmlmort(fileres,title,datafile, firstpass, lastpass, \
                   7193:                     stepm, weightopt,\
                   7194:                     model,imx,p,matcov,agemortsup);
                   7195:     
                   7196:     free_vector(lsurv,1,AGESUP);
                   7197:     free_vector(lpop,1,AGESUP);
                   7198:     free_vector(tpop,1,AGESUP);
1.136     brouard  7199: #ifdef GSL
                   7200:     free_ivector(cens,1,n);
                   7201:     free_vector(agecens,1,n);
                   7202:     free_ivector(dcwave,1,n);
                   7203:     free_matrix(ximort,1,NDIM,1,NDIM);
                   7204: #endif
1.186     brouard  7205:   } /* Endof if mle==-3 mortality only */
                   7206:   /* Standard maximisation */
1.126     brouard  7207:   else{ /* For mle >=1 */
1.132     brouard  7208:     globpr=0;/* debug */
1.186     brouard  7209:     /* Computes likelihood for initial parameters */
1.132     brouard  7210:     likelione(ficres, p, npar, nlstate, &globpr, &ipmx, &sw, &fretone, funcone); /* Prints the contributions to the likelihood */
1.126     brouard  7211:     printf("First Likeli=%12.6f ipmx=%ld sw=%12.6f",fretone,ipmx,sw);
                   7212:     for (k=1; k<=npar;k++)
                   7213:       printf(" %d %8.5f",k,p[k]);
                   7214:     printf("\n");
1.186     brouard  7215:     globpr=1; /* again, to print the contributions */
1.126     brouard  7216:     likelione(ficres, p, npar, nlstate, &globpr, &ipmx, &sw, &fretone, funcone); /* Prints the contributions to the likelihood */
                   7217:     printf("Second Likeli=%12.6f ipmx=%ld sw=%12.6f",fretone,ipmx,sw);
                   7218:     for (k=1; k<=npar;k++)
                   7219:       printf(" %d %8.5f",k,p[k]);
                   7220:     printf("\n");
1.186     brouard  7221:     if(mle>=1){ /* Could be 1 or 2, Real Maximisation */
1.126     brouard  7222:       mlikeli(ficres,p, npar, ncovmodel, nlstate, ftol, func);
                   7223:     }
                   7224:     
                   7225:     /*--------- results files --------------*/
1.192     brouard  7226:     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  7227:     
                   7228:     
                   7229:     fprintf(ficres,"# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
                   7230:     printf("# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
                   7231:     fprintf(ficlog,"# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
                   7232:     for(i=1,jk=1; i <=nlstate; i++){
                   7233:       for(k=1; k <=(nlstate+ndeath); k++){
                   7234:        if (k != i) {
                   7235:          printf("%d%d ",i,k);
                   7236:          fprintf(ficlog,"%d%d ",i,k);
                   7237:          fprintf(ficres,"%1d%1d ",i,k);
                   7238:          for(j=1; j <=ncovmodel; j++){
1.190     brouard  7239:            printf("%12.7f ",p[jk]);
                   7240:            fprintf(ficlog,"%12.7f ",p[jk]);
                   7241:            fprintf(ficres,"%12.7f ",p[jk]);
1.126     brouard  7242:            jk++; 
                   7243:          }
                   7244:          printf("\n");
                   7245:          fprintf(ficlog,"\n");
                   7246:          fprintf(ficres,"\n");
                   7247:        }
                   7248:       }
                   7249:     }
                   7250:     if(mle!=0){
                   7251:       /* Computing hessian and covariance matrix */
                   7252:       ftolhess=ftol; /* Usually correct */
                   7253:       hesscov(matcov, p, npar, delti, ftolhess, func);
                   7254:     }
1.193     brouard  7255:     printf("Parameters and 95%% confidence intervals\n");
                   7256:     fprintf(ficlog, "Parameters, T and confidence intervals\n");
                   7257:     for(i=1,jk=1; i <=nlstate; i++){
                   7258:       for(k=1; k <=(nlstate+ndeath); k++){
                   7259:        if (k != i) {
                   7260:          printf("%d%d ",i,k);
                   7261:          fprintf(ficlog,"%d%d ",i,k);
                   7262:          for(j=1; j <=ncovmodel; j++){
                   7263:            printf("%12.7f T=%8.3f CI=[%12.7f ; %12.7f] ",p[jk], p[jk]/sqrt(matcov[jk][jk]), p[jk]-2*sqrt(matcov[jk][jk]),p[jk]+2*sqrt(matcov[jk][jk]));
                   7264:            fprintf(ficlog,"%12.7f T=%8.3f CI=[%12.7f ; %12.7f] ",p[jk], p[jk]/sqrt(matcov[jk][jk]), p[jk]-2*sqrt(matcov[jk][jk]),p[jk]+2*sqrt(matcov[jk][jk]));
                   7265:            jk++; 
                   7266:          }
                   7267:          printf("\n");
                   7268:          fprintf(ficlog,"\n");
                   7269:        }
                   7270:       }
                   7271:     }
                   7272: 
1.126     brouard  7273:     fprintf(ficres,"# Scales (for hessian or gradient estimation)\n");
                   7274:     printf("# Scales (for hessian or gradient estimation)\n");
                   7275:     fprintf(ficlog,"# Scales (for hessian or gradient estimation)\n");
                   7276:     for(i=1,jk=1; i <=nlstate; i++){
                   7277:       for(j=1; j <=nlstate+ndeath; j++){
                   7278:        if (j!=i) {
                   7279:          fprintf(ficres,"%1d%1d",i,j);
                   7280:          printf("%1d%1d",i,j);
                   7281:          fprintf(ficlog,"%1d%1d",i,j);
                   7282:          for(k=1; k<=ncovmodel;k++){
                   7283:            printf(" %.5e",delti[jk]);
                   7284:            fprintf(ficlog," %.5e",delti[jk]);
                   7285:            fprintf(ficres," %.5e",delti[jk]);
                   7286:            jk++;
                   7287:          }
                   7288:          printf("\n");
                   7289:          fprintf(ficlog,"\n");
                   7290:          fprintf(ficres,"\n");
                   7291:        }
                   7292:       }
                   7293:     }
                   7294:     
                   7295:     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");
                   7296:     if(mle>=1)
                   7297:       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");
                   7298:     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");
                   7299:     /* # 121 Var(a12)\n\ */
                   7300:     /* # 122 Cov(b12,a12) Var(b12)\n\ */
                   7301:     /* # 131 Cov(a13,a12) Cov(a13,b12, Var(a13)\n\ */
                   7302:     /* # 132 Cov(b13,a12) Cov(b13,b12, Cov(b13,a13) Var(b13)\n\ */
                   7303:     /* # 212 Cov(a21,a12) Cov(a21,b12, Cov(a21,a13) Cov(a21,b13) Var(a21)\n\ */
                   7304:     /* # 212 Cov(b21,a12) Cov(b21,b12, Cov(b21,a13) Cov(b21,b13) Cov(b21,a21) Var(b21)\n\ */
                   7305:     /* # 232 Cov(a23,a12) Cov(a23,b12, Cov(a23,a13) Cov(a23,b13) Cov(a23,a21) Cov(a23,b21) Var(a23)\n\ */
                   7306:     /* # 232 Cov(b23,a12) Cov(b23,b12) ... Var (b23)\n" */
                   7307:     
                   7308:     
                   7309:     /* Just to have a covariance matrix which will be more understandable
                   7310:        even is we still don't want to manage dictionary of variables
                   7311:     */
                   7312:     for(itimes=1;itimes<=2;itimes++){
                   7313:       jj=0;
                   7314:       for(i=1; i <=nlstate; i++){
                   7315:        for(j=1; j <=nlstate+ndeath; j++){
                   7316:          if(j==i) continue;
                   7317:          for(k=1; k<=ncovmodel;k++){
                   7318:            jj++;
                   7319:            ca[0]= k+'a'-1;ca[1]='\0';
                   7320:            if(itimes==1){
                   7321:              if(mle>=1)
                   7322:                printf("#%1d%1d%d",i,j,k);
                   7323:              fprintf(ficlog,"#%1d%1d%d",i,j,k);
                   7324:              fprintf(ficres,"#%1d%1d%d",i,j,k);
                   7325:            }else{
                   7326:              if(mle>=1)
                   7327:                printf("%1d%1d%d",i,j,k);
                   7328:              fprintf(ficlog,"%1d%1d%d",i,j,k);
                   7329:              fprintf(ficres,"%1d%1d%d",i,j,k);
                   7330:            }
                   7331:            ll=0;
                   7332:            for(li=1;li <=nlstate; li++){
                   7333:              for(lj=1;lj <=nlstate+ndeath; lj++){
                   7334:                if(lj==li) continue;
                   7335:                for(lk=1;lk<=ncovmodel;lk++){
                   7336:                  ll++;
                   7337:                  if(ll<=jj){
                   7338:                    cb[0]= lk +'a'-1;cb[1]='\0';
                   7339:                    if(ll<jj){
                   7340:                      if(itimes==1){
                   7341:                        if(mle>=1)
                   7342:                          printf(" Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
                   7343:                        fprintf(ficlog," Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
                   7344:                        fprintf(ficres," Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
                   7345:                      }else{
                   7346:                        if(mle>=1)
                   7347:                          printf(" %.5e",matcov[jj][ll]); 
                   7348:                        fprintf(ficlog," %.5e",matcov[jj][ll]); 
                   7349:                        fprintf(ficres," %.5e",matcov[jj][ll]); 
                   7350:                      }
                   7351:                    }else{
                   7352:                      if(itimes==1){
                   7353:                        if(mle>=1)
                   7354:                          printf(" Var(%s%1d%1d)",ca,i,j);
                   7355:                        fprintf(ficlog," Var(%s%1d%1d)",ca,i,j);
                   7356:                        fprintf(ficres," Var(%s%1d%1d)",ca,i,j);
                   7357:                      }else{
                   7358:                        if(mle>=1)
                   7359:                          printf(" %.5e",matcov[jj][ll]); 
                   7360:                        fprintf(ficlog," %.5e",matcov[jj][ll]); 
                   7361:                        fprintf(ficres," %.5e",matcov[jj][ll]); 
                   7362:                      }
                   7363:                    }
                   7364:                  }
                   7365:                } /* end lk */
                   7366:              } /* end lj */
                   7367:            } /* end li */
                   7368:            if(mle>=1)
                   7369:              printf("\n");
                   7370:            fprintf(ficlog,"\n");
                   7371:            fprintf(ficres,"\n");
                   7372:            numlinepar++;
                   7373:          } /* end k*/
                   7374:        } /*end j */
                   7375:       } /* end i */
                   7376:     } /* end itimes */
                   7377:     
                   7378:     fflush(ficlog);
                   7379:     fflush(ficres);
                   7380:     
                   7381:     while((c=getc(ficpar))=='#' && c!= EOF){
                   7382:       ungetc(c,ficpar);
                   7383:       fgets(line, MAXLINE, ficpar);
1.141     brouard  7384:       fputs(line,stdout);
1.126     brouard  7385:       fputs(line,ficparo);
                   7386:     }
                   7387:     ungetc(c,ficpar);
                   7388:     
                   7389:     estepm=0;
                   7390:     fscanf(ficpar,"agemin=%lf agemax=%lf bage=%lf fage=%lf estepm=%d\n",&ageminpar,&agemaxpar, &bage, &fage, &estepm);
                   7391:     if (estepm==0 || estepm < stepm) estepm=stepm;
                   7392:     if (fage <= 2) {
                   7393:       bage = ageminpar;
                   7394:       fage = agemaxpar;
                   7395:     }
                   7396:     
                   7397:     fprintf(ficres,"# agemin agemax for life expectancy, bage fage (if mle==0 ie no data nor Max likelihood).\n");
                   7398:     fprintf(ficres,"agemin=%.0f agemax=%.0f bage=%.0f fage=%.0f estepm=%d\n",ageminpar,agemaxpar,bage,fage, estepm);
                   7399:     fprintf(ficparo,"agemin=%.0f agemax=%.0f bage=%.0f fage=%.0f estepm=%d\n",ageminpar,agemaxpar,bage,fage, estepm);
1.186     brouard  7400: 
                   7401:     /* Other stuffs, more or less useful */    
1.126     brouard  7402:     while((c=getc(ficpar))=='#' && c!= EOF){
                   7403:       ungetc(c,ficpar);
                   7404:       fgets(line, MAXLINE, ficpar);
1.141     brouard  7405:       fputs(line,stdout);
1.126     brouard  7406:       fputs(line,ficparo);
                   7407:     }
                   7408:     ungetc(c,ficpar);
                   7409:     
                   7410:     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);
                   7411:     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);
                   7412:     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);
                   7413:     printf("begin-prev-date=%.lf/%.lf/%.lf end-prev-date=%.lf/%.lf/%.lf mov_average=%d\n",jprev1, mprev1,anprev1,jprev2, mprev2,anprev2,mobilav);
                   7414:     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);
                   7415:     
                   7416:     while((c=getc(ficpar))=='#' && c!= EOF){
                   7417:       ungetc(c,ficpar);
                   7418:       fgets(line, MAXLINE, ficpar);
1.141     brouard  7419:       fputs(line,stdout);
1.126     brouard  7420:       fputs(line,ficparo);
                   7421:     }
                   7422:     ungetc(c,ficpar);
                   7423:     
                   7424:     
                   7425:     dateprev1=anprev1+(mprev1-1)/12.+(jprev1-1)/365.;
                   7426:     dateprev2=anprev2+(mprev2-1)/12.+(jprev2-1)/365.;
                   7427:     
                   7428:     fscanf(ficpar,"pop_based=%d\n",&popbased);
1.193     brouard  7429:     fprintf(ficlog,"pop_based=%d\n",popbased);
1.126     brouard  7430:     fprintf(ficparo,"pop_based=%d\n",popbased);   
                   7431:     fprintf(ficres,"pop_based=%d\n",popbased);   
                   7432:     
                   7433:     while((c=getc(ficpar))=='#' && c!= EOF){
                   7434:       ungetc(c,ficpar);
                   7435:       fgets(line, MAXLINE, ficpar);
1.141     brouard  7436:       fputs(line,stdout);
1.126     brouard  7437:       fputs(line,ficparo);
                   7438:     }
                   7439:     ungetc(c,ficpar);
                   7440:     
                   7441:     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);
                   7442:     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);
                   7443:     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);
                   7444:     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);
                   7445:     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);
                   7446:     /* day and month of proj2 are not used but only year anproj2.*/
                   7447:     
                   7448:     
                   7449:     
1.145     brouard  7450:      /* freqsummary(fileres, agemin, agemax, s, agev, nlstate, imx,Tvaraff,nbcode, ncodemax,mint,anint); */
                   7451:     /* ,dateprev1,dateprev2,jprev1, mprev1,anprev1,jprev2, mprev2,anprev2); */
1.126     brouard  7452:     
                   7453:     replace_back_to_slash(pathc,pathcd); /* Even gnuplot wants a / */
1.194     brouard  7454:     if(ageminpar == AGEOVERFLOW ||agemaxpar == -AGEOVERFLOW){
                   7455:        printf("Warning! Error in gnuplot file with ageminpar %f or agemaxpar %f overflow\n\
                   7456: This is probably because your parameter file doesn't \n  contain the exact number of lines (or columns) corresponding to your model line.\n\
                   7457: Please run with mle=-1 to get a correct covariance matrix.\n",ageminpar,agemaxpar);
                   7458:        fprintf(ficlog,"Warning! Error in gnuplot file with ageminpar %f or agemaxpar %f overflow\n\
                   7459: This is probably because your parameter file doesn't \n  contain the exact number of lines (or columns) corresponding to your model line.\n\
                   7460: Please run with mle=-1 to get a correct covariance matrix.\n",ageminpar,agemaxpar);
                   7461:     }else
                   7462:       printinggnuplot(fileres, optionfilefiname,ageminpar,agemaxpar,fage, pathc,p);
1.126     brouard  7463:     
                   7464:     printinghtml(fileres,title,datafile, firstpass, lastpass, stepm, weightopt,\
                   7465:                 model,imx,jmin,jmax,jmean,rfileres,popforecast,estepm,\
                   7466:                 jprev1,mprev1,anprev1,jprev2,mprev2,anprev2);
                   7467:       
                   7468:    /*------------ free_vector  -------------*/
                   7469:    /*  chdir(path); */
                   7470:  
                   7471:     free_ivector(wav,1,imx);
                   7472:     free_imatrix(dh,1,lastpass-firstpass+1,1,imx);
                   7473:     free_imatrix(bh,1,lastpass-firstpass+1,1,imx);
                   7474:     free_imatrix(mw,1,lastpass-firstpass+1,1,imx);   
                   7475:     free_lvector(num,1,n);
                   7476:     free_vector(agedc,1,n);
                   7477:     /*free_matrix(covar,0,NCOVMAX,1,n);*/
                   7478:     /*free_matrix(covar,1,NCOVMAX,1,n);*/
                   7479:     fclose(ficparo);
                   7480:     fclose(ficres);
                   7481: 
                   7482: 
1.186     brouard  7483:     /* Other results (useful)*/
                   7484: 
                   7485: 
1.126     brouard  7486:     /*--------------- Prevalence limit  (period or stable prevalence) --------------*/
1.180     brouard  7487:     /*#include "prevlim.h"*/  /* Use ficrespl, ficlog */
                   7488:     prlim=matrix(1,nlstate,1,nlstate);
                   7489:     prevalence_limit(p, prlim,  ageminpar, agemaxpar);
1.126     brouard  7490:     fclose(ficrespl);
                   7491: 
1.145     brouard  7492: #ifdef FREEEXIT2
                   7493: #include "freeexit2.h"
                   7494: #endif
                   7495: 
1.126     brouard  7496:     /*------------- h Pij x at various ages ------------*/
1.180     brouard  7497:     /*#include "hpijx.h"*/
                   7498:     hPijx(p, bage, fage);
1.145     brouard  7499:     fclose(ficrespij);
1.126     brouard  7500: 
1.145     brouard  7501:   /*-------------- Variance of one-step probabilities---*/
                   7502:     k=1;
1.126     brouard  7503:     varprob(optionfilefiname, matcov, p, delti, nlstate, bage, fage,k,Tvar,nbcode, ncodemax,strstart);
                   7504: 
                   7505: 
                   7506:     probs= ma3x(1,AGESUP,1,NCOVMAX, 1,NCOVMAX);
                   7507:     for(i=1;i<=AGESUP;i++)
                   7508:       for(j=1;j<=NCOVMAX;j++)
                   7509:        for(k=1;k<=NCOVMAX;k++)
                   7510:          probs[i][j][k]=0.;
                   7511: 
                   7512:     /*---------- Forecasting ------------------*/
                   7513:     /*if((stepm == 1) && (strcmp(model,".")==0)){*/
                   7514:     if(prevfcast==1){
                   7515:       /*    if(stepm ==1){*/
                   7516:       prevforecast(fileres, anproj1, mproj1, jproj1, agemin, agemax, dateprev1, dateprev2, mobilavproj, bage, fage, firstpass, lastpass, anproj2, p, cptcoveff);
                   7517:       /* (popforecast==1) populforecast(fileres, anpyram,mpyram,jpyram, agemin,agemax, dateprev1, dateprev2,mobilav, agedeb, fage, popforecast, popfile, anpyram1,p, i1);*/
                   7518:       /*      }  */
                   7519:       /*      else{ */
                   7520:       /*        erreur=108; */
                   7521:       /*        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); */
                   7522:       /*        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); */
                   7523:       /*      } */
                   7524:     }
1.186     brouard  7525:  
                   7526:     /* ------ Other prevalence ratios------------ */
1.126     brouard  7527: 
1.127     brouard  7528:     /* Computes prevalence between agemin (i.e minimal age computed) and no more ageminpar */
                   7529: 
                   7530:     prevalence(probs, agemin, agemax, s, agev, nlstate, imx, Tvar, nbcode, ncodemax, mint, anint, dateprev1, dateprev2, firstpass, lastpass);
                   7531:     /*  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",\
                   7532:        ageminpar, agemax, s[lastpass][imx], agev[lastpass][imx], nlstate, imx, mint[lastpass][imx],anint[lastpass][imx], dateprev1, dateprev2, firstpass, lastpass);
                   7533:     */
1.126     brouard  7534: 
1.127     brouard  7535:     if (mobilav!=0) {
                   7536:       mobaverage= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
                   7537:       if (movingaverage(probs, bage, fage, mobaverage,mobilav)!=0){
                   7538:        fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav);
                   7539:        printf(" Error in movingaverage mobilav=%d\n",mobilav);
                   7540:       }
1.126     brouard  7541:     }
                   7542: 
                   7543: 
1.127     brouard  7544:     /*---------- Health expectancies, no variances ------------*/
                   7545: 
1.126     brouard  7546:     strcpy(filerese,"e");
                   7547:     strcat(filerese,fileres);
                   7548:     if((ficreseij=fopen(filerese,"w"))==NULL) {
                   7549:       printf("Problem with Health Exp. resultfile: %s\n", filerese); exit(0);
                   7550:       fprintf(ficlog,"Problem with Health Exp. resultfile: %s\n", filerese); exit(0);
                   7551:     }
                   7552:     printf("Computing Health Expectancies: result on file '%s' \n", filerese);
                   7553:     fprintf(ficlog,"Computing Health Expectancies: result on file '%s' \n", filerese);
1.145     brouard  7554:     /*for(cptcov=1,k=0;cptcov<=i1;cptcov++){
                   7555:       for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){*/
                   7556:           
                   7557:     for (k=1; k <= (int) pow(2,cptcoveff); k++){
1.127     brouard  7558:        fprintf(ficreseij,"\n#****** ");
                   7559:        for(j=1;j<=cptcoveff;j++) {
                   7560:          fprintf(ficreseij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
                   7561:        }
                   7562:        fprintf(ficreseij,"******\n");
                   7563: 
                   7564:        eij=ma3x(1,nlstate,1,nlstate,(int) bage, (int) fage);
                   7565:        oldm=oldms;savm=savms;
                   7566:        evsij(eij, p, nlstate, stepm, (int) bage, (int)fage, oldm, savm, k, estepm, strstart);  
                   7567:       
                   7568:        free_ma3x(eij,1,nlstate,1,nlstate,(int) bage, (int)fage);
1.145     brouard  7569:       /*}*/
1.127     brouard  7570:     }
                   7571:     fclose(ficreseij);
                   7572: 
                   7573: 
                   7574:     /*---------- Health expectancies and variances ------------*/
                   7575: 
                   7576: 
                   7577:     strcpy(filerest,"t");
                   7578:     strcat(filerest,fileres);
                   7579:     if((ficrest=fopen(filerest,"w"))==NULL) {
                   7580:       printf("Problem with total LE resultfile: %s\n", filerest);goto end;
                   7581:       fprintf(ficlog,"Problem with total LE resultfile: %s\n", filerest);goto end;
                   7582:     }
                   7583:     printf("Computing Total Life expectancies with their standard errors: file '%s' \n", filerest); 
                   7584:     fprintf(ficlog,"Computing Total Life expectancies with their standard errors: file '%s' \n", filerest); 
                   7585: 
1.126     brouard  7586: 
                   7587:     strcpy(fileresstde,"stde");
                   7588:     strcat(fileresstde,fileres);
                   7589:     if((ficresstdeij=fopen(fileresstde,"w"))==NULL) {
                   7590:       printf("Problem with Health Exp. and std errors resultfile: %s\n", fileresstde); exit(0);
                   7591:       fprintf(ficlog,"Problem with Health Exp. and std errors resultfile: %s\n", fileresstde); exit(0);
                   7592:     }
                   7593:     printf("Computing Health Expectancies and standard errors: result on file '%s' \n", fileresstde);
                   7594:     fprintf(ficlog,"Computing Health Expectancies and standard errors: result on file '%s' \n", fileresstde);
                   7595: 
                   7596:     strcpy(filerescve,"cve");
                   7597:     strcat(filerescve,fileres);
                   7598:     if((ficrescveij=fopen(filerescve,"w"))==NULL) {
                   7599:       printf("Problem with Covar. Health Exp. resultfile: %s\n", filerescve); exit(0);
                   7600:       fprintf(ficlog,"Problem with Covar. Health Exp. resultfile: %s\n", filerescve); exit(0);
                   7601:     }
                   7602:     printf("Computing Covar. of Health Expectancies: result on file '%s' \n", filerescve);
                   7603:     fprintf(ficlog,"Computing Covar. of Health Expectancies: result on file '%s' \n", filerescve);
                   7604: 
                   7605:     strcpy(fileresv,"v");
                   7606:     strcat(fileresv,fileres);
                   7607:     if((ficresvij=fopen(fileresv,"w"))==NULL) {
                   7608:       printf("Problem with variance resultfile: %s\n", fileresv);exit(0);
                   7609:       fprintf(ficlog,"Problem with variance resultfile: %s\n", fileresv);exit(0);
                   7610:     }
                   7611:     printf("Computing Variance-covariance of DFLEs: file '%s' \n", fileresv);
                   7612:     fprintf(ficlog,"Computing Variance-covariance of DFLEs: file '%s' \n", fileresv);
                   7613: 
1.145     brouard  7614:     /*for(cptcov=1,k=0;cptcov<=i1;cptcov++){
                   7615:       for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){*/
                   7616:           
                   7617:     for (k=1; k <= (int) pow(2,cptcoveff); k++){
                   7618:        fprintf(ficrest,"\n#****** ");
1.126     brouard  7619:        for(j=1;j<=cptcoveff;j++) 
                   7620:          fprintf(ficrest,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
                   7621:        fprintf(ficrest,"******\n");
                   7622: 
                   7623:        fprintf(ficresstdeij,"\n#****** ");
                   7624:        fprintf(ficrescveij,"\n#****** ");
                   7625:        for(j=1;j<=cptcoveff;j++) {
                   7626:          fprintf(ficresstdeij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
                   7627:          fprintf(ficrescveij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
                   7628:        }
                   7629:        fprintf(ficresstdeij,"******\n");
                   7630:        fprintf(ficrescveij,"******\n");
                   7631: 
                   7632:        fprintf(ficresvij,"\n#****** ");
                   7633:        for(j=1;j<=cptcoveff;j++) 
                   7634:          fprintf(ficresvij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
                   7635:        fprintf(ficresvij,"******\n");
                   7636: 
                   7637:        eij=ma3x(1,nlstate,1,nlstate,(int) bage, (int) fage);
                   7638:        oldm=oldms;savm=savms;
1.127     brouard  7639:        cvevsij(eij, p, nlstate, stepm, (int) bage, (int)fage, oldm, savm, k, estepm, delti, matcov, strstart);  
1.145     brouard  7640:        /*
                   7641:         */
                   7642:        /* goto endfree; */
1.126     brouard  7643:  
                   7644:        vareij=ma3x(1,nlstate,1,nlstate,(int) bage, (int) fage);
                   7645:        pstamp(ficrest);
1.145     brouard  7646: 
                   7647: 
1.128     brouard  7648:        for(vpopbased=0; vpopbased <= popbased; vpopbased++){ /* Done for vpopbased=0 and vpopbased=1 if popbased==1*/
1.145     brouard  7649:          oldm=oldms;savm=savms; /* Segmentation fault */
1.161     brouard  7650:          cptcod= 0; /* To be deleted */
                   7651:          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  7652:          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  7653:          if(vpopbased==1)
                   7654:            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);
                   7655:          else
                   7656:            fprintf(ficrest,"the age specific period (stable) prevalences in each health state \n");
                   7657:          fprintf(ficrest,"# Age e.. (std) ");
                   7658:          for (i=1;i<=nlstate;i++) fprintf(ficrest,"e.%d (std) ",i);
                   7659:          fprintf(ficrest,"\n");
1.126     brouard  7660: 
1.128     brouard  7661:          epj=vector(1,nlstate+1);
                   7662:          for(age=bage; age <=fage ;age++){
                   7663:            prevalim(prlim, nlstate, p, age, oldm, savm,ftolpl,k);
                   7664:            if (vpopbased==1) {
                   7665:              if(mobilav ==0){
                   7666:                for(i=1; i<=nlstate;i++)
                   7667:                  prlim[i][i]=probs[(int)age][i][k];
                   7668:              }else{ /* mobilav */ 
                   7669:                for(i=1; i<=nlstate;i++)
                   7670:                  prlim[i][i]=mobaverage[(int)age][i][k];
                   7671:              }
1.126     brouard  7672:            }
                   7673:        
1.128     brouard  7674:            fprintf(ficrest," %4.0f",age);
                   7675:            for(j=1, epj[nlstate+1]=0.;j <=nlstate;j++){
                   7676:              for(i=1, epj[j]=0.;i <=nlstate;i++) {
                   7677:                epj[j] += prlim[i][i]*eij[i][j][(int)age];
                   7678:                /*  printf("%lf %lf ", prlim[i][i] ,eij[i][j][(int)age]);*/
                   7679:              }
                   7680:              epj[nlstate+1] +=epj[j];
1.126     brouard  7681:            }
                   7682: 
1.128     brouard  7683:            for(i=1, vepp=0.;i <=nlstate;i++)
                   7684:              for(j=1;j <=nlstate;j++)
                   7685:                vepp += vareij[i][j][(int)age];
                   7686:            fprintf(ficrest," %7.3f (%7.3f)", epj[nlstate+1],sqrt(vepp));
                   7687:            for(j=1;j <=nlstate;j++){
                   7688:              fprintf(ficrest," %7.3f (%7.3f)", epj[j],sqrt(vareij[j][j][(int)age]));
                   7689:            }
                   7690:            fprintf(ficrest,"\n");
1.126     brouard  7691:          }
                   7692:        }
                   7693:        free_ma3x(eij,1,nlstate,1,nlstate,(int) bage, (int)fage);
                   7694:        free_ma3x(vareij,1,nlstate,1,nlstate,(int) bage, (int)fage);
                   7695:        free_vector(epj,1,nlstate+1);
1.145     brouard  7696:       /*}*/
1.126     brouard  7697:     }
                   7698:     free_vector(weight,1,n);
1.145     brouard  7699:     free_imatrix(Tvard,1,NCOVMAX,1,2);
1.126     brouard  7700:     free_imatrix(s,1,maxwav+1,1,n);
                   7701:     free_matrix(anint,1,maxwav,1,n); 
                   7702:     free_matrix(mint,1,maxwav,1,n);
                   7703:     free_ivector(cod,1,n);
                   7704:     free_ivector(tab,1,NCOVMAX);
                   7705:     fclose(ficresstdeij);
                   7706:     fclose(ficrescveij);
                   7707:     fclose(ficresvij);
                   7708:     fclose(ficrest);
                   7709:     fclose(ficpar);
                   7710:   
                   7711:     /*------- Variance of period (stable) prevalence------*/   
                   7712: 
                   7713:     strcpy(fileresvpl,"vpl");
                   7714:     strcat(fileresvpl,fileres);
                   7715:     if((ficresvpl=fopen(fileresvpl,"w"))==NULL) {
                   7716:       printf("Problem with variance of period (stable) prevalence  resultfile: %s\n", fileresvpl);
                   7717:       exit(0);
                   7718:     }
                   7719:     printf("Computing Variance-covariance of period (stable) prevalence: file '%s' \n", fileresvpl);
                   7720: 
1.145     brouard  7721:     /*for(cptcov=1,k=0;cptcov<=i1;cptcov++){
                   7722:       for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){*/
                   7723:           
                   7724:     for (k=1; k <= (int) pow(2,cptcoveff); k++){
                   7725:        fprintf(ficresvpl,"\n#****** ");
1.126     brouard  7726:        for(j=1;j<=cptcoveff;j++) 
                   7727:          fprintf(ficresvpl,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
                   7728:        fprintf(ficresvpl,"******\n");
                   7729:       
                   7730:        varpl=matrix(1,nlstate,(int) bage, (int) fage);
                   7731:        oldm=oldms;savm=savms;
                   7732:        varprevlim(fileres, varpl, matcov, p, delti, nlstate, stepm, (int) bage, (int) fage, oldm, savm, prlim, ftolpl,k,strstart);
                   7733:        free_matrix(varpl,1,nlstate,(int) bage, (int)fage);
1.145     brouard  7734:       /*}*/
1.126     brouard  7735:     }
                   7736: 
                   7737:     fclose(ficresvpl);
                   7738: 
                   7739:     /*---------- End : free ----------------*/
                   7740:     if (mobilav!=0) free_ma3x(mobaverage,1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
                   7741:     free_ma3x(probs,1,AGESUP,1,NCOVMAX, 1,NCOVMAX);
                   7742:   }  /* mle==-3 arrives here for freeing */
1.164     brouard  7743:  /* endfree:*/
1.141     brouard  7744:     free_matrix(prlim,1,nlstate,1,nlstate); /*here or after loop ? */
1.126     brouard  7745:     free_matrix(pmmij,1,nlstate+ndeath,1,nlstate+ndeath);
                   7746:     free_matrix(oldms, 1,nlstate+ndeath,1,nlstate+ndeath);
                   7747:     free_matrix(newms, 1,nlstate+ndeath,1,nlstate+ndeath);
                   7748:     free_matrix(savms, 1,nlstate+ndeath,1,nlstate+ndeath);
                   7749:     free_matrix(covar,0,NCOVMAX,1,n);
                   7750:     free_matrix(matcov,1,npar,1,npar);
                   7751:     /*free_vector(delti,1,npar);*/
                   7752:     free_ma3x(delti3,1,nlstate,1, nlstate+ndeath-1,1,ncovmodel); 
                   7753:     free_matrix(agev,1,maxwav,1,imx);
                   7754:     free_ma3x(param,1,nlstate,1, nlstate+ndeath-1,1,ncovmodel);
                   7755: 
1.145     brouard  7756:     free_ivector(ncodemax,1,NCOVMAX);
1.192     brouard  7757:     free_ivector(ncodemaxwundef,1,NCOVMAX);
1.145     brouard  7758:     free_ivector(Tvar,1,NCOVMAX);
                   7759:     free_ivector(Tprod,1,NCOVMAX);
                   7760:     free_ivector(Tvaraff,1,NCOVMAX);
                   7761:     free_ivector(Tage,1,NCOVMAX);
1.126     brouard  7762: 
                   7763:     free_imatrix(nbcode,0,NCOVMAX,0,NCOVMAX);
                   7764:     free_imatrix(codtab,1,100,1,10);
                   7765:   fflush(fichtm);
                   7766:   fflush(ficgp);
                   7767:   
                   7768: 
                   7769:   if((nberr >0) || (nbwarn>0)){
                   7770:     printf("End of Imach with %d errors and/or %d warnings\n",nberr,nbwarn);
                   7771:     fprintf(ficlog,"End of Imach with %d errors and/or warnings %d\n",nberr,nbwarn);
                   7772:   }else{
                   7773:     printf("End of Imach\n");
                   7774:     fprintf(ficlog,"End of Imach\n");
                   7775:   }
                   7776:   printf("See log file on %s\n",filelog);
                   7777:   /*  gettimeofday(&end_time, (struct timezone*)0);*/  /* after time */
1.157     brouard  7778:   /*(void) gettimeofday(&end_time,&tzp);*/
                   7779:   rend_time = time(NULL);  
                   7780:   end_time = *localtime(&rend_time);
                   7781:   /* tml = *localtime(&end_time.tm_sec); */
                   7782:   strcpy(strtend,asctime(&end_time));
1.126     brouard  7783:   printf("Local time at start %s\nLocal time at end   %s",strstart, strtend); 
                   7784:   fprintf(ficlog,"Local time at start %s\nLocal time at end   %s\n",strstart, strtend); 
1.157     brouard  7785:   printf("Total time used %s\n", asc_diff_time(rend_time -rstart_time,tmpout));
1.126     brouard  7786: 
1.157     brouard  7787:   printf("Total time was %.0lf Sec.\n", difftime(rend_time,rstart_time));
                   7788:   fprintf(ficlog,"Total time used %s\n", asc_diff_time(rend_time -rstart_time,tmpout));
                   7789:   fprintf(ficlog,"Total time was %.0lf Sec.\n", difftime(rend_time,rstart_time));
1.126     brouard  7790:   /*  printf("Total time was %d uSec.\n", total_usecs);*/
                   7791: /*   if(fileappend(fichtm,optionfilehtm)){ */
                   7792:   fprintf(fichtm,"<br>Local time at start %s<br>Local time at end   %s<br>\n</body></html>",strstart, strtend);
                   7793:   fclose(fichtm);
                   7794:   fprintf(fichtmcov,"<br>Local time at start %s<br>Local time at end   %s<br>\n</body></html>",strstart, strtend);
                   7795:   fclose(fichtmcov);
                   7796:   fclose(ficgp);
                   7797:   fclose(ficlog);
                   7798:   /*------ End -----------*/
                   7799: 
                   7800: 
                   7801:    printf("Before Current directory %s!\n",pathcd);
1.184     brouard  7802: #ifdef WIN32
                   7803:    if (_chdir(pathcd) != 0)
                   7804:           printf("Can't move to directory %s!\n",path);
                   7805:    if(_getcwd(pathcd,MAXLINE) > 0)
                   7806: #else
1.126     brouard  7807:    if(chdir(pathcd) != 0)
1.184     brouard  7808:           printf("Can't move to directory %s!\n", path);
                   7809:    if (getcwd(pathcd, MAXLINE) > 0)
                   7810: #endif 
1.126     brouard  7811:     printf("Current directory %s!\n",pathcd);
                   7812:   /*strcat(plotcmd,CHARSEPARATOR);*/
                   7813:   sprintf(plotcmd,"gnuplot");
1.157     brouard  7814: #ifdef _WIN32
1.126     brouard  7815:   sprintf(plotcmd,"\"%sgnuplot.exe\"",pathimach);
                   7816: #endif
                   7817:   if(!stat(plotcmd,&info)){
1.158     brouard  7818:     printf("Error or gnuplot program not found: '%s'\n",plotcmd);fflush(stdout);
1.126     brouard  7819:     if(!stat(getenv("GNUPLOTBIN"),&info)){
1.158     brouard  7820:       printf("Error or gnuplot program not found: '%s' Environment GNUPLOTBIN not set.\n",plotcmd);fflush(stdout);
1.126     brouard  7821:     }else
                   7822:       strcpy(pplotcmd,plotcmd);
1.157     brouard  7823: #ifdef __unix
1.126     brouard  7824:     strcpy(plotcmd,GNUPLOTPROGRAM);
                   7825:     if(!stat(plotcmd,&info)){
1.158     brouard  7826:       printf("Error gnuplot program not found: '%s'\n",plotcmd);fflush(stdout);
1.126     brouard  7827:     }else
                   7828:       strcpy(pplotcmd,plotcmd);
                   7829: #endif
                   7830:   }else
                   7831:     strcpy(pplotcmd,plotcmd);
                   7832:   
                   7833:   sprintf(plotcmd,"%s %s",pplotcmd, optionfilegnuplot);
1.158     brouard  7834:   printf("Starting graphs with: '%s'\n",plotcmd);fflush(stdout);
1.126     brouard  7835: 
                   7836:   if((outcmd=system(plotcmd)) != 0){
1.158     brouard  7837:     printf("gnuplot command might not be in your path: '%s', err=%d\n", plotcmd, outcmd);
1.154     brouard  7838:     printf("\n Trying if gnuplot resides on the same directory that IMaCh\n");
1.152     brouard  7839:     sprintf(plotcmd,"%sgnuplot %s", pathimach, optionfilegnuplot);
1.150     brouard  7840:     if((outcmd=system(plotcmd)) != 0)
1.153     brouard  7841:       printf("\n Still a problem with gnuplot command %s, err=%d\n", plotcmd, outcmd);
1.126     brouard  7842:   }
1.158     brouard  7843:   printf(" Successful, please wait...");
1.126     brouard  7844:   while (z[0] != 'q') {
                   7845:     /* chdir(path); */
1.154     brouard  7846:     printf("\nType e to edit results with your browser, g to graph again and q for exit: ");
1.126     brouard  7847:     scanf("%s",z);
                   7848: /*     if (z[0] == 'c') system("./imach"); */
                   7849:     if (z[0] == 'e') {
1.158     brouard  7850: #ifdef __APPLE__
1.152     brouard  7851:       sprintf(pplotcmd, "open %s", optionfilehtm);
1.157     brouard  7852: #elif __linux
                   7853:       sprintf(pplotcmd, "xdg-open %s", optionfilehtm);
1.153     brouard  7854: #else
1.152     brouard  7855:       sprintf(pplotcmd, "%s", optionfilehtm);
1.153     brouard  7856: #endif
                   7857:       printf("Starting browser with: %s",pplotcmd);fflush(stdout);
                   7858:       system(pplotcmd);
1.126     brouard  7859:     }
                   7860:     else if (z[0] == 'g') system(plotcmd);
                   7861:     else if (z[0] == 'q') exit(0);
                   7862:   }
                   7863:   end:
                   7864:   while (z[0] != 'q') {
1.195     brouard  7865:     printf("\nType  q for exiting: "); fflush(stdout);
1.126     brouard  7866:     scanf("%s",z);
                   7867:   }
                   7868: }

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