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

1.195   ! brouard     1: /* $Id: imach.c,v 1.194 2015/08/18 13:32:00 brouard Exp $
1.126     brouard     2:   $State: Exp $
1.163     brouard     3:   $Log: imach.c,v $
1.195   ! brouard     4:   Revision 1.194  2015/08/18 13:32:00  brouard
        !             5:   Summary:  Adding error when the covariance matrix doesn't contain the exact number of lines required by the model line.
        !             6: 
1.194     brouard     7:   Revision 1.193  2015/08/04 07:17:42  brouard
                      8:   Summary: 0.98q4
                      9: 
1.193     brouard    10:   Revision 1.192  2015/07/16 16:49:02  brouard
                     11:   Summary: Fixing some outputs
                     12: 
1.192     brouard    13:   Revision 1.191  2015/07/14 10:00:33  brouard
                     14:   Summary: Some fixes
                     15: 
1.191     brouard    16:   Revision 1.190  2015/05/05 08:51:13  brouard
                     17:   Summary: Adding digits in output parameters (7 digits instead of 6)
                     18: 
                     19:   Fix 1+age+.
                     20: 
1.190     brouard    21:   Revision 1.189  2015/04/30 14:45:16  brouard
                     22:   Summary: 0.98q2
                     23: 
1.189     brouard    24:   Revision 1.188  2015/04/30 08:27:53  brouard
                     25:   *** empty log message ***
                     26: 
1.188     brouard    27:   Revision 1.187  2015/04/29 09:11:15  brouard
                     28:   *** empty log message ***
                     29: 
1.187     brouard    30:   Revision 1.186  2015/04/23 12:01:52  brouard
                     31:   Summary: V1*age is working now, version 0.98q1
                     32: 
                     33:   Some codes had been disabled in order to simplify and Vn*age was
                     34:   working in the optimization phase, ie, giving correct MLE parameters,
                     35:   but, as usual, outputs were not correct and program core dumped.
                     36: 
1.186     brouard    37:   Revision 1.185  2015/03/11 13:26:42  brouard
                     38:   Summary: Inclusion of compile and links command line for Intel Compiler
                     39: 
1.185     brouard    40:   Revision 1.184  2015/03/11 11:52:39  brouard
                     41:   Summary: Back from Windows 8. Intel Compiler
                     42: 
1.184     brouard    43:   Revision 1.183  2015/03/10 20:34:32  brouard
                     44:   Summary: 0.98q0, trying with directest, mnbrak fixed
                     45: 
                     46:   We use directest instead of original Powell test; probably no
                     47:   incidence on the results, but better justifications;
                     48:   We fixed Numerical Recipes mnbrak routine which was wrong and gave
                     49:   wrong results.
                     50: 
1.183     brouard    51:   Revision 1.182  2015/02/12 08:19:57  brouard
                     52:   Summary: Trying to keep directest which seems simpler and more general
                     53:   Author: Nicolas Brouard
                     54: 
1.182     brouard    55:   Revision 1.181  2015/02/11 23:22:24  brouard
                     56:   Summary: Comments on Powell added
                     57: 
                     58:   Author:
                     59: 
1.181     brouard    60:   Revision 1.180  2015/02/11 17:33:45  brouard
                     61:   Summary: Finishing move from main to function (hpijx and prevalence_limit)
                     62: 
1.180     brouard    63:   Revision 1.179  2015/01/04 09:57:06  brouard
                     64:   Summary: back to OS/X
                     65: 
1.179     brouard    66:   Revision 1.178  2015/01/04 09:35:48  brouard
                     67:   *** empty log message ***
                     68: 
1.178     brouard    69:   Revision 1.177  2015/01/03 18:40:56  brouard
                     70:   Summary: Still testing ilc32 on OSX
                     71: 
1.177     brouard    72:   Revision 1.176  2015/01/03 16:45:04  brouard
                     73:   *** empty log message ***
                     74: 
1.176     brouard    75:   Revision 1.175  2015/01/03 16:33:42  brouard
                     76:   *** empty log message ***
                     77: 
1.175     brouard    78:   Revision 1.174  2015/01/03 16:15:49  brouard
                     79:   Summary: Still in cross-compilation
                     80: 
1.174     brouard    81:   Revision 1.173  2015/01/03 12:06:26  brouard
                     82:   Summary: trying to detect cross-compilation
                     83: 
1.173     brouard    84:   Revision 1.172  2014/12/27 12:07:47  brouard
                     85:   Summary: Back from Visual Studio and Intel, options for compiling for Windows XP
                     86: 
1.172     brouard    87:   Revision 1.171  2014/12/23 13:26:59  brouard
                     88:   Summary: Back from Visual C
                     89: 
                     90:   Still problem with utsname.h on Windows
                     91: 
1.171     brouard    92:   Revision 1.170  2014/12/23 11:17:12  brouard
                     93:   Summary: Cleaning some \%% back to %%
                     94: 
                     95:   The escape was mandatory for a specific compiler (which one?), but too many warnings.
                     96: 
1.170     brouard    97:   Revision 1.169  2014/12/22 23:08:31  brouard
                     98:   Summary: 0.98p
                     99: 
                    100:   Outputs some informations on compiler used, OS etc. Testing on different platforms.
                    101: 
1.169     brouard   102:   Revision 1.168  2014/12/22 15:17:42  brouard
1.170     brouard   103:   Summary: update
1.169     brouard   104: 
1.168     brouard   105:   Revision 1.167  2014/12/22 13:50:56  brouard
                    106:   Summary: Testing uname and compiler version and if compiled 32 or 64
                    107: 
                    108:   Testing on Linux 64
                    109: 
1.167     brouard   110:   Revision 1.166  2014/12/22 11:40:47  brouard
                    111:   *** empty log message ***
                    112: 
1.166     brouard   113:   Revision 1.165  2014/12/16 11:20:36  brouard
                    114:   Summary: After compiling on Visual C
                    115: 
                    116:   * imach.c (Module): Merging 1.61 to 1.162
                    117: 
1.165     brouard   118:   Revision 1.164  2014/12/16 10:52:11  brouard
                    119:   Summary: Merging with Visual C after suppressing some warnings for unused variables. Also fixing Saito's bug 0.98Xn
                    120: 
                    121:   * imach.c (Module): Merging 1.61 to 1.162
                    122: 
1.164     brouard   123:   Revision 1.163  2014/12/16 10:30:11  brouard
                    124:   * imach.c (Module): Merging 1.61 to 1.162
                    125: 
1.163     brouard   126:   Revision 1.162  2014/09/25 11:43:39  brouard
                    127:   Summary: temporary backup 0.99!
                    128: 
1.162     brouard   129:   Revision 1.1  2014/09/16 11:06:58  brouard
                    130:   Summary: With some code (wrong) for nlopt
                    131: 
                    132:   Author:
                    133: 
                    134:   Revision 1.161  2014/09/15 20:41:41  brouard
                    135:   Summary: Problem with macro SQR on Intel compiler
                    136: 
1.161     brouard   137:   Revision 1.160  2014/09/02 09:24:05  brouard
                    138:   *** empty log message ***
                    139: 
1.160     brouard   140:   Revision 1.159  2014/09/01 10:34:10  brouard
                    141:   Summary: WIN32
                    142:   Author: Brouard
                    143: 
1.159     brouard   144:   Revision 1.158  2014/08/27 17:11:51  brouard
                    145:   *** empty log message ***
                    146: 
1.158     brouard   147:   Revision 1.157  2014/08/27 16:26:55  brouard
                    148:   Summary: Preparing windows Visual studio version
                    149:   Author: Brouard
                    150: 
                    151:   In order to compile on Visual studio, time.h is now correct and time_t
                    152:   and tm struct should be used. difftime should be used but sometimes I
                    153:   just make the differences in raw time format (time(&now).
                    154:   Trying to suppress #ifdef LINUX
                    155:   Add xdg-open for __linux in order to open default browser.
                    156: 
1.157     brouard   157:   Revision 1.156  2014/08/25 20:10:10  brouard
                    158:   *** empty log message ***
                    159: 
1.156     brouard   160:   Revision 1.155  2014/08/25 18:32:34  brouard
                    161:   Summary: New compile, minor changes
                    162:   Author: Brouard
                    163: 
1.155     brouard   164:   Revision 1.154  2014/06/20 17:32:08  brouard
                    165:   Summary: Outputs now all graphs of convergence to period prevalence
                    166: 
1.154     brouard   167:   Revision 1.153  2014/06/20 16:45:46  brouard
                    168:   Summary: If 3 live state, convergence to period prevalence on same graph
                    169:   Author: Brouard
                    170: 
1.153     brouard   171:   Revision 1.152  2014/06/18 17:54:09  brouard
                    172:   Summary: open browser, use gnuplot on same dir than imach if not found in the path
                    173: 
1.152     brouard   174:   Revision 1.151  2014/06/18 16:43:30  brouard
                    175:   *** empty log message ***
                    176: 
1.151     brouard   177:   Revision 1.150  2014/06/18 16:42:35  brouard
                    178:   Summary: If gnuplot is not in the path try on same directory than imach binary (OSX)
                    179:   Author: brouard
                    180: 
1.150     brouard   181:   Revision 1.149  2014/06/18 15:51:14  brouard
                    182:   Summary: Some fixes in parameter files errors
                    183:   Author: Nicolas Brouard
                    184: 
1.149     brouard   185:   Revision 1.148  2014/06/17 17:38:48  brouard
                    186:   Summary: Nothing new
                    187:   Author: Brouard
                    188: 
                    189:   Just a new packaging for OS/X version 0.98nS
                    190: 
1.148     brouard   191:   Revision 1.147  2014/06/16 10:33:11  brouard
                    192:   *** empty log message ***
                    193: 
1.147     brouard   194:   Revision 1.146  2014/06/16 10:20:28  brouard
                    195:   Summary: Merge
                    196:   Author: Brouard
                    197: 
                    198:   Merge, before building revised version.
                    199: 
1.146     brouard   200:   Revision 1.145  2014/06/10 21:23:15  brouard
                    201:   Summary: Debugging with valgrind
                    202:   Author: Nicolas Brouard
                    203: 
                    204:   Lot of changes in order to output the results with some covariates
                    205:   After the Edimburgh REVES conference 2014, it seems mandatory to
                    206:   improve the code.
                    207:   No more memory valgrind error but a lot has to be done in order to
                    208:   continue the work of splitting the code into subroutines.
                    209:   Also, decodemodel has been improved. Tricode is still not
                    210:   optimal. nbcode should be improved. Documentation has been added in
                    211:   the source code.
                    212: 
1.144     brouard   213:   Revision 1.143  2014/01/26 09:45:38  brouard
                    214:   Summary: Version 0.98nR (to be improved, but gives same optimization results as 0.98k. Nice, promising
                    215: 
                    216:   * imach.c (Module): Trying to merge old staffs together while being at Tokyo. Not tested...
                    217:   (Module): Version 0.98nR Running ok, but output format still only works for three covariates.
                    218: 
1.143     brouard   219:   Revision 1.142  2014/01/26 03:57:36  brouard
                    220:   Summary: gnuplot changed plot w l 1 has to be changed to plot w l lt 2
                    221: 
                    222:   * imach.c (Module): Trying to merge old staffs together while being at Tokyo. Not tested...
                    223: 
1.142     brouard   224:   Revision 1.141  2014/01/26 02:42:01  brouard
                    225:   * imach.c (Module): Trying to merge old staffs together while being at Tokyo. Not tested...
                    226: 
1.141     brouard   227:   Revision 1.140  2011/09/02 10:37:54  brouard
                    228:   Summary: times.h is ok with mingw32 now.
                    229: 
1.140     brouard   230:   Revision 1.139  2010/06/14 07:50:17  brouard
                    231:   After the theft of my laptop, I probably lost some lines of codes which were not uploaded to the CVS tree.
                    232:   I remember having already fixed agemin agemax which are pointers now but not cvs saved.
                    233: 
1.139     brouard   234:   Revision 1.138  2010/04/30 18:19:40  brouard
                    235:   *** empty log message ***
                    236: 
1.138     brouard   237:   Revision 1.137  2010/04/29 18:11:38  brouard
                    238:   (Module): Checking covariates for more complex models
                    239:   than V1+V2. A lot of change to be done. Unstable.
                    240: 
1.137     brouard   241:   Revision 1.136  2010/04/26 20:30:53  brouard
                    242:   (Module): merging some libgsl code. Fixing computation
                    243:   of likelione (using inter/intrapolation if mle = 0) in order to
                    244:   get same likelihood as if mle=1.
                    245:   Some cleaning of code and comments added.
                    246: 
1.136     brouard   247:   Revision 1.135  2009/10/29 15:33:14  brouard
                    248:   (Module): Now imach stops if date of birth, at least year of birth, is not given. Some cleaning of the code.
                    249: 
1.135     brouard   250:   Revision 1.134  2009/10/29 13:18:53  brouard
                    251:   (Module): Now imach stops if date of birth, at least year of birth, is not given. Some cleaning of the code.
                    252: 
1.134     brouard   253:   Revision 1.133  2009/07/06 10:21:25  brouard
                    254:   just nforces
                    255: 
1.133     brouard   256:   Revision 1.132  2009/07/06 08:22:05  brouard
                    257:   Many tings
                    258: 
1.132     brouard   259:   Revision 1.131  2009/06/20 16:22:47  brouard
                    260:   Some dimensions resccaled
                    261: 
1.131     brouard   262:   Revision 1.130  2009/05/26 06:44:34  brouard
                    263:   (Module): Max Covariate is now set to 20 instead of 8. A
                    264:   lot of cleaning with variables initialized to 0. Trying to make
                    265:   V2+V3*age+V1+V4 strb=V3*age+V1+V4 working better.
                    266: 
1.130     brouard   267:   Revision 1.129  2007/08/31 13:49:27  lievre
                    268:   Modification of the way of exiting when the covariate is not binary in order to see on the window the error message before exiting
                    269: 
1.129     lievre    270:   Revision 1.128  2006/06/30 13:02:05  brouard
                    271:   (Module): Clarifications on computing e.j
                    272: 
1.128     brouard   273:   Revision 1.127  2006/04/28 18:11:50  brouard
                    274:   (Module): Yes the sum of survivors was wrong since
                    275:   imach-114 because nhstepm was no more computed in the age
                    276:   loop. Now we define nhstepma in the age loop.
                    277:   (Module): In order to speed up (in case of numerous covariates) we
                    278:   compute health expectancies (without variances) in a first step
                    279:   and then all the health expectancies with variances or standard
                    280:   deviation (needs data from the Hessian matrices) which slows the
                    281:   computation.
                    282:   In the future we should be able to stop the program is only health
                    283:   expectancies and graph are needed without standard deviations.
                    284: 
1.127     brouard   285:   Revision 1.126  2006/04/28 17:23:28  brouard
                    286:   (Module): Yes the sum of survivors was wrong since
                    287:   imach-114 because nhstepm was no more computed in the age
                    288:   loop. Now we define nhstepma in the age loop.
                    289:   Version 0.98h
                    290: 
1.126     brouard   291:   Revision 1.125  2006/04/04 15:20:31  lievre
                    292:   Errors in calculation of health expectancies. Age was not initialized.
                    293:   Forecasting file added.
                    294: 
                    295:   Revision 1.124  2006/03/22 17:13:53  lievre
                    296:   Parameters are printed with %lf instead of %f (more numbers after the comma).
                    297:   The log-likelihood is printed in the log file
                    298: 
                    299:   Revision 1.123  2006/03/20 10:52:43  brouard
                    300:   * imach.c (Module): <title> changed, corresponds to .htm file
                    301:   name. <head> headers where missing.
                    302: 
                    303:   * imach.c (Module): Weights can have a decimal point as for
                    304:   English (a comma might work with a correct LC_NUMERIC environment,
                    305:   otherwise the weight is truncated).
                    306:   Modification of warning when the covariates values are not 0 or
                    307:   1.
                    308:   Version 0.98g
                    309: 
                    310:   Revision 1.122  2006/03/20 09:45:41  brouard
                    311:   (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.121  2006/03/16 17:45:01  lievre
                    319:   * imach.c (Module): Comments concerning covariates added
                    320: 
                    321:   * imach.c (Module): refinements in the computation of lli if
                    322:   status=-2 in order to have more reliable computation if stepm is
                    323:   not 1 month. Version 0.98f
                    324: 
                    325:   Revision 1.120  2006/03/16 15:10:38  lievre
                    326:   (Module): refinements in the computation of lli if
                    327:   status=-2 in order to have more reliable computation if stepm is
                    328:   not 1 month. Version 0.98f
                    329: 
                    330:   Revision 1.119  2006/03/15 17:42:26  brouard
                    331:   (Module): Bug if status = -2, the loglikelihood was
                    332:   computed as likelihood omitting the logarithm. Version O.98e
                    333: 
                    334:   Revision 1.118  2006/03/14 18:20:07  brouard
                    335:   (Module): varevsij Comments added explaining the second
                    336:   table of variances if popbased=1 .
                    337:   (Module): Covariances of eij, ekl added, graphs fixed, new html link.
                    338:   (Module): Function pstamp added
                    339:   (Module): Version 0.98d
                    340: 
                    341:   Revision 1.117  2006/03/14 17:16:22  brouard
                    342:   (Module): varevsij Comments added explaining the second
                    343:   table of variances if popbased=1 .
                    344:   (Module): Covariances of eij, ekl added, graphs fixed, new html link.
                    345:   (Module): Function pstamp added
                    346:   (Module): Version 0.98d
                    347: 
                    348:   Revision 1.116  2006/03/06 10:29:27  brouard
                    349:   (Module): Variance-covariance wrong links and
                    350:   varian-covariance of ej. is needed (Saito).
                    351: 
                    352:   Revision 1.115  2006/02/27 12:17:45  brouard
                    353:   (Module): One freematrix added in mlikeli! 0.98c
                    354: 
                    355:   Revision 1.114  2006/02/26 12:57:58  brouard
                    356:   (Module): Some improvements in processing parameter
                    357:   filename with strsep.
                    358: 
                    359:   Revision 1.113  2006/02/24 14:20:24  brouard
                    360:   (Module): Memory leaks checks with valgrind and:
                    361:   datafile was not closed, some imatrix were not freed and on matrix
                    362:   allocation too.
                    363: 
                    364:   Revision 1.112  2006/01/30 09:55:26  brouard
                    365:   (Module): Back to gnuplot.exe instead of wgnuplot.exe
                    366: 
                    367:   Revision 1.111  2006/01/25 20:38:18  brouard
                    368:   (Module): Lots of cleaning and bugs added (Gompertz)
                    369:   (Module): Comments can be added in data file. Missing date values
                    370:   can be a simple dot '.'.
                    371: 
                    372:   Revision 1.110  2006/01/25 00:51:50  brouard
                    373:   (Module): Lots of cleaning and bugs added (Gompertz)
                    374: 
                    375:   Revision 1.109  2006/01/24 19:37:15  brouard
                    376:   (Module): Comments (lines starting with a #) are allowed in data.
                    377: 
                    378:   Revision 1.108  2006/01/19 18:05:42  lievre
                    379:   Gnuplot problem appeared...
                    380:   To be fixed
                    381: 
                    382:   Revision 1.107  2006/01/19 16:20:37  brouard
                    383:   Test existence of gnuplot in imach path
                    384: 
                    385:   Revision 1.106  2006/01/19 13:24:36  brouard
                    386:   Some cleaning and links added in html output
                    387: 
                    388:   Revision 1.105  2006/01/05 20:23:19  lievre
                    389:   *** empty log message ***
                    390: 
                    391:   Revision 1.104  2005/09/30 16:11:43  lievre
                    392:   (Module): sump fixed, loop imx fixed, and simplifications.
                    393:   (Module): If the status is missing at the last wave but we know
                    394:   that the person is alive, then we can code his/her status as -2
                    395:   (instead of missing=-1 in earlier versions) and his/her
                    396:   contributions to the likelihood is 1 - Prob of dying from last
                    397:   health status (= 1-p13= p11+p12 in the easiest case of somebody in
                    398:   the healthy state at last known wave). Version is 0.98
                    399: 
                    400:   Revision 1.103  2005/09/30 15:54:49  lievre
                    401:   (Module): sump fixed, loop imx fixed, and simplifications.
                    402: 
                    403:   Revision 1.102  2004/09/15 17:31:30  brouard
                    404:   Add the possibility to read data file including tab characters.
                    405: 
                    406:   Revision 1.101  2004/09/15 10:38:38  brouard
                    407:   Fix on curr_time
                    408: 
                    409:   Revision 1.100  2004/07/12 18:29:06  brouard
                    410:   Add version for Mac OS X. Just define UNIX in Makefile
                    411: 
                    412:   Revision 1.99  2004/06/05 08:57:40  brouard
                    413:   *** empty log message ***
                    414: 
                    415:   Revision 1.98  2004/05/16 15:05:56  brouard
                    416:   New version 0.97 . First attempt to estimate force of mortality
                    417:   directly from the data i.e. without the need of knowing the health
                    418:   state at each age, but using a Gompertz model: log u =a + b*age .
                    419:   This is the basic analysis of mortality and should be done before any
                    420:   other analysis, in order to test if the mortality estimated from the
                    421:   cross-longitudinal survey is different from the mortality estimated
                    422:   from other sources like vital statistic data.
                    423: 
                    424:   The same imach parameter file can be used but the option for mle should be -3.
                    425: 
1.133     brouard   426:   Agnès, who wrote this part of the code, tried to keep most of the
1.126     brouard   427:   former routines in order to include the new code within the former code.
                    428: 
                    429:   The output is very simple: only an estimate of the intercept and of
                    430:   the slope with 95% confident intervals.
                    431: 
                    432:   Current limitations:
                    433:   A) Even if you enter covariates, i.e. with the
                    434:   model= V1+V2 equation for example, the programm does only estimate a unique global model without covariates.
                    435:   B) There is no computation of Life Expectancy nor Life Table.
                    436: 
                    437:   Revision 1.97  2004/02/20 13:25:42  lievre
                    438:   Version 0.96d. Population forecasting command line is (temporarily)
                    439:   suppressed.
                    440: 
                    441:   Revision 1.96  2003/07/15 15:38:55  brouard
                    442:   * imach.c (Repository): Errors in subdirf, 2, 3 while printing tmpout is
                    443:   rewritten within the same printf. Workaround: many printfs.
                    444: 
                    445:   Revision 1.95  2003/07/08 07:54:34  brouard
                    446:   * imach.c (Repository):
                    447:   (Repository): Using imachwizard code to output a more meaningful covariance
                    448:   matrix (cov(a12,c31) instead of numbers.
                    449: 
                    450:   Revision 1.94  2003/06/27 13:00:02  brouard
                    451:   Just cleaning
                    452: 
                    453:   Revision 1.93  2003/06/25 16:33:55  brouard
                    454:   (Module): On windows (cygwin) function asctime_r doesn't
                    455:   exist so I changed back to asctime which exists.
                    456:   (Module): Version 0.96b
                    457: 
                    458:   Revision 1.92  2003/06/25 16:30:45  brouard
                    459:   (Module): On windows (cygwin) function asctime_r doesn't
                    460:   exist so I changed back to asctime which exists.
                    461: 
                    462:   Revision 1.91  2003/06/25 15:30:29  brouard
                    463:   * imach.c (Repository): Duplicated warning errors corrected.
                    464:   (Repository): Elapsed time after each iteration is now output. It
                    465:   helps to forecast when convergence will be reached. Elapsed time
                    466:   is stamped in powell.  We created a new html file for the graphs
                    467:   concerning matrix of covariance. It has extension -cov.htm.
                    468: 
                    469:   Revision 1.90  2003/06/24 12:34:15  brouard
                    470:   (Module): Some bugs corrected for windows. Also, when
                    471:   mle=-1 a template is output in file "or"mypar.txt with the design
                    472:   of the covariance matrix to be input.
                    473: 
                    474:   Revision 1.89  2003/06/24 12:30:52  brouard
                    475:   (Module): Some bugs corrected for windows. Also, when
                    476:   mle=-1 a template is output in file "or"mypar.txt with the design
                    477:   of the covariance matrix to be input.
                    478: 
                    479:   Revision 1.88  2003/06/23 17:54:56  brouard
                    480:   * 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.
                    481: 
                    482:   Revision 1.87  2003/06/18 12:26:01  brouard
                    483:   Version 0.96
                    484: 
                    485:   Revision 1.86  2003/06/17 20:04:08  brouard
                    486:   (Module): Change position of html and gnuplot routines and added
                    487:   routine fileappend.
                    488: 
                    489:   Revision 1.85  2003/06/17 13:12:43  brouard
                    490:   * imach.c (Repository): Check when date of death was earlier that
                    491:   current date of interview. It may happen when the death was just
                    492:   prior to the death. In this case, dh was negative and likelihood
                    493:   was wrong (infinity). We still send an "Error" but patch by
                    494:   assuming that the date of death was just one stepm after the
                    495:   interview.
                    496:   (Repository): Because some people have very long ID (first column)
                    497:   we changed int to long in num[] and we added a new lvector for
                    498:   memory allocation. But we also truncated to 8 characters (left
                    499:   truncation)
                    500:   (Repository): No more line truncation errors.
                    501: 
                    502:   Revision 1.84  2003/06/13 21:44:43  brouard
                    503:   * imach.c (Repository): Replace "freqsummary" at a correct
                    504:   place. It differs from routine "prevalence" which may be called
                    505:   many times. Probs is memory consuming and must be used with
                    506:   parcimony.
                    507:   Version 0.95a3 (should output exactly the same maximization than 0.8a2)
                    508: 
                    509:   Revision 1.83  2003/06/10 13:39:11  lievre
                    510:   *** empty log message ***
                    511: 
                    512:   Revision 1.82  2003/06/05 15:57:20  brouard
                    513:   Add log in  imach.c and  fullversion number is now printed.
                    514: 
                    515: */
                    516: /*
                    517:    Interpolated Markov Chain
                    518: 
                    519:   Short summary of the programme:
                    520:   
                    521:   This program computes Healthy Life Expectancies from
                    522:   cross-longitudinal data. Cross-longitudinal data consist in: -1- a
                    523:   first survey ("cross") where individuals from different ages are
                    524:   interviewed on their health status or degree of disability (in the
                    525:   case of a health survey which is our main interest) -2- at least a
                    526:   second wave of interviews ("longitudinal") which measure each change
                    527:   (if any) in individual health status.  Health expectancies are
                    528:   computed from the time spent in each health state according to a
                    529:   model. More health states you consider, more time is necessary to reach the
                    530:   Maximum Likelihood of the parameters involved in the model.  The
                    531:   simplest model is the multinomial logistic model where pij is the
                    532:   probability to be observed in state j at the second wave
                    533:   conditional to be observed in state i at the first wave. Therefore
                    534:   the model is: log(pij/pii)= aij + bij*age+ cij*sex + etc , where
                    535:   'age' is age and 'sex' is a covariate. If you want to have a more
                    536:   complex model than "constant and age", you should modify the program
                    537:   where the markup *Covariates have to be included here again* invites
                    538:   you to do it.  More covariates you add, slower the
                    539:   convergence.
                    540: 
                    541:   The advantage of this computer programme, compared to a simple
                    542:   multinomial logistic model, is clear when the delay between waves is not
                    543:   identical for each individual. Also, if a individual missed an
                    544:   intermediate interview, the information is lost, but taken into
                    545:   account using an interpolation or extrapolation.  
                    546: 
                    547:   hPijx is the probability to be observed in state i at age x+h
                    548:   conditional to the observed state i at age x. The delay 'h' can be
                    549:   split into an exact number (nh*stepm) of unobserved intermediate
                    550:   states. This elementary transition (by month, quarter,
                    551:   semester or year) is modelled as a multinomial logistic.  The hPx
                    552:   matrix is simply the matrix product of nh*stepm elementary matrices
                    553:   and the contribution of each individual to the likelihood is simply
                    554:   hPijx.
                    555: 
                    556:   Also this programme outputs the covariance matrix of the parameters but also
                    557:   of the life expectancies. It also computes the period (stable) prevalence. 
                    558:   
1.133     brouard   559:   Authors: Nicolas Brouard (brouard@ined.fr) and Agnès Lièvre (lievre@ined.fr).
                    560:            Institut national d'études démographiques, Paris.
1.126     brouard   561:   This software have been partly granted by Euro-REVES, a concerted action
                    562:   from the European Union.
                    563:   It is copyrighted identically to a GNU software product, ie programme and
                    564:   software can be distributed freely for non commercial use. Latest version
                    565:   can be accessed at http://euroreves.ined.fr/imach .
                    566: 
                    567:   Help to debug: LD_PRELOAD=/usr/local/lib/libnjamd.so ./imach foo.imach
                    568:   or better on gdb : set env LD_PRELOAD=/usr/local/lib/libnjamd.so
                    569:   
                    570:   **********************************************************************/
                    571: /*
                    572:   main
                    573:   read parameterfile
                    574:   read datafile
                    575:   concatwav
                    576:   freqsummary
                    577:   if (mle >= 1)
                    578:     mlikeli
                    579:   print results files
                    580:   if mle==1 
                    581:      computes hessian
                    582:   read end of parameter file: agemin, agemax, bage, fage, estepm
                    583:       begin-prev-date,...
                    584:   open gnuplot file
                    585:   open html file
1.145     brouard   586:   period (stable) prevalence      | pl_nom    1-1 2-2 etc by covariate
                    587:    for age prevalim()             | #****** V1=0  V2=1  V3=1  V4=0 ******
                    588:                                   | 65 1 0 2 1 3 1 4 0  0.96326 0.03674
                    589:     freexexit2 possible for memory heap.
                    590: 
                    591:   h Pij x                         | pij_nom  ficrestpij
                    592:    # Cov Agex agex+h hpijx with i,j= 1-1 1-2     1-3     2-1     2-2     2-3
                    593:        1  85   85    1.00000             0.00000 0.00000 0.00000 1.00000 0.00000
                    594:        1  85   86    0.68299             0.22291 0.09410 0.71093 0.00000 0.28907
                    595: 
                    596:        1  65   99    0.00364             0.00322 0.99314 0.00350 0.00310 0.99340
                    597:        1  65  100    0.00214             0.00204 0.99581 0.00206 0.00196 0.99597
                    598:   variance of p one-step probabilities varprob  | prob_nom   ficresprob #One-step probabilities and stand. devi in ()
                    599:    Standard deviation of one-step probabilities | probcor_nom   ficresprobcor #One-step probabilities and correlation matrix
                    600:    Matrix of variance covariance of one-step probabilities |  probcov_nom ficresprobcov #One-step probabilities and covariance matrix
                    601: 
1.126     brouard   602:   forecasting if prevfcast==1 prevforecast call prevalence()
                    603:   health expectancies
                    604:   Variance-covariance of DFLE
                    605:   prevalence()
                    606:    movingaverage()
                    607:   varevsij() 
                    608:   if popbased==1 varevsij(,popbased)
                    609:   total life expectancies
                    610:   Variance of period (stable) prevalence
                    611:  end
                    612: */
                    613: 
1.187     brouard   614: /* #define DEBUG */
                    615: /* #define DEBUGBRENT */
1.165     brouard   616: #define POWELL /* Instead of NLOPT */
1.192     brouard   617: #define POWELLF1F3 /* Skip test */
1.186     brouard   618: /* #define POWELLORIGINAL /\* Don't use Directest to decide new direction but original Powell test *\/ */
                    619: /* #define MNBRAKORIGINAL /\* Don't use mnbrak fix *\/ */
1.126     brouard   620: 
                    621: #include <math.h>
                    622: #include <stdio.h>
                    623: #include <stdlib.h>
                    624: #include <string.h>
1.159     brouard   625: 
                    626: #ifdef _WIN32
                    627: #include <io.h>
1.172     brouard   628: #include <windows.h>
                    629: #include <tchar.h>
1.159     brouard   630: #else
1.126     brouard   631: #include <unistd.h>
1.159     brouard   632: #endif
1.126     brouard   633: 
                    634: #include <limits.h>
                    635: #include <sys/types.h>
1.171     brouard   636: 
                    637: #if defined(__GNUC__)
                    638: #include <sys/utsname.h> /* Doesn't work on Windows */
                    639: #endif
                    640: 
1.126     brouard   641: #include <sys/stat.h>
                    642: #include <errno.h>
1.159     brouard   643: /* extern int errno; */
1.126     brouard   644: 
1.157     brouard   645: /* #ifdef LINUX */
                    646: /* #include <time.h> */
                    647: /* #include "timeval.h" */
                    648: /* #else */
                    649: /* #include <sys/time.h> */
                    650: /* #endif */
                    651: 
1.126     brouard   652: #include <time.h>
                    653: 
1.136     brouard   654: #ifdef GSL
                    655: #include <gsl/gsl_errno.h>
                    656: #include <gsl/gsl_multimin.h>
                    657: #endif
                    658: 
1.167     brouard   659: 
1.162     brouard   660: #ifdef NLOPT
                    661: #include <nlopt.h>
                    662: typedef struct {
                    663:   double (* function)(double [] );
                    664: } myfunc_data ;
                    665: #endif
                    666: 
1.126     brouard   667: /* #include <libintl.h> */
                    668: /* #define _(String) gettext (String) */
                    669: 
1.141     brouard   670: #define MAXLINE 1024 /* Was 256. Overflow with 312 with 2 states and 4 covariates. Should be ok */
1.126     brouard   671: 
                    672: #define GNUPLOTPROGRAM "gnuplot"
                    673: /*#define GNUPLOTPROGRAM "..\\gp37mgw\\wgnuplot"*/
                    674: #define FILENAMELENGTH 132
                    675: 
                    676: #define        GLOCK_ERROR_NOPATH              -1      /* empty path */
                    677: #define        GLOCK_ERROR_GETCWD              -2      /* cannot get cwd */
                    678: 
1.144     brouard   679: #define MAXPARM 128 /**< Maximum number of parameters for the optimization */
                    680: #define NPARMAX 64 /**< (nlstate+ndeath-1)*nlstate*ncovmodel */
1.126     brouard   681: 
                    682: #define NINTERVMAX 8
1.144     brouard   683: #define NLSTATEMAX 8 /**< Maximum number of live states (for func) */
                    684: #define NDEATHMAX 8 /**< Maximum number of dead states (for func) */
                    685: #define NCOVMAX 20 /**< Maximum number of covariates, including generated covariates V1*V2 */
1.145     brouard   686: #define codtabm(h,k)  1 & (h-1) >> (k-1) ;
1.126     brouard   687: #define MAXN 20000
1.144     brouard   688: #define YEARM 12. /**< Number of months per year */
1.126     brouard   689: #define AGESUP 130
                    690: #define AGEBASE 40
1.194     brouard   691: #define AGEOVERFLOW 1.e20
1.164     brouard   692: #define AGEGOMP 10 /**< Minimal age for Gompertz adjustment */
1.157     brouard   693: #ifdef _WIN32
                    694: #define DIRSEPARATOR '\\'
                    695: #define CHARSEPARATOR "\\"
                    696: #define ODIRSEPARATOR '/'
                    697: #else
1.126     brouard   698: #define DIRSEPARATOR '/'
                    699: #define CHARSEPARATOR "/"
                    700: #define ODIRSEPARATOR '\\'
                    701: #endif
                    702: 
1.195   ! brouard   703: /* $Id: imach.c,v 1.194 2015/08/18 13:32:00 brouard Exp $ */
1.126     brouard   704: /* $State: Exp $ */
                    705: 
1.194     brouard   706: char version[]="Imach version 0.98q5, August 2015,INED-EUROREVES-Institut de longevite-Japan Society for the Promotion of Science (Grant-in-Aid for Scientific Research 25293121), Intel Software 2015";
1.195   ! brouard   707: char fullversion[]="$Revision: 1.194 $ $Date: 2015/08/18 13:32:00 $"; 
1.126     brouard   708: char strstart[80];
                    709: char optionfilext[10], optionfilefiname[FILENAMELENGTH];
1.130     brouard   710: int erreur=0, nberr=0, nbwarn=0; /* Error number, number of errors number of warnings  */
1.187     brouard   711: int nagesqr=0, nforce=0; /* nagesqr=1 if model is including age*age, number of forces */
1.145     brouard   712: /* Number of covariates model=V2+V1+ V3*age+V2*V4 */
                    713: int cptcovn=0; /**< cptcovn number of covariates added in the model (excepting constant and age and age*product) */
                    714: int cptcovt=0; /**< cptcovt number of covariates added in the model (excepting constant and age) */
                    715: int cptcovs=0; /**< cptcovs number of simple covariates V2+V1 =2 */
                    716: int cptcovage=0; /**< Number of covariates with age: V3*age only =1 */
                    717: int cptcovprodnoage=0; /**< Number of covariate products without age */   
                    718: int cptcoveff=0; /* Total number of covariates to vary for printing results */
                    719: int cptcov=0; /* Working variable */
1.126     brouard   720: int npar=NPARMAX;
                    721: int nlstate=2; /* Number of live states */
                    722: int ndeath=1; /* Number of dead states */
1.130     brouard   723: int ncovmodel=0, ncovcol=0;     /* Total number of covariables including constant a12*1 +b12*x ncovmodel=2 */
1.126     brouard   724: int popbased=0;
                    725: 
                    726: int *wav; /* Number of waves for this individuual 0 is possible */
1.130     brouard   727: int maxwav=0; /* Maxim number of waves */
                    728: int jmin=0, jmax=0; /* min, max spacing between 2 waves */
                    729: int ijmin=0, ijmax=0; /* Individuals having jmin and jmax */ 
                    730: int gipmx=0, gsw=0; /* Global variables on the number of contributions 
1.126     brouard   731:                   to the likelihood and the sum of weights (done by funcone)*/
1.130     brouard   732: int mle=1, weightopt=0;
1.126     brouard   733: int **mw; /* mw[mi][i] is number of the mi wave for this individual */
                    734: int **dh; /* dh[mi][i] is number of steps between mi,mi+1 for this individual */
                    735: int **bh; /* bh[mi][i] is the bias (+ or -) for this individual if the delay between
                    736:           * wave mi and wave mi+1 is not an exact multiple of stepm. */
1.162     brouard   737: int countcallfunc=0;  /* Count the number of calls to func */
1.130     brouard   738: double jmean=1; /* Mean space between 2 waves */
1.145     brouard   739: double **matprod2(); /* test */
1.126     brouard   740: double **oldm, **newm, **savm; /* Working pointers to matrices */
                    741: double **oldms, **newms, **savms; /* Fixed working pointers to matrices */
1.136     brouard   742: /*FILE *fic ; */ /* Used in readdata only */
                    743: FILE *ficpar, *ficparo,*ficres, *ficresp, *ficrespl, *ficrespij, *ficrest,*ficresf,*ficrespop;
1.126     brouard   744: FILE *ficlog, *ficrespow;
1.130     brouard   745: int globpr=0; /* Global variable for printing or not */
1.126     brouard   746: double fretone; /* Only one call to likelihood */
1.130     brouard   747: long ipmx=0; /* Number of contributions */
1.126     brouard   748: double sw; /* Sum of weights */
                    749: char filerespow[FILENAMELENGTH];
                    750: char fileresilk[FILENAMELENGTH]; /* File of individual contributions to the likelihood */
                    751: FILE *ficresilk;
                    752: FILE *ficgp,*ficresprob,*ficpop, *ficresprobcov, *ficresprobcor;
                    753: FILE *ficresprobmorprev;
                    754: FILE *fichtm, *fichtmcov; /* Html File */
                    755: FILE *ficreseij;
                    756: char filerese[FILENAMELENGTH];
                    757: FILE *ficresstdeij;
                    758: char fileresstde[FILENAMELENGTH];
                    759: FILE *ficrescveij;
                    760: char filerescve[FILENAMELENGTH];
                    761: FILE  *ficresvij;
                    762: char fileresv[FILENAMELENGTH];
                    763: FILE  *ficresvpl;
                    764: char fileresvpl[FILENAMELENGTH];
                    765: char title[MAXLINE];
                    766: char optionfile[FILENAMELENGTH], datafile[FILENAMELENGTH],  filerespl[FILENAMELENGTH];
                    767: char plotcmd[FILENAMELENGTH], pplotcmd[FILENAMELENGTH];
                    768: char tmpout[FILENAMELENGTH],  tmpout2[FILENAMELENGTH]; 
                    769: char command[FILENAMELENGTH];
                    770: int  outcmd=0;
                    771: 
                    772: char fileres[FILENAMELENGTH], filerespij[FILENAMELENGTH], filereso[FILENAMELENGTH], rfileres[FILENAMELENGTH];
                    773: 
                    774: char filelog[FILENAMELENGTH]; /* Log file */
                    775: char filerest[FILENAMELENGTH];
                    776: char fileregp[FILENAMELENGTH];
                    777: char popfile[FILENAMELENGTH];
                    778: 
                    779: char optionfilegnuplot[FILENAMELENGTH], optionfilehtm[FILENAMELENGTH], optionfilehtmcov[FILENAMELENGTH] ;
                    780: 
1.157     brouard   781: /* struct timeval start_time, end_time, curr_time, last_time, forecast_time; */
                    782: /* struct timezone tzp; */
                    783: /* extern int gettimeofday(); */
                    784: struct tm tml, *gmtime(), *localtime();
                    785: 
                    786: extern time_t time();
                    787: 
                    788: struct tm start_time, end_time, curr_time, last_time, forecast_time;
                    789: time_t  rstart_time, rend_time, rcurr_time, rlast_time, rforecast_time; /* raw time */
                    790: struct tm tm;
                    791: 
1.126     brouard   792: char strcurr[80], strfor[80];
                    793: 
                    794: char *endptr;
                    795: long lval;
                    796: double dval;
                    797: 
                    798: #define NR_END 1
                    799: #define FREE_ARG char*
                    800: #define FTOL 1.0e-10
                    801: 
                    802: #define NRANSI 
                    803: #define ITMAX 200 
                    804: 
                    805: #define TOL 2.0e-4 
                    806: 
                    807: #define CGOLD 0.3819660 
                    808: #define ZEPS 1.0e-10 
                    809: #define SHFT(a,b,c,d) (a)=(b);(b)=(c);(c)=(d); 
                    810: 
                    811: #define GOLD 1.618034 
                    812: #define GLIMIT 100.0 
                    813: #define TINY 1.0e-20 
                    814: 
                    815: static double maxarg1,maxarg2;
                    816: #define FMAX(a,b) (maxarg1=(a),maxarg2=(b),(maxarg1)>(maxarg2)? (maxarg1):(maxarg2))
                    817: #define FMIN(a,b) (maxarg1=(a),maxarg2=(b),(maxarg1)<(maxarg2)? (maxarg1):(maxarg2))
                    818:   
                    819: #define SIGN(a,b) ((b)>0.0 ? fabs(a) : -fabs(a))
                    820: #define rint(a) floor(a+0.5)
1.166     brouard   821: /* http://www.thphys.uni-heidelberg.de/~robbers/cmbeasy/doc/html/myutils_8h-source.html */
1.183     brouard   822: #define mytinydouble 1.0e-16
1.166     brouard   823: /* #define DEQUAL(a,b) (fabs((a)-(b))<mytinydouble) */
                    824: /* http://www.thphys.uni-heidelberg.de/~robbers/cmbeasy/doc/html/mynrutils_8h-source.html */
                    825: /* static double dsqrarg; */
                    826: /* #define DSQR(a) (DEQUAL((dsqrarg=(a)),0.0) ? 0.0 : dsqrarg*dsqrarg) */
1.126     brouard   827: static double sqrarg;
                    828: #define SQR(a) ((sqrarg=(a)) == 0.0 ? 0.0 :sqrarg*sqrarg)
                    829: #define SWAP(a,b) {temp=(a);(a)=(b);(b)=temp;} 
                    830: int agegomp= AGEGOMP;
                    831: 
                    832: int imx; 
                    833: int stepm=1;
                    834: /* Stepm, step in month: minimum step interpolation*/
                    835: 
                    836: int estepm;
                    837: /* Estepm, step in month to interpolate survival function in order to approximate Life Expectancy*/
                    838: 
                    839: int m,nb;
                    840: long *num;
1.192     brouard   841: int firstpass=0, lastpass=4,*cod, *Tage,*cens;
                    842: int *ncodemax;  /* ncodemax[j]= Number of modalities of the j th
                    843:                   covariate for which somebody answered excluding 
                    844:                   undefined. Usually 2: 0 and 1. */
                    845: int *ncodemaxwundef;  /* ncodemax[j]= Number of modalities of the j th
                    846:                             covariate for which somebody answered including 
                    847:                             undefined. Usually 3: -1, 0 and 1. */
1.126     brouard   848: double **agev,*moisnais, *annais, *moisdc, *andc,**mint, **anint;
                    849: double **pmmij, ***probs;
                    850: double *ageexmed,*agecens;
                    851: double dateintmean=0;
                    852: 
                    853: double *weight;
                    854: int **s; /* Status */
1.141     brouard   855: double *agedc;
1.145     brouard   856: double  **covar; /**< covar[j,i], value of jth covariate for individual i,
1.141     brouard   857:                  * covar=matrix(0,NCOVMAX,1,n); 
1.187     brouard   858:                  * cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*age; */
1.141     brouard   859: double  idx; 
                    860: int **nbcode, *Tvar; /**< model=V2 => Tvar[1]= 2 */
1.145     brouard   861: int *Ndum; /** Freq of modality (tricode */
1.141     brouard   862: int **codtab; /**< codtab=imatrix(1,100,1,10); */
                    863: int **Tvard, *Tprod, cptcovprod, *Tvaraff;
1.126     brouard   864: double *lsurv, *lpop, *tpop;
                    865: 
1.143     brouard   866: double ftol=FTOL; /**< Tolerance for computing Max Likelihood */
                    867: double ftolhess; /**< Tolerance for computing hessian */
1.126     brouard   868: 
                    869: /**************** split *************************/
                    870: static int split( char *path, char *dirc, char *name, char *ext, char *finame )
                    871: {
                    872:   /* From a file name with (full) path (either Unix or Windows) we extract the directory (dirc)
                    873:      the name of the file (name), its extension only (ext) and its first part of the name (finame)
                    874:   */ 
                    875:   char *ss;                            /* pointer */
1.186     brouard   876:   int  l1=0, l2=0;                             /* length counters */
1.126     brouard   877: 
                    878:   l1 = strlen(path );                  /* length of path */
                    879:   if ( l1 == 0 ) return( GLOCK_ERROR_NOPATH );
                    880:   ss= strrchr( path, DIRSEPARATOR );           /* find last / */
                    881:   if ( ss == NULL ) {                  /* no directory, so determine current directory */
                    882:     strcpy( name, path );              /* we got the fullname name because no directory */
                    883:     /*if(strrchr(path, ODIRSEPARATOR )==NULL)
                    884:       printf("Warning you should use %s as a separator\n",DIRSEPARATOR);*/
                    885:     /* get current working directory */
                    886:     /*    extern  char* getcwd ( char *buf , int len);*/
1.184     brouard   887: #ifdef WIN32
                    888:     if (_getcwd( dirc, FILENAME_MAX ) == NULL ) {
                    889: #else
                    890:        if (getcwd(dirc, FILENAME_MAX) == NULL) {
                    891: #endif
1.126     brouard   892:       return( GLOCK_ERROR_GETCWD );
                    893:     }
                    894:     /* got dirc from getcwd*/
                    895:     printf(" DIRC = %s \n",dirc);
                    896:   } else {                             /* strip direcotry from path */
                    897:     ss++;                              /* after this, the filename */
                    898:     l2 = strlen( ss );                 /* length of filename */
                    899:     if ( l2 == 0 ) return( GLOCK_ERROR_NOPATH );
                    900:     strcpy( name, ss );                /* save file name */
                    901:     strncpy( dirc, path, l1 - l2 );    /* now the directory */
1.186     brouard   902:     dirc[l1-l2] = '\0';                        /* add zero */
1.126     brouard   903:     printf(" DIRC2 = %s \n",dirc);
                    904:   }
                    905:   /* We add a separator at the end of dirc if not exists */
                    906:   l1 = strlen( dirc );                 /* length of directory */
                    907:   if( dirc[l1-1] != DIRSEPARATOR ){
                    908:     dirc[l1] =  DIRSEPARATOR;
                    909:     dirc[l1+1] = 0; 
                    910:     printf(" DIRC3 = %s \n",dirc);
                    911:   }
                    912:   ss = strrchr( name, '.' );           /* find last / */
                    913:   if (ss >0){
                    914:     ss++;
                    915:     strcpy(ext,ss);                    /* save extension */
                    916:     l1= strlen( name);
                    917:     l2= strlen(ss)+1;
                    918:     strncpy( finame, name, l1-l2);
                    919:     finame[l1-l2]= 0;
                    920:   }
                    921: 
                    922:   return( 0 );                         /* we're done */
                    923: }
                    924: 
                    925: 
                    926: /******************************************/
                    927: 
                    928: void replace_back_to_slash(char *s, char*t)
                    929: {
                    930:   int i;
                    931:   int lg=0;
                    932:   i=0;
                    933:   lg=strlen(t);
                    934:   for(i=0; i<= lg; i++) {
                    935:     (s[i] = t[i]);
                    936:     if (t[i]== '\\') s[i]='/';
                    937:   }
                    938: }
                    939: 
1.132     brouard   940: char *trimbb(char *out, char *in)
1.137     brouard   941: { /* Trim multiple blanks in line but keeps first blanks if line starts with blanks */
1.132     brouard   942:   char *s;
                    943:   s=out;
                    944:   while (*in != '\0'){
1.137     brouard   945:     while( *in == ' ' && *(in+1) == ' '){ /* && *(in+1) != '\0'){*/
1.132     brouard   946:       in++;
                    947:     }
                    948:     *out++ = *in++;
                    949:   }
                    950:   *out='\0';
                    951:   return s;
                    952: }
                    953: 
1.187     brouard   954: /* char *substrchaine(char *out, char *in, char *chain) */
                    955: /* { */
                    956: /*   /\* Substract chain 'chain' from 'in', return and output 'out' *\/ */
                    957: /*   char *s, *t; */
                    958: /*   t=in;s=out; */
                    959: /*   while ((*in != *chain) && (*in != '\0')){ */
                    960: /*     *out++ = *in++; */
                    961: /*   } */
                    962: 
                    963: /*   /\* *in matches *chain *\/ */
                    964: /*   while ((*in++ == *chain++) && (*in != '\0')){ */
                    965: /*     printf("*in = %c, *out= %c *chain= %c \n", *in, *out, *chain);  */
                    966: /*   } */
                    967: /*   in--; chain--; */
                    968: /*   while ( (*in != '\0')){ */
                    969: /*     printf("Bef *in = %c, *out= %c *chain= %c \n", *in, *out, *chain);  */
                    970: /*     *out++ = *in++; */
                    971: /*     printf("Aft *in = %c, *out= %c *chain= %c \n", *in, *out, *chain);  */
                    972: /*   } */
                    973: /*   *out='\0'; */
                    974: /*   out=s; */
                    975: /*   return out; */
                    976: /* } */
                    977: char *substrchaine(char *out, char *in, char *chain)
                    978: {
                    979:   /* Substract chain 'chain' from 'in', return and output 'out' */
                    980:   /* in="V1+V1*age+age*age+V2", chain="age*age" */
                    981: 
                    982:   char *strloc;
                    983: 
                    984:   strcpy (out, in); 
                    985:   strloc = strstr(out, chain); /* strloc points to out at age*age+V2 */
                    986:   printf("Bef strloc=%s chain=%s out=%s \n", strloc, chain, out);
                    987:   if(strloc != NULL){ 
                    988:     /* will affect out */ /* strloc+strlenc(chain)=+V2 */ /* Will also work in Unicode */
                    989:     memmove(strloc,strloc+strlen(chain), strlen(strloc+strlen(chain))+1);
                    990:     /* strcpy (strloc, strloc +strlen(chain));*/
                    991:   }
                    992:   printf("Aft strloc=%s chain=%s in=%s out=%s \n", strloc, chain, in, out);
                    993:   return out;
                    994: }
                    995: 
                    996: 
1.145     brouard   997: char *cutl(char *blocc, char *alocc, char *in, char occ)
                    998: {
1.187     brouard   999:   /* cuts string in into blocc and alocc where blocc ends before FIRST occurence of char 'occ' 
1.145     brouard  1000:      and alocc starts after first occurence of char 'occ' : ex cutv(blocc,alocc,"abcdef2ghi2j",'2')
1.187     brouard  1001:      gives blocc="abcdef" and alocc="ghi2j".
1.145     brouard  1002:      If occ is not found blocc is null and alocc is equal to in. Returns blocc
                   1003:   */
1.160     brouard  1004:   char *s, *t;
1.145     brouard  1005:   t=in;s=in;
                   1006:   while ((*in != occ) && (*in != '\0')){
                   1007:     *alocc++ = *in++;
                   1008:   }
                   1009:   if( *in == occ){
                   1010:     *(alocc)='\0';
                   1011:     s=++in;
                   1012:   }
                   1013:  
                   1014:   if (s == t) {/* occ not found */
                   1015:     *(alocc-(in-s))='\0';
                   1016:     in=s;
                   1017:   }
                   1018:   while ( *in != '\0'){
                   1019:     *blocc++ = *in++;
                   1020:   }
                   1021: 
                   1022:   *blocc='\0';
                   1023:   return t;
                   1024: }
1.137     brouard  1025: char *cutv(char *blocc, char *alocc, char *in, char occ)
                   1026: {
1.187     brouard  1027:   /* cuts string in into blocc and alocc where blocc ends before LAST occurence of char 'occ' 
1.137     brouard  1028:      and alocc starts after last occurence of char 'occ' : ex cutv(blocc,alocc,"abcdef2ghi2j",'2')
                   1029:      gives blocc="abcdef2ghi" and alocc="j".
                   1030:      If occ is not found blocc is null and alocc is equal to in. Returns alocc
                   1031:   */
                   1032:   char *s, *t;
                   1033:   t=in;s=in;
                   1034:   while (*in != '\0'){
                   1035:     while( *in == occ){
                   1036:       *blocc++ = *in++;
                   1037:       s=in;
                   1038:     }
                   1039:     *blocc++ = *in++;
                   1040:   }
                   1041:   if (s == t) /* occ not found */
                   1042:     *(blocc-(in-s))='\0';
                   1043:   else
                   1044:     *(blocc-(in-s)-1)='\0';
                   1045:   in=s;
                   1046:   while ( *in != '\0'){
                   1047:     *alocc++ = *in++;
                   1048:   }
                   1049: 
                   1050:   *alocc='\0';
                   1051:   return s;
                   1052: }
                   1053: 
1.126     brouard  1054: int nbocc(char *s, char occ)
                   1055: {
                   1056:   int i,j=0;
                   1057:   int lg=20;
                   1058:   i=0;
                   1059:   lg=strlen(s);
                   1060:   for(i=0; i<= lg; i++) {
                   1061:   if  (s[i] == occ ) j++;
                   1062:   }
                   1063:   return j;
                   1064: }
                   1065: 
1.137     brouard  1066: /* void cutv(char *u,char *v, char*t, char occ) */
                   1067: /* { */
                   1068: /*   /\* cuts string t into u and v where u ends before last occurence of char 'occ'  */
                   1069: /*      and v starts after last occurence of char 'occ' : ex cutv(u,v,"abcdef2ghi2j",'2') */
                   1070: /*      gives u="abcdef2ghi" and v="j" *\/ */
                   1071: /*   int i,lg,j,p=0; */
                   1072: /*   i=0; */
                   1073: /*   lg=strlen(t); */
                   1074: /*   for(j=0; j<=lg-1; j++) { */
                   1075: /*     if((t[j]!= occ) && (t[j+1]== occ)) p=j+1; */
                   1076: /*   } */
1.126     brouard  1077: 
1.137     brouard  1078: /*   for(j=0; j<p; j++) { */
                   1079: /*     (u[j] = t[j]); */
                   1080: /*   } */
                   1081: /*      u[p]='\0'; */
1.126     brouard  1082: 
1.137     brouard  1083: /*    for(j=0; j<= lg; j++) { */
                   1084: /*     if (j>=(p+1))(v[j-p-1] = t[j]); */
                   1085: /*   } */
                   1086: /* } */
1.126     brouard  1087: 
1.160     brouard  1088: #ifdef _WIN32
                   1089: char * strsep(char **pp, const char *delim)
                   1090: {
                   1091:   char *p, *q;
                   1092:          
                   1093:   if ((p = *pp) == NULL)
                   1094:     return 0;
                   1095:   if ((q = strpbrk (p, delim)) != NULL)
                   1096:   {
                   1097:     *pp = q + 1;
                   1098:     *q = '\0';
                   1099:   }
                   1100:   else
                   1101:     *pp = 0;
                   1102:   return p;
                   1103: }
                   1104: #endif
                   1105: 
1.126     brouard  1106: /********************** nrerror ********************/
                   1107: 
                   1108: void nrerror(char error_text[])
                   1109: {
                   1110:   fprintf(stderr,"ERREUR ...\n");
                   1111:   fprintf(stderr,"%s\n",error_text);
                   1112:   exit(EXIT_FAILURE);
                   1113: }
                   1114: /*********************** vector *******************/
                   1115: double *vector(int nl, int nh)
                   1116: {
                   1117:   double *v;
                   1118:   v=(double *) malloc((size_t)((nh-nl+1+NR_END)*sizeof(double)));
                   1119:   if (!v) nrerror("allocation failure in vector");
                   1120:   return v-nl+NR_END;
                   1121: }
                   1122: 
                   1123: /************************ free vector ******************/
                   1124: void free_vector(double*v, int nl, int nh)
                   1125: {
                   1126:   free((FREE_ARG)(v+nl-NR_END));
                   1127: }
                   1128: 
                   1129: /************************ivector *******************************/
                   1130: int *ivector(long nl,long nh)
                   1131: {
                   1132:   int *v;
                   1133:   v=(int *) malloc((size_t)((nh-nl+1+NR_END)*sizeof(int)));
                   1134:   if (!v) nrerror("allocation failure in ivector");
                   1135:   return v-nl+NR_END;
                   1136: }
                   1137: 
                   1138: /******************free ivector **************************/
                   1139: void free_ivector(int *v, long nl, long nh)
                   1140: {
                   1141:   free((FREE_ARG)(v+nl-NR_END));
                   1142: }
                   1143: 
                   1144: /************************lvector *******************************/
                   1145: long *lvector(long nl,long nh)
                   1146: {
                   1147:   long *v;
                   1148:   v=(long *) malloc((size_t)((nh-nl+1+NR_END)*sizeof(long)));
                   1149:   if (!v) nrerror("allocation failure in ivector");
                   1150:   return v-nl+NR_END;
                   1151: }
                   1152: 
                   1153: /******************free lvector **************************/
                   1154: void free_lvector(long *v, long nl, long nh)
                   1155: {
                   1156:   free((FREE_ARG)(v+nl-NR_END));
                   1157: }
                   1158: 
                   1159: /******************* imatrix *******************************/
                   1160: int **imatrix(long nrl, long nrh, long ncl, long nch) 
                   1161:      /* allocate a int matrix with subscript range m[nrl..nrh][ncl..nch] */ 
                   1162: { 
                   1163:   long i, nrow=nrh-nrl+1,ncol=nch-ncl+1; 
                   1164:   int **m; 
                   1165:   
                   1166:   /* allocate pointers to rows */ 
                   1167:   m=(int **) malloc((size_t)((nrow+NR_END)*sizeof(int*))); 
                   1168:   if (!m) nrerror("allocation failure 1 in matrix()"); 
                   1169:   m += NR_END; 
                   1170:   m -= nrl; 
                   1171:   
                   1172:   
                   1173:   /* allocate rows and set pointers to them */ 
                   1174:   m[nrl]=(int *) malloc((size_t)((nrow*ncol+NR_END)*sizeof(int))); 
                   1175:   if (!m[nrl]) nrerror("allocation failure 2 in matrix()"); 
                   1176:   m[nrl] += NR_END; 
                   1177:   m[nrl] -= ncl; 
                   1178:   
                   1179:   for(i=nrl+1;i<=nrh;i++) m[i]=m[i-1]+ncol; 
                   1180:   
                   1181:   /* return pointer to array of pointers to rows */ 
                   1182:   return m; 
                   1183: } 
                   1184: 
                   1185: /****************** free_imatrix *************************/
                   1186: void free_imatrix(m,nrl,nrh,ncl,nch)
                   1187:       int **m;
                   1188:       long nch,ncl,nrh,nrl; 
                   1189:      /* free an int matrix allocated by imatrix() */ 
                   1190: { 
                   1191:   free((FREE_ARG) (m[nrl]+ncl-NR_END)); 
                   1192:   free((FREE_ARG) (m+nrl-NR_END)); 
                   1193: } 
                   1194: 
                   1195: /******************* matrix *******************************/
                   1196: double **matrix(long nrl, long nrh, long ncl, long nch)
                   1197: {
                   1198:   long i, nrow=nrh-nrl+1, ncol=nch-ncl+1;
                   1199:   double **m;
                   1200: 
                   1201:   m=(double **) malloc((size_t)((nrow+NR_END)*sizeof(double*)));
                   1202:   if (!m) nrerror("allocation failure 1 in matrix()");
                   1203:   m += NR_END;
                   1204:   m -= nrl;
                   1205: 
                   1206:   m[nrl]=(double *) malloc((size_t)((nrow*ncol+NR_END)*sizeof(double)));
                   1207:   if (!m[nrl]) nrerror("allocation failure 2 in matrix()");
                   1208:   m[nrl] += NR_END;
                   1209:   m[nrl] -= ncl;
                   1210: 
                   1211:   for (i=nrl+1; i<=nrh; i++) m[i]=m[i-1]+ncol;
                   1212:   return m;
1.145     brouard  1213:   /* print *(*(m+1)+70) or print m[1][70]; print m+1 or print &(m[1]) or &(m[1][0])
                   1214: m[i] = address of ith row of the table. &(m[i]) is its value which is another adress
                   1215: that of m[i][0]. In order to get the value p m[i][0] but it is unitialized.
1.126     brouard  1216:    */
                   1217: }
                   1218: 
                   1219: /*************************free matrix ************************/
                   1220: void free_matrix(double **m, long nrl, long nrh, long ncl, long nch)
                   1221: {
                   1222:   free((FREE_ARG)(m[nrl]+ncl-NR_END));
                   1223:   free((FREE_ARG)(m+nrl-NR_END));
                   1224: }
                   1225: 
                   1226: /******************* ma3x *******************************/
                   1227: double ***ma3x(long nrl, long nrh, long ncl, long nch, long nll, long nlh)
                   1228: {
                   1229:   long i, j, nrow=nrh-nrl+1, ncol=nch-ncl+1, nlay=nlh-nll+1;
                   1230:   double ***m;
                   1231: 
                   1232:   m=(double ***) malloc((size_t)((nrow+NR_END)*sizeof(double*)));
                   1233:   if (!m) nrerror("allocation failure 1 in matrix()");
                   1234:   m += NR_END;
                   1235:   m -= nrl;
                   1236: 
                   1237:   m[nrl]=(double **) malloc((size_t)((nrow*ncol+NR_END)*sizeof(double)));
                   1238:   if (!m[nrl]) nrerror("allocation failure 2 in matrix()");
                   1239:   m[nrl] += NR_END;
                   1240:   m[nrl] -= ncl;
                   1241: 
                   1242:   for (i=nrl+1; i<=nrh; i++) m[i]=m[i-1]+ncol;
                   1243: 
                   1244:   m[nrl][ncl]=(double *) malloc((size_t)((nrow*ncol*nlay+NR_END)*sizeof(double)));
                   1245:   if (!m[nrl][ncl]) nrerror("allocation failure 3 in matrix()");
                   1246:   m[nrl][ncl] += NR_END;
                   1247:   m[nrl][ncl] -= nll;
                   1248:   for (j=ncl+1; j<=nch; j++) 
                   1249:     m[nrl][j]=m[nrl][j-1]+nlay;
                   1250:   
                   1251:   for (i=nrl+1; i<=nrh; i++) {
                   1252:     m[i][ncl]=m[i-1l][ncl]+ncol*nlay;
                   1253:     for (j=ncl+1; j<=nch; j++) 
                   1254:       m[i][j]=m[i][j-1]+nlay;
                   1255:   }
                   1256:   return m; 
                   1257:   /*  gdb: p *(m+1) <=> p m[1] and p (m+1) <=> p (m+1) <=> p &(m[1])
                   1258:            &(m[i][j][k]) <=> *((*(m+i) + j)+k)
                   1259:   */
                   1260: }
                   1261: 
                   1262: /*************************free ma3x ************************/
                   1263: void free_ma3x(double ***m, long nrl, long nrh, long ncl, long nch,long nll, long nlh)
                   1264: {
                   1265:   free((FREE_ARG)(m[nrl][ncl]+ nll-NR_END));
                   1266:   free((FREE_ARG)(m[nrl]+ncl-NR_END));
                   1267:   free((FREE_ARG)(m+nrl-NR_END));
                   1268: }
                   1269: 
                   1270: /*************** function subdirf ***********/
                   1271: char *subdirf(char fileres[])
                   1272: {
                   1273:   /* Caution optionfilefiname is hidden */
                   1274:   strcpy(tmpout,optionfilefiname);
                   1275:   strcat(tmpout,"/"); /* Add to the right */
                   1276:   strcat(tmpout,fileres);
                   1277:   return tmpout;
                   1278: }
                   1279: 
                   1280: /*************** function subdirf2 ***********/
                   1281: char *subdirf2(char fileres[], char *preop)
                   1282: {
                   1283:   
                   1284:   /* Caution optionfilefiname is hidden */
                   1285:   strcpy(tmpout,optionfilefiname);
                   1286:   strcat(tmpout,"/");
                   1287:   strcat(tmpout,preop);
                   1288:   strcat(tmpout,fileres);
                   1289:   return tmpout;
                   1290: }
                   1291: 
                   1292: /*************** function subdirf3 ***********/
                   1293: char *subdirf3(char fileres[], char *preop, char *preop2)
                   1294: {
                   1295:   
                   1296:   /* Caution optionfilefiname is hidden */
                   1297:   strcpy(tmpout,optionfilefiname);
                   1298:   strcat(tmpout,"/");
                   1299:   strcat(tmpout,preop);
                   1300:   strcat(tmpout,preop2);
                   1301:   strcat(tmpout,fileres);
                   1302:   return tmpout;
                   1303: }
                   1304: 
1.162     brouard  1305: char *asc_diff_time(long time_sec, char ascdiff[])
                   1306: {
                   1307:   long sec_left, days, hours, minutes;
                   1308:   days = (time_sec) / (60*60*24);
                   1309:   sec_left = (time_sec) % (60*60*24);
                   1310:   hours = (sec_left) / (60*60) ;
                   1311:   sec_left = (sec_left) %(60*60);
                   1312:   minutes = (sec_left) /60;
                   1313:   sec_left = (sec_left) % (60);
                   1314:   sprintf(ascdiff,"%ld day(s) %ld hour(s) %ld minute(s) %ld second(s)",days, hours, minutes, sec_left);  
                   1315:   return ascdiff;
                   1316: }
                   1317: 
1.126     brouard  1318: /***************** f1dim *************************/
                   1319: extern int ncom; 
                   1320: extern double *pcom,*xicom;
                   1321: extern double (*nrfunc)(double []); 
                   1322:  
                   1323: double f1dim(double x) 
                   1324: { 
                   1325:   int j; 
                   1326:   double f;
                   1327:   double *xt; 
                   1328:  
                   1329:   xt=vector(1,ncom); 
                   1330:   for (j=1;j<=ncom;j++) xt[j]=pcom[j]+x*xicom[j]; 
                   1331:   f=(*nrfunc)(xt); 
                   1332:   free_vector(xt,1,ncom); 
                   1333:   return f; 
                   1334: } 
                   1335: 
                   1336: /*****************brent *************************/
                   1337: double brent(double ax, double bx, double cx, double (*f)(double), double tol,         double *xmin) 
1.187     brouard  1338: {
                   1339:   /* Given a function f, and given a bracketing triplet of abscissas ax, bx, cx (such that bx is
                   1340:    * between ax and cx, and f(bx) is less than both f(ax) and f(cx) ), this routine isolates
                   1341:    * the minimum to a fractional precision of about tol using Brent’s method. The abscissa of
                   1342:    * the minimum is returned as xmin, and the minimum function value is returned as brent , the
                   1343:    * returned function value. 
                   1344:   */
1.126     brouard  1345:   int iter; 
                   1346:   double a,b,d,etemp;
1.159     brouard  1347:   double fu=0,fv,fw,fx;
1.164     brouard  1348:   double ftemp=0.;
1.126     brouard  1349:   double p,q,r,tol1,tol2,u,v,w,x,xm; 
                   1350:   double e=0.0; 
                   1351:  
                   1352:   a=(ax < cx ? ax : cx); 
                   1353:   b=(ax > cx ? ax : cx); 
                   1354:   x=w=v=bx; 
                   1355:   fw=fv=fx=(*f)(x); 
                   1356:   for (iter=1;iter<=ITMAX;iter++) { 
                   1357:     xm=0.5*(a+b); 
                   1358:     tol2=2.0*(tol1=tol*fabs(x)+ZEPS); 
                   1359:     /*         if (2.0*fabs(fp-(*fret)) <= ftol*(fabs(fp)+fabs(*fret)))*/
                   1360:     printf(".");fflush(stdout);
                   1361:     fprintf(ficlog,".");fflush(ficlog);
1.162     brouard  1362: #ifdef DEBUGBRENT
1.126     brouard  1363:     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);
                   1364:     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);
                   1365:     /*         if ((fabs(x-xm) <= (tol2-0.5*(b-a)))||(2.0*fabs(fu-ftemp) <= ftol*1.e-2*(fabs(fu)+fabs(ftemp)))) { */
                   1366: #endif
                   1367:     if (fabs(x-xm) <= (tol2-0.5*(b-a))){ 
                   1368:       *xmin=x; 
                   1369:       return fx; 
                   1370:     } 
                   1371:     ftemp=fu;
                   1372:     if (fabs(e) > tol1) { 
                   1373:       r=(x-w)*(fx-fv); 
                   1374:       q=(x-v)*(fx-fw); 
                   1375:       p=(x-v)*q-(x-w)*r; 
                   1376:       q=2.0*(q-r); 
                   1377:       if (q > 0.0) p = -p; 
                   1378:       q=fabs(q); 
                   1379:       etemp=e; 
                   1380:       e=d; 
                   1381:       if (fabs(p) >= fabs(0.5*q*etemp) || p <= q*(a-x) || p >= q*(b-x)) 
                   1382:        d=CGOLD*(e=(x >= xm ? a-x : b-x)); 
                   1383:       else { 
                   1384:        d=p/q; 
                   1385:        u=x+d; 
                   1386:        if (u-a < tol2 || b-u < tol2) 
                   1387:          d=SIGN(tol1,xm-x); 
                   1388:       } 
                   1389:     } else { 
                   1390:       d=CGOLD*(e=(x >= xm ? a-x : b-x)); 
                   1391:     } 
                   1392:     u=(fabs(d) >= tol1 ? x+d : x+SIGN(tol1,d)); 
                   1393:     fu=(*f)(u); 
                   1394:     if (fu <= fx) { 
                   1395:       if (u >= x) a=x; else b=x; 
                   1396:       SHFT(v,w,x,u) 
1.183     brouard  1397:       SHFT(fv,fw,fx,fu) 
                   1398:     } else { 
                   1399:       if (u < x) a=u; else b=u; 
                   1400:       if (fu <= fw || w == x) { 
                   1401:        v=w; 
                   1402:        w=u; 
                   1403:        fv=fw; 
                   1404:        fw=fu; 
                   1405:       } else if (fu <= fv || v == x || v == w) { 
                   1406:        v=u; 
                   1407:        fv=fu; 
                   1408:       } 
                   1409:     } 
1.126     brouard  1410:   } 
                   1411:   nrerror("Too many iterations in brent"); 
                   1412:   *xmin=x; 
                   1413:   return fx; 
                   1414: } 
                   1415: 
                   1416: /****************** mnbrak ***********************/
                   1417: 
                   1418: void mnbrak(double *ax, double *bx, double *cx, double *fa, double *fb, double *fc, 
                   1419:            double (*func)(double)) 
1.183     brouard  1420: { /* Given a function func , and given distinct initial points ax and bx , this routine searches in
                   1421: the downhill direction (defined by the function as evaluated at the initial points) and returns
                   1422: new points ax , bx , cx that bracket a minimum of the function. Also returned are the function
                   1423: values at the three points, fa, fb , and fc such that fa > fb and fb < fc.
                   1424:    */
1.126     brouard  1425:   double ulim,u,r,q, dum;
                   1426:   double fu; 
1.187     brouard  1427: 
                   1428:   double scale=10.;
                   1429:   int iterscale=0;
                   1430: 
                   1431:   *fa=(*func)(*ax); /*  xta[j]=pcom[j]+(*ax)*xicom[j]; fa=f(xta[j])*/
                   1432:   *fb=(*func)(*bx); /*  xtb[j]=pcom[j]+(*bx)*xicom[j]; fb=f(xtb[j]) */
                   1433: 
                   1434: 
                   1435:   /* while(*fb != *fb){ /\* *ax should be ok, reducing distance to *ax *\/ */
                   1436:   /*   printf("Warning mnbrak *fb = %lf, *bx=%lf *ax=%lf *fa==%lf iter=%d\n",*fb, *bx, *ax, *fa, iterscale++); */
                   1437:   /*   *bx = *ax - (*ax - *bx)/scale; */
                   1438:   /*   *fb=(*func)(*bx);  /\*  xtb[j]=pcom[j]+(*bx)*xicom[j]; fb=f(xtb[j]) *\/ */
                   1439:   /* } */
                   1440: 
1.126     brouard  1441:   if (*fb > *fa) { 
                   1442:     SHFT(dum,*ax,*bx,dum) 
1.183     brouard  1443:     SHFT(dum,*fb,*fa,dum) 
                   1444:   } 
1.126     brouard  1445:   *cx=(*bx)+GOLD*(*bx-*ax); 
                   1446:   *fc=(*func)(*cx); 
1.183     brouard  1447: #ifdef DEBUG
                   1448:   printf("mnbrak0 *fb=%.12e *fc=%.12e\n",*fb,*fc);
                   1449:   fprintf(ficlog,"mnbrak0 *fb=%.12e *fc=%.12e\n",*fb,*fc);
                   1450: #endif
                   1451:   while (*fb > *fc) { /* Declining a,b,c with fa> fb > fc */
1.126     brouard  1452:     r=(*bx-*ax)*(*fb-*fc); 
                   1453:     q=(*bx-*cx)*(*fb-*fa); 
                   1454:     u=(*bx)-((*bx-*cx)*q-(*bx-*ax)*r)/ 
1.183     brouard  1455:       (2.0*SIGN(FMAX(fabs(q-r),TINY),q-r)); /* Minimum abscissa of a parabolic estimated from (a,fa), (b,fb) and (c,fc). */
                   1456:     ulim=(*bx)+GLIMIT*(*cx-*bx); /* Maximum abscissa where function should be evaluated */
                   1457:     if ((*bx-u)*(u-*cx) > 0.0) { /* if u_p is between b and c */
1.126     brouard  1458:       fu=(*func)(u); 
1.163     brouard  1459: #ifdef DEBUG
                   1460:       /* f(x)=A(x-u)**2+f(u) */
                   1461:       double A, fparabu; 
                   1462:       A= (*fb - *fa)/(*bx-*ax)/(*bx+*ax-2*u);
                   1463:       fparabu= *fa - A*(*ax-u)*(*ax-u);
                   1464:       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);
                   1465:       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  1466:       /* And thus,it can be that fu > *fc even if fparabu < *fc */
                   1467:       /* mnbrak (*ax=7.666299858533, *fa=299039.693133272231), (*bx=8.595447774979, *fb=298976.598289369489),
                   1468:         (*cx=10.098840694817, *fc=298946.631474258087),  (*u=9.852501168332, fu=298948.773013752128, fparabu=298945.434711494134) */
                   1469:       /* In that case, there is no bracket in the output! Routine is wrong with many consequences.*/
1.163     brouard  1470: #endif 
1.184     brouard  1471: #ifdef MNBRAKORIGINAL
1.183     brouard  1472: #else
1.191     brouard  1473: /*       if (fu > *fc) { */
                   1474: /* #ifdef DEBUG */
                   1475: /*       printf("mnbrak4  fu > fc \n"); */
                   1476: /*       fprintf(ficlog, "mnbrak4 fu > fc\n"); */
                   1477: /* #endif */
                   1478: /*     /\* 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 *\\/  *\/ */
                   1479: /*     /\* SHFT(*fa,*fc,fu,*fc) /\\* (b, u, c) is a bracket while test fb > fc will be fu > fc  will exit *\\/ *\/ */
                   1480: /*     dum=u; /\* Shifting c and u *\/ */
                   1481: /*     u = *cx; */
                   1482: /*     *cx = dum; */
                   1483: /*     dum = fu; */
                   1484: /*     fu = *fc; */
                   1485: /*     *fc =dum; */
                   1486: /*       } else { /\* end *\/ */
                   1487: /* #ifdef DEBUG */
                   1488: /*       printf("mnbrak3  fu < fc \n"); */
                   1489: /*       fprintf(ficlog, "mnbrak3 fu < fc\n"); */
                   1490: /* #endif */
                   1491: /*     dum=u; /\* Shifting c and u *\/ */
                   1492: /*     u = *cx; */
                   1493: /*     *cx = dum; */
                   1494: /*     dum = fu; */
                   1495: /*     fu = *fc; */
                   1496: /*     *fc =dum; */
                   1497: /*       } */
1.183     brouard  1498: #ifdef DEBUG
1.191     brouard  1499:       printf("mnbrak34  fu < or >= fc \n");
                   1500:       fprintf(ficlog, "mnbrak34 fu < fc\n");
1.183     brouard  1501: #endif
1.191     brouard  1502:       dum=u; /* Shifting c and u */
                   1503:       u = *cx;
                   1504:       *cx = dum;
                   1505:       dum = fu;
                   1506:       fu = *fc;
                   1507:       *fc =dum;
1.183     brouard  1508: #endif
1.162     brouard  1509:     } else if ((*cx-u)*(u-ulim) > 0.0) { /* u is after c but before ulim */
1.183     brouard  1510: #ifdef DEBUG
                   1511:       printf("mnbrak2  u after c but before ulim\n");
                   1512:       fprintf(ficlog, "mnbrak2 u after c but before ulim\n");
                   1513: #endif
1.126     brouard  1514:       fu=(*func)(u); 
                   1515:       if (fu < *fc) { 
1.183     brouard  1516: #ifdef DEBUG
                   1517:       printf("mnbrak2  u after c but before ulim AND fu < fc\n");
                   1518:       fprintf(ficlog, "mnbrak2 u after c but before ulim AND fu <fc \n");
                   1519: #endif
1.126     brouard  1520:        SHFT(*bx,*cx,u,*cx+GOLD*(*cx-*bx)) 
1.183     brouard  1521:        SHFT(*fb,*fc,fu,(*func)(u)) 
                   1522:       } 
1.162     brouard  1523:     } else if ((u-ulim)*(ulim-*cx) >= 0.0) { /* u outside ulim (verifying that ulim is beyond c) */
1.183     brouard  1524: #ifdef DEBUG
                   1525:       printf("mnbrak2  u outside ulim (verifying that ulim is beyond c)\n");
                   1526:       fprintf(ficlog, "mnbrak2 u outside ulim (verifying that ulim is beyond c)\n");
                   1527: #endif
1.126     brouard  1528:       u=ulim; 
                   1529:       fu=(*func)(u); 
1.183     brouard  1530:     } else { /* u could be left to b (if r > q parabola has a maximum) */
                   1531: #ifdef DEBUG
                   1532:       printf("mnbrak2  u could be left to b (if r > q parabola has a maximum)\n");
                   1533:       fprintf(ficlog, "mnbrak2  u could be left to b (if r > q parabola has a maximum)\n");
                   1534: #endif
1.126     brouard  1535:       u=(*cx)+GOLD*(*cx-*bx); 
                   1536:       fu=(*func)(u); 
1.183     brouard  1537:     } /* end tests */
1.126     brouard  1538:     SHFT(*ax,*bx,*cx,u) 
1.183     brouard  1539:     SHFT(*fa,*fb,*fc,fu) 
                   1540: #ifdef DEBUG
                   1541:       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);
                   1542:       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);
                   1543: #endif
                   1544:   } /* 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  1545: } 
                   1546: 
                   1547: /*************** linmin ************************/
1.162     brouard  1548: /* Given an n -dimensional point p[1..n] and an n -dimensional direction xi[1..n] , moves and
                   1549: resets p to where the function func(p) takes on a minimum along the direction xi from p ,
                   1550: and replaces xi by the actual vector displacement that p was moved. Also returns as fret
                   1551: the value of func at the returned location p . This is actually all accomplished by calling the
                   1552: routines mnbrak and brent .*/
1.126     brouard  1553: int ncom; 
                   1554: double *pcom,*xicom;
                   1555: double (*nrfunc)(double []); 
                   1556:  
                   1557: void linmin(double p[], double xi[], int n, double *fret,double (*func)(double [])) 
                   1558: { 
                   1559:   double brent(double ax, double bx, double cx, 
                   1560:               double (*f)(double), double tol, double *xmin); 
                   1561:   double f1dim(double x); 
                   1562:   void mnbrak(double *ax, double *bx, double *cx, double *fa, double *fb, 
                   1563:              double *fc, double (*func)(double)); 
                   1564:   int j; 
                   1565:   double xx,xmin,bx,ax; 
                   1566:   double fx,fb,fa;
1.187     brouard  1567: 
                   1568:   double scale=10., axs, xxs, xxss; /* Scale added for infinity */
1.126     brouard  1569:  
                   1570:   ncom=n; 
                   1571:   pcom=vector(1,n); 
                   1572:   xicom=vector(1,n); 
                   1573:   nrfunc=func; 
                   1574:   for (j=1;j<=n;j++) { 
                   1575:     pcom[j]=p[j]; 
                   1576:     xicom[j]=xi[j]; 
                   1577:   } 
1.187     brouard  1578: 
1.192     brouard  1579:   /* axs=0.0; */
                   1580:   /* xxss=1; /\* 1 and using scale *\/ */
1.187     brouard  1581:   xxs=1;
1.192     brouard  1582:   /* do{ */
1.187     brouard  1583:     ax=0.;
                   1584:     xx= xxs;
                   1585:     mnbrak(&ax,&xx,&bx,&fa,&fx,&fb,f1dim);  /* Outputs: xtx[j]=pcom[j]+(*xx)*xicom[j]; fx=f(xtx[j]) */
                   1586:     /* brackets with inputs ax=0 and xx=1, but points, pcom=p, and directions values, xicom=xi, are sent via f1dim(x) */
                   1587:     /* 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))   */
                   1588:     /* Outputs: fa=f(p(j)) and fx=f(p(j) + xxs * xi(j) ) and f(bx)= f(p(j)+ bx* xi(j)) */
                   1589:     /* Given input ax=axs and xx=xxs, xx might be too far from ax to get a finite f(xx) */
                   1590:     /* Searches on line, outputs (ax, xx, bx) such that fx < min(fa and fb) */
                   1591:     /* 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  1592:   /*   if (fx != fx){ */
                   1593:   /*   xxs=xxs/scale; /\* Trying a smaller xx, closer to initial ax=0 *\/ */
                   1594:   /*   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); */
                   1595:   /*   } */
                   1596:   /* }while(fx != fx); */
1.187     brouard  1597: 
1.191     brouard  1598: #ifdef DEBUGLINMIN
                   1599:   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);
                   1600: #endif
1.187     brouard  1601:   *fret=brent(ax,xx,bx,f1dim,TOL,&xmin); /* Giving a bracketting triplet (ax, xx, bx), find a minimum, xmin, according to f1dim, *fret(xmin),*/
                   1602:   /* fa = f(p[j] + ax * xi[j]), fx = f(p[j] + xx * xi[j]), fb = f(p[j] + bx * xi[j]) */
                   1603:   /* fmin = f(p[j] + xmin * xi[j]) */
                   1604:   /* P+lambda n in that direction (lambdamin), with TOL between abscisses */
                   1605:   /* f1dim(xmin): for (j=1;j<=ncom;j++) xt[j]=pcom[j]+xmin*xicom[j]; */
1.126     brouard  1606: #ifdef DEBUG
                   1607:   printf("retour brent fret=%.12e xmin=%.12e\n",*fret,xmin);
                   1608:   fprintf(ficlog,"retour brent fret=%.12e xmin=%.12e\n",*fret,xmin);
                   1609: #endif
1.191     brouard  1610: #ifdef DEBUGLINMIN
                   1611:   printf("linmin end ");
                   1612: #endif
1.126     brouard  1613:   for (j=1;j<=n;j++) { 
1.188     brouard  1614:     /* printf(" before xi[%d]=%12.8f", j,xi[j]); */
1.187     brouard  1615:     xi[j] *= xmin; /* xi rescaled by xmin: if xmin=-1.237 and xi=(1,0,...,0) xi=(-1.237,0,...,0) */
1.189     brouard  1616:     /* if(xxs <1.0) */
                   1617:     /*   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  1618:     p[j] += xi[j]; /* Parameters values are updated accordingly */
1.126     brouard  1619:   } 
1.189     brouard  1620:   /* printf("\n"); */
1.191     brouard  1621: #ifdef DEBUGLINMIN
                   1622:   printf("Comparing last *frec(xmin=%12.8f)=%12.8f from Brent and frec(0.)=%12.8f \n", xmin, *fret, (*func)(p));
                   1623:   for (j=1;j<=n;j++) { 
                   1624:     printf(" xi[%d]= %12.7f p[%d]= %12.7f",j,xi[j],j,p[j]);
                   1625:     if(j % ncovmodel == 0)
                   1626:       printf("\n");
                   1627:   }
                   1628: #endif
1.126     brouard  1629:   free_vector(xicom,1,n); 
                   1630:   free_vector(pcom,1,n); 
                   1631: } 
                   1632: 
                   1633: 
                   1634: /*************** powell ************************/
1.162     brouard  1635: /*
                   1636: Minimization of a function func of n variables. Input consists of an initial starting point
                   1637: p[1..n] ; an initial matrix xi[1..n][1..n] , whose columns contain the initial set of di-
                   1638: rections (usually the n unit vectors); and ftol , the fractional tolerance in the function value
                   1639: such that failure to decrease by more than this amount on one iteration signals doneness. On
                   1640: output, p is set to the best point found, xi is the then-current direction set, fret is the returned
                   1641: function value at p , and iter is the number of iterations taken. The routine linmin is used.
                   1642:  */
1.126     brouard  1643: void powell(double p[], double **xi, int n, double ftol, int *iter, double *fret, 
                   1644:            double (*func)(double [])) 
                   1645: { 
                   1646:   void linmin(double p[], double xi[], int n, double *fret, 
                   1647:              double (*func)(double [])); 
                   1648:   int i,ibig,j; 
                   1649:   double del,t,*pt,*ptt,*xit;
1.181     brouard  1650:   double directest;
1.126     brouard  1651:   double fp,fptt;
                   1652:   double *xits;
                   1653:   int niterf, itmp;
                   1654: 
                   1655:   pt=vector(1,n); 
                   1656:   ptt=vector(1,n); 
                   1657:   xit=vector(1,n); 
                   1658:   xits=vector(1,n); 
                   1659:   *fret=(*func)(p); 
                   1660:   for (j=1;j<=n;j++) pt[j]=p[j]; 
1.157     brouard  1661:     rcurr_time = time(NULL);  
1.126     brouard  1662:   for (*iter=1;;++(*iter)) { 
1.187     brouard  1663:     fp=(*fret); /* From former iteration or initial value */
1.126     brouard  1664:     ibig=0; 
                   1665:     del=0.0; 
1.157     brouard  1666:     rlast_time=rcurr_time;
                   1667:     /* (void) gettimeofday(&curr_time,&tzp); */
                   1668:     rcurr_time = time(NULL);  
                   1669:     curr_time = *localtime(&rcurr_time);
                   1670:     printf("\nPowell iter=%d -2*LL=%.12f %ld sec. %ld sec.",*iter,*fret, rcurr_time-rlast_time, rcurr_time-rstart_time);fflush(stdout);
                   1671:     fprintf(ficlog,"\nPowell iter=%d -2*LL=%.12f %ld sec. %ld sec.",*iter,*fret,rcurr_time-rlast_time, rcurr_time-rstart_time); fflush(ficlog);
                   1672: /*     fprintf(ficrespow,"%d %.12f %ld",*iter,*fret,curr_time.tm_sec-start_time.tm_sec); */
1.192     brouard  1673:     for (i=1;i<=n;i++) {
1.126     brouard  1674:       printf(" %d %.12f",i, p[i]);
                   1675:       fprintf(ficlog," %d %.12lf",i, p[i]);
                   1676:       fprintf(ficrespow," %.12lf", p[i]);
                   1677:     }
                   1678:     printf("\n");
                   1679:     fprintf(ficlog,"\n");
                   1680:     fprintf(ficrespow,"\n");fflush(ficrespow);
                   1681:     if(*iter <=3){
1.157     brouard  1682:       tml = *localtime(&rcurr_time);
                   1683:       strcpy(strcurr,asctime(&tml));
                   1684:       rforecast_time=rcurr_time; 
1.126     brouard  1685:       itmp = strlen(strcurr);
                   1686:       if(strcurr[itmp-1]=='\n')  /* Windows outputs with a new line */
                   1687:        strcurr[itmp-1]='\0';
1.162     brouard  1688:       printf("\nConsidering the time needed for the last iteration #%d: %ld seconds,\n",*iter,rcurr_time-rlast_time);
1.157     brouard  1689:       fprintf(ficlog,"\nConsidering the time needed for this last iteration #%d: %ld seconds,\n",*iter,rcurr_time-rlast_time);
1.126     brouard  1690:       for(niterf=10;niterf<=30;niterf+=10){
1.157     brouard  1691:        rforecast_time=rcurr_time+(niterf-*iter)*(rcurr_time-rlast_time);
                   1692:        forecast_time = *localtime(&rforecast_time);
                   1693:        strcpy(strfor,asctime(&forecast_time));
1.126     brouard  1694:        itmp = strlen(strfor);
                   1695:        if(strfor[itmp-1]=='\n')
                   1696:        strfor[itmp-1]='\0';
1.157     brouard  1697:        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);
                   1698:        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  1699:       }
                   1700:     }
1.187     brouard  1701:     for (i=1;i<=n;i++) { /* For each direction i */
                   1702:       for (j=1;j<=n;j++) xit[j]=xi[j][i]; /* Directions stored from previous iteration with previous scales */
1.126     brouard  1703:       fptt=(*fret); 
                   1704: #ifdef DEBUG
1.164     brouard  1705:          printf("fret=%lf, %lf, %lf \n", *fret, *fret, *fret);
                   1706:          fprintf(ficlog, "fret=%lf, %lf, %lf \n", *fret, *fret, *fret);
1.126     brouard  1707: #endif
1.187     brouard  1708:          printf("%d",i);fflush(stdout); /* print direction (parameter) i */
1.126     brouard  1709:       fprintf(ficlog,"%d",i);fflush(ficlog);
1.188     brouard  1710:       linmin(p,xit,n,fret,func); /* Point p[n]. xit[n] has been loaded for direction i as input.*/
                   1711:                                    /* Outputs are fret(new point p) p is updated and xit rescaled */
                   1712:       if (fabs(fptt-(*fret)) > del) { /* We are keeping the max gain on each of the n directions */
                   1713:        /* because that direction will be replaced unless the gain del is small */
                   1714:        /* in comparison with the 'probable' gain, mu^2, with the last average direction. */
                   1715:        /* Unless the n directions are conjugate some gain in the determinant may be obtained */
                   1716:        /* with the new direction. */
1.126     brouard  1717:        del=fabs(fptt-(*fret)); 
                   1718:        ibig=i; 
                   1719:       } 
                   1720: #ifdef DEBUG
                   1721:       printf("%d %.12e",i,(*fret));
                   1722:       fprintf(ficlog,"%d %.12e",i,(*fret));
                   1723:       for (j=1;j<=n;j++) {
                   1724:        xits[j]=FMAX(fabs(p[j]-pt[j]),1.e-5);
                   1725:        printf(" x(%d)=%.12e",j,xit[j]);
                   1726:        fprintf(ficlog," x(%d)=%.12e",j,xit[j]);
                   1727:       }
                   1728:       for(j=1;j<=n;j++) {
1.162     brouard  1729:        printf(" p(%d)=%.12e",j,p[j]);
                   1730:        fprintf(ficlog," p(%d)=%.12e",j,p[j]);
1.126     brouard  1731:       }
                   1732:       printf("\n");
                   1733:       fprintf(ficlog,"\n");
                   1734: #endif
1.187     brouard  1735:     } /* end loop on each direction i */
                   1736:     /* Convergence test will use last linmin estimation (fret) and compare former iteration (fp) */ 
1.188     brouard  1737:     /* But p and xit have been updated at the end of linmin, *fret corresponds to new p, xit  */
1.187     brouard  1738:     /* New value of last point Pn is not computed, P(n-1) */
1.182     brouard  1739:     if (2.0*fabs(fp-(*fret)) <= ftol*(fabs(fp)+fabs(*fret))) { /* Did we reach enough precision? */
1.188     brouard  1740:       /* We could compare with a chi^2. chisquare(0.95,ddl=1)=3.84 */
                   1741:       /* By adding age*age in a model, the new -2LL should be lower and the difference follows a */
                   1742:       /* a chisquare statistics with 1 degree. To be significant at the 95% level, it should have */
                   1743:       /* decreased of more than 3.84  */
                   1744:       /* By adding age*age and V1*age the gain (-2LL) should be more than 5.99 (ddl=2) */
                   1745:       /* By using V1+V2+V3, the gain should be  7.82, compared with basic 1+age. */
                   1746:       /* By adding 10 parameters more the gain should be 18.31 */
                   1747: 
                   1748:       /* Starting the program with initial values given by a former maximization will simply change */
                   1749:       /* the scales of the directions and the directions, because the are reset to canonical directions */
                   1750:       /* Thus the first calls to linmin will give new points and better maximizations until fp-(*fret) is */
                   1751:       /* under the tolerance value. If the tolerance is very small 1.e-9, it could last long.  */
1.126     brouard  1752: #ifdef DEBUG
                   1753:       int k[2],l;
                   1754:       k[0]=1;
                   1755:       k[1]=-1;
                   1756:       printf("Max: %.12e",(*func)(p));
                   1757:       fprintf(ficlog,"Max: %.12e",(*func)(p));
                   1758:       for (j=1;j<=n;j++) {
                   1759:        printf(" %.12e",p[j]);
                   1760:        fprintf(ficlog," %.12e",p[j]);
                   1761:       }
                   1762:       printf("\n");
                   1763:       fprintf(ficlog,"\n");
                   1764:       for(l=0;l<=1;l++) {
                   1765:        for (j=1;j<=n;j++) {
                   1766:          ptt[j]=p[j]+(p[j]-pt[j])*k[l];
                   1767:          printf("l=%d j=%d ptt=%.12e, xits=%.12e, p=%.12e, xit=%.12e", l,j,ptt[j],xits[j],p[j],xit[j]);
                   1768:          fprintf(ficlog,"l=%d j=%d ptt=%.12e, xits=%.12e, p=%.12e, xit=%.12e", l,j,ptt[j],xits[j],p[j],xit[j]);
                   1769:        }
                   1770:        printf("func(ptt)=%.12e, deriv=%.12e\n",(*func)(ptt),(ptt[j]-p[j])/((*func)(ptt)-(*func)(p)));
                   1771:        fprintf(ficlog,"func(ptt)=%.12e, deriv=%.12e\n",(*func)(ptt),(ptt[j]-p[j])/((*func)(ptt)-(*func)(p)));
                   1772:       }
                   1773: #endif
                   1774: 
                   1775: 
                   1776:       free_vector(xit,1,n); 
                   1777:       free_vector(xits,1,n); 
                   1778:       free_vector(ptt,1,n); 
                   1779:       free_vector(pt,1,n); 
                   1780:       return; 
1.192     brouard  1781:     } /* enough precision */ 
1.126     brouard  1782:     if (*iter == ITMAX) nrerror("powell exceeding maximum iterations."); 
1.181     brouard  1783:     for (j=1;j<=n;j++) { /* Computes the extrapolated point P_0 + 2 (P_n-P_0) */
1.126     brouard  1784:       ptt[j]=2.0*p[j]-pt[j]; 
                   1785:       xit[j]=p[j]-pt[j]; 
                   1786:       pt[j]=p[j]; 
                   1787:     } 
1.181     brouard  1788:     fptt=(*func)(ptt); /* f_3 */
1.192     brouard  1789: #ifdef POWELLF1F3
                   1790: #else
1.161     brouard  1791:     if (fptt < fp) { /* If extrapolated point is better, decide if we keep that new direction or not */
1.192     brouard  1792: #endif
1.162     brouard  1793:       /* (x1 f1=fp), (x2 f2=*fret), (x3 f3=fptt), (xm fm) */
1.161     brouard  1794:       /* From x1 (P0) distance of x2 is at h and x3 is 2h */
1.162     brouard  1795:       /* Let f"(x2) be the 2nd derivative equal everywhere.  */
                   1796:       /* Then the parabolic through (x1,f1), (x2,f2) and (x3,f3) */
                   1797:       /* will reach at f3 = fm + h^2/2 f"m  ; f" = (f1 -2f2 +f3 ) / h**2 */
1.181     brouard  1798:       /* Conditional for using this new direction is that mu^2 = (f1-2f2+f3)^2 /2 < del */
1.161     brouard  1799:       /* t=2.0*(fp-2.0*(*fret)+fptt)*SQR(fp-(*fret)-del)-del*SQR(fp-fptt); */
1.183     brouard  1800: #ifdef NRCORIGINAL
                   1801:       t=2.0*(fp-2.0*(*fret)+fptt)*SQR(fp-(*fret)-del)- del*SQR(fp-fptt); /* Original Numerical Recipes in C*/
                   1802: #else
                   1803:       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  1804:       t= t- del*SQR(fp-fptt);
1.183     brouard  1805: #endif
1.182     brouard  1806:       directest = fp-2.0*(*fret)+fptt - 2.0 * del; /* If del was big enough we change it for a new direction */
1.161     brouard  1807: #ifdef DEBUG
1.181     brouard  1808:       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);
                   1809:       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  1810:       printf("t3= %.12lf, t4= %.12lf, t3*= %.12lf, t4*= %.12lf\n",SQR(fp-(*fret)-del),SQR(fp-fptt),
                   1811:             (fp-(*fret)-del)*(fp-(*fret)-del),(fp-fptt)*(fp-fptt));
                   1812:       fprintf(ficlog,"t3= %.12lf, t4= %.12lf, t3*= %.12lf, t4*= %.12lf\n",SQR(fp-(*fret)-del),SQR(fp-fptt),
                   1813:             (fp-(*fret)-del)*(fp-(*fret)-del),(fp-fptt)*(fp-fptt));
                   1814:       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);
                   1815:       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);
                   1816: #endif
1.183     brouard  1817: #ifdef POWELLORIGINAL
                   1818:       if (t < 0.0) { /* Then we use it for new direction */
                   1819: #else
1.182     brouard  1820:       if (directest*t < 0.0) { /* Contradiction between both tests */
1.192     brouard  1821:        printf("directest= %.12lf, t= %.12lf, f1= %.12lf,f2= %.12lf,f3= %.12lf, del= %.12lf\n",directest, t, fp,(*fret),fptt,del);
                   1822:         printf("f1-2f2+f3= %.12lf, f1-f2-del= %.12lf, f1-f3= %.12lf\n",fp-2.0*(*fret)+fptt, fp -(*fret) -del, fp-fptt);
                   1823:         fprintf(ficlog,"directest= %.12lf, t= %.12lf, f1= %.12lf,f2= %.12lf,f3= %.12lf, del= %.12lf\n",directest, t, fp,(*fret),fptt, del);
                   1824:         fprintf(ficlog,"f1-2f2+f3= %.12lf, f1-f2-del= %.12lf, f1-f3= %.12lf\n",fp-2.0*(*fret)+fptt, fp -(*fret) -del, fp-fptt);
                   1825:       } 
1.181     brouard  1826:       if (directest < 0.0) { /* Then we use it for new direction */
                   1827: #endif
1.191     brouard  1828: #ifdef DEBUGLINMIN
                   1829:        printf("Before linmin in direction P%d-P0\n",n);
                   1830:        for (j=1;j<=n;j++) { 
                   1831:          printf("Before xit[%d]= %12.7f p[%d]= %12.7f",j,xit[j],j,p[j]);
                   1832:          if(j % ncovmodel == 0)
                   1833:            printf("\n");
                   1834:        }
                   1835: #endif
1.187     brouard  1836:        linmin(p,xit,n,fret,func); /* computes minimum on the extrapolated direction: changes p and rescales xit.*/
1.191     brouard  1837: #ifdef DEBUGLINMIN
                   1838:        for (j=1;j<=n;j++) { 
                   1839:          printf("After xit[%d]= %12.7f p[%d]= %12.7f",j,xit[j],j,p[j]);
                   1840:          if(j % ncovmodel == 0)
                   1841:            printf("\n");
                   1842:        }
                   1843: #endif
1.126     brouard  1844:        for (j=1;j<=n;j++) { 
1.181     brouard  1845:          xi[j][ibig]=xi[j][n]; /* Replace direction with biggest decrease by last direction n */
                   1846:          xi[j][n]=xit[j];      /* and this nth direction by the by the average p_0 p_n */
1.126     brouard  1847:        }
1.181     brouard  1848:        printf("Gaining to use new average direction of P0 P%d instead of biggest increase direction %d :\n",n,ibig);
                   1849:        fprintf(ficlog,"Gaining to use new average direction of P0 P%d instead of biggest increase direction %d :\n",n,ibig);
1.161     brouard  1850: 
1.126     brouard  1851: #ifdef DEBUG
1.164     brouard  1852:        printf("Direction changed  last moved %d in place of ibig=%d, new last is the average:\n",n,ibig);
                   1853:        fprintf(ficlog,"Direction changed  last moved %d in place of ibig=%d, new last is the average:\n",n,ibig);
1.126     brouard  1854:        for(j=1;j<=n;j++){
                   1855:          printf(" %.12e",xit[j]);
                   1856:          fprintf(ficlog," %.12e",xit[j]);
                   1857:        }
                   1858:        printf("\n");
                   1859:        fprintf(ficlog,"\n");
                   1860: #endif
1.192     brouard  1861:       } /* end of t or directest negative */
                   1862: #ifdef POWELLF1F3
                   1863: #else
1.162     brouard  1864:     } /* end if (fptt < fp)  */
1.192     brouard  1865: #endif
                   1866:   } /* loop iteration */ 
1.126     brouard  1867: } 
                   1868: 
                   1869: /**** Prevalence limit (stable or period prevalence)  ****************/
                   1870: 
                   1871: double **prevalim(double **prlim, int nlstate, double x[], double age, double **oldm, double **savm, double ftolpl, int ij)
                   1872: {
                   1873:   /* Computes the prevalence limit in each live state at age x by left multiplying the unit
                   1874:      matrix by transitions matrix until convergence is reached */
1.169     brouard  1875:   
1.126     brouard  1876:   int i, ii,j,k;
                   1877:   double min, max, maxmin, maxmax,sumnew=0.;
1.145     brouard  1878:   /* double **matprod2(); */ /* test */
1.131     brouard  1879:   double **out, cov[NCOVMAX+1], **pmij();
1.126     brouard  1880:   double **newm;
                   1881:   double agefin, delaymax=50 ; /* Max number of years to converge */
1.169     brouard  1882:   
1.126     brouard  1883:   for (ii=1;ii<=nlstate+ndeath;ii++)
                   1884:     for (j=1;j<=nlstate+ndeath;j++){
                   1885:       oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   1886:     }
1.169     brouard  1887:   
                   1888:   cov[1]=1.;
                   1889:   
                   1890:   /* Even if hstepm = 1, at least one multiplication by the unit matrix */
1.126     brouard  1891:   for(agefin=age-stepm/YEARM; agefin>=age-delaymax; agefin=agefin-stepm/YEARM){
                   1892:     newm=savm;
                   1893:     /* Covariates have to be included here again */
1.138     brouard  1894:     cov[2]=agefin;
1.187     brouard  1895:     if(nagesqr==1)
                   1896:       cov[3]= agefin*agefin;;
1.138     brouard  1897:     for (k=1; k<=cptcovn;k++) {
1.187     brouard  1898:       cov[2+nagesqr+k]=nbcode[Tvar[k]][codtab[ij][Tvar[k]]];
1.145     brouard  1899:       /*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  1900:     }
1.186     brouard  1901:     /*wrong? for (k=1; k<=cptcovage;k++) cov[2+Tage[k]]=cov[2+Tage[k]]*cov[2]; */
1.187     brouard  1902:     for (k=1; k<=cptcovage;k++) cov[2+nagesqr+Tage[k]]=nbcode[Tvar[k]][codtab[ij][Tvar[k]]]*cov[2];
1.186     brouard  1903:     for (k=1; k<=cptcovprod;k++) /* Useless */
1.187     brouard  1904:       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  1905:     
                   1906:     /*printf("ij=%d cptcovprod=%d tvar=%d ", ij, cptcovprod, Tvar[1]);*/
                   1907:     /*printf("ij=%d cov[3]=%lf cov[4]=%lf \n",ij, cov[3],cov[4]);*/
                   1908:     /*printf("ij=%d cov[3]=%lf \n",ij, cov[3]);*/
1.145     brouard  1909:     /* savm=pmij(pmmij,cov,ncovmodel,x,nlstate); */
                   1910:     /* out=matprod2(newm, pmij(pmmij,cov,ncovmodel,x,nlstate),1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, oldm); /\* Bug Valgrind *\/ */
1.142     brouard  1911:     out=matprod2(newm, pmij(pmmij,cov,ncovmodel,x,nlstate),1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, oldm); /* Bug Valgrind */
1.138     brouard  1912:     
1.126     brouard  1913:     savm=oldm;
                   1914:     oldm=newm;
                   1915:     maxmax=0.;
                   1916:     for(j=1;j<=nlstate;j++){
                   1917:       min=1.;
                   1918:       max=0.;
                   1919:       for(i=1; i<=nlstate; i++) {
                   1920:        sumnew=0;
                   1921:        for(k=1; k<=ndeath; k++) sumnew+=newm[i][nlstate+k];
                   1922:        prlim[i][j]= newm[i][j]/(1-sumnew);
1.145     brouard  1923:         /*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  1924:        max=FMAX(max,prlim[i][j]);
                   1925:        min=FMIN(min,prlim[i][j]);
                   1926:       }
                   1927:       maxmin=max-min;
                   1928:       maxmax=FMAX(maxmax,maxmin);
1.169     brouard  1929:     } /* j loop */
1.126     brouard  1930:     if(maxmax < ftolpl){
                   1931:       return prlim;
                   1932:     }
1.169     brouard  1933:   } /* age loop */
                   1934:   return prlim; /* should not reach here */
1.126     brouard  1935: }
                   1936: 
                   1937: /*************** transition probabilities ***************/ 
                   1938: 
                   1939: double **pmij(double **ps, double *cov, int ncovmodel, double *x, int nlstate )
                   1940: {
1.138     brouard  1941:   /* According to parameters values stored in x and the covariate's values stored in cov,
                   1942:      computes the probability to be observed in state j being in state i by appying the
                   1943:      model to the ncovmodel covariates (including constant and age).
                   1944:      lnpijopii=ln(pij/pii)= aij+bij*age+cij*v1+dij*v2+... = sum_nc=1^ncovmodel xij(nc)*cov[nc]
                   1945:      and, according on how parameters are entered, the position of the coefficient xij(nc) of the
                   1946:      ncth covariate in the global vector x is given by the formula:
                   1947:      j<i nc+((i-1)*(nlstate+ndeath-1)+j-1)*ncovmodel
                   1948:      j>=i nc + ((i-1)*(nlstate+ndeath-1)+(j-2))*ncovmodel
                   1949:      Computes ln(pij/pii) (lnpijopii), deduces pij/pii by exponentiation,
                   1950:      sums on j different of i to get 1-pii/pii, deduces pii, and then all pij.
                   1951:      Outputs ps[i][j] the probability to be observed in j being in j according to
                   1952:      the values of the covariates cov[nc] and corresponding parameter values x[nc+shiftij]
                   1953:   */
                   1954:   double s1, lnpijopii;
1.126     brouard  1955:   /*double t34;*/
1.164     brouard  1956:   int i,j, nc, ii, jj;
1.126     brouard  1957: 
                   1958:     for(i=1; i<= nlstate; i++){
                   1959:       for(j=1; j<i;j++){
1.138     brouard  1960:        for (nc=1, lnpijopii=0.;nc <=ncovmodel; nc++){
                   1961:          /*lnpijopii += param[i][j][nc]*cov[nc];*/
                   1962:          lnpijopii += x[nc+((i-1)*(nlstate+ndeath-1)+j-1)*ncovmodel]*cov[nc];
                   1963: /*      printf("Int j<i s1=%.17e, lnpijopii=%.17e\n",s1,lnpijopii); */
1.126     brouard  1964:        }
1.138     brouard  1965:        ps[i][j]=lnpijopii; /* In fact ln(pij/pii) */
                   1966: /*     printf("s1=%.17e, lnpijopii=%.17e\n",s1,lnpijopii); */
1.126     brouard  1967:       }
                   1968:       for(j=i+1; j<=nlstate+ndeath;j++){
1.138     brouard  1969:        for (nc=1, lnpijopii=0.;nc <=ncovmodel; nc++){
                   1970:          /*lnpijopii += x[(i-1)*nlstate*ncovmodel+(j-2)*ncovmodel+nc+(i-1)*(ndeath-1)*ncovmodel]*cov[nc];*/
                   1971:          lnpijopii += x[nc + ((i-1)*(nlstate+ndeath-1)+(j-2))*ncovmodel]*cov[nc];
                   1972: /*       printf("Int j>i s1=%.17e, lnpijopii=%.17e %lx %lx\n",s1,lnpijopii,s1,lnpijopii); */
1.126     brouard  1973:        }
1.138     brouard  1974:        ps[i][j]=lnpijopii; /* In fact ln(pij/pii) */
1.126     brouard  1975:       }
                   1976:     }
                   1977:     
                   1978:     for(i=1; i<= nlstate; i++){
                   1979:       s1=0;
1.131     brouard  1980:       for(j=1; j<i; j++){
1.138     brouard  1981:        s1+=exp(ps[i][j]); /* In fact sums pij/pii */
1.131     brouard  1982:        /*printf("debug1 %d %d ps=%lf exp(ps)=%lf s1+=%lf\n",i,j,ps[i][j],exp(ps[i][j]),s1); */
                   1983:       }
                   1984:       for(j=i+1; j<=nlstate+ndeath; j++){
1.138     brouard  1985:        s1+=exp(ps[i][j]); /* In fact sums pij/pii */
1.131     brouard  1986:        /*printf("debug2 %d %d ps=%lf exp(ps)=%lf s1+=%lf\n",i,j,ps[i][j],exp(ps[i][j]),s1); */
                   1987:       }
1.138     brouard  1988:       /* s1= sum_{j<>i} pij/pii=(1-pii)/pii and thus pii is known from s1 */
1.126     brouard  1989:       ps[i][i]=1./(s1+1.);
1.138     brouard  1990:       /* Computing other pijs */
1.126     brouard  1991:       for(j=1; j<i; j++)
                   1992:        ps[i][j]= exp(ps[i][j])*ps[i][i];
                   1993:       for(j=i+1; j<=nlstate+ndeath; j++)
                   1994:        ps[i][j]= exp(ps[i][j])*ps[i][i];
                   1995:       /* ps[i][nlstate+1]=1.-s1- ps[i][i];*/ /* Sum should be 1 */
                   1996:     } /* end i */
                   1997:     
                   1998:     for(ii=nlstate+1; ii<= nlstate+ndeath; ii++){
                   1999:       for(jj=1; jj<= nlstate+ndeath; jj++){
                   2000:        ps[ii][jj]=0;
                   2001:        ps[ii][ii]=1;
                   2002:       }
                   2003:     }
                   2004:     
1.145     brouard  2005:     
                   2006:     /* for(ii=1; ii<= nlstate+ndeath; ii++){ */
                   2007:     /*   for(jj=1; jj<= nlstate+ndeath; jj++){ */
                   2008:     /*         printf(" pmij  ps[%d][%d]=%lf ",ii,jj,ps[ii][jj]); */
                   2009:     /*   } */
                   2010:     /*   printf("\n "); */
                   2011:     /* } */
                   2012:     /* printf("\n ");printf("%lf ",cov[2]);*/
                   2013:     /*
1.126     brouard  2014:       for(i=1; i<= npar; i++) printf("%f ",x[i]);
                   2015:       goto end;*/
                   2016:     return ps;
                   2017: }
                   2018: 
                   2019: /**************** Product of 2 matrices ******************/
                   2020: 
1.145     brouard  2021: double **matprod2(double **out, double **in,int nrl, int nrh, int ncl, int nch, int ncolol, int ncoloh, double **b)
1.126     brouard  2022: {
                   2023:   /* Computes the matrix product of in(1,nrh-nrl+1)(1,nch-ncl+1) times
                   2024:      b(1,nch-ncl+1)(1,ncoloh-ncolol+1) into out(...) */
                   2025:   /* in, b, out are matrice of pointers which should have been initialized 
                   2026:      before: only the contents of out is modified. The function returns
                   2027:      a pointer to pointers identical to out */
1.145     brouard  2028:   int i, j, k;
1.126     brouard  2029:   for(i=nrl; i<= nrh; i++)
1.145     brouard  2030:     for(k=ncolol; k<=ncoloh; k++){
                   2031:       out[i][k]=0.;
                   2032:       for(j=ncl; j<=nch; j++)
                   2033:        out[i][k] +=in[i][j]*b[j][k];
                   2034:     }
1.126     brouard  2035:   return out;
                   2036: }
                   2037: 
                   2038: 
                   2039: /************* Higher Matrix Product ***************/
                   2040: 
                   2041: double ***hpxij(double ***po, int nhstepm, double age, int hstepm, double *x, int nlstate, int stepm, double **oldm, double **savm, int ij )
                   2042: {
                   2043:   /* Computes the transition matrix starting at age 'age' over 
                   2044:      'nhstepm*hstepm*stepm' months (i.e. until
                   2045:      age (in years)  age+nhstepm*hstepm*stepm/12) by multiplying 
                   2046:      nhstepm*hstepm matrices. 
                   2047:      Output is stored in matrix po[i][j][h] for h every 'hstepm' step 
                   2048:      (typically every 2 years instead of every month which is too big 
                   2049:      for the memory).
                   2050:      Model is determined by parameters x and covariates have to be 
                   2051:      included manually here. 
                   2052: 
                   2053:      */
                   2054: 
                   2055:   int i, j, d, h, k;
1.131     brouard  2056:   double **out, cov[NCOVMAX+1];
1.126     brouard  2057:   double **newm;
1.187     brouard  2058:   double agexact;
1.126     brouard  2059: 
                   2060:   /* Hstepm could be zero and should return the unit matrix */
                   2061:   for (i=1;i<=nlstate+ndeath;i++)
                   2062:     for (j=1;j<=nlstate+ndeath;j++){
                   2063:       oldm[i][j]=(i==j ? 1.0 : 0.0);
                   2064:       po[i][j][0]=(i==j ? 1.0 : 0.0);
                   2065:     }
                   2066:   /* Even if hstepm = 1, at least one multiplication by the unit matrix */
                   2067:   for(h=1; h <=nhstepm; h++){
                   2068:     for(d=1; d <=hstepm; d++){
                   2069:       newm=savm;
                   2070:       /* Covariates have to be included here again */
                   2071:       cov[1]=1.;
1.187     brouard  2072:       agexact=age+((h-1)*hstepm + (d-1))*stepm/YEARM;
                   2073:       cov[2]=agexact;
                   2074:       if(nagesqr==1)
                   2075:        cov[3]= agexact*agexact;
1.131     brouard  2076:       for (k=1; k<=cptcovn;k++) 
1.187     brouard  2077:        cov[2+nagesqr+k]=nbcode[Tvar[k]][codtab[ij][Tvar[k]]];
1.186     brouard  2078:       for (k=1; k<=cptcovage;k++) /* Should start at cptcovn+1 */
                   2079:        /* cov[2+Tage[k]]=cov[2+Tage[k]]*cov[2]; */
1.187     brouard  2080:        cov[2+nagesqr+Tage[k]]=nbcode[Tvar[Tage[k]]][codtab[ij][Tvar[Tage[k]]]]*cov[2];
1.145     brouard  2081:       for (k=1; k<=cptcovprod;k++) /* Useless because included in cptcovn */
1.187     brouard  2082:        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  2083: 
                   2084: 
                   2085:       /*printf("hxi cptcov=%d cptcode=%d\n",cptcov,cptcode);*/
                   2086:       /*printf("h=%d d=%d age=%f cov=%f\n",h,d,age,cov[2]);*/
                   2087:       out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, 
                   2088:                   pmij(pmmij,cov,ncovmodel,x,nlstate));
                   2089:       savm=oldm;
                   2090:       oldm=newm;
                   2091:     }
                   2092:     for(i=1; i<=nlstate+ndeath; i++)
                   2093:       for(j=1;j<=nlstate+ndeath;j++) {
                   2094:        po[i][j][h]=newm[i][j];
1.128     brouard  2095:        /*if(h==nhstepm) printf("po[%d][%d][%d]=%f ",i,j,h,po[i][j][h]);*/
1.126     brouard  2096:       }
1.128     brouard  2097:     /*printf("h=%d ",h);*/
1.126     brouard  2098:   } /* end h */
1.128     brouard  2099: /*     printf("\n H=%d \n",h); */
1.126     brouard  2100:   return po;
                   2101: }
                   2102: 
1.162     brouard  2103: #ifdef NLOPT
                   2104:   double  myfunc(unsigned n, const double *p1, double *grad, void *pd){
                   2105:   double fret;
                   2106:   double *xt;
                   2107:   int j;
                   2108:   myfunc_data *d2 = (myfunc_data *) pd;
                   2109: /* xt = (p1-1); */
                   2110:   xt=vector(1,n); 
                   2111:   for (j=1;j<=n;j++)   xt[j]=p1[j-1]; /* xt[1]=p1[0] */
                   2112: 
                   2113:   fret=(d2->function)(xt); /*  p xt[1]@8 is fine */
                   2114:   /* fret=(*func)(xt); /\*  p xt[1]@8 is fine *\/ */
                   2115:   printf("Function = %.12lf ",fret);
                   2116:   for (j=1;j<=n;j++) printf(" %d %.8lf", j, xt[j]); 
                   2117:   printf("\n");
                   2118:  free_vector(xt,1,n);
                   2119:   return fret;
                   2120: }
                   2121: #endif
1.126     brouard  2122: 
                   2123: /*************** log-likelihood *************/
                   2124: double func( double *x)
                   2125: {
                   2126:   int i, ii, j, k, mi, d, kk;
1.131     brouard  2127:   double l, ll[NLSTATEMAX+1], cov[NCOVMAX+1];
1.126     brouard  2128:   double **out;
                   2129:   double sw; /* Sum of weights */
                   2130:   double lli; /* Individual log likelihood */
                   2131:   int s1, s2;
                   2132:   double bbh, survp;
                   2133:   long ipmx;
1.187     brouard  2134:   double agexact;
1.126     brouard  2135:   /*extern weight */
                   2136:   /* We are differentiating ll according to initial status */
                   2137:   /*  for (i=1;i<=npar;i++) printf("%f ", x[i]);*/
                   2138:   /*for(i=1;i<imx;i++) 
                   2139:     printf(" %d\n",s[4][i]);
                   2140:   */
1.162     brouard  2141: 
                   2142:   ++countcallfunc;
                   2143: 
1.126     brouard  2144:   cov[1]=1.;
                   2145: 
                   2146:   for(k=1; k<=nlstate; k++) ll[k]=0.;
                   2147: 
                   2148:   if(mle==1){
                   2149:     for (i=1,ipmx=0, sw=0.; i<=imx; i++){
1.138     brouard  2150:       /* Computes the values of the ncovmodel covariates of the model
                   2151:         depending if the covariates are fixed or variying (age dependent) and stores them in cov[]
                   2152:         Then computes with function pmij which return a matrix p[i][j] giving the elementary probability
                   2153:         to be observed in j being in i according to the model.
                   2154:        */
1.145     brouard  2155:       for (k=1; k<=cptcovn;k++){ /* Simple and product covariates without age* products */
1.187     brouard  2156:          cov[2+nagesqr+k]=covar[Tvar[k]][i];
1.145     brouard  2157:       }
1.137     brouard  2158:       /* In model V2+V1*V4+age*V3+V3*V2 Tvar[1] is V2, Tvar[2=V1*V4] 
1.138     brouard  2159:         is 6, Tvar[3=age*V3] should not be computed because of age Tvar[4=V3*V2] 
1.137     brouard  2160:         has been calculated etc */
1.126     brouard  2161:       for(mi=1; mi<= wav[i]-1; mi++){
                   2162:        for (ii=1;ii<=nlstate+ndeath;ii++)
                   2163:          for (j=1;j<=nlstate+ndeath;j++){
                   2164:            oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   2165:            savm[ii][j]=(ii==j ? 1.0 : 0.0);
                   2166:          }
                   2167:        for(d=0; d<dh[mi][i]; d++){
                   2168:          newm=savm;
1.187     brouard  2169:          agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;
                   2170:          cov[2]=agexact;
                   2171:          if(nagesqr==1)
                   2172:            cov[3]= agexact*agexact;
1.126     brouard  2173:          for (kk=1; kk<=cptcovage;kk++) {
1.187     brouard  2174:            cov[Tage[kk]+2+nagesqr]=covar[Tvar[Tage[kk]]][i]*agexact; /* Tage[kk] gives the data-covariate associated with age */
1.126     brouard  2175:          }
                   2176:          out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
                   2177:                       1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
                   2178:          savm=oldm;
                   2179:          oldm=newm;
                   2180:        } /* end mult */
                   2181:       
                   2182:        /*lli=log(out[s[mw[mi][i]][i]][s[mw[mi+1][i]][i]]);*/ /* Original formula */
                   2183:        /* But now since version 0.9 we anticipate for bias at large stepm.
                   2184:         * If stepm is larger than one month (smallest stepm) and if the exact delay 
                   2185:         * (in months) between two waves is not a multiple of stepm, we rounded to 
                   2186:         * the nearest (and in case of equal distance, to the lowest) interval but now
                   2187:         * we keep into memory the bias bh[mi][i] and also the previous matrix product
                   2188:         * (i.e to dh[mi][i]-1) saved in 'savm'. Then we inter(extra)polate the
                   2189:         * probability in order to take into account the bias as a fraction of the way
                   2190:         * from savm to out if bh is negative or even beyond if bh is positive. bh varies
                   2191:         * -stepm/2 to stepm/2 .
                   2192:         * For stepm=1 the results are the same as for previous versions of Imach.
                   2193:         * For stepm > 1 the results are less biased than in previous versions. 
                   2194:         */
                   2195:        s1=s[mw[mi][i]][i];
                   2196:        s2=s[mw[mi+1][i]][i];
                   2197:        bbh=(double)bh[mi][i]/(double)stepm; 
                   2198:        /* bias bh is positive if real duration
                   2199:         * is higher than the multiple of stepm and negative otherwise.
                   2200:         */
                   2201:        /* lli= (savm[s1][s2]>1.e-8 ?(1.+bbh)*log(out[s1][s2])- bbh*log(savm[s1][s2]):log((1.+bbh)*out[s1][s2]));*/
                   2202:        if( s2 > nlstate){ 
                   2203:          /* i.e. if s2 is a death state and if the date of death is known 
                   2204:             then the contribution to the likelihood is the probability to 
                   2205:             die between last step unit time and current  step unit time, 
                   2206:             which is also equal to probability to die before dh 
                   2207:             minus probability to die before dh-stepm . 
                   2208:             In version up to 0.92 likelihood was computed
                   2209:        as if date of death was unknown. Death was treated as any other
                   2210:        health state: the date of the interview describes the actual state
                   2211:        and not the date of a change in health state. The former idea was
                   2212:        to consider that at each interview the state was recorded
                   2213:        (healthy, disable or death) and IMaCh was corrected; but when we
                   2214:        introduced the exact date of death then we should have modified
                   2215:        the contribution of an exact death to the likelihood. This new
                   2216:        contribution is smaller and very dependent of the step unit
                   2217:        stepm. It is no more the probability to die between last interview
                   2218:        and month of death but the probability to survive from last
                   2219:        interview up to one month before death multiplied by the
                   2220:        probability to die within a month. Thanks to Chris
                   2221:        Jackson for correcting this bug.  Former versions increased
                   2222:        mortality artificially. The bad side is that we add another loop
                   2223:        which slows down the processing. The difference can be up to 10%
                   2224:        lower mortality.
                   2225:          */
1.183     brouard  2226:        /* If, at the beginning of the maximization mostly, the
                   2227:           cumulative probability or probability to be dead is
                   2228:           constant (ie = 1) over time d, the difference is equal to
                   2229:           0.  out[s1][3] = savm[s1][3]: probability, being at state
                   2230:           s1 at precedent wave, to be dead a month before current
                   2231:           wave is equal to probability, being at state s1 at
                   2232:           precedent wave, to be dead at mont of the current
                   2233:           wave. Then the observed probability (that this person died)
                   2234:           is null according to current estimated parameter. In fact,
                   2235:           it should be very low but not zero otherwise the log go to
                   2236:           infinity.
                   2237:        */
                   2238: /* #ifdef INFINITYORIGINAL */
                   2239: /*         lli=log(out[s1][s2] - savm[s1][s2]); */
                   2240: /* #else */
                   2241: /*       if ((out[s1][s2] - savm[s1][s2]) < mytinydouble)  */
                   2242: /*         lli=log(mytinydouble); */
                   2243: /*       else */
                   2244: /*         lli=log(out[s1][s2] - savm[s1][s2]); */
                   2245: /* #endif */
                   2246:            lli=log(out[s1][s2] - savm[s1][s2]);
1.126     brouard  2247: 
                   2248:        } else if  (s2==-2) {
                   2249:          for (j=1,survp=0. ; j<=nlstate; j++) 
                   2250:            survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j];
                   2251:          /*survp += out[s1][j]; */
                   2252:          lli= log(survp);
                   2253:        }
                   2254:        
                   2255:        else if  (s2==-4) { 
                   2256:          for (j=3,survp=0. ; j<=nlstate; j++)  
                   2257:            survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j];
                   2258:          lli= log(survp); 
                   2259:        } 
                   2260: 
                   2261:        else if  (s2==-5) { 
                   2262:          for (j=1,survp=0. ; j<=2; j++)  
                   2263:            survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j];
                   2264:          lli= log(survp); 
                   2265:        } 
                   2266:        
                   2267:        else{
                   2268:          lli= log((1.+bbh)*out[s1][s2]- bbh*savm[s1][s2]); /* linear interpolation */
                   2269:          /*  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 */
                   2270:        } 
                   2271:        /*lli=(1.+bbh)*log(out[s1][s2])- bbh*log(savm[s1][s2]);*/
                   2272:        /*if(lli ==000.0)*/
                   2273:        /*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); */
                   2274:        ipmx +=1;
                   2275:        sw += weight[i];
                   2276:        ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
1.183     brouard  2277:        /* if (lli < log(mytinydouble)){ */
                   2278:        /*   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); */
                   2279:        /*   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]); */
                   2280:        /* } */
1.126     brouard  2281:       } /* end of wave */
                   2282:     } /* end of individual */
                   2283:   }  else if(mle==2){
                   2284:     for (i=1,ipmx=0, sw=0.; i<=imx; i++){
1.187     brouard  2285:       for (k=1; k<=cptcovn;k++) cov[2+nagesqr+k]=covar[Tvar[k]][i];
1.126     brouard  2286:       for(mi=1; mi<= wav[i]-1; mi++){
                   2287:        for (ii=1;ii<=nlstate+ndeath;ii++)
                   2288:          for (j=1;j<=nlstate+ndeath;j++){
                   2289:            oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   2290:            savm[ii][j]=(ii==j ? 1.0 : 0.0);
                   2291:          }
                   2292:        for(d=0; d<=dh[mi][i]; d++){
                   2293:          newm=savm;
1.187     brouard  2294:          agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;
                   2295:          cov[2]=agexact;
                   2296:          if(nagesqr==1)
                   2297:            cov[3]= agexact*agexact;
1.126     brouard  2298:          for (kk=1; kk<=cptcovage;kk++) {
1.187     brouard  2299:            cov[Tage[kk]+2+nagesqr]=covar[Tvar[Tage[kk]]][i]*agexact;
1.126     brouard  2300:          }
                   2301:          out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
                   2302:                       1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
                   2303:          savm=oldm;
                   2304:          oldm=newm;
                   2305:        } /* end mult */
                   2306:       
                   2307:        s1=s[mw[mi][i]][i];
                   2308:        s2=s[mw[mi+1][i]][i];
                   2309:        bbh=(double)bh[mi][i]/(double)stepm; 
                   2310:        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 */
                   2311:        ipmx +=1;
                   2312:        sw += weight[i];
                   2313:        ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
                   2314:       } /* end of wave */
                   2315:     } /* end of individual */
                   2316:   }  else if(mle==3){  /* exponential inter-extrapolation */
                   2317:     for (i=1,ipmx=0, sw=0.; i<=imx; i++){
1.187     brouard  2318:       for (k=1; k<=cptcovn;k++) cov[2+nagesqr+k]=covar[Tvar[k]][i];
1.126     brouard  2319:       for(mi=1; mi<= wav[i]-1; mi++){
                   2320:        for (ii=1;ii<=nlstate+ndeath;ii++)
                   2321:          for (j=1;j<=nlstate+ndeath;j++){
                   2322:            oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   2323:            savm[ii][j]=(ii==j ? 1.0 : 0.0);
                   2324:          }
                   2325:        for(d=0; d<dh[mi][i]; d++){
                   2326:          newm=savm;
1.187     brouard  2327:          agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;
                   2328:          cov[2]=agexact;
                   2329:          if(nagesqr==1)
                   2330:            cov[3]= agexact*agexact;
1.126     brouard  2331:          for (kk=1; kk<=cptcovage;kk++) {
1.187     brouard  2332:            cov[Tage[kk]+2+nagesqr]=covar[Tvar[Tage[kk]]][i]*agexact;
1.126     brouard  2333:          }
                   2334:          out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
                   2335:                       1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
                   2336:          savm=oldm;
                   2337:          oldm=newm;
                   2338:        } /* end mult */
                   2339:       
                   2340:        s1=s[mw[mi][i]][i];
                   2341:        s2=s[mw[mi+1][i]][i];
                   2342:        bbh=(double)bh[mi][i]/(double)stepm; 
                   2343:        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 */
                   2344:        ipmx +=1;
                   2345:        sw += weight[i];
                   2346:        ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
                   2347:       } /* end of wave */
                   2348:     } /* end of individual */
                   2349:   }else if (mle==4){  /* ml=4 no inter-extrapolation */
                   2350:     for (i=1,ipmx=0, sw=0.; i<=imx; i++){
1.187     brouard  2351:       for (k=1; k<=cptcovn;k++) cov[2+nagesqr+k]=covar[Tvar[k]][i];
1.126     brouard  2352:       for(mi=1; mi<= wav[i]-1; mi++){
                   2353:        for (ii=1;ii<=nlstate+ndeath;ii++)
                   2354:          for (j=1;j<=nlstate+ndeath;j++){
                   2355:            oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   2356:            savm[ii][j]=(ii==j ? 1.0 : 0.0);
                   2357:          }
                   2358:        for(d=0; d<dh[mi][i]; d++){
                   2359:          newm=savm;
1.187     brouard  2360:          agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;
                   2361:          cov[2]=agexact;
                   2362:          if(nagesqr==1)
                   2363:            cov[3]= agexact*agexact;
1.126     brouard  2364:          for (kk=1; kk<=cptcovage;kk++) {
1.187     brouard  2365:            cov[Tage[kk]+2+nagesqr]=covar[Tvar[Tage[kk]]][i]*agexact;
1.126     brouard  2366:          }
                   2367:        
                   2368:          out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
                   2369:                       1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
                   2370:          savm=oldm;
                   2371:          oldm=newm;
                   2372:        } /* end mult */
                   2373:       
                   2374:        s1=s[mw[mi][i]][i];
                   2375:        s2=s[mw[mi+1][i]][i];
                   2376:        if( s2 > nlstate){ 
                   2377:          lli=log(out[s1][s2] - savm[s1][s2]);
                   2378:        }else{
                   2379:          lli=log(out[s[mw[mi][i]][i]][s[mw[mi+1][i]][i]]); /* Original formula */
                   2380:        }
                   2381:        ipmx +=1;
                   2382:        sw += weight[i];
                   2383:        ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
                   2384: /*     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]); */
                   2385:       } /* end of wave */
                   2386:     } /* end of individual */
                   2387:   }else{  /* ml=5 no inter-extrapolation no jackson =0.8a */
                   2388:     for (i=1,ipmx=0, sw=0.; i<=imx; i++){
1.187     brouard  2389:       for (k=1; k<=cptcovn;k++) cov[2+nagesqr+k]=covar[Tvar[k]][i];
1.126     brouard  2390:       for(mi=1; mi<= wav[i]-1; mi++){
                   2391:        for (ii=1;ii<=nlstate+ndeath;ii++)
                   2392:          for (j=1;j<=nlstate+ndeath;j++){
                   2393:            oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   2394:            savm[ii][j]=(ii==j ? 1.0 : 0.0);
                   2395:          }
                   2396:        for(d=0; d<dh[mi][i]; d++){
                   2397:          newm=savm;
1.187     brouard  2398:          agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;
                   2399:          cov[2]=agexact;
                   2400:          if(nagesqr==1)
                   2401:            cov[3]= agexact*agexact;
1.126     brouard  2402:          for (kk=1; kk<=cptcovage;kk++) {
1.187     brouard  2403:            cov[Tage[kk]+2+nagesqr]=covar[Tvar[Tage[kk]]][i]*agexact;
1.126     brouard  2404:          }
                   2405:        
                   2406:          out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
                   2407:                       1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
                   2408:          savm=oldm;
                   2409:          oldm=newm;
                   2410:        } /* end mult */
                   2411:       
                   2412:        s1=s[mw[mi][i]][i];
                   2413:        s2=s[mw[mi+1][i]][i];
                   2414:        lli=log(out[s[mw[mi][i]][i]][s[mw[mi+1][i]][i]]); /* Original formula */
                   2415:        ipmx +=1;
                   2416:        sw += weight[i];
                   2417:        ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
                   2418:        /*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]);*/
                   2419:       } /* end of wave */
                   2420:     } /* end of individual */
                   2421:   } /* End of if */
                   2422:   for(k=1,l=0.; k<=nlstate; k++) l += ll[k];
                   2423:   /* printf("l1=%f l2=%f ",ll[1],ll[2]); */
                   2424:   l= l*ipmx/sw; /* To get the same order of magnitude as if weight=1 for every body */
                   2425:   return -l;
                   2426: }
                   2427: 
                   2428: /*************** log-likelihood *************/
                   2429: double funcone( double *x)
                   2430: {
                   2431:   /* Same as likeli but slower because of a lot of printf and if */
                   2432:   int i, ii, j, k, mi, d, kk;
1.131     brouard  2433:   double l, ll[NLSTATEMAX+1], cov[NCOVMAX+1];
1.126     brouard  2434:   double **out;
                   2435:   double lli; /* Individual log likelihood */
                   2436:   double llt;
                   2437:   int s1, s2;
                   2438:   double bbh, survp;
1.187     brouard  2439:   double agexact;
1.126     brouard  2440:   /*extern weight */
                   2441:   /* We are differentiating ll according to initial status */
                   2442:   /*  for (i=1;i<=npar;i++) printf("%f ", x[i]);*/
                   2443:   /*for(i=1;i<imx;i++) 
                   2444:     printf(" %d\n",s[4][i]);
                   2445:   */
                   2446:   cov[1]=1.;
                   2447: 
                   2448:   for(k=1; k<=nlstate; k++) ll[k]=0.;
                   2449: 
                   2450:   for (i=1,ipmx=0, sw=0.; i<=imx; i++){
1.187     brouard  2451:     for (k=1; k<=cptcovn;k++) cov[2+nagesqr+k]=covar[Tvar[k]][i];
1.126     brouard  2452:     for(mi=1; mi<= wav[i]-1; mi++){
                   2453:       for (ii=1;ii<=nlstate+ndeath;ii++)
                   2454:        for (j=1;j<=nlstate+ndeath;j++){
                   2455:          oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   2456:          savm[ii][j]=(ii==j ? 1.0 : 0.0);
                   2457:        }
                   2458:       for(d=0; d<dh[mi][i]; d++){
                   2459:        newm=savm;
1.187     brouard  2460:        agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;
                   2461:        cov[2]=agexact;
                   2462:        if(nagesqr==1)
                   2463:          cov[3]= agexact*agexact;
1.126     brouard  2464:        for (kk=1; kk<=cptcovage;kk++) {
1.187     brouard  2465:          cov[Tage[kk]+2+nagesqr]=covar[Tvar[Tage[kk]]][i]*agexact;
1.126     brouard  2466:        }
1.187     brouard  2467: 
1.145     brouard  2468:        /* savm=pmij(pmmij,cov,ncovmodel,x,nlstate); */
1.126     brouard  2469:        out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
                   2470:                     1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
1.145     brouard  2471:        /* out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath, */
                   2472:        /*           1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate)); */
1.126     brouard  2473:        savm=oldm;
                   2474:        oldm=newm;
                   2475:       } /* end mult */
                   2476:       
                   2477:       s1=s[mw[mi][i]][i];
                   2478:       s2=s[mw[mi+1][i]][i];
                   2479:       bbh=(double)bh[mi][i]/(double)stepm; 
                   2480:       /* bias is positive if real duration
                   2481:        * is higher than the multiple of stepm and negative otherwise.
                   2482:        */
                   2483:       if( s2 > nlstate && (mle <5) ){  /* Jackson */
                   2484:        lli=log(out[s1][s2] - savm[s1][s2]);
                   2485:       } else if  (s2==-2) {
                   2486:        for (j=1,survp=0. ; j<=nlstate; j++) 
                   2487:          survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j];
                   2488:        lli= log(survp);
                   2489:       }else if (mle==1){
                   2490:        lli= log((1.+bbh)*out[s1][s2]- bbh*savm[s1][s2]); /* linear interpolation */
                   2491:       } else if(mle==2){
                   2492:        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 */
                   2493:       } else if(mle==3){  /* exponential inter-extrapolation */
                   2494:        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 */
                   2495:       } else if (mle==4){  /* mle=4 no inter-extrapolation */
                   2496:        lli=log(out[s1][s2]); /* Original formula */
1.136     brouard  2497:       } else{  /* mle=0 back to 1 */
                   2498:        lli= log((1.+bbh)*out[s1][s2]- bbh*savm[s1][s2]); /* linear interpolation */
                   2499:        /*lli=log(out[s1][s2]); */ /* Original formula */
1.126     brouard  2500:       } /* End of if */
                   2501:       ipmx +=1;
                   2502:       sw += weight[i];
                   2503:       ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
1.132     brouard  2504:       /*printf("i=%6d s1=%1d s2=%1d mi=%1d mw=%1d dh=%3d prob=%10.6f w=%6.4f out=%10.6f sav=%10.6f\n",i,s1,s2,mi,mw[mi][i],dh[mi][i],exp(lli),weight[i],out[s1][s2],savm[s1][s2]); */
1.126     brouard  2505:       if(globpr){
1.141     brouard  2506:        fprintf(ficresilk,"%9ld %6d %2d %2d %1d %1d %3d %11.6f %8.4f\
1.126     brouard  2507:  %11.6f %11.6f %11.6f ", \
                   2508:                num[i],i,s1,s2,mi,mw[mi][i],dh[mi][i],exp(lli),weight[i],
                   2509:                2*weight[i]*lli,out[s1][s2],savm[s1][s2]);
                   2510:        for(k=1,llt=0.,l=0.; k<=nlstate; k++){
                   2511:          llt +=ll[k]*gipmx/gsw;
                   2512:          fprintf(ficresilk," %10.6f",-ll[k]*gipmx/gsw);
                   2513:        }
                   2514:        fprintf(ficresilk," %10.6f\n", -llt);
                   2515:       }
                   2516:     } /* end of wave */
                   2517:   } /* end of individual */
                   2518:   for(k=1,l=0.; k<=nlstate; k++) l += ll[k];
                   2519:   /* printf("l1=%f l2=%f ",ll[1],ll[2]); */
                   2520:   l= l*ipmx/sw; /* To get the same order of magnitude as if weight=1 for every body */
                   2521:   if(globpr==0){ /* First time we count the contributions and weights */
                   2522:     gipmx=ipmx;
                   2523:     gsw=sw;
                   2524:   }
                   2525:   return -l;
                   2526: }
                   2527: 
                   2528: 
                   2529: /*************** function likelione ***********/
                   2530: void likelione(FILE *ficres,double p[], int npar, int nlstate, int *globpri, long *ipmx, double *sw, double *fretone, double (*funcone)(double []))
                   2531: {
                   2532:   /* This routine should help understanding what is done with 
                   2533:      the selection of individuals/waves and
                   2534:      to check the exact contribution to the likelihood.
                   2535:      Plotting could be done.
                   2536:    */
                   2537:   int k;
                   2538: 
                   2539:   if(*globpri !=0){ /* Just counts and sums, no printings */
                   2540:     strcpy(fileresilk,"ilk"); 
                   2541:     strcat(fileresilk,fileres);
                   2542:     if((ficresilk=fopen(fileresilk,"w"))==NULL) {
                   2543:       printf("Problem with resultfile: %s\n", fileresilk);
                   2544:       fprintf(ficlog,"Problem with resultfile: %s\n", fileresilk);
                   2545:     }
                   2546:     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");
                   2547:     fprintf(ficresilk, "#num_i i s1 s2 mi mw dh likeli weight 2wlli out sav ");
                   2548:     /*         i,s1,s2,mi,mw[mi][i],dh[mi][i],exp(lli),weight[i],2*weight[i]*lli,out[s1][s2],savm[s1][s2]); */
                   2549:     for(k=1; k<=nlstate; k++) 
                   2550:       fprintf(ficresilk," -2*gipw/gsw*weight*ll[%d]++",k);
                   2551:     fprintf(ficresilk," -2*gipw/gsw*weight*ll(total)\n");
                   2552:   }
                   2553: 
                   2554:   *fretone=(*funcone)(p);
                   2555:   if(*globpri !=0){
                   2556:     fclose(ficresilk);
                   2557:     fprintf(fichtm,"\n<br>File of contributions to the likelihood: <a href=\"%s\">%s</a><br>\n",subdirf(fileresilk),subdirf(fileresilk));
                   2558:     fflush(fichtm); 
                   2559:   } 
                   2560:   return;
                   2561: }
                   2562: 
                   2563: 
                   2564: /*********** Maximum Likelihood Estimation ***************/
                   2565: 
                   2566: void mlikeli(FILE *ficres,double p[], int npar, int ncovmodel, int nlstate, double ftol, double (*func)(double []))
                   2567: {
1.165     brouard  2568:   int i,j, iter=0;
1.126     brouard  2569:   double **xi;
                   2570:   double fret;
                   2571:   double fretone; /* Only one call to likelihood */
                   2572:   /*  char filerespow[FILENAMELENGTH];*/
1.162     brouard  2573: 
                   2574: #ifdef NLOPT
                   2575:   int creturn;
                   2576:   nlopt_opt opt;
                   2577:   /* double lb[9] = { -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL }; /\* lower bounds *\/ */
                   2578:   double *lb;
                   2579:   double minf; /* the minimum objective value, upon return */
                   2580:   double * p1; /* Shifted parameters from 0 instead of 1 */
                   2581:   myfunc_data dinst, *d = &dinst;
                   2582: #endif
                   2583: 
                   2584: 
1.126     brouard  2585:   xi=matrix(1,npar,1,npar);
                   2586:   for (i=1;i<=npar;i++)
                   2587:     for (j=1;j<=npar;j++)
                   2588:       xi[i][j]=(i==j ? 1.0 : 0.0);
                   2589:   printf("Powell\n");  fprintf(ficlog,"Powell\n");
                   2590:   strcpy(filerespow,"pow"); 
                   2591:   strcat(filerespow,fileres);
                   2592:   if((ficrespow=fopen(filerespow,"w"))==NULL) {
                   2593:     printf("Problem with resultfile: %s\n", filerespow);
                   2594:     fprintf(ficlog,"Problem with resultfile: %s\n", filerespow);
                   2595:   }
                   2596:   fprintf(ficrespow,"# Powell\n# iter -2*LL");
                   2597:   for (i=1;i<=nlstate;i++)
                   2598:     for(j=1;j<=nlstate+ndeath;j++)
                   2599:       if(j!=i)fprintf(ficrespow," p%1d%1d",i,j);
                   2600:   fprintf(ficrespow,"\n");
1.162     brouard  2601: #ifdef POWELL
1.126     brouard  2602:   powell(p,xi,npar,ftol,&iter,&fret,func);
1.162     brouard  2603: #endif
1.126     brouard  2604: 
1.162     brouard  2605: #ifdef NLOPT
                   2606: #ifdef NEWUOA
                   2607:   opt = nlopt_create(NLOPT_LN_NEWUOA,npar);
                   2608: #else
                   2609:   opt = nlopt_create(NLOPT_LN_BOBYQA,npar);
                   2610: #endif
                   2611:   lb=vector(0,npar-1);
                   2612:   for (i=0;i<npar;i++) lb[i]= -HUGE_VAL;
                   2613:   nlopt_set_lower_bounds(opt, lb);
                   2614:   nlopt_set_initial_step1(opt, 0.1);
                   2615:   
                   2616:   p1= (p+1); /*  p *(p+1)@8 and p *(p1)@8 are equal p1[0]=p[1] */
                   2617:   d->function = func;
                   2618:   printf(" Func %.12lf \n",myfunc(npar,p1,NULL,d));
                   2619:   nlopt_set_min_objective(opt, myfunc, d);
                   2620:   nlopt_set_xtol_rel(opt, ftol);
                   2621:   if ((creturn=nlopt_optimize(opt, p1, &minf)) < 0) {
                   2622:     printf("nlopt failed! %d\n",creturn); 
                   2623:   }
                   2624:   else {
                   2625:     printf("found minimum after %d evaluations (NLOPT=%d)\n", countcallfunc ,NLOPT);
                   2626:     printf("found minimum at f(%g,%g) = %0.10g\n", p[0], p[1], minf);
                   2627:     iter=1; /* not equal */
                   2628:   }
                   2629:   nlopt_destroy(opt);
                   2630: #endif
1.126     brouard  2631:   free_matrix(xi,1,npar,1,npar);
                   2632:   fclose(ficrespow);
1.180     brouard  2633:   printf("#Number of iterations & function calls = %d & %d, -2 Log likelihood = %.12f\n",iter, countcallfunc,func(p));
                   2634:   fprintf(ficlog,"#Number of iterations & function calls = %d & %d, -2 Log likelihood = %.12f\n",iter, countcallfunc,func(p));
                   2635:   fprintf(ficres,"#Number of iterations & function calls = %d & %d, -2 Log likelihood = %.12f\n",iter, countcallfunc,func(p));
1.126     brouard  2636: 
                   2637: }
                   2638: 
                   2639: /**** Computes Hessian and covariance matrix ***/
                   2640: void hesscov(double **matcov, double p[], int npar, double delti[], double ftolhess, double (*func)(double []))
                   2641: {
                   2642:   double  **a,**y,*x,pd;
                   2643:   double **hess;
1.164     brouard  2644:   int i, j;
1.126     brouard  2645:   int *indx;
                   2646: 
                   2647:   double hessii(double p[], double delta, int theta, double delti[],double (*func)(double []),int npar);
                   2648:   double hessij(double p[], double delti[], int i, int j,double (*func)(double []),int npar);
                   2649:   void lubksb(double **a, int npar, int *indx, double b[]) ;
                   2650:   void ludcmp(double **a, int npar, int *indx, double *d) ;
                   2651:   double gompertz(double p[]);
                   2652:   hess=matrix(1,npar,1,npar);
                   2653: 
                   2654:   printf("\nCalculation of the hessian matrix. Wait...\n");
                   2655:   fprintf(ficlog,"\nCalculation of the hessian matrix. Wait...\n");
                   2656:   for (i=1;i<=npar;i++){
                   2657:     printf("%d",i);fflush(stdout);
                   2658:     fprintf(ficlog,"%d",i);fflush(ficlog);
                   2659:    
                   2660:      hess[i][i]=hessii(p,ftolhess,i,delti,func,npar);
                   2661:     
                   2662:     /*  printf(" %f ",p[i]);
                   2663:        printf(" %lf %lf %lf",hess[i][i],ftolhess,delti[i]);*/
                   2664:   }
                   2665:   
                   2666:   for (i=1;i<=npar;i++) {
                   2667:     for (j=1;j<=npar;j++)  {
                   2668:       if (j>i) { 
                   2669:        printf(".%d%d",i,j);fflush(stdout);
                   2670:        fprintf(ficlog,".%d%d",i,j);fflush(ficlog);
                   2671:        hess[i][j]=hessij(p,delti,i,j,func,npar);
                   2672:        
                   2673:        hess[j][i]=hess[i][j];    
                   2674:        /*printf(" %lf ",hess[i][j]);*/
                   2675:       }
                   2676:     }
                   2677:   }
                   2678:   printf("\n");
                   2679:   fprintf(ficlog,"\n");
                   2680: 
                   2681:   printf("\nInverting the hessian to get the covariance matrix. Wait...\n");
                   2682:   fprintf(ficlog,"\nInverting the hessian to get the covariance matrix. Wait...\n");
                   2683:   
                   2684:   a=matrix(1,npar,1,npar);
                   2685:   y=matrix(1,npar,1,npar);
                   2686:   x=vector(1,npar);
                   2687:   indx=ivector(1,npar);
                   2688:   for (i=1;i<=npar;i++)
                   2689:     for (j=1;j<=npar;j++) a[i][j]=hess[i][j];
                   2690:   ludcmp(a,npar,indx,&pd);
                   2691: 
                   2692:   for (j=1;j<=npar;j++) {
                   2693:     for (i=1;i<=npar;i++) x[i]=0;
                   2694:     x[j]=1;
                   2695:     lubksb(a,npar,indx,x);
                   2696:     for (i=1;i<=npar;i++){ 
                   2697:       matcov[i][j]=x[i];
                   2698:     }
                   2699:   }
                   2700: 
                   2701:   printf("\n#Hessian matrix#\n");
                   2702:   fprintf(ficlog,"\n#Hessian matrix#\n");
                   2703:   for (i=1;i<=npar;i++) { 
                   2704:     for (j=1;j<=npar;j++) { 
                   2705:       printf("%.3e ",hess[i][j]);
                   2706:       fprintf(ficlog,"%.3e ",hess[i][j]);
                   2707:     }
                   2708:     printf("\n");
                   2709:     fprintf(ficlog,"\n");
                   2710:   }
                   2711: 
                   2712:   /* Recompute Inverse */
                   2713:   for (i=1;i<=npar;i++)
                   2714:     for (j=1;j<=npar;j++) a[i][j]=matcov[i][j];
                   2715:   ludcmp(a,npar,indx,&pd);
                   2716: 
                   2717:   /*  printf("\n#Hessian matrix recomputed#\n");
                   2718: 
                   2719:   for (j=1;j<=npar;j++) {
                   2720:     for (i=1;i<=npar;i++) x[i]=0;
                   2721:     x[j]=1;
                   2722:     lubksb(a,npar,indx,x);
                   2723:     for (i=1;i<=npar;i++){ 
                   2724:       y[i][j]=x[i];
                   2725:       printf("%.3e ",y[i][j]);
                   2726:       fprintf(ficlog,"%.3e ",y[i][j]);
                   2727:     }
                   2728:     printf("\n");
                   2729:     fprintf(ficlog,"\n");
                   2730:   }
                   2731:   */
                   2732: 
                   2733:   free_matrix(a,1,npar,1,npar);
                   2734:   free_matrix(y,1,npar,1,npar);
                   2735:   free_vector(x,1,npar);
                   2736:   free_ivector(indx,1,npar);
                   2737:   free_matrix(hess,1,npar,1,npar);
                   2738: 
                   2739: 
                   2740: }
                   2741: 
                   2742: /*************** hessian matrix ****************/
                   2743: double hessii(double x[], double delta, int theta, double delti[], double (*func)(double []), int npar)
                   2744: {
                   2745:   int i;
                   2746:   int l=1, lmax=20;
                   2747:   double k1,k2;
1.132     brouard  2748:   double p2[MAXPARM+1]; /* identical to x */
1.126     brouard  2749:   double res;
                   2750:   double delt=0.0001, delts, nkhi=10.,nkhif=1., khi=1.e-4;
                   2751:   double fx;
                   2752:   int k=0,kmax=10;
                   2753:   double l1;
                   2754: 
                   2755:   fx=func(x);
                   2756:   for (i=1;i<=npar;i++) p2[i]=x[i];
1.145     brouard  2757:   for(l=0 ; l <=lmax; l++){  /* Enlarging the zone around the Maximum */
1.126     brouard  2758:     l1=pow(10,l);
                   2759:     delts=delt;
                   2760:     for(k=1 ; k <kmax; k=k+1){
                   2761:       delt = delta*(l1*k);
                   2762:       p2[theta]=x[theta] +delt;
1.145     brouard  2763:       k1=func(p2)-fx;   /* Might be negative if too close to the theoretical maximum */
1.126     brouard  2764:       p2[theta]=x[theta]-delt;
                   2765:       k2=func(p2)-fx;
                   2766:       /*res= (k1-2.0*fx+k2)/delt/delt; */
                   2767:       res= (k1+k2)/delt/delt/2.; /* Divided by because L and not 2*L */
                   2768:       
1.132     brouard  2769: #ifdef DEBUGHESS
1.126     brouard  2770:       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);
                   2771:       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);
                   2772: #endif
                   2773:       /*if(fabs(k1-2.0*fx+k2) <1.e-13){ */
                   2774:       if((k1 <khi/nkhi/2.) || (k2 <khi/nkhi/2.)){
                   2775:        k=kmax;
                   2776:       }
                   2777:       else if((k1 >khi/nkhif) || (k2 >khi/nkhif)){ /* Keeps lastvalue before 3.84/2 KHI2 5% 1d.f. */
1.164     brouard  2778:        k=kmax; l=lmax*10;
1.126     brouard  2779:       }
                   2780:       else if((k1 >khi/nkhi) || (k2 >khi/nkhi)){ 
                   2781:        delts=delt;
                   2782:       }
                   2783:     }
                   2784:   }
                   2785:   delti[theta]=delts;
                   2786:   return res; 
                   2787:   
                   2788: }
                   2789: 
                   2790: double hessij( double x[], double delti[], int thetai,int thetaj,double (*func)(double []),int npar)
                   2791: {
                   2792:   int i;
1.164     brouard  2793:   int l=1, lmax=20;
1.126     brouard  2794:   double k1,k2,k3,k4,res,fx;
1.132     brouard  2795:   double p2[MAXPARM+1];
1.126     brouard  2796:   int k;
                   2797: 
                   2798:   fx=func(x);
                   2799:   for (k=1; k<=2; k++) {
                   2800:     for (i=1;i<=npar;i++) p2[i]=x[i];
                   2801:     p2[thetai]=x[thetai]+delti[thetai]/k;
                   2802:     p2[thetaj]=x[thetaj]+delti[thetaj]/k;
                   2803:     k1=func(p2)-fx;
                   2804:   
                   2805:     p2[thetai]=x[thetai]+delti[thetai]/k;
                   2806:     p2[thetaj]=x[thetaj]-delti[thetaj]/k;
                   2807:     k2=func(p2)-fx;
                   2808:   
                   2809:     p2[thetai]=x[thetai]-delti[thetai]/k;
                   2810:     p2[thetaj]=x[thetaj]+delti[thetaj]/k;
                   2811:     k3=func(p2)-fx;
                   2812:   
                   2813:     p2[thetai]=x[thetai]-delti[thetai]/k;
                   2814:     p2[thetaj]=x[thetaj]-delti[thetaj]/k;
                   2815:     k4=func(p2)-fx;
                   2816:     res=(k1-k2-k3+k4)/4.0/delti[thetai]*k/delti[thetaj]*k/2.; /* Because of L not 2*L */
                   2817: #ifdef DEBUG
                   2818:     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);
                   2819:     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);
                   2820: #endif
                   2821:   }
                   2822:   return res;
                   2823: }
                   2824: 
                   2825: /************** Inverse of matrix **************/
                   2826: void ludcmp(double **a, int n, int *indx, double *d) 
                   2827: { 
                   2828:   int i,imax,j,k; 
                   2829:   double big,dum,sum,temp; 
                   2830:   double *vv; 
                   2831:  
                   2832:   vv=vector(1,n); 
                   2833:   *d=1.0; 
                   2834:   for (i=1;i<=n;i++) { 
                   2835:     big=0.0; 
                   2836:     for (j=1;j<=n;j++) 
                   2837:       if ((temp=fabs(a[i][j])) > big) big=temp; 
                   2838:     if (big == 0.0) nrerror("Singular matrix in routine ludcmp"); 
                   2839:     vv[i]=1.0/big; 
                   2840:   } 
                   2841:   for (j=1;j<=n;j++) { 
                   2842:     for (i=1;i<j;i++) { 
                   2843:       sum=a[i][j]; 
                   2844:       for (k=1;k<i;k++) sum -= a[i][k]*a[k][j]; 
                   2845:       a[i][j]=sum; 
                   2846:     } 
                   2847:     big=0.0; 
                   2848:     for (i=j;i<=n;i++) { 
                   2849:       sum=a[i][j]; 
                   2850:       for (k=1;k<j;k++) 
                   2851:        sum -= a[i][k]*a[k][j]; 
                   2852:       a[i][j]=sum; 
                   2853:       if ( (dum=vv[i]*fabs(sum)) >= big) { 
                   2854:        big=dum; 
                   2855:        imax=i; 
                   2856:       } 
                   2857:     } 
                   2858:     if (j != imax) { 
                   2859:       for (k=1;k<=n;k++) { 
                   2860:        dum=a[imax][k]; 
                   2861:        a[imax][k]=a[j][k]; 
                   2862:        a[j][k]=dum; 
                   2863:       } 
                   2864:       *d = -(*d); 
                   2865:       vv[imax]=vv[j]; 
                   2866:     } 
                   2867:     indx[j]=imax; 
                   2868:     if (a[j][j] == 0.0) a[j][j]=TINY; 
                   2869:     if (j != n) { 
                   2870:       dum=1.0/(a[j][j]); 
                   2871:       for (i=j+1;i<=n;i++) a[i][j] *= dum; 
                   2872:     } 
                   2873:   } 
                   2874:   free_vector(vv,1,n);  /* Doesn't work */
                   2875: ;
                   2876: } 
                   2877: 
                   2878: void lubksb(double **a, int n, int *indx, double b[]) 
                   2879: { 
                   2880:   int i,ii=0,ip,j; 
                   2881:   double sum; 
                   2882:  
                   2883:   for (i=1;i<=n;i++) { 
                   2884:     ip=indx[i]; 
                   2885:     sum=b[ip]; 
                   2886:     b[ip]=b[i]; 
                   2887:     if (ii) 
                   2888:       for (j=ii;j<=i-1;j++) sum -= a[i][j]*b[j]; 
                   2889:     else if (sum) ii=i; 
                   2890:     b[i]=sum; 
                   2891:   } 
                   2892:   for (i=n;i>=1;i--) { 
                   2893:     sum=b[i]; 
                   2894:     for (j=i+1;j<=n;j++) sum -= a[i][j]*b[j]; 
                   2895:     b[i]=sum/a[i][i]; 
                   2896:   } 
                   2897: } 
                   2898: 
                   2899: void pstamp(FILE *fichier)
                   2900: {
                   2901:   fprintf(fichier,"# %s.%s\n#%s\n#%s\n# %s", optionfilefiname,optionfilext,version,fullversion,strstart);
                   2902: }
                   2903: 
                   2904: /************ Frequencies ********************/
                   2905: 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[])
                   2906: {  /* Some frequencies */
                   2907:   
1.164     brouard  2908:   int i, m, jk, j1, bool, z1,j;
1.126     brouard  2909:   int first;
                   2910:   double ***freq; /* Frequencies */
                   2911:   double *pp, **prop;
                   2912:   double pos,posprop, k2, dateintsum=0,k2cpt=0;
                   2913:   char fileresp[FILENAMELENGTH];
                   2914:   
                   2915:   pp=vector(1,nlstate);
                   2916:   prop=matrix(1,nlstate,iagemin,iagemax+3);
                   2917:   strcpy(fileresp,"p");
                   2918:   strcat(fileresp,fileres);
                   2919:   if((ficresp=fopen(fileresp,"w"))==NULL) {
                   2920:     printf("Problem with prevalence resultfile: %s\n", fileresp);
                   2921:     fprintf(ficlog,"Problem with prevalence resultfile: %s\n", fileresp);
                   2922:     exit(0);
                   2923:   }
                   2924:   freq= ma3x(-5,nlstate+ndeath,-5,nlstate+ndeath,iagemin,iagemax+3);
                   2925:   j1=0;
                   2926:   
                   2927:   j=cptcoveff;
                   2928:   if (cptcovn<1) {j=1;ncodemax[1]=1;}
                   2929: 
                   2930:   first=1;
                   2931: 
1.169     brouard  2932:   /* for(k1=1; k1<=j ; k1++){ */  /* Loop on covariates */
                   2933:   /*  for(i1=1; i1<=ncodemax[k1];i1++){ */ /* Now it is 2 */
                   2934:   /*    j1++; */
1.145     brouard  2935:   for (j1 = 1; j1 <= (int) pow(2,cptcoveff); j1++){
1.126     brouard  2936:       /*printf("cptcoveff=%d Tvaraff=%d", cptcoveff,Tvaraff[1]);
                   2937:        scanf("%d", i);*/
                   2938:       for (i=-5; i<=nlstate+ndeath; i++)  
                   2939:        for (jk=-5; jk<=nlstate+ndeath; jk++)  
                   2940:          for(m=iagemin; m <= iagemax+3; m++)
                   2941:            freq[i][jk][m]=0;
1.143     brouard  2942:       
                   2943:       for (i=1; i<=nlstate; i++)  
                   2944:        for(m=iagemin; m <= iagemax+3; m++)
                   2945:          prop[i][m]=0;
1.126     brouard  2946:       
                   2947:       dateintsum=0;
                   2948:       k2cpt=0;
                   2949:       for (i=1; i<=imx; i++) {
                   2950:        bool=1;
1.144     brouard  2951:        if  (cptcovn>0) { /* Filter is here: Must be looked at for model=V1+V2+V3+V4 */
                   2952:          for (z1=1; z1<=cptcoveff; z1++)       
                   2953:             if (covar[Tvaraff[z1]][i]!= nbcode[Tvaraff[z1]][codtab[j1][z1]]){
1.145     brouard  2954:                 /* Tests if the value of each of the covariates of i is equal to filter j1 */
1.144     brouard  2955:               bool=0;
1.145     brouard  2956:               /* 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", 
                   2957:                 bool,i,z1, z1, Tvaraff[z1],i,covar[Tvaraff[z1]][i],j1,z1,codtab[j1][z1],
                   2958:                 j1,z1,nbcode[Tvaraff[z1]][codtab[j1][z1]],j1);*/
1.144     brouard  2959:               /* For j1=7 in V1+V2+V3+V4 = 0 1 1 0 and codtab[7][3]=1 and nbcde[3][?]=1*/
                   2960:             } 
1.126     brouard  2961:        }
1.144     brouard  2962:  
1.126     brouard  2963:        if (bool==1){
                   2964:          for(m=firstpass; m<=lastpass; m++){
                   2965:            k2=anint[m][i]+(mint[m][i]/12.);
                   2966:            /*if ((k2>=dateprev1) && (k2<=dateprev2)) {*/
                   2967:              if(agev[m][i]==0) agev[m][i]=iagemax+1;
                   2968:              if(agev[m][i]==1) agev[m][i]=iagemax+2;
                   2969:              if (s[m][i]>0 && s[m][i]<=nlstate) prop[s[m][i]][(int)agev[m][i]] += weight[i];
                   2970:              if (m<lastpass) {
                   2971:                freq[s[m][i]][s[m+1][i]][(int)agev[m][i]] += weight[i];
                   2972:                freq[s[m][i]][s[m+1][i]][iagemax+3] += weight[i];
                   2973:              }
                   2974:              
                   2975:              if ((agev[m][i]>1) && (agev[m][i]< (iagemax+3))) {
                   2976:                dateintsum=dateintsum+k2;
                   2977:                k2cpt++;
                   2978:              }
                   2979:              /*}*/
                   2980:          }
                   2981:        }
1.145     brouard  2982:       } /* end i */
1.126     brouard  2983:        
                   2984:       /*      fprintf(ficresp, "#Count between %.lf/%.lf/%.lf and %.lf/%.lf/%.lf\n",jprev1, mprev1,anprev1,jprev2, mprev2,anprev2);*/
                   2985:       pstamp(ficresp);
                   2986:       if  (cptcovn>0) {
                   2987:        fprintf(ficresp, "\n#********** Variable "); 
                   2988:        for (z1=1; z1<=cptcoveff; z1++) fprintf(ficresp, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtab[j1][z1]]);
                   2989:        fprintf(ficresp, "**********\n#");
1.143     brouard  2990:        fprintf(ficlog, "\n#********** Variable "); 
                   2991:        for (z1=1; z1<=cptcoveff; z1++) fprintf(ficlog, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtab[j1][z1]]);
                   2992:        fprintf(ficlog, "**********\n#");
1.126     brouard  2993:       }
                   2994:       for(i=1; i<=nlstate;i++) 
                   2995:        fprintf(ficresp, " Age Prev(%d) N(%d) N",i,i);
                   2996:       fprintf(ficresp, "\n");
                   2997:       
                   2998:       for(i=iagemin; i <= iagemax+3; i++){
                   2999:        if(i==iagemax+3){
                   3000:          fprintf(ficlog,"Total");
                   3001:        }else{
                   3002:          if(first==1){
                   3003:            first=0;
                   3004:            printf("See log file for details...\n");
                   3005:          }
                   3006:          fprintf(ficlog,"Age %d", i);
                   3007:        }
                   3008:        for(jk=1; jk <=nlstate ; jk++){
                   3009:          for(m=-1, pp[jk]=0; m <=nlstate+ndeath ; m++)
                   3010:            pp[jk] += freq[jk][m][i]; 
                   3011:        }
                   3012:        for(jk=1; jk <=nlstate ; jk++){
                   3013:          for(m=-1, pos=0; m <=0 ; m++)
                   3014:            pos += freq[jk][m][i];
                   3015:          if(pp[jk]>=1.e-10){
                   3016:            if(first==1){
1.132     brouard  3017:              printf(" %d.=%.0f loss[%d]=%.1f%%",jk,pp[jk],jk,100*pos/pp[jk]);
1.126     brouard  3018:            }
                   3019:            fprintf(ficlog," %d.=%.0f loss[%d]=%.1f%%",jk,pp[jk],jk,100*pos/pp[jk]);
                   3020:          }else{
                   3021:            if(first==1)
                   3022:              printf(" %d.=%.0f loss[%d]=NaNQ%%",jk,pp[jk],jk);
                   3023:            fprintf(ficlog," %d.=%.0f loss[%d]=NaNQ%%",jk,pp[jk],jk);
                   3024:          }
                   3025:        }
                   3026: 
                   3027:        for(jk=1; jk <=nlstate ; jk++){
                   3028:          for(m=0, pp[jk]=0; m <=nlstate+ndeath; m++)
                   3029:            pp[jk] += freq[jk][m][i];
                   3030:        }       
                   3031:        for(jk=1,pos=0,posprop=0; jk <=nlstate ; jk++){
                   3032:          pos += pp[jk];
                   3033:          posprop += prop[jk][i];
                   3034:        }
                   3035:        for(jk=1; jk <=nlstate ; jk++){
                   3036:          if(pos>=1.e-5){
                   3037:            if(first==1)
                   3038:              printf(" %d.=%.0f prev[%d]=%.1f%%",jk,pp[jk],jk,100*pp[jk]/pos);
                   3039:            fprintf(ficlog," %d.=%.0f prev[%d]=%.1f%%",jk,pp[jk],jk,100*pp[jk]/pos);
                   3040:          }else{
                   3041:            if(first==1)
                   3042:              printf(" %d.=%.0f prev[%d]=NaNQ%%",jk,pp[jk],jk);
                   3043:            fprintf(ficlog," %d.=%.0f prev[%d]=NaNQ%%",jk,pp[jk],jk);
                   3044:          }
                   3045:          if( i <= iagemax){
                   3046:            if(pos>=1.e-5){
                   3047:              fprintf(ficresp," %d %.5f %.0f %.0f",i,prop[jk][i]/posprop, prop[jk][i],posprop);
                   3048:              /*probs[i][jk][j1]= pp[jk]/pos;*/
                   3049:              /*printf("\ni=%d jk=%d j1=%d %.5f %.0f %.0f %f",i,jk,j1,pp[jk]/pos, pp[jk],pos,probs[i][jk][j1]);*/
                   3050:            }
                   3051:            else
                   3052:              fprintf(ficresp," %d NaNq %.0f %.0f",i,prop[jk][i],posprop);
                   3053:          }
                   3054:        }
                   3055:        
                   3056:        for(jk=-1; jk <=nlstate+ndeath; jk++)
                   3057:          for(m=-1; m <=nlstate+ndeath; m++)
                   3058:            if(freq[jk][m][i] !=0 ) {
                   3059:            if(first==1)
                   3060:              printf(" %d%d=%.0f",jk,m,freq[jk][m][i]);
                   3061:              fprintf(ficlog," %d%d=%.0f",jk,m,freq[jk][m][i]);
                   3062:            }
                   3063:        if(i <= iagemax)
                   3064:          fprintf(ficresp,"\n");
                   3065:        if(first==1)
                   3066:          printf("Others in log...\n");
                   3067:        fprintf(ficlog,"\n");
                   3068:       }
1.145     brouard  3069:       /*}*/
1.126     brouard  3070:   }
                   3071:   dateintmean=dateintsum/k2cpt; 
                   3072:  
                   3073:   fclose(ficresp);
                   3074:   free_ma3x(freq,-5,nlstate+ndeath,-5,nlstate+ndeath, iagemin, iagemax+3);
                   3075:   free_vector(pp,1,nlstate);
                   3076:   free_matrix(prop,1,nlstate,iagemin, iagemax+3);
                   3077:   /* End of Freq */
                   3078: }
                   3079: 
                   3080: /************ Prevalence ********************/
                   3081: 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)
                   3082: {  
                   3083:   /* Compute observed prevalence between dateprev1 and dateprev2 by counting the number of people
                   3084:      in each health status at the date of interview (if between dateprev1 and dateprev2).
                   3085:      We still use firstpass and lastpass as another selection.
                   3086:   */
                   3087:  
1.164     brouard  3088:   int i, m, jk, j1, bool, z1,j;
                   3089: 
                   3090:   double **prop;
                   3091:   double posprop; 
1.126     brouard  3092:   double  y2; /* in fractional years */
                   3093:   int iagemin, iagemax;
1.145     brouard  3094:   int first; /** to stop verbosity which is redirected to log file */
1.126     brouard  3095: 
                   3096:   iagemin= (int) agemin;
                   3097:   iagemax= (int) agemax;
                   3098:   /*pp=vector(1,nlstate);*/
                   3099:   prop=matrix(1,nlstate,iagemin,iagemax+3); 
                   3100:   /*  freq=ma3x(-1,nlstate+ndeath,-1,nlstate+ndeath,iagemin,iagemax+3);*/
                   3101:   j1=0;
                   3102:   
1.145     brouard  3103:   /*j=cptcoveff;*/
1.126     brouard  3104:   if (cptcovn<1) {j=1;ncodemax[1]=1;}
                   3105:   
1.145     brouard  3106:   first=1;
                   3107:   for(j1=1; j1<= (int) pow(2,cptcoveff);j1++){
                   3108:     /*for(i1=1; i1<=ncodemax[k1];i1++){
                   3109:       j1++;*/
1.126     brouard  3110:       
                   3111:       for (i=1; i<=nlstate; i++)  
                   3112:        for(m=iagemin; m <= iagemax+3; m++)
                   3113:          prop[i][m]=0.0;
                   3114:      
                   3115:       for (i=1; i<=imx; i++) { /* Each individual */
                   3116:        bool=1;
                   3117:        if  (cptcovn>0) {
                   3118:          for (z1=1; z1<=cptcoveff; z1++) 
                   3119:            if (covar[Tvaraff[z1]][i]!= nbcode[Tvaraff[z1]][codtab[j1][z1]]) 
                   3120:              bool=0;
                   3121:        } 
                   3122:        if (bool==1) { 
                   3123:          for(m=firstpass; m<=lastpass; m++){/* Other selection (we can limit to certain interviews*/
                   3124:            y2=anint[m][i]+(mint[m][i]/12.); /* Fractional date in year */
                   3125:            if ((y2>=dateprev1) && (y2<=dateprev2)) { /* Here is the main selection (fractional years) */
                   3126:              if(agev[m][i]==0) agev[m][i]=iagemax+1;
                   3127:              if(agev[m][i]==1) agev[m][i]=iagemax+2;
                   3128:              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); 
                   3129:              if (s[m][i]>0 && s[m][i]<=nlstate) { 
                   3130:                /*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]]);*/
                   3131:                prop[s[m][i]][(int)agev[m][i]] += weight[i];
                   3132:                prop[s[m][i]][iagemax+3] += weight[i]; 
                   3133:              } 
                   3134:            }
                   3135:          } /* end selection of waves */
                   3136:        }
                   3137:       }
                   3138:       for(i=iagemin; i <= iagemax+3; i++){  
                   3139:        for(jk=1,posprop=0; jk <=nlstate ; jk++) { 
                   3140:          posprop += prop[jk][i]; 
                   3141:        } 
1.145     brouard  3142:        
1.126     brouard  3143:        for(jk=1; jk <=nlstate ; jk++){     
                   3144:          if( i <=  iagemax){ 
                   3145:            if(posprop>=1.e-5){ 
                   3146:              probs[i][jk][j1]= prop[jk][i]/posprop;
1.145     brouard  3147:            } else{
                   3148:              if(first==1){
                   3149:                first=0;
                   3150:                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]);
                   3151:              }
                   3152:            }
1.126     brouard  3153:          } 
                   3154:        }/* end jk */ 
                   3155:       }/* end i */ 
1.145     brouard  3156:     /*} *//* end i1 */
                   3157:   } /* end j1 */
1.126     brouard  3158:   
                   3159:   /*  free_ma3x(freq,-1,nlstate+ndeath,-1,nlstate+ndeath, iagemin, iagemax+3);*/
                   3160:   /*free_vector(pp,1,nlstate);*/
                   3161:   free_matrix(prop,1,nlstate, iagemin,iagemax+3);
                   3162: }  /* End of prevalence */
                   3163: 
                   3164: /************* Waves Concatenation ***************/
                   3165: 
                   3166: 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)
                   3167: {
                   3168:   /* Concatenates waves: wav[i] is the number of effective (useful waves) of individual i.
                   3169:      Death is a valid wave (if date is known).
                   3170:      mw[mi][i] is the mi (mi=1 to wav[i])  effective wave of individual i
                   3171:      dh[m][i] or dh[mw[mi][i]][i] is the delay between two effective waves m=mw[mi][i]
                   3172:      and mw[mi+1][i]. dh depends on stepm.
                   3173:      */
                   3174: 
                   3175:   int i, mi, m;
                   3176:   /* int j, k=0,jk, ju, jl,jmin=1e+5, jmax=-1;
                   3177:      double sum=0., jmean=0.;*/
                   3178:   int first;
                   3179:   int j, k=0,jk, ju, jl;
                   3180:   double sum=0.;
                   3181:   first=0;
1.164     brouard  3182:   jmin=100000;
1.126     brouard  3183:   jmax=-1;
                   3184:   jmean=0.;
                   3185:   for(i=1; i<=imx; i++){
                   3186:     mi=0;
                   3187:     m=firstpass;
                   3188:     while(s[m][i] <= nlstate){
                   3189:       if(s[m][i]>=1 || s[m][i]==-2 || s[m][i]==-4 || s[m][i]==-5)
                   3190:        mw[++mi][i]=m;
                   3191:       if(m >=lastpass)
                   3192:        break;
                   3193:       else
                   3194:        m++;
                   3195:     }/* end while */
                   3196:     if (s[m][i] > nlstate){
                   3197:       mi++;    /* Death is another wave */
                   3198:       /* if(mi==0)  never been interviewed correctly before death */
                   3199:         /* Only death is a correct wave */
                   3200:       mw[mi][i]=m;
                   3201:     }
                   3202: 
                   3203:     wav[i]=mi;
                   3204:     if(mi==0){
                   3205:       nbwarn++;
                   3206:       if(first==0){
                   3207:        printf("Warning! No valid information for individual %ld line=%d (skipped) and may be others, see log file\n",num[i],i);
                   3208:        first=1;
                   3209:       }
                   3210:       if(first==1){
                   3211:        fprintf(ficlog,"Warning! No valid information for individual %ld line=%d (skipped)\n",num[i],i);
                   3212:       }
                   3213:     } /* end mi==0 */
                   3214:   } /* End individuals */
                   3215: 
                   3216:   for(i=1; i<=imx; i++){
                   3217:     for(mi=1; mi<wav[i];mi++){
                   3218:       if (stepm <=0)
                   3219:        dh[mi][i]=1;
                   3220:       else{
                   3221:        if (s[mw[mi+1][i]][i] > nlstate) { /* A death */
                   3222:          if (agedc[i] < 2*AGESUP) {
                   3223:            j= rint(agedc[i]*12-agev[mw[mi][i]][i]*12); 
                   3224:            if(j==0) j=1;  /* Survives at least one month after exam */
                   3225:            else if(j<0){
                   3226:              nberr++;
                   3227:              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]);
                   3228:              j=1; /* Temporary Dangerous patch */
                   3229:              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);
                   3230:              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]);
                   3231:              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);
                   3232:            }
                   3233:            k=k+1;
                   3234:            if (j >= jmax){
                   3235:              jmax=j;
                   3236:              ijmax=i;
                   3237:            }
                   3238:            if (j <= jmin){
                   3239:              jmin=j;
                   3240:              ijmin=i;
                   3241:            }
                   3242:            sum=sum+j;
                   3243:            /*if (j<0) printf("j=%d num=%d \n",j,i);*/
                   3244:            /*    printf("%d %d %d %d\n", s[mw[mi][i]][i] ,s[mw[mi+1][i]][i],j,i);*/
                   3245:          }
                   3246:        }
                   3247:        else{
                   3248:          j= rint( (agev[mw[mi+1][i]][i]*12 - agev[mw[mi][i]][i]*12));
                   3249: /*       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]); */
                   3250: 
                   3251:          k=k+1;
                   3252:          if (j >= jmax) {
                   3253:            jmax=j;
                   3254:            ijmax=i;
                   3255:          }
                   3256:          else if (j <= jmin){
                   3257:            jmin=j;
                   3258:            ijmin=i;
                   3259:          }
                   3260:          /*        if (j<10) printf("j=%d jmin=%d num=%d ",j,jmin,i); */
                   3261:          /*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]);*/
                   3262:          if(j<0){
                   3263:            nberr++;
                   3264:            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]);
                   3265:            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]);
                   3266:          }
                   3267:          sum=sum+j;
                   3268:        }
                   3269:        jk= j/stepm;
                   3270:        jl= j -jk*stepm;
                   3271:        ju= j -(jk+1)*stepm;
                   3272:        if(mle <=1){ /* only if we use a the linear-interpoloation pseudo-likelihood */
                   3273:          if(jl==0){
                   3274:            dh[mi][i]=jk;
                   3275:            bh[mi][i]=0;
                   3276:          }else{ /* We want a negative bias in order to only have interpolation ie
1.136     brouard  3277:                  * to avoid the price of an extra matrix product in likelihood */
1.126     brouard  3278:            dh[mi][i]=jk+1;
                   3279:            bh[mi][i]=ju;
                   3280:          }
                   3281:        }else{
                   3282:          if(jl <= -ju){
                   3283:            dh[mi][i]=jk;
                   3284:            bh[mi][i]=jl;       /* bias is positive if real duration
                   3285:                                 * is higher than the multiple of stepm and negative otherwise.
                   3286:                                 */
                   3287:          }
                   3288:          else{
                   3289:            dh[mi][i]=jk+1;
                   3290:            bh[mi][i]=ju;
                   3291:          }
                   3292:          if(dh[mi][i]==0){
                   3293:            dh[mi][i]=1; /* At least one step */
                   3294:            bh[mi][i]=ju; /* At least one step */
                   3295:            /*  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);*/
                   3296:          }
                   3297:        } /* end if mle */
                   3298:       }
                   3299:     } /* end wave */
                   3300:   }
                   3301:   jmean=sum/k;
                   3302:   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  3303:   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  3304:  }
                   3305: 
                   3306: /*********** Tricode ****************************/
1.145     brouard  3307: void tricode(int *Tvar, int **nbcode, int imx, int *Ndum)
1.126     brouard  3308: {
1.144     brouard  3309:   /**< Uses cptcovn+2*cptcovprod as the number of covariates */
                   3310:   /*     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  3311:    * Boring subroutine which should only output nbcode[Tvar[j]][k]
1.145     brouard  3312:    * Tvar[5] in V2+V1+V3*age+V2*V4 is 2 (V2)
1.169     brouard  3313:    * nbcode[Tvar[j]][1]= 
1.144     brouard  3314:   */
1.130     brouard  3315: 
1.145     brouard  3316:   int ij=1, k=0, j=0, i=0, maxncov=NCOVMAX;
1.136     brouard  3317:   int modmaxcovj=0; /* Modality max of covariates j */
1.145     brouard  3318:   int cptcode=0; /* Modality max of covariates j */
                   3319:   int modmincovj=0; /* Modality min of covariates j */
                   3320: 
                   3321: 
1.126     brouard  3322:   cptcoveff=0; 
                   3323:  
1.144     brouard  3324:   for (k=1; k <= maxncov; k++) ncodemax[k]=0; /* Horrible constant again replaced by NCOVMAX */
1.126     brouard  3325: 
1.145     brouard  3326:   /* Loop on covariates without age and products */
1.186     brouard  3327:   for (j=1; j<=(cptcovs); j++) { /* From model V1 + V2*age+ V3 + V3*V4 keeps V1 + V3 = 2 only */
1.192     brouard  3328:     for (k=-1; k < maxncov; k++) Ndum[k]=0;
1.186     brouard  3329:     for (i=1; i<=imx; i++) { /* Loop on individuals: reads the data file to get the maximum value of the 
1.136     brouard  3330:                               modality of this covariate Vj*/ 
1.145     brouard  3331:       ij=(int)(covar[Tvar[j]][i]); /* ij=0 or 1 or -1. Value of the covariate Tvar[j] for individual i
                   3332:                                    * If product of Vn*Vm, still boolean *:
                   3333:                                    * If it was coded 1, 2, 3, 4 should be splitted into 3 boolean variables
                   3334:                                    * 1 => 0 0 0, 2 => 0 0 1, 3 => 0 1 1, 4=1 0 0   */
                   3335:       /* Finds for covariate j, n=Tvar[j] of Vn . ij is the
1.136     brouard  3336:                                      modality of the nth covariate of individual i. */
1.145     brouard  3337:       if (ij > modmaxcovj)
                   3338:         modmaxcovj=ij; 
                   3339:       else if (ij < modmincovj) 
                   3340:        modmincovj=ij; 
                   3341:       if ((ij < -1) && (ij > NCOVMAX)){
                   3342:        printf( "Error: minimal is less than -1 or maximal is bigger than %d. Exiting. \n", NCOVMAX );
                   3343:        exit(1);
                   3344:       }else
1.136     brouard  3345:       Ndum[ij]++; /*counts and stores the occurence of this modality 0, 1, -1*/
1.145     brouard  3346:       /*  If coded 1, 2, 3 , counts the number of 1 Ndum[1], number of 2, Ndum[2], etc */
1.126     brouard  3347:       /*printf("i=%d ij=%d Ndum[ij]=%d imx=%d",i,ij,Ndum[ij],imx);*/
1.136     brouard  3348:       /* getting the maximum value of the modality of the covariate
                   3349:         (should be 0 or 1 now) Tvar[j]. If V=sex and male is coded 0 and
                   3350:         female is 1, then modmaxcovj=1.*/
1.192     brouard  3351:     } /* end for loop on individuals i */
1.145     brouard  3352:     printf(" Minimal and maximal values of %d th covariate V%d: min=%d max=%d \n", j, Tvar[j], modmincovj, modmaxcovj);
1.192     brouard  3353:     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  3354:     cptcode=modmaxcovj;
1.137     brouard  3355:     /* Ndum[0] = frequency of 0 for model-covariate j, Ndum[1] frequency of 1 etc. */
1.145     brouard  3356:    /*for (i=0; i<=cptcode; i++) {*/
1.192     brouard  3357:     for (k=modmincovj;  k<=modmaxcovj; k++) { /* k=-1 ? 0 and 1*//* For each value k of the modality of model-cov j */
                   3358:       printf("Frequencies of covariates %d ie V%d with value %d: %d\n", j, Tvar[j], k, Ndum[k]);
                   3359:       fprintf(ficlog, "Frequencies of covariates %d ie V%d with value %d: %d\n", j, Tvar[j], k, Ndum[k]);
                   3360:       if( Ndum[k] != 0 ){ /* Counts if nobody answered modality k ie empty modality, we skip it and reorder */
                   3361:        if( k != -1){
                   3362:          ncodemax[j]++;  /* ncodemax[j]= Number of modalities of the j th
                   3363:                             covariate for which somebody answered excluding 
                   3364:                             undefined. Usually 2: 0 and 1. */
                   3365:        }
                   3366:        ncodemaxwundef[j]++; /* ncodemax[j]= Number of modalities of the j th
                   3367:                             covariate for which somebody answered including 
                   3368:                             undefined. Usually 3: -1, 0 and 1. */
1.145     brouard  3369:       }
                   3370:       /* In fact  ncodemax[j]=2 (dichotom. variables only) but it could be more for
                   3371:         historical reasons: 3 if coded 1, 2, 3 and 4 and Ndum[2]=0 */
1.131     brouard  3372:     } /* Ndum[-1] number of undefined modalities */
1.126     brouard  3373: 
1.136     brouard  3374:     /* j is a covariate, n=Tvar[j] of Vn; Fills nbcode */
1.186     brouard  3375:     /* For covariate j, modalities could be 1, 2, 3, 4, 5, 6, 7. 
                   3376:        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  3377:        modmincovj=3; modmaxcovj = 7;
1.186     brouard  3378:        There are only 3 modalities non empty 3, 6, 7 (or 2 if 27 is too few) : ncodemax[j]=3;
                   3379:        which will be coded 0, 1, 2 which in binary on 2=3-1 digits are 0=00 1=01, 2=10;
                   3380:        defining two dummy variables: variables V1_1 and V1_2.
1.145     brouard  3381:        nbcode[Tvar[j]][ij]=k;
                   3382:        nbcode[Tvar[j]][1]=0;
                   3383:        nbcode[Tvar[j]][2]=1;
                   3384:        nbcode[Tvar[j]][3]=2;
                   3385:     */
1.192     brouard  3386:     ij=0; /* ij is similar to i but can jumps over null modalities */
                   3387:     for (i=modmincovj; i<=modmaxcovj; i++) { /* i= 1 to 2 for dichotomous, or from 1 to 3 or from -1 to 1*/
                   3388:        if (Ndum[i] == 0) { /* If at least one individual responded to this modality k */
                   3389:          break;
                   3390:        }
                   3391:        ij++;
                   3392:        nbcode[Tvar[j]][ij]=i;  /* stores the original modality i in an array nbcode, ij modality from 1 to last non-nul modality.*/
                   3393:        cptcode = ij; /* New max modality for covar j */
                   3394:     } /* end of loop on modality i=-1 to 1 or more */
                   3395:       
                   3396:     /*   for (k=0; k<= cptcode; k++) { /\* k=-1 ? k=0 to 1 *\//\* Could be 1 to 4 *\//\* cptcode=modmaxcovj *\/ */
                   3397:     /*         /\*recode from 0 *\/ */
                   3398:     /*                                      k is a modality. If we have model=V1+V1*sex  */
                   3399:     /*                                      then: nbcode[1][1]=0 ; nbcode[1][2]=1; nbcode[2][1]=0 ; nbcode[2][2]=1; */
                   3400:     /*                                   But if some modality were not used, it is recoded from 0 to a newer modmaxcovj=cptcode *\/ */
                   3401:     /*         } */
                   3402:     /*         /\* cptcode = ij; *\/ /\* New max modality for covar j *\/ */
                   3403:     /*         if (ij > ncodemax[j]) { */
                   3404:     /*           printf( " Error ij=%d > ncodemax[%d]=%d\n", ij, j, ncodemax[j]);  */
                   3405:     /*           fprintf(ficlog, " Error ij=%d > ncodemax[%d]=%d\n", ij, j, ncodemax[j]); */
                   3406:     /*           break; */
                   3407:     /*         } */
                   3408:     /*   }  /\* end of loop on modality k *\/ */
1.137     brouard  3409:   } /* end of loop on model-covariate j. nbcode[Tvarj][1]=0 and nbcode[Tvarj][2]=1 sets the value of covariate j*/  
                   3410:   
1.145     brouard  3411:  for (k=-1; k< maxncov; k++) Ndum[k]=0; 
1.137     brouard  3412:   
1.187     brouard  3413:   for (i=1; i<=ncovmodel-2-nagesqr; i++) { /* -2, cste and age and eventually age*age */ 
1.145     brouard  3414:    /* Listing of all covariables in statement model to see if some covariates appear twice. For example, V1 appears twice in V1+V1*V2.*/ 
                   3415:    ij=Tvar[i]; /* Tvar might be -1 if status was unknown */ 
1.187     brouard  3416:    Ndum[ij]++; /* Might be supersed V1 + V1*age */
1.145     brouard  3417:  } 
1.126     brouard  3418: 
1.192     brouard  3419:  ij=0;
1.145     brouard  3420:  for (i=0; i<=  maxncov-1; i++) { /* modmaxcovj is unknown here. Only Ndum[2(V2),3(age*V3), 5(V3*V2) 6(V1*V4) */
                   3421:    /*printf("Ndum[%d]=%d\n",i, Ndum[i]);*/
1.126     brouard  3422:    if((Ndum[i]!=0) && (i<=ncovcol)){
1.192     brouard  3423:      ij++;
1.145     brouard  3424:      /*printf("diff Ndum[%d]=%d\n",i, Ndum[i]);*/
                   3425:      Tvaraff[ij]=i; /*For printing (unclear) */
1.192     brouard  3426:    }else{
                   3427:        /* Tvaraff[ij]=0; */
                   3428:    }
1.126     brouard  3429:  }
1.192     brouard  3430:  /* ij--; */
1.144     brouard  3431:  cptcoveff=ij; /*Number of total covariates*/
1.145     brouard  3432: 
1.126     brouard  3433: }
                   3434: 
1.145     brouard  3435: 
1.126     brouard  3436: /*********** Health Expectancies ****************/
                   3437: 
1.127     brouard  3438: 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  3439: 
                   3440: {
                   3441:   /* Health expectancies, no variances */
1.164     brouard  3442:   int i, j, nhstepm, hstepm, h, nstepm;
1.126     brouard  3443:   int nhstepma, nstepma; /* Decreasing with age */
                   3444:   double age, agelim, hf;
                   3445:   double ***p3mat;
                   3446:   double eip;
                   3447: 
                   3448:   pstamp(ficreseij);
                   3449:   fprintf(ficreseij,"# (a) Life expectancies by health status at initial age and (b) health expectancies by health status at initial age\n");
                   3450:   fprintf(ficreseij,"# Age");
                   3451:   for(i=1; i<=nlstate;i++){
                   3452:     for(j=1; j<=nlstate;j++){
                   3453:       fprintf(ficreseij," e%1d%1d ",i,j);
                   3454:     }
                   3455:     fprintf(ficreseij," e%1d. ",i);
                   3456:   }
                   3457:   fprintf(ficreseij,"\n");
                   3458: 
                   3459:   
                   3460:   if(estepm < stepm){
                   3461:     printf ("Problem %d lower than %d\n",estepm, stepm);
                   3462:   }
                   3463:   else  hstepm=estepm;   
                   3464:   /* We compute the life expectancy from trapezoids spaced every estepm months
                   3465:    * This is mainly to measure the difference between two models: for example
                   3466:    * if stepm=24 months pijx are given only every 2 years and by summing them
                   3467:    * we are calculating an estimate of the Life Expectancy assuming a linear 
                   3468:    * progression in between and thus overestimating or underestimating according
                   3469:    * to the curvature of the survival function. If, for the same date, we 
                   3470:    * estimate the model with stepm=1 month, we can keep estepm to 24 months
                   3471:    * to compare the new estimate of Life expectancy with the same linear 
                   3472:    * hypothesis. A more precise result, taking into account a more precise
                   3473:    * curvature will be obtained if estepm is as small as stepm. */
                   3474: 
                   3475:   /* For example we decided to compute the life expectancy with the smallest unit */
                   3476:   /* hstepm beeing the number of stepms, if hstepm=1 the length of hstepm is stepm. 
                   3477:      nhstepm is the number of hstepm from age to agelim 
                   3478:      nstepm is the number of stepm from age to agelin. 
                   3479:      Look at hpijx to understand the reason of that which relies in memory size
                   3480:      and note for a fixed period like estepm months */
                   3481:   /* We decided (b) to get a life expectancy respecting the most precise curvature of the
                   3482:      survival function given by stepm (the optimization length). Unfortunately it
                   3483:      means that if the survival funtion is printed only each two years of age and if
                   3484:      you sum them up and add 1 year (area under the trapezoids) you won't get the same 
                   3485:      results. So we changed our mind and took the option of the best precision.
                   3486:   */
                   3487:   hstepm=hstepm/stepm; /* Typically in stepm units, if stepm=6 & estepm=24 , = 24/6 months = 4 */ 
                   3488: 
                   3489:   agelim=AGESUP;
                   3490:   /* If stepm=6 months */
                   3491:     /* Computed by stepm unit matrices, product of hstepm matrices, stored
                   3492:        in an array of nhstepm length: nhstepm=10, hstepm=4, stepm=6 months */
                   3493:     
                   3494: /* nhstepm age range expressed in number of stepm */
                   3495:   nstepm=(int) rint((agelim-bage)*YEARM/stepm); /* Biggest nstepm */
                   3496:   /* Typically if 20 years nstepm = 20*12/6=40 stepm */ 
                   3497:   /* if (stepm >= YEARM) hstepm=1;*/
                   3498:   nhstepm = nstepm/hstepm;/* Expressed in hstepm, typically nhstepm=40/4=10 */
                   3499:   p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   3500: 
                   3501:   for (age=bage; age<=fage; age ++){ 
                   3502:     nstepma=(int) rint((agelim-bage)*YEARM/stepm); /* Biggest nstepm */
                   3503:     /* Typically if 20 years nstepm = 20*12/6=40 stepm */ 
                   3504:     /* if (stepm >= YEARM) hstepm=1;*/
                   3505:     nhstepma = nstepma/hstepm;/* Expressed in hstepm, typically nhstepma=40/4=10 */
                   3506: 
                   3507:     /* If stepm=6 months */
                   3508:     /* Computed by stepm unit matrices, product of hstepma matrices, stored
                   3509:        in an array of nhstepma length: nhstepma=10, hstepm=4, stepm=6 months */
                   3510:     
                   3511:     hpxij(p3mat,nhstepma,age,hstepm,x,nlstate,stepm,oldm, savm, cij);  
                   3512:     
                   3513:     hf=hstepm*stepm/YEARM;  /* Duration of hstepm expressed in year unit. */
                   3514:     
                   3515:     printf("%d|",(int)age);fflush(stdout);
                   3516:     fprintf(ficlog,"%d|",(int)age);fflush(ficlog);
                   3517:     
                   3518:     /* Computing expectancies */
                   3519:     for(i=1; i<=nlstate;i++)
                   3520:       for(j=1; j<=nlstate;j++)
                   3521:        for (h=0, eij[i][j][(int)age]=0; h<=nhstepm-1; h++){
                   3522:          eij[i][j][(int)age] += (p3mat[i][j][h]+p3mat[i][j][h+1])/2.0*hf;
                   3523:          
                   3524:          /* 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]);*/
                   3525: 
                   3526:        }
                   3527: 
                   3528:     fprintf(ficreseij,"%3.0f",age );
                   3529:     for(i=1; i<=nlstate;i++){
                   3530:       eip=0;
                   3531:       for(j=1; j<=nlstate;j++){
                   3532:        eip +=eij[i][j][(int)age];
                   3533:        fprintf(ficreseij,"%9.4f", eij[i][j][(int)age] );
                   3534:       }
                   3535:       fprintf(ficreseij,"%9.4f", eip );
                   3536:     }
                   3537:     fprintf(ficreseij,"\n");
                   3538:     
                   3539:   }
                   3540:   free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   3541:   printf("\n");
                   3542:   fprintf(ficlog,"\n");
                   3543:   
                   3544: }
                   3545: 
1.127     brouard  3546: 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  3547: 
                   3548: {
                   3549:   /* Covariances of health expectancies eij and of total life expectancies according
                   3550:    to initial status i, ei. .
                   3551:   */
                   3552:   int i, j, nhstepm, hstepm, h, nstepm, k, cptj, cptj2, i2, j2, ij, ji;
                   3553:   int nhstepma, nstepma; /* Decreasing with age */
                   3554:   double age, agelim, hf;
                   3555:   double ***p3matp, ***p3matm, ***varhe;
                   3556:   double **dnewm,**doldm;
                   3557:   double *xp, *xm;
                   3558:   double **gp, **gm;
                   3559:   double ***gradg, ***trgradg;
                   3560:   int theta;
                   3561: 
                   3562:   double eip, vip;
                   3563: 
                   3564:   varhe=ma3x(1,nlstate*nlstate,1,nlstate*nlstate,(int) bage, (int) fage);
                   3565:   xp=vector(1,npar);
                   3566:   xm=vector(1,npar);
                   3567:   dnewm=matrix(1,nlstate*nlstate,1,npar);
                   3568:   doldm=matrix(1,nlstate*nlstate,1,nlstate*nlstate);
                   3569:   
                   3570:   pstamp(ficresstdeij);
                   3571:   fprintf(ficresstdeij,"# Health expectancies with standard errors\n");
                   3572:   fprintf(ficresstdeij,"# Age");
                   3573:   for(i=1; i<=nlstate;i++){
                   3574:     for(j=1; j<=nlstate;j++)
                   3575:       fprintf(ficresstdeij," e%1d%1d (SE)",i,j);
                   3576:     fprintf(ficresstdeij," e%1d. ",i);
                   3577:   }
                   3578:   fprintf(ficresstdeij,"\n");
                   3579: 
                   3580:   pstamp(ficrescveij);
                   3581:   fprintf(ficrescveij,"# Subdiagonal matrix of covariances of health expectancies by age: cov(eij,ekl)\n");
                   3582:   fprintf(ficrescveij,"# Age");
                   3583:   for(i=1; i<=nlstate;i++)
                   3584:     for(j=1; j<=nlstate;j++){
                   3585:       cptj= (j-1)*nlstate+i;
                   3586:       for(i2=1; i2<=nlstate;i2++)
                   3587:        for(j2=1; j2<=nlstate;j2++){
                   3588:          cptj2= (j2-1)*nlstate+i2;
                   3589:          if(cptj2 <= cptj)
                   3590:            fprintf(ficrescveij,"  %1d%1d,%1d%1d",i,j,i2,j2);
                   3591:        }
                   3592:     }
                   3593:   fprintf(ficrescveij,"\n");
                   3594:   
                   3595:   if(estepm < stepm){
                   3596:     printf ("Problem %d lower than %d\n",estepm, stepm);
                   3597:   }
                   3598:   else  hstepm=estepm;   
                   3599:   /* We compute the life expectancy from trapezoids spaced every estepm months
                   3600:    * This is mainly to measure the difference between two models: for example
                   3601:    * if stepm=24 months pijx are given only every 2 years and by summing them
                   3602:    * we are calculating an estimate of the Life Expectancy assuming a linear 
                   3603:    * progression in between and thus overestimating or underestimating according
                   3604:    * to the curvature of the survival function. If, for the same date, we 
                   3605:    * estimate the model with stepm=1 month, we can keep estepm to 24 months
                   3606:    * to compare the new estimate of Life expectancy with the same linear 
                   3607:    * hypothesis. A more precise result, taking into account a more precise
                   3608:    * curvature will be obtained if estepm is as small as stepm. */
                   3609: 
                   3610:   /* For example we decided to compute the life expectancy with the smallest unit */
                   3611:   /* hstepm beeing the number of stepms, if hstepm=1 the length of hstepm is stepm. 
                   3612:      nhstepm is the number of hstepm from age to agelim 
                   3613:      nstepm is the number of stepm from age to agelin. 
                   3614:      Look at hpijx to understand the reason of that which relies in memory size
                   3615:      and note for a fixed period like estepm months */
                   3616:   /* We decided (b) to get a life expectancy respecting the most precise curvature of the
                   3617:      survival function given by stepm (the optimization length). Unfortunately it
                   3618:      means that if the survival funtion is printed only each two years of age and if
                   3619:      you sum them up and add 1 year (area under the trapezoids) you won't get the same 
                   3620:      results. So we changed our mind and took the option of the best precision.
                   3621:   */
                   3622:   hstepm=hstepm/stepm; /* Typically in stepm units, if stepm=6 & estepm=24 , = 24/6 months = 4 */ 
                   3623: 
                   3624:   /* If stepm=6 months */
                   3625:   /* nhstepm age range expressed in number of stepm */
                   3626:   agelim=AGESUP;
                   3627:   nstepm=(int) rint((agelim-bage)*YEARM/stepm); 
                   3628:   /* Typically if 20 years nstepm = 20*12/6=40 stepm */ 
                   3629:   /* if (stepm >= YEARM) hstepm=1;*/
                   3630:   nhstepm = nstepm/hstepm;/* Expressed in hstepm, typically nhstepm=40/4=10 */
                   3631:   
                   3632:   p3matp=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   3633:   p3matm=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   3634:   gradg=ma3x(0,nhstepm,1,npar,1,nlstate*nlstate);
                   3635:   trgradg =ma3x(0,nhstepm,1,nlstate*nlstate,1,npar);
                   3636:   gp=matrix(0,nhstepm,1,nlstate*nlstate);
                   3637:   gm=matrix(0,nhstepm,1,nlstate*nlstate);
                   3638: 
                   3639:   for (age=bage; age<=fage; age ++){ 
                   3640:     nstepma=(int) rint((agelim-bage)*YEARM/stepm); /* Biggest nstepm */
                   3641:     /* Typically if 20 years nstepm = 20*12/6=40 stepm */ 
                   3642:     /* if (stepm >= YEARM) hstepm=1;*/
                   3643:     nhstepma = nstepma/hstepm;/* Expressed in hstepm, typically nhstepma=40/4=10 */
                   3644: 
                   3645:     /* If stepm=6 months */
                   3646:     /* Computed by stepm unit matrices, product of hstepma matrices, stored
                   3647:        in an array of nhstepma length: nhstepma=10, hstepm=4, stepm=6 months */
                   3648:     
                   3649:     hf=hstepm*stepm/YEARM;  /* Duration of hstepm expressed in year unit. */
                   3650: 
                   3651:     /* Computing  Variances of health expectancies */
                   3652:     /* Gradient is computed with plus gp and minus gm. Code is duplicated in order to
                   3653:        decrease memory allocation */
                   3654:     for(theta=1; theta <=npar; theta++){
                   3655:       for(i=1; i<=npar; i++){ 
                   3656:        xp[i] = x[i] + (i==theta ?delti[theta]:0);
                   3657:        xm[i] = x[i] - (i==theta ?delti[theta]:0);
                   3658:       }
                   3659:       hpxij(p3matp,nhstepm,age,hstepm,xp,nlstate,stepm,oldm,savm, cij);  
                   3660:       hpxij(p3matm,nhstepm,age,hstepm,xm,nlstate,stepm,oldm,savm, cij);  
                   3661:   
                   3662:       for(j=1; j<= nlstate; j++){
                   3663:        for(i=1; i<=nlstate; i++){
                   3664:          for(h=0; h<=nhstepm-1; h++){
                   3665:            gp[h][(j-1)*nlstate + i] = (p3matp[i][j][h]+p3matp[i][j][h+1])/2.;
                   3666:            gm[h][(j-1)*nlstate + i] = (p3matm[i][j][h]+p3matm[i][j][h+1])/2.;
                   3667:          }
                   3668:        }
                   3669:       }
                   3670:      
                   3671:       for(ij=1; ij<= nlstate*nlstate; ij++)
                   3672:        for(h=0; h<=nhstepm-1; h++){
                   3673:          gradg[h][theta][ij]= (gp[h][ij]-gm[h][ij])/2./delti[theta];
                   3674:        }
                   3675:     }/* End theta */
                   3676:     
                   3677:     
                   3678:     for(h=0; h<=nhstepm-1; h++)
                   3679:       for(j=1; j<=nlstate*nlstate;j++)
                   3680:        for(theta=1; theta <=npar; theta++)
                   3681:          trgradg[h][j][theta]=gradg[h][theta][j];
                   3682:     
                   3683: 
                   3684:      for(ij=1;ij<=nlstate*nlstate;ij++)
                   3685:       for(ji=1;ji<=nlstate*nlstate;ji++)
                   3686:        varhe[ij][ji][(int)age] =0.;
                   3687: 
                   3688:      printf("%d|",(int)age);fflush(stdout);
                   3689:      fprintf(ficlog,"%d|",(int)age);fflush(ficlog);
                   3690:      for(h=0;h<=nhstepm-1;h++){
                   3691:       for(k=0;k<=nhstepm-1;k++){
                   3692:        matprod2(dnewm,trgradg[h],1,nlstate*nlstate,1,npar,1,npar,matcov);
                   3693:        matprod2(doldm,dnewm,1,nlstate*nlstate,1,npar,1,nlstate*nlstate,gradg[k]);
                   3694:        for(ij=1;ij<=nlstate*nlstate;ij++)
                   3695:          for(ji=1;ji<=nlstate*nlstate;ji++)
                   3696:            varhe[ij][ji][(int)age] += doldm[ij][ji]*hf*hf;
                   3697:       }
                   3698:     }
                   3699: 
                   3700:     /* Computing expectancies */
                   3701:     hpxij(p3matm,nhstepm,age,hstepm,x,nlstate,stepm,oldm, savm, cij);  
                   3702:     for(i=1; i<=nlstate;i++)
                   3703:       for(j=1; j<=nlstate;j++)
                   3704:        for (h=0, eij[i][j][(int)age]=0; h<=nhstepm-1; h++){
                   3705:          eij[i][j][(int)age] += (p3matm[i][j][h]+p3matm[i][j][h+1])/2.0*hf;
                   3706:          
                   3707:          /* 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]);*/
                   3708: 
                   3709:        }
                   3710: 
                   3711:     fprintf(ficresstdeij,"%3.0f",age );
                   3712:     for(i=1; i<=nlstate;i++){
                   3713:       eip=0.;
                   3714:       vip=0.;
                   3715:       for(j=1; j<=nlstate;j++){
                   3716:        eip += eij[i][j][(int)age];
                   3717:        for(k=1; k<=nlstate;k++) /* Sum on j and k of cov(eij,eik) */
                   3718:          vip += varhe[(j-1)*nlstate+i][(k-1)*nlstate+i][(int)age];
                   3719:        fprintf(ficresstdeij," %9.4f (%.4f)", eij[i][j][(int)age], sqrt(varhe[(j-1)*nlstate+i][(j-1)*nlstate+i][(int)age]) );
                   3720:       }
                   3721:       fprintf(ficresstdeij," %9.4f (%.4f)", eip, sqrt(vip));
                   3722:     }
                   3723:     fprintf(ficresstdeij,"\n");
                   3724: 
                   3725:     fprintf(ficrescveij,"%3.0f",age );
                   3726:     for(i=1; i<=nlstate;i++)
                   3727:       for(j=1; j<=nlstate;j++){
                   3728:        cptj= (j-1)*nlstate+i;
                   3729:        for(i2=1; i2<=nlstate;i2++)
                   3730:          for(j2=1; j2<=nlstate;j2++){
                   3731:            cptj2= (j2-1)*nlstate+i2;
                   3732:            if(cptj2 <= cptj)
                   3733:              fprintf(ficrescveij," %.4f", varhe[cptj][cptj2][(int)age]);
                   3734:          }
                   3735:       }
                   3736:     fprintf(ficrescveij,"\n");
                   3737:    
                   3738:   }
                   3739:   free_matrix(gm,0,nhstepm,1,nlstate*nlstate);
                   3740:   free_matrix(gp,0,nhstepm,1,nlstate*nlstate);
                   3741:   free_ma3x(gradg,0,nhstepm,1,npar,1,nlstate*nlstate);
                   3742:   free_ma3x(trgradg,0,nhstepm,1,nlstate*nlstate,1,npar);
                   3743:   free_ma3x(p3matm,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   3744:   free_ma3x(p3matp,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   3745:   printf("\n");
                   3746:   fprintf(ficlog,"\n");
                   3747: 
                   3748:   free_vector(xm,1,npar);
                   3749:   free_vector(xp,1,npar);
                   3750:   free_matrix(dnewm,1,nlstate*nlstate,1,npar);
                   3751:   free_matrix(doldm,1,nlstate*nlstate,1,nlstate*nlstate);
                   3752:   free_ma3x(varhe,1,nlstate*nlstate,1,nlstate*nlstate,(int) bage, (int)fage);
                   3753: }
                   3754: 
                   3755: /************ Variance ******************/
                   3756: 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[])
                   3757: {
                   3758:   /* Variance of health expectancies */
                   3759:   /*  double **prevalim(double **prlim, int nlstate, double *xp, double age, double **oldm, double ** savm,double ftolpl);*/
                   3760:   /* double **newm;*/
1.169     brouard  3761:   /* int movingaverage(double ***probs, double bage,double fage, double ***mobaverage, int mobilav)*/
                   3762:   
                   3763:   int movingaverage();
1.126     brouard  3764:   double **dnewm,**doldm;
                   3765:   double **dnewmp,**doldmp;
                   3766:   int i, j, nhstepm, hstepm, h, nstepm ;
1.164     brouard  3767:   int k;
1.126     brouard  3768:   double *xp;
                   3769:   double **gp, **gm;  /* for var eij */
                   3770:   double ***gradg, ***trgradg; /*for var eij */
                   3771:   double **gradgp, **trgradgp; /* for var p point j */
                   3772:   double *gpp, *gmp; /* for var p point j */
                   3773:   double **varppt; /* for var p point j nlstate to nlstate+ndeath */
                   3774:   double ***p3mat;
                   3775:   double age,agelim, hf;
                   3776:   double ***mobaverage;
                   3777:   int theta;
                   3778:   char digit[4];
                   3779:   char digitp[25];
                   3780: 
                   3781:   char fileresprobmorprev[FILENAMELENGTH];
                   3782: 
                   3783:   if(popbased==1){
                   3784:     if(mobilav!=0)
                   3785:       strcpy(digitp,"-populbased-mobilav-");
                   3786:     else strcpy(digitp,"-populbased-nomobil-");
                   3787:   }
                   3788:   else 
                   3789:     strcpy(digitp,"-stablbased-");
                   3790: 
                   3791:   if (mobilav!=0) {
                   3792:     mobaverage= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
                   3793:     if (movingaverage(probs, bage, fage, mobaverage,mobilav)!=0){
                   3794:       fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav);
                   3795:       printf(" Error in movingaverage mobilav=%d\n",mobilav);
                   3796:     }
                   3797:   }
                   3798: 
                   3799:   strcpy(fileresprobmorprev,"prmorprev"); 
                   3800:   sprintf(digit,"%-d",ij);
                   3801:   /*printf("DIGIT=%s, ij=%d ijr=%-d|\n",digit, ij,ij);*/
                   3802:   strcat(fileresprobmorprev,digit); /* Tvar to be done */
                   3803:   strcat(fileresprobmorprev,digitp); /* Popbased or not, mobilav or not */
                   3804:   strcat(fileresprobmorprev,fileres);
                   3805:   if((ficresprobmorprev=fopen(fileresprobmorprev,"w"))==NULL) {
                   3806:     printf("Problem with resultfile: %s\n", fileresprobmorprev);
                   3807:     fprintf(ficlog,"Problem with resultfile: %s\n", fileresprobmorprev);
                   3808:   }
                   3809:   printf("Computing total mortality p.j=w1*p1j+w2*p2j+..: result on file '%s' \n",fileresprobmorprev);
                   3810:  
                   3811:   fprintf(ficlog,"Computing total mortality p.j=w1*p1j+w2*p2j+..: result on file '%s' \n",fileresprobmorprev);
                   3812:   pstamp(ficresprobmorprev);
                   3813:   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);
                   3814:   fprintf(ficresprobmorprev,"# Age cov=%-d",ij);
                   3815:   for(j=nlstate+1; j<=(nlstate+ndeath);j++){
                   3816:     fprintf(ficresprobmorprev," p.%-d SE",j);
                   3817:     for(i=1; i<=nlstate;i++)
                   3818:       fprintf(ficresprobmorprev," w%1d p%-d%-d",i,i,j);
                   3819:   }  
                   3820:   fprintf(ficresprobmorprev,"\n");
                   3821:   fprintf(ficgp,"\n# Routine varevsij");
                   3822:   /* fprintf(fichtm, "#Local time at start: %s", strstart);*/
                   3823:   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");
                   3824:   fprintf(fichtm,"\n<br>%s  <br>\n",digitp);
                   3825: /*   } */
                   3826:   varppt = matrix(nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);
                   3827:   pstamp(ficresvij);
                   3828:   fprintf(ficresvij,"# Variance and covariance of health expectancies e.j \n#  (weighted average of eij where weights are ");
                   3829:   if(popbased==1)
1.128     brouard  3830:     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  3831:   else
                   3832:     fprintf(ficresvij,"the age specific period (stable) prevalences in each health state \n");
                   3833:   fprintf(ficresvij,"# Age");
                   3834:   for(i=1; i<=nlstate;i++)
                   3835:     for(j=1; j<=nlstate;j++)
                   3836:       fprintf(ficresvij," Cov(e.%1d, e.%1d)",i,j);
                   3837:   fprintf(ficresvij,"\n");
                   3838: 
                   3839:   xp=vector(1,npar);
                   3840:   dnewm=matrix(1,nlstate,1,npar);
                   3841:   doldm=matrix(1,nlstate,1,nlstate);
                   3842:   dnewmp= matrix(nlstate+1,nlstate+ndeath,1,npar);
                   3843:   doldmp= matrix(nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);
                   3844: 
                   3845:   gradgp=matrix(1,npar,nlstate+1,nlstate+ndeath);
                   3846:   gpp=vector(nlstate+1,nlstate+ndeath);
                   3847:   gmp=vector(nlstate+1,nlstate+ndeath);
                   3848:   trgradgp =matrix(nlstate+1,nlstate+ndeath,1,npar); /* mu or p point j*/
                   3849:   
                   3850:   if(estepm < stepm){
                   3851:     printf ("Problem %d lower than %d\n",estepm, stepm);
                   3852:   }
                   3853:   else  hstepm=estepm;   
                   3854:   /* For example we decided to compute the life expectancy with the smallest unit */
                   3855:   /* hstepm beeing the number of stepms, if hstepm=1 the length of hstepm is stepm. 
                   3856:      nhstepm is the number of hstepm from age to agelim 
                   3857:      nstepm is the number of stepm from age to agelin. 
1.128     brouard  3858:      Look at function hpijx to understand why (it is linked to memory size questions) */
1.126     brouard  3859:   /* We decided (b) to get a life expectancy respecting the most precise curvature of the
                   3860:      survival function given by stepm (the optimization length). Unfortunately it
                   3861:      means that if the survival funtion is printed every two years of age and if
                   3862:      you sum them up and add 1 year (area under the trapezoids) you won't get the same 
                   3863:      results. So we changed our mind and took the option of the best precision.
                   3864:   */
                   3865:   hstepm=hstepm/stepm; /* Typically in stepm units, if stepm=6 & estepm=24 , = 24/6 months = 4 */ 
                   3866:   agelim = AGESUP;
                   3867:   for (age=bage; age<=fage; age ++){ /* If stepm=6 months */
                   3868:     nstepm=(int) rint((agelim-age)*YEARM/stepm); /* Typically 20 years = 20*12/6=40 */ 
                   3869:     nhstepm = nstepm/hstepm;/* Expressed in hstepm, typically nhstepm=40/4=10 */
                   3870:     p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   3871:     gradg=ma3x(0,nhstepm,1,npar,1,nlstate);
                   3872:     gp=matrix(0,nhstepm,1,nlstate);
                   3873:     gm=matrix(0,nhstepm,1,nlstate);
                   3874: 
                   3875: 
                   3876:     for(theta=1; theta <=npar; theta++){
                   3877:       for(i=1; i<=npar; i++){ /* Computes gradient x + delta*/
                   3878:        xp[i] = x[i] + (i==theta ?delti[theta]:0);
                   3879:       }
                   3880:       hpxij(p3mat,nhstepm,age,hstepm,xp,nlstate,stepm,oldm,savm, ij);  
                   3881:       prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ij);
                   3882: 
                   3883:       if (popbased==1) {
                   3884:        if(mobilav ==0){
                   3885:          for(i=1; i<=nlstate;i++)
                   3886:            prlim[i][i]=probs[(int)age][i][ij];
                   3887:        }else{ /* mobilav */ 
                   3888:          for(i=1; i<=nlstate;i++)
                   3889:            prlim[i][i]=mobaverage[(int)age][i][ij];
                   3890:        }
                   3891:       }
                   3892:   
                   3893:       for(j=1; j<= nlstate; j++){
                   3894:        for(h=0; h<=nhstepm; h++){
                   3895:          for(i=1, gp[h][j]=0.;i<=nlstate;i++)
                   3896:            gp[h][j] += prlim[i][i]*p3mat[i][j][h];
                   3897:        }
                   3898:       }
                   3899:       /* This for computing probability of death (h=1 means
                   3900:          computed over hstepm matrices product = hstepm*stepm months) 
                   3901:          as a weighted average of prlim.
                   3902:       */
                   3903:       for(j=nlstate+1;j<=nlstate+ndeath;j++){
                   3904:        for(i=1,gpp[j]=0.; i<= nlstate; i++)
                   3905:          gpp[j] += prlim[i][i]*p3mat[i][j][1];
                   3906:       }    
                   3907:       /* end probability of death */
                   3908: 
                   3909:       for(i=1; i<=npar; i++) /* Computes gradient x - delta */
                   3910:        xp[i] = x[i] - (i==theta ?delti[theta]:0);
                   3911:       hpxij(p3mat,nhstepm,age,hstepm,xp,nlstate,stepm,oldm,savm, ij);  
                   3912:       prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ij);
                   3913:  
                   3914:       if (popbased==1) {
                   3915:        if(mobilav ==0){
                   3916:          for(i=1; i<=nlstate;i++)
                   3917:            prlim[i][i]=probs[(int)age][i][ij];
                   3918:        }else{ /* mobilav */ 
                   3919:          for(i=1; i<=nlstate;i++)
                   3920:            prlim[i][i]=mobaverage[(int)age][i][ij];
                   3921:        }
                   3922:       }
                   3923: 
1.128     brouard  3924:       for(j=1; j<= nlstate; j++){  /* Sum of wi * eij = e.j */
1.126     brouard  3925:        for(h=0; h<=nhstepm; h++){
                   3926:          for(i=1, gm[h][j]=0.;i<=nlstate;i++)
                   3927:            gm[h][j] += prlim[i][i]*p3mat[i][j][h];
                   3928:        }
                   3929:       }
                   3930:       /* This for computing probability of death (h=1 means
                   3931:          computed over hstepm matrices product = hstepm*stepm months) 
                   3932:          as a weighted average of prlim.
                   3933:       */
                   3934:       for(j=nlstate+1;j<=nlstate+ndeath;j++){
                   3935:        for(i=1,gmp[j]=0.; i<= nlstate; i++)
                   3936:          gmp[j] += prlim[i][i]*p3mat[i][j][1];
                   3937:       }    
                   3938:       /* end probability of death */
                   3939: 
                   3940:       for(j=1; j<= nlstate; j++) /* vareij */
                   3941:        for(h=0; h<=nhstepm; h++){
                   3942:          gradg[h][theta][j]= (gp[h][j]-gm[h][j])/2./delti[theta];
                   3943:        }
                   3944: 
                   3945:       for(j=nlstate+1; j<= nlstate+ndeath; j++){ /* var mu */
                   3946:        gradgp[theta][j]= (gpp[j]-gmp[j])/2./delti[theta];
                   3947:       }
                   3948: 
                   3949:     } /* End theta */
                   3950: 
                   3951:     trgradg =ma3x(0,nhstepm,1,nlstate,1,npar); /* veij */
                   3952: 
                   3953:     for(h=0; h<=nhstepm; h++) /* veij */
                   3954:       for(j=1; j<=nlstate;j++)
                   3955:        for(theta=1; theta <=npar; theta++)
                   3956:          trgradg[h][j][theta]=gradg[h][theta][j];
                   3957: 
                   3958:     for(j=nlstate+1; j<=nlstate+ndeath;j++) /* mu */
                   3959:       for(theta=1; theta <=npar; theta++)
                   3960:        trgradgp[j][theta]=gradgp[theta][j];
                   3961:   
                   3962: 
                   3963:     hf=hstepm*stepm/YEARM;  /* Duration of hstepm expressed in year unit. */
                   3964:     for(i=1;i<=nlstate;i++)
                   3965:       for(j=1;j<=nlstate;j++)
                   3966:        vareij[i][j][(int)age] =0.;
                   3967: 
                   3968:     for(h=0;h<=nhstepm;h++){
                   3969:       for(k=0;k<=nhstepm;k++){
                   3970:        matprod2(dnewm,trgradg[h],1,nlstate,1,npar,1,npar,matcov);
                   3971:        matprod2(doldm,dnewm,1,nlstate,1,npar,1,nlstate,gradg[k]);
                   3972:        for(i=1;i<=nlstate;i++)
                   3973:          for(j=1;j<=nlstate;j++)
                   3974:            vareij[i][j][(int)age] += doldm[i][j]*hf*hf;
                   3975:       }
                   3976:     }
                   3977:   
                   3978:     /* pptj */
                   3979:     matprod2(dnewmp,trgradgp,nlstate+1,nlstate+ndeath,1,npar,1,npar,matcov);
                   3980:     matprod2(doldmp,dnewmp,nlstate+1,nlstate+ndeath,1,npar,nlstate+1,nlstate+ndeath,gradgp);
                   3981:     for(j=nlstate+1;j<=nlstate+ndeath;j++)
                   3982:       for(i=nlstate+1;i<=nlstate+ndeath;i++)
                   3983:        varppt[j][i]=doldmp[j][i];
                   3984:     /* end ppptj */
                   3985:     /*  x centered again */
                   3986:     hpxij(p3mat,nhstepm,age,hstepm,x,nlstate,stepm,oldm,savm, ij);  
                   3987:     prevalim(prlim,nlstate,x,age,oldm,savm,ftolpl,ij);
                   3988:  
                   3989:     if (popbased==1) {
                   3990:       if(mobilav ==0){
                   3991:        for(i=1; i<=nlstate;i++)
                   3992:          prlim[i][i]=probs[(int)age][i][ij];
                   3993:       }else{ /* mobilav */ 
                   3994:        for(i=1; i<=nlstate;i++)
                   3995:          prlim[i][i]=mobaverage[(int)age][i][ij];
                   3996:       }
                   3997:     }
                   3998:              
                   3999:     /* This for computing probability of death (h=1 means
                   4000:        computed over hstepm (estepm) matrices product = hstepm*stepm months) 
                   4001:        as a weighted average of prlim.
                   4002:     */
                   4003:     for(j=nlstate+1;j<=nlstate+ndeath;j++){
                   4004:       for(i=1,gmp[j]=0.;i<= nlstate; i++) 
                   4005:        gmp[j] += prlim[i][i]*p3mat[i][j][1]; 
                   4006:     }    
                   4007:     /* end probability of death */
                   4008: 
                   4009:     fprintf(ficresprobmorprev,"%3d %d ",(int) age, ij);
                   4010:     for(j=nlstate+1; j<=(nlstate+ndeath);j++){
                   4011:       fprintf(ficresprobmorprev," %11.3e %11.3e",gmp[j], sqrt(varppt[j][j]));
                   4012:       for(i=1; i<=nlstate;i++){
                   4013:        fprintf(ficresprobmorprev," %11.3e %11.3e ",prlim[i][i],p3mat[i][j][1]);
                   4014:       }
                   4015:     } 
                   4016:     fprintf(ficresprobmorprev,"\n");
                   4017: 
                   4018:     fprintf(ficresvij,"%.0f ",age );
                   4019:     for(i=1; i<=nlstate;i++)
                   4020:       for(j=1; j<=nlstate;j++){
                   4021:        fprintf(ficresvij," %.4f", vareij[i][j][(int)age]);
                   4022:       }
                   4023:     fprintf(ficresvij,"\n");
                   4024:     free_matrix(gp,0,nhstepm,1,nlstate);
                   4025:     free_matrix(gm,0,nhstepm,1,nlstate);
                   4026:     free_ma3x(gradg,0,nhstepm,1,npar,1,nlstate);
                   4027:     free_ma3x(trgradg,0,nhstepm,1,nlstate,1,npar);
                   4028:     free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   4029:   } /* End age */
                   4030:   free_vector(gpp,nlstate+1,nlstate+ndeath);
                   4031:   free_vector(gmp,nlstate+1,nlstate+ndeath);
                   4032:   free_matrix(gradgp,1,npar,nlstate+1,nlstate+ndeath);
                   4033:   free_matrix(trgradgp,nlstate+1,nlstate+ndeath,1,npar); /* mu or p point j*/
1.145     brouard  4034:   fprintf(ficgp,"\nunset parametric;unset label; set ter png small size 320, 240");
1.126     brouard  4035:   /* for(j=nlstate+1; j<= nlstate+ndeath; j++){ *//* Only the first actually */
1.131     brouard  4036:   fprintf(ficgp,"\n set log y; unset log x;set xlabel \"Age\"; set ylabel \"Force of mortality (year-1)\";");
1.126     brouard  4037: /*   fprintf(ficgp,"\n plot \"%s\"  u 1:($3*%6.3f) not w l 1 ",fileresprobmorprev,YEARM/estepm); */
                   4038: /*   fprintf(ficgp,"\n replot \"%s\"  u 1:(($3+1.96*$4)*%6.3f) t \"95\%% interval\" w l 2 ",fileresprobmorprev,YEARM/estepm); */
                   4039: /*   fprintf(ficgp,"\n replot \"%s\"  u 1:(($3-1.96*$4)*%6.3f) not w l 2 ",fileresprobmorprev,YEARM/estepm); */
1.145     brouard  4040:   fprintf(ficgp,"\n plot \"%s\"  u 1:($3) not w l lt 1 ",subdirf(fileresprobmorprev));
1.170     brouard  4041:   fprintf(ficgp,"\n replot \"%s\"  u 1:(($3+1.96*$4)) t \"95%% interval\" w l lt 2 ",subdirf(fileresprobmorprev));
1.145     brouard  4042:   fprintf(ficgp,"\n replot \"%s\"  u 1:(($3-1.96*$4)) not w l lt 2 ",subdirf(fileresprobmorprev));
1.126     brouard  4043:   fprintf(fichtm,"\n<br> File (multiple files are possible if covariates are present): <A href=\"%s\">%s</a>\n",subdirf(fileresprobmorprev),subdirf(fileresprobmorprev));
                   4044:   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);
                   4045:   /*  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);
                   4046: */
                   4047: /*   fprintf(ficgp,"\nset out \"varmuptjgr%s%s%s.png\";replot;",digitp,optionfilefiname,digit); */
                   4048:   fprintf(ficgp,"\nset out \"%s%s.png\";replot;\n",subdirf3(optionfilefiname,"varmuptjgr",digitp),digit);
                   4049: 
                   4050:   free_vector(xp,1,npar);
                   4051:   free_matrix(doldm,1,nlstate,1,nlstate);
                   4052:   free_matrix(dnewm,1,nlstate,1,npar);
                   4053:   free_matrix(doldmp,nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);
                   4054:   free_matrix(dnewmp,nlstate+1,nlstate+ndeath,1,npar);
                   4055:   free_matrix(varppt,nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);
                   4056:   if (mobilav!=0) free_ma3x(mobaverage,1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
                   4057:   fclose(ficresprobmorprev);
                   4058:   fflush(ficgp);
                   4059:   fflush(fichtm); 
                   4060: }  /* end varevsij */
                   4061: 
                   4062: /************ Variance of prevlim ******************/
                   4063: 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[])
                   4064: {
                   4065:   /* Variance of prevalence limit */
                   4066:   /*  double **prevalim(double **prlim, int nlstate, double *xp, double age, double **oldm, double **savm,double ftolpl);*/
1.164     brouard  4067: 
1.126     brouard  4068:   double **dnewm,**doldm;
                   4069:   int i, j, nhstepm, hstepm;
                   4070:   double *xp;
                   4071:   double *gp, *gm;
                   4072:   double **gradg, **trgradg;
                   4073:   double age,agelim;
                   4074:   int theta;
                   4075:   
                   4076:   pstamp(ficresvpl);
                   4077:   fprintf(ficresvpl,"# Standard deviation of period (stable) prevalences \n");
                   4078:   fprintf(ficresvpl,"# Age");
                   4079:   for(i=1; i<=nlstate;i++)
                   4080:       fprintf(ficresvpl," %1d-%1d",i,i);
                   4081:   fprintf(ficresvpl,"\n");
                   4082: 
                   4083:   xp=vector(1,npar);
                   4084:   dnewm=matrix(1,nlstate,1,npar);
                   4085:   doldm=matrix(1,nlstate,1,nlstate);
                   4086:   
                   4087:   hstepm=1*YEARM; /* Every year of age */
                   4088:   hstepm=hstepm/stepm; /* Typically in stepm units, if j= 2 years, = 2/6 months = 4 */ 
                   4089:   agelim = AGESUP;
                   4090:   for (age=bage; age<=fage; age ++){ /* If stepm=6 months */
                   4091:     nhstepm=(int) rint((agelim-age)*YEARM/stepm); /* Typically 20 years = 20*12/6=40 */ 
                   4092:     if (stepm >= YEARM) hstepm=1;
                   4093:     nhstepm = nhstepm/hstepm; /* Typically 40/4=10 */
                   4094:     gradg=matrix(1,npar,1,nlstate);
                   4095:     gp=vector(1,nlstate);
                   4096:     gm=vector(1,nlstate);
                   4097: 
                   4098:     for(theta=1; theta <=npar; theta++){
                   4099:       for(i=1; i<=npar; i++){ /* Computes gradient */
                   4100:        xp[i] = x[i] + (i==theta ?delti[theta]:0);
                   4101:       }
                   4102:       prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ij);
                   4103:       for(i=1;i<=nlstate;i++)
                   4104:        gp[i] = prlim[i][i];
                   4105:     
                   4106:       for(i=1; i<=npar; i++) /* Computes gradient */
                   4107:        xp[i] = x[i] - (i==theta ?delti[theta]:0);
                   4108:       prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ij);
                   4109:       for(i=1;i<=nlstate;i++)
                   4110:        gm[i] = prlim[i][i];
                   4111: 
                   4112:       for(i=1;i<=nlstate;i++)
                   4113:        gradg[theta][i]= (gp[i]-gm[i])/2./delti[theta];
                   4114:     } /* End theta */
                   4115: 
                   4116:     trgradg =matrix(1,nlstate,1,npar);
                   4117: 
                   4118:     for(j=1; j<=nlstate;j++)
                   4119:       for(theta=1; theta <=npar; theta++)
                   4120:        trgradg[j][theta]=gradg[theta][j];
                   4121: 
                   4122:     for(i=1;i<=nlstate;i++)
                   4123:       varpl[i][(int)age] =0.;
                   4124:     matprod2(dnewm,trgradg,1,nlstate,1,npar,1,npar,matcov);
                   4125:     matprod2(doldm,dnewm,1,nlstate,1,npar,1,nlstate,gradg);
                   4126:     for(i=1;i<=nlstate;i++)
                   4127:       varpl[i][(int)age] = doldm[i][i]; /* Covariances are useless */
                   4128: 
                   4129:     fprintf(ficresvpl,"%.0f ",age );
                   4130:     for(i=1; i<=nlstate;i++)
                   4131:       fprintf(ficresvpl," %.5f (%.5f)",prlim[i][i],sqrt(varpl[i][(int)age]));
                   4132:     fprintf(ficresvpl,"\n");
                   4133:     free_vector(gp,1,nlstate);
                   4134:     free_vector(gm,1,nlstate);
                   4135:     free_matrix(gradg,1,npar,1,nlstate);
                   4136:     free_matrix(trgradg,1,nlstate,1,npar);
                   4137:   } /* End age */
                   4138: 
                   4139:   free_vector(xp,1,npar);
                   4140:   free_matrix(doldm,1,nlstate,1,npar);
                   4141:   free_matrix(dnewm,1,nlstate,1,nlstate);
                   4142: 
                   4143: }
                   4144: 
                   4145: /************ Variance of one-step probabilities  ******************/
                   4146: 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[])
                   4147: {
1.164     brouard  4148:   int i, j=0,  k1, l1, tj;
1.126     brouard  4149:   int k2, l2, j1,  z1;
1.164     brouard  4150:   int k=0, l;
1.145     brouard  4151:   int first=1, first1, first2;
1.126     brouard  4152:   double cv12, mu1, mu2, lc1, lc2, v12, v21, v11, v22,v1,v2, c12, tnalp;
                   4153:   double **dnewm,**doldm;
                   4154:   double *xp;
                   4155:   double *gp, *gm;
                   4156:   double **gradg, **trgradg;
                   4157:   double **mu;
1.164     brouard  4158:   double age, cov[NCOVMAX+1];
1.126     brouard  4159:   double std=2.0; /* Number of standard deviation wide of confidence ellipsoids */
                   4160:   int theta;
                   4161:   char fileresprob[FILENAMELENGTH];
                   4162:   char fileresprobcov[FILENAMELENGTH];
                   4163:   char fileresprobcor[FILENAMELENGTH];
                   4164:   double ***varpij;
                   4165: 
                   4166:   strcpy(fileresprob,"prob"); 
                   4167:   strcat(fileresprob,fileres);
                   4168:   if((ficresprob=fopen(fileresprob,"w"))==NULL) {
                   4169:     printf("Problem with resultfile: %s\n", fileresprob);
                   4170:     fprintf(ficlog,"Problem with resultfile: %s\n", fileresprob);
                   4171:   }
                   4172:   strcpy(fileresprobcov,"probcov"); 
                   4173:   strcat(fileresprobcov,fileres);
                   4174:   if((ficresprobcov=fopen(fileresprobcov,"w"))==NULL) {
                   4175:     printf("Problem with resultfile: %s\n", fileresprobcov);
                   4176:     fprintf(ficlog,"Problem with resultfile: %s\n", fileresprobcov);
                   4177:   }
                   4178:   strcpy(fileresprobcor,"probcor"); 
                   4179:   strcat(fileresprobcor,fileres);
                   4180:   if((ficresprobcor=fopen(fileresprobcor,"w"))==NULL) {
                   4181:     printf("Problem with resultfile: %s\n", fileresprobcor);
                   4182:     fprintf(ficlog,"Problem with resultfile: %s\n", fileresprobcor);
                   4183:   }
                   4184:   printf("Computing standard deviation of one-step probabilities: result on file '%s' \n",fileresprob);
                   4185:   fprintf(ficlog,"Computing standard deviation of one-step probabilities: result on file '%s' \n",fileresprob);
                   4186:   printf("Computing matrix of variance covariance of one-step probabilities: result on file '%s' \n",fileresprobcov);
                   4187:   fprintf(ficlog,"Computing matrix of variance covariance of one-step probabilities: result on file '%s' \n",fileresprobcov);
                   4188:   printf("and correlation matrix of one-step probabilities: result on file '%s' \n",fileresprobcor);
                   4189:   fprintf(ficlog,"and correlation matrix of one-step probabilities: result on file '%s' \n",fileresprobcor);
                   4190:   pstamp(ficresprob);
                   4191:   fprintf(ficresprob,"#One-step probabilities and stand. devi in ()\n");
                   4192:   fprintf(ficresprob,"# Age");
                   4193:   pstamp(ficresprobcov);
                   4194:   fprintf(ficresprobcov,"#One-step probabilities and covariance matrix\n");
                   4195:   fprintf(ficresprobcov,"# Age");
                   4196:   pstamp(ficresprobcor);
                   4197:   fprintf(ficresprobcor,"#One-step probabilities and correlation matrix\n");
                   4198:   fprintf(ficresprobcor,"# Age");
                   4199: 
                   4200: 
                   4201:   for(i=1; i<=nlstate;i++)
                   4202:     for(j=1; j<=(nlstate+ndeath);j++){
                   4203:       fprintf(ficresprob," p%1d-%1d (SE)",i,j);
                   4204:       fprintf(ficresprobcov," p%1d-%1d ",i,j);
                   4205:       fprintf(ficresprobcor," p%1d-%1d ",i,j);
                   4206:     }  
                   4207:  /* fprintf(ficresprob,"\n");
                   4208:   fprintf(ficresprobcov,"\n");
                   4209:   fprintf(ficresprobcor,"\n");
                   4210:  */
1.131     brouard  4211:   xp=vector(1,npar);
1.126     brouard  4212:   dnewm=matrix(1,(nlstate)*(nlstate+ndeath),1,npar);
                   4213:   doldm=matrix(1,(nlstate)*(nlstate+ndeath),1,(nlstate)*(nlstate+ndeath));
                   4214:   mu=matrix(1,(nlstate)*(nlstate+ndeath), (int) bage, (int)fage);
                   4215:   varpij=ma3x(1,nlstate*(nlstate+ndeath),1,nlstate*(nlstate+ndeath),(int) bage, (int) fage);
                   4216:   first=1;
                   4217:   fprintf(ficgp,"\n# Routine varprob");
                   4218:   fprintf(fichtm,"\n<li><h4> Computing and drawing one step probabilities with their confidence intervals</h4></li>\n");
                   4219:   fprintf(fichtm,"\n");
                   4220: 
                   4221:   fprintf(fichtm,"\n<li><h4> <a href=\"%s\">Matrix of variance-covariance of pairs of step probabilities (drawings)</a></h4></li>\n",optionfilehtmcov);
                   4222:   fprintf(fichtmcov,"\n<h4>Matrix of variance-covariance of pairs of step probabilities</h4>\n\
                   4223:   file %s<br>\n",optionfilehtmcov);
                   4224:   fprintf(fichtmcov,"\nEllipsoids of confidence centered on point (p<inf>ij</inf>, p<inf>kl</inf>) are estimated\
                   4225: and drawn. It helps understanding how is the covariance between two incidences.\
                   4226:  They are expressed in year<sup>-1</sup> in order to be less dependent of stepm.<br>\n");
                   4227:   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. \
                   4228: It can be understood this way: if pij and pkl where uncorrelated the (2x2) matrix of covariance \
                   4229: would have been (1/(var pij), 0 , 0, 1/(var pkl)), and the confidence interval would be 2 \
                   4230: standard deviations wide on each axis. <br>\
                   4231:  Now, if both incidences are correlated (usual case) we diagonalised the inverse of the covariance matrix\
                   4232:  and made the appropriate rotation to look at the uncorrelated principal directions.<br>\
                   4233: To be simple, these graphs help to understand the significativity of each parameter in relation to a second other one.<br> \n");
                   4234: 
                   4235:   cov[1]=1;
1.145     brouard  4236:   /* tj=cptcoveff; */
                   4237:   tj = (int) pow(2,cptcoveff);
1.126     brouard  4238:   if (cptcovn<1) {tj=1;ncodemax[1]=1;}
                   4239:   j1=0;
1.145     brouard  4240:   for(j1=1; j1<=tj;j1++){
                   4241:     /*for(i1=1; i1<=ncodemax[t];i1++){ */
                   4242:     /*j1++;*/
1.126     brouard  4243:       if  (cptcovn>0) {
                   4244:        fprintf(ficresprob, "\n#********** Variable "); 
                   4245:        for (z1=1; z1<=cptcoveff; z1++) fprintf(ficresprob, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtab[j1][z1]]);
                   4246:        fprintf(ficresprob, "**********\n#\n");
                   4247:        fprintf(ficresprobcov, "\n#********** Variable "); 
                   4248:        for (z1=1; z1<=cptcoveff; z1++) fprintf(ficresprobcov, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtab[j1][z1]]);
                   4249:        fprintf(ficresprobcov, "**********\n#\n");
                   4250:        
                   4251:        fprintf(ficgp, "\n#********** Variable "); 
                   4252:        for (z1=1; z1<=cptcoveff; z1++) fprintf(ficgp, " V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtab[j1][z1]]);
                   4253:        fprintf(ficgp, "**********\n#\n");
                   4254:        
                   4255:        
                   4256:        fprintf(fichtmcov, "\n<hr  size=\"2\" color=\"#EC5E5E\">********** Variable "); 
                   4257:        for (z1=1; z1<=cptcoveff; z1++) fprintf(fichtm, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtab[j1][z1]]);
                   4258:        fprintf(fichtmcov, "**********\n<hr size=\"2\" color=\"#EC5E5E\">");
                   4259:        
                   4260:        fprintf(ficresprobcor, "\n#********** Variable ");    
                   4261:        for (z1=1; z1<=cptcoveff; z1++) fprintf(ficresprobcor, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtab[j1][z1]]);
                   4262:        fprintf(ficresprobcor, "**********\n#");    
                   4263:       }
                   4264:       
1.145     brouard  4265:       gradg=matrix(1,npar,1,(nlstate)*(nlstate+ndeath));
                   4266:       trgradg=matrix(1,(nlstate)*(nlstate+ndeath),1,npar);
                   4267:       gp=vector(1,(nlstate)*(nlstate+ndeath));
                   4268:       gm=vector(1,(nlstate)*(nlstate+ndeath));
1.126     brouard  4269:       for (age=bage; age<=fage; age ++){ 
                   4270:        cov[2]=age;
1.187     brouard  4271:        if(nagesqr==1)
                   4272:          cov[3]= age*age;
1.126     brouard  4273:        for (k=1; k<=cptcovn;k++) {
1.187     brouard  4274:          cov[2+nagesqr+k]=nbcode[Tvar[k]][codtab[j1][Tvar[k]]];/* j1 1 2 3 4
1.145     brouard  4275:                                                         * 1  1 1 1 1
                   4276:                                                         * 2  2 1 1 1
                   4277:                                                         * 3  1 2 1 1
                   4278:                                                         */
                   4279:          /* nbcode[1][1]=0 nbcode[1][2]=1;*/
1.126     brouard  4280:        }
1.186     brouard  4281:        /* for (k=1; k<=cptcovage;k++) cov[2+Tage[k]]=cov[2+Tage[k]]*cov[2]; */
                   4282:        for (k=1; k<=cptcovage;k++) cov[2+Tage[k]]=nbcode[Tvar[Tage[k]]][codtab[ij][Tvar[Tage[k]]]]*cov[2];
1.126     brouard  4283:        for (k=1; k<=cptcovprod;k++)
1.187     brouard  4284:          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  4285:        
                   4286:     
                   4287:        for(theta=1; theta <=npar; theta++){
                   4288:          for(i=1; i<=npar; i++)
                   4289:            xp[i] = x[i] + (i==theta ?delti[theta]:(double)0);
                   4290:          
                   4291:          pmij(pmmij,cov,ncovmodel,xp,nlstate);
                   4292:          
                   4293:          k=0;
                   4294:          for(i=1; i<= (nlstate); i++){
                   4295:            for(j=1; j<=(nlstate+ndeath);j++){
                   4296:              k=k+1;
                   4297:              gp[k]=pmmij[i][j];
                   4298:            }
                   4299:          }
                   4300:          
                   4301:          for(i=1; i<=npar; i++)
                   4302:            xp[i] = x[i] - (i==theta ?delti[theta]:(double)0);
                   4303:     
                   4304:          pmij(pmmij,cov,ncovmodel,xp,nlstate);
                   4305:          k=0;
                   4306:          for(i=1; i<=(nlstate); i++){
                   4307:            for(j=1; j<=(nlstate+ndeath);j++){
                   4308:              k=k+1;
                   4309:              gm[k]=pmmij[i][j];
                   4310:            }
                   4311:          }
                   4312:      
                   4313:          for(i=1; i<= (nlstate)*(nlstate+ndeath); i++) 
                   4314:            gradg[theta][i]=(gp[i]-gm[i])/(double)2./delti[theta];  
                   4315:        }
                   4316: 
                   4317:        for(j=1; j<=(nlstate)*(nlstate+ndeath);j++)
                   4318:          for(theta=1; theta <=npar; theta++)
                   4319:            trgradg[j][theta]=gradg[theta][j];
                   4320:        
                   4321:        matprod2(dnewm,trgradg,1,(nlstate)*(nlstate+ndeath),1,npar,1,npar,matcov); 
                   4322:        matprod2(doldm,dnewm,1,(nlstate)*(nlstate+ndeath),1,npar,1,(nlstate)*(nlstate+ndeath),gradg);
                   4323: 
                   4324:        pmij(pmmij,cov,ncovmodel,x,nlstate);
                   4325:        
                   4326:        k=0;
                   4327:        for(i=1; i<=(nlstate); i++){
                   4328:          for(j=1; j<=(nlstate+ndeath);j++){
                   4329:            k=k+1;
                   4330:            mu[k][(int) age]=pmmij[i][j];
                   4331:          }
                   4332:        }
                   4333:        for(i=1;i<=(nlstate)*(nlstate+ndeath);i++)
                   4334:          for(j=1;j<=(nlstate)*(nlstate+ndeath);j++)
                   4335:            varpij[i][j][(int)age] = doldm[i][j];
                   4336: 
                   4337:        /*printf("\n%d ",(int)age);
                   4338:          for (i=1; i<=(nlstate)*(nlstate+ndeath);i++){
                   4339:          printf("%e [%e ;%e] ",gm[i],gm[i]-2*sqrt(doldm[i][i]),gm[i]+2*sqrt(doldm[i][i]));
                   4340:          fprintf(ficlog,"%e [%e ;%e] ",gm[i],gm[i]-2*sqrt(doldm[i][i]),gm[i]+2*sqrt(doldm[i][i]));
                   4341:          }*/
                   4342: 
                   4343:        fprintf(ficresprob,"\n%d ",(int)age);
                   4344:        fprintf(ficresprobcov,"\n%d ",(int)age);
                   4345:        fprintf(ficresprobcor,"\n%d ",(int)age);
                   4346: 
                   4347:        for (i=1; i<=(nlstate)*(nlstate+ndeath);i++)
                   4348:          fprintf(ficresprob,"%11.3e (%11.3e) ",mu[i][(int) age],sqrt(varpij[i][i][(int)age]));
                   4349:        for (i=1; i<=(nlstate)*(nlstate+ndeath);i++){
                   4350:          fprintf(ficresprobcov,"%11.3e ",mu[i][(int) age]);
                   4351:          fprintf(ficresprobcor,"%11.3e ",mu[i][(int) age]);
                   4352:        }
                   4353:        i=0;
                   4354:        for (k=1; k<=(nlstate);k++){
                   4355:          for (l=1; l<=(nlstate+ndeath);l++){ 
1.145     brouard  4356:            i++;
1.126     brouard  4357:            fprintf(ficresprobcov,"\n%d %d-%d",(int)age,k,l);
                   4358:            fprintf(ficresprobcor,"\n%d %d-%d",(int)age,k,l);
                   4359:            for (j=1; j<=i;j++){
1.145     brouard  4360:              /* printf(" k=%d l=%d i=%d j=%d\n",k,l,i,j);fflush(stdout); */
1.126     brouard  4361:              fprintf(ficresprobcov," %11.3e",varpij[i][j][(int)age]);
                   4362:              fprintf(ficresprobcor," %11.3e",varpij[i][j][(int) age]/sqrt(varpij[i][i][(int) age])/sqrt(varpij[j][j][(int)age]));
                   4363:            }
                   4364:          }
                   4365:        }/* end of loop for state */
                   4366:       } /* end of loop for age */
1.145     brouard  4367:       free_vector(gp,1,(nlstate+ndeath)*(nlstate+ndeath));
                   4368:       free_vector(gm,1,(nlstate+ndeath)*(nlstate+ndeath));
                   4369:       free_matrix(trgradg,1,(nlstate+ndeath)*(nlstate+ndeath),1,npar);
                   4370:       free_matrix(gradg,1,(nlstate+ndeath)*(nlstate+ndeath),1,npar);
                   4371:       
1.126     brouard  4372:       /* Confidence intervalle of pij  */
                   4373:       /*
1.131     brouard  4374:        fprintf(ficgp,"\nunset parametric;unset label");
1.126     brouard  4375:        fprintf(ficgp,"\nset log y;unset log x; set xlabel \"Age\";set ylabel \"probability (year-1)\"");
                   4376:        fprintf(ficgp,"\nset ter png small\nset size 0.65,0.65");
                   4377:        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);
                   4378:        fprintf(fichtm,"\n<br><img src=\"pijgr%s.png\"> ",optionfilefiname);
                   4379:        fprintf(ficgp,"\nset out \"pijgr%s.png\"",optionfilefiname);
                   4380:        fprintf(ficgp,"\nplot \"%s\" every :::%d::%d u 1:2 \"\%%lf",k1,k2,xfilevarprob);
                   4381:       */
                   4382: 
                   4383:       /* Drawing ellipsoids of confidence of two variables p(k1-l1,k2-l2)*/
1.145     brouard  4384:       first1=1;first2=2;
1.126     brouard  4385:       for (k2=1; k2<=(nlstate);k2++){
                   4386:        for (l2=1; l2<=(nlstate+ndeath);l2++){ 
                   4387:          if(l2==k2) continue;
                   4388:          j=(k2-1)*(nlstate+ndeath)+l2;
                   4389:          for (k1=1; k1<=(nlstate);k1++){
                   4390:            for (l1=1; l1<=(nlstate+ndeath);l1++){ 
                   4391:              if(l1==k1) continue;
                   4392:              i=(k1-1)*(nlstate+ndeath)+l1;
                   4393:              if(i<=j) continue;
                   4394:              for (age=bage; age<=fage; age ++){ 
                   4395:                if ((int)age %5==0){
                   4396:                  v1=varpij[i][i][(int)age]/stepm*YEARM/stepm*YEARM;
                   4397:                  v2=varpij[j][j][(int)age]/stepm*YEARM/stepm*YEARM;
                   4398:                  cv12=varpij[i][j][(int)age]/stepm*YEARM/stepm*YEARM;
                   4399:                  mu1=mu[i][(int) age]/stepm*YEARM ;
                   4400:                  mu2=mu[j][(int) age]/stepm*YEARM;
                   4401:                  c12=cv12/sqrt(v1*v2);
                   4402:                  /* Computing eigen value of matrix of covariance */
                   4403:                  lc1=((v1+v2)+sqrt((v1+v2)*(v1+v2) - 4*(v1*v2-cv12*cv12)))/2.;
                   4404:                  lc2=((v1+v2)-sqrt((v1+v2)*(v1+v2) - 4*(v1*v2-cv12*cv12)))/2.;
1.135     brouard  4405:                  if ((lc2 <0) || (lc1 <0) ){
1.145     brouard  4406:                    if(first2==1){
                   4407:                      first1=0;
                   4408:                    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);
                   4409:                    }
                   4410:                    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);
                   4411:                    /* lc1=fabs(lc1); */ /* If we want to have them positive */
                   4412:                    /* lc2=fabs(lc2); */
1.135     brouard  4413:                  }
                   4414: 
1.126     brouard  4415:                  /* Eigen vectors */
                   4416:                  v11=(1./sqrt(1+(v1-lc1)*(v1-lc1)/cv12/cv12));
                   4417:                  /*v21=sqrt(1.-v11*v11); *//* error */
                   4418:                  v21=(lc1-v1)/cv12*v11;
                   4419:                  v12=-v21;
                   4420:                  v22=v11;
                   4421:                  tnalp=v21/v11;
                   4422:                  if(first1==1){
                   4423:                    first1=0;
                   4424:                    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);
                   4425:                  }
                   4426:                  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);
                   4427:                  /*printf(fignu*/
                   4428:                  /* mu1+ v11*lc1*cost + v12*lc2*sin(t) */
                   4429:                  /* mu2+ v21*lc1*cost + v22*lc2*sin(t) */
                   4430:                  if(first==1){
                   4431:                    first=0;
                   4432:                    fprintf(ficgp,"\nset parametric;unset label");
                   4433:                    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  4434:                    fprintf(ficgp,"\nset ter png small size 320, 240");
1.126     brouard  4435:                    fprintf(fichtmcov,"\n<br>Ellipsoids of confidence cov(p%1d%1d,p%1d%1d) expressed in year<sup>-1</sup>\
                   4436:  :<a href=\"%s%d%1d%1d-%1d%1d.png\">\
                   4437: %s%d%1d%1d-%1d%1d.png</A>, ",k1,l1,k2,l2,\
                   4438:                            subdirf2(optionfilefiname,"varpijgr"), j1,k1,l1,k2,l2,\
                   4439:                            subdirf2(optionfilefiname,"varpijgr"), j1,k1,l1,k2,l2);
                   4440:                    fprintf(fichtmcov,"\n<br><img src=\"%s%d%1d%1d-%1d%1d.png\"> ",subdirf2(optionfilefiname,"varpijgr"), j1,k1,l1,k2,l2);
                   4441:                    fprintf(fichtmcov,"\n<br> Correlation at age %d (%.3f),",(int) age, c12);
                   4442:                    fprintf(ficgp,"\nset out \"%s%d%1d%1d-%1d%1d.png\"",subdirf2(optionfilefiname,"varpijgr"), j1,k1,l1,k2,l2);
                   4443:                    fprintf(ficgp,"\nset label \"%d\" at %11.3e,%11.3e center",(int) age, mu1,mu2);
                   4444:                    fprintf(ficgp,"\n# Age %d, p%1d%1d - p%1d%1d",(int) age, k1,l1,k2,l2);
                   4445:                    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",\
                   4446:                            mu1,std,v11,sqrt(lc1),v12,sqrt(lc2),\
                   4447:                            mu2,std,v21,sqrt(lc1),v22,sqrt(lc2));
                   4448:                  }else{
                   4449:                    first=0;
                   4450:                    fprintf(fichtmcov," %d (%.3f),",(int) age, c12);
                   4451:                    fprintf(ficgp,"\n# Age %d, p%1d%1d - p%1d%1d",(int) age, k1,l1,k2,l2);
                   4452:                    fprintf(ficgp,"\nset label \"%d\" at %11.3e,%11.3e center",(int) age, mu1,mu2);
                   4453:                    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",\
                   4454:                            mu1,std,v11,sqrt(lc1),v12,sqrt(lc2),\
                   4455:                            mu2,std,v21,sqrt(lc1),v22,sqrt(lc2));
                   4456:                  }/* if first */
                   4457:                } /* age mod 5 */
                   4458:              } /* end loop age */
                   4459:              fprintf(ficgp,"\nset out \"%s%d%1d%1d-%1d%1d.png\";replot;",subdirf2(optionfilefiname,"varpijgr"), j1,k1,l1,k2,l2);
                   4460:              first=1;
                   4461:            } /*l12 */
                   4462:          } /* k12 */
                   4463:        } /*l1 */
                   4464:       }/* k1 */
1.169     brouard  4465:       /* } */ /* loop covariates */
1.126     brouard  4466:   }
                   4467:   free_ma3x(varpij,1,nlstate,1,nlstate+ndeath,(int) bage, (int)fage);
                   4468:   free_matrix(mu,1,(nlstate+ndeath)*(nlstate+ndeath),(int) bage, (int)fage);
                   4469:   free_matrix(doldm,1,(nlstate)*(nlstate+ndeath),1,(nlstate)*(nlstate+ndeath));
                   4470:   free_matrix(dnewm,1,(nlstate)*(nlstate+ndeath),1,npar);
                   4471:   free_vector(xp,1,npar);
                   4472:   fclose(ficresprob);
                   4473:   fclose(ficresprobcov);
                   4474:   fclose(ficresprobcor);
                   4475:   fflush(ficgp);
                   4476:   fflush(fichtmcov);
                   4477: }
                   4478: 
                   4479: 
                   4480: /******************* Printing html file ***********/
                   4481: void printinghtml(char fileres[], char title[], char datafile[], int firstpass, \
                   4482:                  int lastpass, int stepm, int weightopt, char model[],\
                   4483:                  int imx,int jmin, int jmax, double jmeanint,char rfileres[],\
                   4484:                  int popforecast, int estepm ,\
                   4485:                  double jprev1, double mprev1,double anprev1, \
                   4486:                  double jprev2, double mprev2,double anprev2){
                   4487:   int jj1, k1, i1, cpt;
                   4488: 
                   4489:    fprintf(fichtm,"<ul><li><a href='#firstorder'>Result files (first order: no variance)</a>\n \
                   4490:    <li><a href='#secondorder'>Result files (second order (variance)</a>\n \
                   4491: </ul>");
                   4492:    fprintf(fichtm,"<ul><li><h4><a name='firstorder'>Result files (first order: no variance)</a></h4>\n \
                   4493:  - Observed prevalence in each state (during the period defined between %.lf/%.lf/%.lf and %.lf/%.lf/%.lf): <a href=\"%s\">%s</a> <br>\n ",
                   4494:           jprev1, mprev1,anprev1,jprev2, mprev2,anprev2,subdirf2(fileres,"p"),subdirf2(fileres,"p"));
                   4495:    fprintf(fichtm,"\
                   4496:  - Estimated transition probabilities over %d (stepm) months: <a href=\"%s\">%s</a><br>\n ",
                   4497:           stepm,subdirf2(fileres,"pij"),subdirf2(fileres,"pij"));
                   4498:    fprintf(fichtm,"\
                   4499:  - Period (stable) prevalence in each health state: <a href=\"%s\">%s</a> <br>\n",
                   4500:           subdirf2(fileres,"pl"),subdirf2(fileres,"pl"));
                   4501:    fprintf(fichtm,"\
1.128     brouard  4502:  - (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  4503:    <a href=\"%s\">%s</a> <br>\n",
                   4504:           estepm,subdirf2(fileres,"e"),subdirf2(fileres,"e"));
                   4505:    fprintf(fichtm,"\
                   4506:  - Population projections by age and states: \
                   4507:    <a href=\"%s\">%s</a> <br>\n</li>", subdirf2(fileres,"f"),subdirf2(fileres,"f"));
                   4508: 
                   4509: fprintf(fichtm," \n<ul><li><b>Graphs</b></li><p>");
                   4510: 
1.145     brouard  4511:  m=pow(2,cptcoveff);
1.126     brouard  4512:  if (cptcovn < 1) {m=1;ncodemax[1]=1;}
                   4513: 
                   4514:  jj1=0;
                   4515:  for(k1=1; k1<=m;k1++){
1.192     brouard  4516:    /* for(i1=1; i1<=ncodemax[k1];i1++){ */
1.126     brouard  4517:      jj1++;
                   4518:      if (cptcovn > 0) {
                   4519:        fprintf(fichtm,"<hr  size=\"2\" color=\"#EC5E5E\">************ Results for covariates");
1.192     brouard  4520:        for (cpt=1; cpt<=cptcoveff;cpt++){ 
1.126     brouard  4521:         fprintf(fichtm," V%d=%d ",Tvaraff[cpt],nbcode[Tvaraff[cpt]][codtab[jj1][cpt]]);
1.192     brouard  4522:         printf(" V%d=%d ",Tvaraff[cpt],nbcode[Tvaraff[cpt]][codtab[jj1][cpt]]);fflush(stdout);
                   4523:        }
1.126     brouard  4524:        fprintf(fichtm," ************\n<hr size=\"2\" color=\"#EC5E5E\">");
                   4525:      }
                   4526:      /* Pij */
1.145     brouard  4527:      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> \
                   4528: <img src=\"%s%d_1.png\">",stepm,subdirf2(optionfilefiname,"pe"),jj1,subdirf2(optionfilefiname,"pe"),jj1,subdirf2(optionfilefiname,"pe"),jj1);     
1.126     brouard  4529:      /* Quasi-incidences */
                   4530:      fprintf(fichtm,"<br>- Pij or Conditional probabilities to be observed in state j being in state i %d (stepm) months\
1.145     brouard  4531:  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> \
                   4532: <img src=\"%s%d_2.png\">",stepm,subdirf2(optionfilefiname,"pe"),jj1,subdirf2(optionfilefiname,"pe"),jj1,subdirf2(optionfilefiname,"pe"),jj1); 
1.126     brouard  4533:        /* Period (stable) prevalence in each health state */
1.154     brouard  4534:        for(cpt=1; cpt<=nlstate;cpt++){
1.166     brouard  4535:         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> \
                   4536: <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  4537:        }
                   4538:      for(cpt=1; cpt<=nlstate;cpt++) {
1.154     brouard  4539:         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> \
                   4540: <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  4541:      }
1.192     brouard  4542:    /* } /\* end i1 *\/ */
1.126     brouard  4543:  }/* End k1 */
                   4544:  fprintf(fichtm,"</ul>");
                   4545: 
                   4546:  fprintf(fichtm,"\
                   4547: \n<br><li><h4> <a name='secondorder'>Result files (second order: variances)</a></h4>\n\
1.193     brouard  4548:  - Parameter file with estimated parameters and covariance matrix: <a href=\"%s\">%s</a> <br> \
                   4549:  - 95%% confidence intervals and T statistics are in the log file.<br>\n", rfileres,rfileres);
1.126     brouard  4550: 
1.193     brouard  4551:  fprintf(fichtm," - Standard deviation of one-step probabilities: <a href=\"%s\">%s</a> <br>\n",
1.126     brouard  4552:         subdirf2(fileres,"prob"),subdirf2(fileres,"prob"));
                   4553:  fprintf(fichtm,"\
                   4554:  - Variance-covariance of one-step probabilities: <a href=\"%s\">%s</a> <br>\n",
                   4555:         subdirf2(fileres,"probcov"),subdirf2(fileres,"probcov"));
                   4556: 
                   4557:  fprintf(fichtm,"\
                   4558:  - Correlation matrix of one-step probabilities: <a href=\"%s\">%s</a> <br>\n",
                   4559:         subdirf2(fileres,"probcor"),subdirf2(fileres,"probcor"));
                   4560:  fprintf(fichtm,"\
                   4561:  - 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): \
                   4562:    <a href=\"%s\">%s</a> <br>\n</li>",
                   4563:           estepm,subdirf2(fileres,"cve"),subdirf2(fileres,"cve"));
                   4564:  fprintf(fichtm,"\
                   4565:  - (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): \
                   4566:    <a href=\"%s\">%s</a> <br>\n</li>",
                   4567:           estepm,subdirf2(fileres,"stde"),subdirf2(fileres,"stde"));
                   4568:  fprintf(fichtm,"\
1.128     brouard  4569:  - 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  4570:         estepm, subdirf2(fileres,"v"),subdirf2(fileres,"v"));
                   4571:  fprintf(fichtm,"\
1.128     brouard  4572:  - 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",
                   4573:         estepm, subdirf2(fileres,"t"),subdirf2(fileres,"t"));
1.126     brouard  4574:  fprintf(fichtm,"\
                   4575:  - Standard deviation of period (stable) prevalences: <a href=\"%s\">%s</a> <br>\n",\
                   4576:         subdirf2(fileres,"vpl"),subdirf2(fileres,"vpl"));
                   4577: 
                   4578: /*  if(popforecast==1) fprintf(fichtm,"\n */
                   4579: /*  - Prevalences forecasting: <a href=\"f%s\">f%s</a> <br>\n */
                   4580: /*  - Population forecasting (if popforecast=1): <a href=\"pop%s\">pop%s</a> <br>\n */
                   4581: /*     <br>",fileres,fileres,fileres,fileres); */
                   4582: /*  else  */
                   4583: /*    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); */
                   4584:  fflush(fichtm);
                   4585:  fprintf(fichtm," <ul><li><b>Graphs</b></li><p>");
                   4586: 
1.145     brouard  4587:  m=pow(2,cptcoveff);
1.126     brouard  4588:  if (cptcovn < 1) {m=1;ncodemax[1]=1;}
                   4589: 
                   4590:  jj1=0;
                   4591:  for(k1=1; k1<=m;k1++){
1.192     brouard  4592:    /* for(i1=1; i1<=ncodemax[k1];i1++){ */
1.126     brouard  4593:      jj1++;
                   4594:      if (cptcovn > 0) {
                   4595:        fprintf(fichtm,"<hr  size=\"2\" color=\"#EC5E5E\">************ Results for covariates");
                   4596:        for (cpt=1; cpt<=cptcoveff;cpt++) 
                   4597:         fprintf(fichtm," V%d=%d ",Tvaraff[cpt],nbcode[Tvaraff[cpt]][codtab[jj1][cpt]]);
                   4598:        fprintf(fichtm," ************\n<hr size=\"2\" color=\"#EC5E5E\">");
                   4599:      }
                   4600:      for(cpt=1; cpt<=nlstate;cpt++) {
                   4601:        fprintf(fichtm,"<br>- Observed (cross-sectional) and period (incidence based) \
1.145     brouard  4602: prevalence (with 95%% confidence interval) in state (%d): %s%d_%d.png <br>\
                   4603: <img src=\"%s%d_%d.png\">",cpt,subdirf2(optionfilefiname,"v"),cpt,jj1,subdirf2(optionfilefiname,"v"),cpt,jj1);  
1.126     brouard  4604:      }
                   4605:      fprintf(fichtm,"\n<br>- Total life expectancy by age and \
1.128     brouard  4606: health expectancies in states (1) and (2). If popbased=1 the smooth (due to the model) \
                   4607: true period expectancies (those weighted with period prevalences are also\
                   4608:  drawn in addition to the population based expectancies computed using\
                   4609:  observed and cahotic prevalences: %s%d.png<br>\
1.126     brouard  4610: <img src=\"%s%d.png\">",subdirf2(optionfilefiname,"e"),jj1,subdirf2(optionfilefiname,"e"),jj1);
1.192     brouard  4611:    /* } /\* end i1 *\/ */
1.126     brouard  4612:  }/* End k1 */
                   4613:  fprintf(fichtm,"</ul>");
                   4614:  fflush(fichtm);
                   4615: }
                   4616: 
                   4617: /******************* Gnuplot file **************/
                   4618: void printinggnuplot(char fileres[], char optionfilefiname[], double ageminpar, double agemaxpar, double fage , char pathc[], double p[]){
                   4619: 
                   4620:   char dirfileres[132],optfileres[132];
1.164     brouard  4621:   int cpt=0,k1=0,i=0,k=0,j=0,jk=0,k2=0,k3=0,ij=0,l=0;
1.130     brouard  4622:   int ng=0;
1.126     brouard  4623: /*   if((ficgp=fopen(optionfilegnuplot,"a"))==NULL) { */
                   4624: /*     printf("Problem with file %s",optionfilegnuplot); */
                   4625: /*     fprintf(ficlog,"Problem with file %s",optionfilegnuplot); */
                   4626: /*   } */
                   4627: 
                   4628:   /*#ifdef windows */
                   4629:   fprintf(ficgp,"cd \"%s\" \n",pathc);
                   4630:     /*#endif */
                   4631:   m=pow(2,cptcoveff);
                   4632: 
                   4633:   strcpy(dirfileres,optionfilefiname);
                   4634:   strcpy(optfileres,"vpl");
                   4635:  /* 1eme*/
1.153     brouard  4636:   fprintf(ficgp,"\n# 1st: Period (stable) prevalence with CI: 'vpl' files\n");
1.126     brouard  4637:   for (cpt=1; cpt<= nlstate ; cpt ++) {
1.145     brouard  4638:     for (k1=1; k1<= m ; k1 ++) { /* plot [100000000000000000000:-100000000000000000000] "mysbiaspar/vplrmysbiaspar.txt to check */
                   4639:      fprintf(ficgp,"\nset out \"%s%d_%d.png\" \n",subdirf2(optionfilefiname,"v"),cpt,k1);
                   4640:      fprintf(ficgp,"\n#set out \"v%s%d_%d.png\" \n",optionfilefiname,cpt,k1);
1.126     brouard  4641:      fprintf(ficgp,"set xlabel \"Age\" \n\
                   4642: set ylabel \"Probability\" \n\
1.145     brouard  4643: set ter png small size 320, 240\n\
1.170     brouard  4644: plot [%.f:%.f] \"%s\" every :::%d::%d u 1:2 \"%%lf",ageminpar,fage,subdirf2(fileres,"vpl"),k1-1,k1-1);
1.126     brouard  4645: 
                   4646:      for (i=1; i<= nlstate ; i ++) {
1.170     brouard  4647:        if (i==cpt) fprintf(ficgp," %%lf (%%lf)");
                   4648:        else        fprintf(ficgp," %%*lf (%%*lf)");
1.126     brouard  4649:      }
1.170     brouard  4650:      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  4651:      for (i=1; i<= nlstate ; i ++) {
1.170     brouard  4652:        if (i==cpt) fprintf(ficgp," %%lf (%%lf)");
                   4653:        else fprintf(ficgp," %%*lf (%%*lf)");
1.126     brouard  4654:      } 
1.170     brouard  4655:      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  4656:      for (i=1; i<= nlstate ; i ++) {
1.170     brouard  4657:        if (i==cpt) fprintf(ficgp," %%lf (%%lf)");
                   4658:        else fprintf(ficgp," %%*lf (%%*lf)");
1.126     brouard  4659:      }  
1.145     brouard  4660:      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  4661:    }
                   4662:   }
                   4663:   /*2 eme*/
1.153     brouard  4664:   fprintf(ficgp,"\n# 2nd: Total life expectancy with CI: 't' files\n");
1.126     brouard  4665:   for (k1=1; k1<= m ; k1 ++) { 
                   4666:     fprintf(ficgp,"\nset out \"%s%d.png\" \n",subdirf2(optionfilefiname,"e"),k1);
1.145     brouard  4667:     fprintf(ficgp,"set ylabel \"Years\" \nset ter png small size 320, 240\nplot [%.f:%.f] ",ageminpar,fage);
1.126     brouard  4668:     
                   4669:     for (i=1; i<= nlstate+1 ; i ++) {
                   4670:       k=2*i;
1.170     brouard  4671:       fprintf(ficgp,"\"%s\" every :::%d::%d u 1:2 \"%%lf",subdirf2(fileres,"t"),k1-1,k1-1);
1.126     brouard  4672:       for (j=1; j<= nlstate+1 ; j ++) {
1.170     brouard  4673:        if (j==i) fprintf(ficgp," %%lf (%%lf)");
                   4674:        else fprintf(ficgp," %%*lf (%%*lf)");
1.126     brouard  4675:       }   
                   4676:       if (i== 1) fprintf(ficgp,"\" t\"TLE\" w l ,");
                   4677:       else fprintf(ficgp,"\" t\"LE in state (%d)\" w l ,",i-1);
1.170     brouard  4678:       fprintf(ficgp,"\"%s\" every :::%d::%d u 1:($2-$3*2) \"%%lf",subdirf2(fileres,"t"),k1-1,k1-1);
1.126     brouard  4679:       for (j=1; j<= nlstate+1 ; j ++) {
1.170     brouard  4680:        if (j==i) fprintf(ficgp," %%lf (%%lf)");
                   4681:        else fprintf(ficgp," %%*lf (%%*lf)");
1.126     brouard  4682:       }   
1.145     brouard  4683:       fprintf(ficgp,"\" t\"\" w l lt 0,");
1.170     brouard  4684:       fprintf(ficgp,"\"%s\" every :::%d::%d u 1:($2+$3*2) \"%%lf",subdirf2(fileres,"t"),k1-1,k1-1);
1.126     brouard  4685:       for (j=1; j<= nlstate+1 ; j ++) {
1.170     brouard  4686:        if (j==i) fprintf(ficgp," %%lf (%%lf)");
                   4687:        else fprintf(ficgp," %%*lf (%%*lf)");
1.126     brouard  4688:       }   
1.145     brouard  4689:       if (i== (nlstate+1)) fprintf(ficgp,"\" t\"\" w l lt 0");
                   4690:       else fprintf(ficgp,"\" t\"\" w l lt 0,");
1.126     brouard  4691:     }
                   4692:   }
                   4693:   
                   4694:   /*3eme*/
                   4695:   
                   4696:   for (k1=1; k1<= m ; k1 ++) { 
                   4697:     for (cpt=1; cpt<= nlstate ; cpt ++) {
                   4698:       /*       k=2+nlstate*(2*cpt-2); */
                   4699:       k=2+(nlstate+1)*(cpt-1);
                   4700:       fprintf(ficgp,"\nset out \"%s%d%d.png\" \n",subdirf2(optionfilefiname,"exp"),cpt,k1);
1.145     brouard  4701:       fprintf(ficgp,"set ter png small size 320, 240\n\
1.126     brouard  4702: 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);
                   4703:       /*fprintf(ficgp,",\"e%s\" every :::%d::%d u 1:($%d-2*$%d) \"\%%lf ",fileres,k1-1,k1-1,k,k+1);
                   4704:        for (i=1; i<= nlstate*2 ; i ++) fprintf(ficgp,"\%%lf (\%%lf) ");
                   4705:        fprintf(ficgp,"\" t \"e%d1\" w l",cpt);
                   4706:        fprintf(ficgp,",\"e%s\" every :::%d::%d u 1:($%d+2*$%d) \"\%%lf ",fileres,k1-1,k1-1,k,k+1);
                   4707:        for (i=1; i<= nlstate*2 ; i ++) fprintf(ficgp,"\%%lf (\%%lf) ");
                   4708:        fprintf(ficgp,"\" t \"e%d1\" w l",cpt);
                   4709:        
                   4710:       */
                   4711:       for (i=1; i< nlstate ; i ++) {
                   4712:        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);
                   4713:        /*      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);*/
                   4714:        
                   4715:       } 
                   4716:       fprintf(ficgp," ,\"%s\" every :::%d::%d u 1:%d t \"e%d.\" w l",subdirf2(fileres,"e"),k1-1,k1-1,k+nlstate,cpt);
                   4717:     }
                   4718:   }
                   4719:   
                   4720:   /* CV preval stable (period) */
1.153     brouard  4721:   for (k1=1; k1<= m ; k1 ++) { /* For each multivariate if any */
                   4722:     for (cpt=1; cpt<=nlstate ; cpt ++) { /* For each life state */
1.126     brouard  4723:       k=3;
1.153     brouard  4724:       fprintf(ficgp,"\n#\n#\n#CV preval stable (period): 'pij' files, cov=%d state=%d",k1, cpt);
1.145     brouard  4725:       fprintf(ficgp,"\nset out \"%s%d_%d.png\" \n",subdirf2(optionfilefiname,"p"),cpt,k1);
1.126     brouard  4726:       fprintf(ficgp,"set xlabel \"Age\" \nset ylabel \"Probability\" \n\
1.145     brouard  4727: set ter png small size 320, 240\n\
1.126     brouard  4728: unset log y\n\
1.153     brouard  4729: plot [%.f:%.f]  ", ageminpar, agemaxpar);
                   4730:       for (i=1; i<= nlstate ; i ++){
                   4731:        if(i==1)
                   4732:          fprintf(ficgp,"\"%s\"",subdirf2(fileres,"pij"));
                   4733:        else
                   4734:          fprintf(ficgp,", '' ");
1.154     brouard  4735:        l=(nlstate+ndeath)*(i-1)+1;
                   4736:        fprintf(ficgp," u ($1==%d ? ($3):1/0):($%d/($%d",k1,k+l+(cpt-1),k+l);
1.153     brouard  4737:        for (j=1; j<= (nlstate-1) ; j ++)
                   4738:          fprintf(ficgp,"+$%d",k+l+j);
                   4739:        fprintf(ficgp,")) t \"prev(%d,%d)\" w l",i,cpt);
                   4740:       } /* nlstate */
                   4741:       fprintf(ficgp,"\n");
                   4742:     } /* end cpt state*/ 
                   4743:   } /* end covariate */  
1.126     brouard  4744:   
                   4745:   /* proba elementaires */
1.187     brouard  4746:   fprintf(ficgp,"\n##############\n#MLE estimated parameters\n#############\n");
1.126     brouard  4747:   for(i=1,jk=1; i <=nlstate; i++){
1.187     brouard  4748:     fprintf(ficgp,"# initial state %d\n",i);
1.126     brouard  4749:     for(k=1; k <=(nlstate+ndeath); k++){
                   4750:       if (k != i) {
1.187     brouard  4751:        fprintf(ficgp,"#   current state %d\n",k);
1.126     brouard  4752:        for(j=1; j <=ncovmodel; j++){
1.187     brouard  4753:          fprintf(ficgp,"p%d=%f; ",jk,p[jk]);
1.126     brouard  4754:          jk++; 
                   4755:        }
1.187     brouard  4756:        fprintf(ficgp,"\n");
1.126     brouard  4757:       }
                   4758:     }
                   4759:    }
1.187     brouard  4760:   fprintf(ficgp,"##############\n#\n");
                   4761: 
1.145     brouard  4762:   /*goto avoid;*/
1.187     brouard  4763:   fprintf(ficgp,"\n##############\n#Graphics of of probabilities or incidences\n#############\n");
                   4764:   fprintf(ficgp,"# logi(p12/p11)=a12+b12*age+c12age*age+d12*V1+e12*V1*age\n");
                   4765:   fprintf(ficgp,"# logi(p12/p11)=p1 +p2*age +p3*age*age+ p4*V1+ p5*V1*age\n");
                   4766:   fprintf(ficgp,"# logi(p13/p11)=a13+b13*age+c13age*age+d13*V1+e13*V1*age\n");
                   4767:   fprintf(ficgp,"# logi(p13/p11)=p6 +p7*age +p8*age*age+ p9*V1+ p10*V1*age\n");
                   4768:   fprintf(ficgp,"# p12+p13+p14+p11=1=p11(1+exp(a12+b12*age+c12age*age+d12*V1+e12*V1*age)\n");
                   4769:   fprintf(ficgp,"#                      +exp(a13+b13*age+c13age*age+d13*V1+e13*V1*age)+...)\n");
                   4770:   fprintf(ficgp,"# p11=1/(1+exp(a12+b12*age+c12age*age+d12*V1+e12*V1*age)\n");
                   4771:   fprintf(ficgp,"#                      +exp(a13+b13*age+c13age*age+d13*V1+e13*V1*age)+...)\n");
                   4772:   fprintf(ficgp,"# p12=exp(a12+b12*age+c12age*age+d12*V1+e12*V1*age)/\n");
                   4773:   fprintf(ficgp,"#     (1+exp(a12+b12*age+c12age*age+d12*V1+e12*V1*age)\n");
                   4774:   fprintf(ficgp,"#       +exp(a13+b13*age+c13age*age+d13*V1+e13*V1*age))\n");
                   4775:   fprintf(ficgp,"#       +exp(a14+b14*age+c14age*age+d14*V1+e14*V1*age)+...)\n");
                   4776:   fprintf(ficgp,"#\n");
1.126     brouard  4777:    for(ng=1; ng<=2;ng++){ /* Number of graphics: first is probabilities second is incidence per year*/
1.187     brouard  4778:      fprintf(ficgp,"# ng=%d\n",ng);
                   4779:      fprintf(ficgp,"#   jk=1 to 2^%d=%d\n",cptcoveff,m);
1.126     brouard  4780:      for(jk=1; jk <=m; jk++) {
1.187     brouard  4781:        fprintf(ficgp,"#    jk=%d\n",jk);
1.145     brouard  4782:        fprintf(ficgp,"\nset out \"%s%d_%d.png\" \n",subdirf2(optionfilefiname,"pe"),jk,ng); 
1.126     brouard  4783:        if (ng==2)
                   4784:         fprintf(ficgp,"\nset ylabel \"Quasi-incidence per year\"\n");
                   4785:        else
                   4786:         fprintf(ficgp,"\nset title \"Probability\"\n");
1.145     brouard  4787:        fprintf(ficgp,"\nset ter png small size 320, 240\nset log y\nplot  [%.f:%.f] ",ageminpar,agemaxpar);
1.126     brouard  4788:        i=1;
                   4789:        for(k2=1; k2<=nlstate; k2++) {
                   4790:         k3=i;
                   4791:         for(k=1; k<=(nlstate+ndeath); k++) {
                   4792:           if (k != k2){
                   4793:             if(ng==2)
1.187     brouard  4794:               if(nagesqr==0)
                   4795:                 fprintf(ficgp," %f*exp(p%d+p%d*x",YEARM/stepm,i,i+1);
                   4796:               else /* nagesqr =1 */
                   4797:                 fprintf(ficgp," %f*exp(p%d+p%d*x+p%d*x*x",YEARM/stepm,i,i+1,i+1+nagesqr);
1.126     brouard  4798:             else
1.187     brouard  4799:               if(nagesqr==0)
                   4800:                 fprintf(ficgp," exp(p%d+p%d*x",i,i+1);
                   4801:               else /* nagesqr =1 */
                   4802:                 fprintf(ficgp," exp(p%d+p%d*x+p%d*x*x",i,i+1,i+1+nagesqr);
1.141     brouard  4803:             ij=1;/* To be checked else nbcode[0][0] wrong */
1.187     brouard  4804:             for(j=3; j <=ncovmodel-nagesqr; j++) {
1.186     brouard  4805:               if(((j-2)==Tage[ij]) &&(ij <=cptcovage)) { /* Bug valgrind */
1.187     brouard  4806:                 fprintf(ficgp,"+p%d*%d*x",i+j+nagesqr-1,nbcode[Tvar[j-2]][codtab[jk][Tvar[j-2]]]);
1.186     brouard  4807:                 ij++;
                   4808:               }
                   4809:               else
1.187     brouard  4810:                 fprintf(ficgp,"+p%d*%d",i+j+nagesqr-1,nbcode[Tvar[j-2]][codtab[jk][j-2]]);
1.126     brouard  4811:             }
                   4812:             fprintf(ficgp,")/(1");
                   4813:             
1.187     brouard  4814:             for(k1=1; k1 <=nlstate; k1++){ 
                   4815:               if(nagesqr==0)
                   4816:                 fprintf(ficgp,"+exp(p%d+p%d*x",k3+(k1-1)*ncovmodel,k3+(k1-1)*ncovmodel+1);
                   4817:               else /* nagesqr =1 */
                   4818:                 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);
                   4819:   
1.126     brouard  4820:               ij=1;
1.187     brouard  4821:               for(j=3; j <=ncovmodel-nagesqr; j++){
1.186     brouard  4822:                 if(((j-2)==Tage[ij]) &&(ij <=cptcovage)) {
1.187     brouard  4823:                   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  4824:                   ij++;
                   4825:                 }
                   4826:                 else
1.187     brouard  4827:                   fprintf(ficgp,"+p%d*%d",k3+(k1-1)*ncovmodel+1+j-2+nagesqr,nbcode[Tvar[j-2]][codtab[jk][j-2]]);
1.126     brouard  4828:               }
                   4829:               fprintf(ficgp,")");
                   4830:             }
                   4831:             fprintf(ficgp,") t \"p%d%d\" ", k2,k);
                   4832:             if ((k+k2)!= (nlstate*2+ndeath)) fprintf(ficgp,",");
                   4833:             i=i+ncovmodel;
                   4834:           }
                   4835:         } /* end k */
                   4836:        } /* end k2 */
                   4837:      } /* end jk */
                   4838:    } /* end ng */
1.164     brouard  4839:  /* avoid: */
1.126     brouard  4840:    fflush(ficgp); 
                   4841: }  /* end gnuplot */
                   4842: 
                   4843: 
                   4844: /*************** Moving average **************/
                   4845: int movingaverage(double ***probs, double bage,double fage, double ***mobaverage, int mobilav){
                   4846: 
                   4847:   int i, cpt, cptcod;
                   4848:   int modcovmax =1;
                   4849:   int mobilavrange, mob;
                   4850:   double age;
                   4851: 
                   4852:   modcovmax=2*cptcoveff;/* Max number of modalities. We suppose 
                   4853:                           a covariate has 2 modalities */
                   4854:   if (cptcovn<1) modcovmax=1; /* At least 1 pass */
                   4855: 
                   4856:   if(mobilav==1||mobilav ==3 ||mobilav==5 ||mobilav== 7){
                   4857:     if(mobilav==1) mobilavrange=5; /* default */
                   4858:     else mobilavrange=mobilav;
                   4859:     for (age=bage; age<=fage; age++)
                   4860:       for (i=1; i<=nlstate;i++)
                   4861:        for (cptcod=1;cptcod<=modcovmax;cptcod++)
                   4862:          mobaverage[(int)age][i][cptcod]=probs[(int)age][i][cptcod];
                   4863:     /* We keep the original values on the extreme ages bage, fage and for 
                   4864:        fage+1 and bage-1 we use a 3 terms moving average; for fage+2 bage+2
                   4865:        we use a 5 terms etc. until the borders are no more concerned. 
                   4866:     */ 
                   4867:     for (mob=3;mob <=mobilavrange;mob=mob+2){
                   4868:       for (age=bage+(mob-1)/2; age<=fage-(mob-1)/2; 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:              for (cpt=1;cpt<=(mob-1)/2;cpt++){
                   4873:                mobaverage[(int)age][i][cptcod] +=probs[(int)age-cpt][i][cptcod];
                   4874:                mobaverage[(int)age][i][cptcod] +=probs[(int)age+cpt][i][cptcod];
                   4875:              }
                   4876:            mobaverage[(int)age][i][cptcod]=mobaverage[(int)age][i][cptcod]/mob;
                   4877:          }
                   4878:        }
                   4879:       }/* end age */
                   4880:     }/* end mob */
                   4881:   }else return -1;
                   4882:   return 0;
                   4883: }/* End movingaverage */
                   4884: 
                   4885: 
                   4886: /************** Forecasting ******************/
1.169     brouard  4887: 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  4888:   /* proj1, year, month, day of starting projection 
                   4889:      agemin, agemax range of age
                   4890:      dateprev1 dateprev2 range of dates during which prevalence is computed
                   4891:      anproj2 year of en of projection (same day and month as proj1).
                   4892:   */
1.164     brouard  4893:   int yearp, stepsize, hstepm, nhstepm, j, k, cptcod, i, h, i1;
1.126     brouard  4894:   double agec; /* generic age */
                   4895:   double agelim, ppij, yp,yp1,yp2,jprojmean,mprojmean,anprojmean;
                   4896:   double *popeffectif,*popcount;
                   4897:   double ***p3mat;
                   4898:   double ***mobaverage;
                   4899:   char fileresf[FILENAMELENGTH];
                   4900: 
                   4901:   agelim=AGESUP;
                   4902:   prevalence(probs, ageminpar, agemax, s, agev, nlstate, imx, Tvar, nbcode, ncodemax, mint, anint, dateprev1, dateprev2, firstpass, lastpass);
                   4903:  
                   4904:   strcpy(fileresf,"f"); 
                   4905:   strcat(fileresf,fileres);
                   4906:   if((ficresf=fopen(fileresf,"w"))==NULL) {
                   4907:     printf("Problem with forecast resultfile: %s\n", fileresf);
                   4908:     fprintf(ficlog,"Problem with forecast resultfile: %s\n", fileresf);
                   4909:   }
                   4910:   printf("Computing forecasting: result on file '%s' \n", fileresf);
                   4911:   fprintf(ficlog,"Computing forecasting: result on file '%s' \n", fileresf);
                   4912: 
                   4913:   if (cptcoveff==0) ncodemax[cptcoveff]=1;
                   4914: 
                   4915:   if (mobilav!=0) {
                   4916:     mobaverage= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
                   4917:     if (movingaverage(probs, ageminpar, fage, mobaverage,mobilav)!=0){
                   4918:       fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav);
                   4919:       printf(" Error in movingaverage mobilav=%d\n",mobilav);
                   4920:     }
                   4921:   }
                   4922: 
                   4923:   stepsize=(int) (stepm+YEARM-1)/YEARM;
                   4924:   if (stepm<=12) stepsize=1;
                   4925:   if(estepm < stepm){
                   4926:     printf ("Problem %d lower than %d\n",estepm, stepm);
                   4927:   }
                   4928:   else  hstepm=estepm;   
                   4929: 
                   4930:   hstepm=hstepm/stepm; 
                   4931:   yp1=modf(dateintmean,&yp);/* extracts integral of datemean in yp  and
                   4932:                                fractional in yp1 */
                   4933:   anprojmean=yp;
                   4934:   yp2=modf((yp1*12),&yp);
                   4935:   mprojmean=yp;
                   4936:   yp1=modf((yp2*30.5),&yp);
                   4937:   jprojmean=yp;
                   4938:   if(jprojmean==0) jprojmean=1;
                   4939:   if(mprojmean==0) jprojmean=1;
                   4940: 
                   4941:   i1=cptcoveff;
                   4942:   if (cptcovn < 1){i1=1;}
                   4943:   
                   4944:   fprintf(ficresf,"# Mean day of interviews %.lf/%.lf/%.lf (%.2f) between %.2f and %.2f \n",jprojmean,mprojmean,anprojmean,dateintmean,dateprev1,dateprev2); 
                   4945:   
                   4946:   fprintf(ficresf,"#****** Routine prevforecast **\n");
                   4947: 
                   4948: /*           if (h==(int)(YEARM*yearp)){ */
                   4949:   for(cptcov=1, k=0;cptcov<=i1;cptcov++){
                   4950:     for(cptcod=1;cptcod<=ncodemax[cptcoveff];cptcod++){
                   4951:       k=k+1;
                   4952:       fprintf(ficresf,"\n#******");
                   4953:       for(j=1;j<=cptcoveff;j++) {
                   4954:        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]]);
                   4955:       }
                   4956:       fprintf(ficresf,"******\n");
                   4957:       fprintf(ficresf,"# Covariate valuofcovar yearproj age");
                   4958:       for(j=1; j<=nlstate+ndeath;j++){ 
                   4959:        for(i=1; i<=nlstate;i++)              
                   4960:           fprintf(ficresf," p%d%d",i,j);
                   4961:        fprintf(ficresf," p.%d",j);
                   4962:       }
                   4963:       for (yearp=0; yearp<=(anproj2-anproj1);yearp +=stepsize) { 
                   4964:        fprintf(ficresf,"\n");
                   4965:        fprintf(ficresf,"\n# Forecasting at date %.lf/%.lf/%.lf ",jproj1,mproj1,anproj1+yearp);   
                   4966: 
                   4967:        for (agec=fage; agec>=(ageminpar-1); agec--){ 
                   4968:          nhstepm=(int) rint((agelim-agec)*YEARM/stepm); 
                   4969:          nhstepm = nhstepm/hstepm; 
                   4970:          p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   4971:          oldm=oldms;savm=savms;
                   4972:          hpxij(p3mat,nhstepm,agec,hstepm,p,nlstate,stepm,oldm,savm, k);  
                   4973:        
                   4974:          for (h=0; h<=nhstepm; h++){
                   4975:            if (h*hstepm/YEARM*stepm ==yearp) {
                   4976:               fprintf(ficresf,"\n");
                   4977:               for(j=1;j<=cptcoveff;j++) 
                   4978:                 fprintf(ficresf,"%d %d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
                   4979:              fprintf(ficresf,"%.f %.f ",anproj1+yearp,agec+h*hstepm/YEARM*stepm);
                   4980:            } 
                   4981:            for(j=1; j<=nlstate+ndeath;j++) {
                   4982:              ppij=0.;
                   4983:              for(i=1; i<=nlstate;i++) {
                   4984:                if (mobilav==1) 
                   4985:                  ppij=ppij+p3mat[i][j][h]*mobaverage[(int)agec][i][cptcod];
                   4986:                else {
                   4987:                  ppij=ppij+p3mat[i][j][h]*probs[(int)(agec)][i][cptcod];
                   4988:                }
                   4989:                if (h*hstepm/YEARM*stepm== yearp) {
                   4990:                  fprintf(ficresf," %.3f", p3mat[i][j][h]);
                   4991:                }
                   4992:              } /* end i */
                   4993:              if (h*hstepm/YEARM*stepm==yearp) {
                   4994:                fprintf(ficresf," %.3f", ppij);
                   4995:              }
                   4996:            }/* end j */
                   4997:          } /* end h */
                   4998:          free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   4999:        } /* end agec */
                   5000:       } /* end yearp */
                   5001:     } /* end cptcod */
                   5002:   } /* end  cptcov */
                   5003:        
                   5004:   if (mobilav!=0) free_ma3x(mobaverage,1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
                   5005: 
                   5006:   fclose(ficresf);
                   5007: }
                   5008: 
                   5009: /************** Forecasting *****not tested NB*************/
1.169     brouard  5010: 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  5011:   
                   5012:   int cpt, stepsize, hstepm, nhstepm, j,k,c, cptcod, i,h;
                   5013:   int *popage;
                   5014:   double calagedatem, agelim, kk1, kk2;
                   5015:   double *popeffectif,*popcount;
                   5016:   double ***p3mat,***tabpop,***tabpopprev;
                   5017:   double ***mobaverage;
                   5018:   char filerespop[FILENAMELENGTH];
                   5019: 
                   5020:   tabpop= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
                   5021:   tabpopprev= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
                   5022:   agelim=AGESUP;
                   5023:   calagedatem=(anpyram+mpyram/12.+jpyram/365.-dateintmean)*YEARM;
                   5024:   
                   5025:   prevalence(probs, ageminpar, agemax, s, agev, nlstate, imx, Tvar, nbcode, ncodemax, mint, anint, dateprev1, dateprev2, firstpass, lastpass);
                   5026:   
                   5027:   
                   5028:   strcpy(filerespop,"pop"); 
                   5029:   strcat(filerespop,fileres);
                   5030:   if((ficrespop=fopen(filerespop,"w"))==NULL) {
                   5031:     printf("Problem with forecast resultfile: %s\n", filerespop);
                   5032:     fprintf(ficlog,"Problem with forecast resultfile: %s\n", filerespop);
                   5033:   }
                   5034:   printf("Computing forecasting: result on file '%s' \n", filerespop);
                   5035:   fprintf(ficlog,"Computing forecasting: result on file '%s' \n", filerespop);
                   5036: 
                   5037:   if (cptcoveff==0) ncodemax[cptcoveff]=1;
                   5038: 
                   5039:   if (mobilav!=0) {
                   5040:     mobaverage= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
                   5041:     if (movingaverage(probs, ageminpar, fage, mobaverage,mobilav)!=0){
                   5042:       fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav);
                   5043:       printf(" Error in movingaverage mobilav=%d\n",mobilav);
                   5044:     }
                   5045:   }
                   5046: 
                   5047:   stepsize=(int) (stepm+YEARM-1)/YEARM;
                   5048:   if (stepm<=12) stepsize=1;
                   5049:   
                   5050:   agelim=AGESUP;
                   5051:   
                   5052:   hstepm=1;
                   5053:   hstepm=hstepm/stepm; 
                   5054:   
                   5055:   if (popforecast==1) {
                   5056:     if((ficpop=fopen(popfile,"r"))==NULL) {
                   5057:       printf("Problem with population file : %s\n",popfile);exit(0);
                   5058:       fprintf(ficlog,"Problem with population file : %s\n",popfile);exit(0);
                   5059:     } 
                   5060:     popage=ivector(0,AGESUP);
                   5061:     popeffectif=vector(0,AGESUP);
                   5062:     popcount=vector(0,AGESUP);
                   5063:     
                   5064:     i=1;   
                   5065:     while ((c=fscanf(ficpop,"%d %lf\n",&popage[i],&popcount[i])) != EOF) i=i+1;
                   5066:    
                   5067:     imx=i;
                   5068:     for (i=1; i<imx;i++) popeffectif[popage[i]]=popcount[i];
                   5069:   }
                   5070: 
                   5071:   for(cptcov=1,k=0;cptcov<=i2;cptcov++){
                   5072:    for(cptcod=1;cptcod<=ncodemax[cptcoveff];cptcod++){
                   5073:       k=k+1;
                   5074:       fprintf(ficrespop,"\n#******");
                   5075:       for(j=1;j<=cptcoveff;j++) {
                   5076:        fprintf(ficrespop," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
                   5077:       }
                   5078:       fprintf(ficrespop,"******\n");
                   5079:       fprintf(ficrespop,"# Age");
                   5080:       for(j=1; j<=nlstate+ndeath;j++) fprintf(ficrespop," P.%d",j);
                   5081:       if (popforecast==1)  fprintf(ficrespop," [Population]");
                   5082:       
                   5083:       for (cpt=0; cpt<=0;cpt++) { 
                   5084:        fprintf(ficrespop,"\n\n# Forecasting at date %.lf/%.lf/%.lf ",jpyram,mpyram,anpyram+cpt);   
                   5085:        
                   5086:        for (agedeb=(fage-((int)calagedatem %12/12.)); agedeb>=(ageminpar-((int)calagedatem %12)/12.); agedeb--){ 
                   5087:          nhstepm=(int) rint((agelim-agedeb)*YEARM/stepm); 
                   5088:          nhstepm = nhstepm/hstepm; 
                   5089:          
                   5090:          p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   5091:          oldm=oldms;savm=savms;
                   5092:          hpxij(p3mat,nhstepm,agedeb,hstepm,p,nlstate,stepm,oldm,savm, k);  
                   5093:        
                   5094:          for (h=0; h<=nhstepm; h++){
                   5095:            if (h==(int) (calagedatem+YEARM*cpt)) {
                   5096:              fprintf(ficrespop,"\n %3.f ",agedeb+h*hstepm/YEARM*stepm);
                   5097:            } 
                   5098:            for(j=1; j<=nlstate+ndeath;j++) {
                   5099:              kk1=0.;kk2=0;
                   5100:              for(i=1; i<=nlstate;i++) {              
                   5101:                if (mobilav==1) 
                   5102:                  kk1=kk1+p3mat[i][j][h]*mobaverage[(int)agedeb+1][i][cptcod];
                   5103:                else {
                   5104:                  kk1=kk1+p3mat[i][j][h]*probs[(int)(agedeb+1)][i][cptcod];
                   5105:                }
                   5106:              }
                   5107:              if (h==(int)(calagedatem+12*cpt)){
                   5108:                tabpop[(int)(agedeb)][j][cptcod]=kk1;
                   5109:                  /*fprintf(ficrespop," %.3f", kk1);
                   5110:                    if (popforecast==1) fprintf(ficrespop," [%.f]", kk1*popeffectif[(int)agedeb+1]);*/
                   5111:              }
                   5112:            }
                   5113:            for(i=1; i<=nlstate;i++){
                   5114:              kk1=0.;
                   5115:                for(j=1; j<=nlstate;j++){
                   5116:                  kk1= kk1+tabpop[(int)(agedeb)][j][cptcod]; 
                   5117:                }
                   5118:                  tabpopprev[(int)(agedeb)][i][cptcod]=tabpop[(int)(agedeb)][i][cptcod]/kk1*popeffectif[(int)(agedeb+(calagedatem+12*cpt)*hstepm/YEARM*stepm-1)];
                   5119:            }
                   5120: 
                   5121:            if (h==(int)(calagedatem+12*cpt)) for(j=1; j<=nlstate;j++) 
                   5122:              fprintf(ficrespop," %15.2f",tabpopprev[(int)(agedeb+1)][j][cptcod]);
                   5123:          }
                   5124:          free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   5125:        }
                   5126:       }
                   5127:  
                   5128:   /******/
                   5129: 
                   5130:       for (cpt=1; cpt<=(anpyram1-anpyram);cpt++) { 
                   5131:        fprintf(ficrespop,"\n\n# Forecasting at date %.lf/%.lf/%.lf ",jpyram,mpyram,anpyram+cpt);   
                   5132:        for (agedeb=(fage-((int)calagedatem %12/12.)); agedeb>=(ageminpar-((int)calagedatem %12)/12.); agedeb--){ 
                   5133:          nhstepm=(int) rint((agelim-agedeb)*YEARM/stepm); 
                   5134:          nhstepm = nhstepm/hstepm; 
                   5135:          
                   5136:          p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   5137:          oldm=oldms;savm=savms;
                   5138:          hpxij(p3mat,nhstepm,agedeb,hstepm,p,nlstate,stepm,oldm,savm, k);  
                   5139:          for (h=0; h<=nhstepm; h++){
                   5140:            if (h==(int) (calagedatem+YEARM*cpt)) {
                   5141:              fprintf(ficresf,"\n %3.f ",agedeb+h*hstepm/YEARM*stepm);
                   5142:            } 
                   5143:            for(j=1; j<=nlstate+ndeath;j++) {
                   5144:              kk1=0.;kk2=0;
                   5145:              for(i=1; i<=nlstate;i++) {              
                   5146:                kk1=kk1+p3mat[i][j][h]*tabpopprev[(int)agedeb+1][i][cptcod];    
                   5147:              }
                   5148:              if (h==(int)(calagedatem+12*cpt)) fprintf(ficresf," %15.2f", kk1);        
                   5149:            }
                   5150:          }
                   5151:          free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   5152:        }
                   5153:       }
                   5154:    } 
                   5155:   }
                   5156:  
                   5157:   if (mobilav!=0) free_ma3x(mobaverage,1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
                   5158: 
                   5159:   if (popforecast==1) {
                   5160:     free_ivector(popage,0,AGESUP);
                   5161:     free_vector(popeffectif,0,AGESUP);
                   5162:     free_vector(popcount,0,AGESUP);
                   5163:   }
                   5164:   free_ma3x(tabpop,1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
                   5165:   free_ma3x(tabpopprev,1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
                   5166:   fclose(ficrespop);
                   5167: } /* End of popforecast */
                   5168: 
                   5169: int fileappend(FILE *fichier, char *optionfich)
                   5170: {
                   5171:   if((fichier=fopen(optionfich,"a"))==NULL) {
                   5172:     printf("Problem with file: %s\n", optionfich);
                   5173:     fprintf(ficlog,"Problem with file: %s\n", optionfich);
                   5174:     return (0);
                   5175:   }
                   5176:   fflush(fichier);
                   5177:   return (1);
                   5178: }
                   5179: 
                   5180: 
                   5181: /**************** function prwizard **********************/
                   5182: void prwizard(int ncovmodel, int nlstate, int ndeath,  char model[], FILE *ficparo)
                   5183: {
                   5184: 
                   5185:   /* Wizard to print covariance matrix template */
                   5186: 
1.164     brouard  5187:   char ca[32], cb[32];
                   5188:   int i,j, k, li, lj, lk, ll, jj, npar, itimes;
1.126     brouard  5189:   int numlinepar;
                   5190: 
                   5191:   printf("# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
                   5192:   fprintf(ficparo,"# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
                   5193:   for(i=1; i <=nlstate; i++){
                   5194:     jj=0;
                   5195:     for(j=1; j <=nlstate+ndeath; j++){
                   5196:       if(j==i) continue;
                   5197:       jj++;
                   5198:       /*ca[0]= k+'a'-1;ca[1]='\0';*/
                   5199:       printf("%1d%1d",i,j);
                   5200:       fprintf(ficparo,"%1d%1d",i,j);
                   5201:       for(k=1; k<=ncovmodel;k++){
                   5202:        /*        printf(" %lf",param[i][j][k]); */
                   5203:        /*        fprintf(ficparo," %lf",param[i][j][k]); */
                   5204:        printf(" 0.");
                   5205:        fprintf(ficparo," 0.");
                   5206:       }
                   5207:       printf("\n");
                   5208:       fprintf(ficparo,"\n");
                   5209:     }
                   5210:   }
                   5211:   printf("# Scales (for hessian or gradient estimation)\n");
                   5212:   fprintf(ficparo,"# Scales (for hessian or gradient estimation)\n");
                   5213:   npar= (nlstate+ndeath-1)*nlstate*ncovmodel; /* Number of parameters*/ 
                   5214:   for(i=1; i <=nlstate; i++){
                   5215:     jj=0;
                   5216:     for(j=1; j <=nlstate+ndeath; j++){
                   5217:       if(j==i) continue;
                   5218:       jj++;
                   5219:       fprintf(ficparo,"%1d%1d",i,j);
                   5220:       printf("%1d%1d",i,j);
                   5221:       fflush(stdout);
                   5222:       for(k=1; k<=ncovmodel;k++){
                   5223:        /*      printf(" %le",delti3[i][j][k]); */
                   5224:        /*      fprintf(ficparo," %le",delti3[i][j][k]); */
                   5225:        printf(" 0.");
                   5226:        fprintf(ficparo," 0.");
                   5227:       }
                   5228:       numlinepar++;
                   5229:       printf("\n");
                   5230:       fprintf(ficparo,"\n");
                   5231:     }
                   5232:   }
                   5233:   printf("# Covariance matrix\n");
                   5234: /* # 121 Var(a12)\n\ */
                   5235: /* # 122 Cov(b12,a12) Var(b12)\n\ */
                   5236: /* # 131 Cov(a13,a12) Cov(a13,b12, Var(a13)\n\ */
                   5237: /* # 132 Cov(b13,a12) Cov(b13,b12, Cov(b13,a13) Var(b13)\n\ */
                   5238: /* # 212 Cov(a21,a12) Cov(a21,b12, Cov(a21,a13) Cov(a21,b13) Var(a21)\n\ */
                   5239: /* # 212 Cov(b21,a12) Cov(b21,b12, Cov(b21,a13) Cov(b21,b13) Cov(b21,a21) Var(b21)\n\ */
                   5240: /* # 232 Cov(a23,a12) Cov(a23,b12, Cov(a23,a13) Cov(a23,b13) Cov(a23,a21) Cov(a23,b21) Var(a23)\n\ */
                   5241: /* # 232 Cov(b23,a12) Cov(b23,b12) ... Var (b23)\n" */
                   5242:   fflush(stdout);
                   5243:   fprintf(ficparo,"# Covariance matrix\n");
                   5244:   /* # 121 Var(a12)\n\ */
                   5245:   /* # 122 Cov(b12,a12) Var(b12)\n\ */
                   5246:   /* #   ...\n\ */
                   5247:   /* # 232 Cov(b23,a12)  Cov(b23,b12) ... Var (b23)\n" */
                   5248:   
                   5249:   for(itimes=1;itimes<=2;itimes++){
                   5250:     jj=0;
                   5251:     for(i=1; i <=nlstate; i++){
                   5252:       for(j=1; j <=nlstate+ndeath; j++){
                   5253:        if(j==i) continue;
                   5254:        for(k=1; k<=ncovmodel;k++){
                   5255:          jj++;
                   5256:          ca[0]= k+'a'-1;ca[1]='\0';
                   5257:          if(itimes==1){
                   5258:            printf("#%1d%1d%d",i,j,k);
                   5259:            fprintf(ficparo,"#%1d%1d%d",i,j,k);
                   5260:          }else{
                   5261:            printf("%1d%1d%d",i,j,k);
                   5262:            fprintf(ficparo,"%1d%1d%d",i,j,k);
                   5263:            /*  printf(" %.5le",matcov[i][j]); */
                   5264:          }
                   5265:          ll=0;
                   5266:          for(li=1;li <=nlstate; li++){
                   5267:            for(lj=1;lj <=nlstate+ndeath; lj++){
                   5268:              if(lj==li) continue;
                   5269:              for(lk=1;lk<=ncovmodel;lk++){
                   5270:                ll++;
                   5271:                if(ll<=jj){
                   5272:                  cb[0]= lk +'a'-1;cb[1]='\0';
                   5273:                  if(ll<jj){
                   5274:                    if(itimes==1){
                   5275:                      printf(" Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
                   5276:                      fprintf(ficparo," Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
                   5277:                    }else{
                   5278:                      printf(" 0.");
                   5279:                      fprintf(ficparo," 0.");
                   5280:                    }
                   5281:                  }else{
                   5282:                    if(itimes==1){
                   5283:                      printf(" Var(%s%1d%1d)",ca,i,j);
                   5284:                      fprintf(ficparo," Var(%s%1d%1d)",ca,i,j);
                   5285:                    }else{
                   5286:                      printf(" 0.");
                   5287:                      fprintf(ficparo," 0.");
                   5288:                    }
                   5289:                  }
                   5290:                }
                   5291:              } /* end lk */
                   5292:            } /* end lj */
                   5293:          } /* end li */
                   5294:          printf("\n");
                   5295:          fprintf(ficparo,"\n");
                   5296:          numlinepar++;
                   5297:        } /* end k*/
                   5298:       } /*end j */
                   5299:     } /* end i */
                   5300:   } /* end itimes */
                   5301: 
                   5302: } /* end of prwizard */
                   5303: /******************* Gompertz Likelihood ******************************/
                   5304: double gompertz(double x[])
                   5305: { 
                   5306:   double A,B,L=0.0,sump=0.,num=0.;
                   5307:   int i,n=0; /* n is the size of the sample */
                   5308: 
                   5309:   for (i=0;i<=imx-1 ; i++) {
                   5310:     sump=sump+weight[i];
                   5311:     /*    sump=sump+1;*/
                   5312:     num=num+1;
                   5313:   }
                   5314:  
                   5315:  
                   5316:   /* for (i=0; i<=imx; i++) 
                   5317:      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]);*/
                   5318: 
                   5319:   for (i=1;i<=imx ; i++)
                   5320:     {
                   5321:       if (cens[i] == 1 && wav[i]>1)
                   5322:        A=-x[1]/(x[2])*(exp(x[2]*(agecens[i]-agegomp))-exp(x[2]*(ageexmed[i]-agegomp)));
                   5323:       
                   5324:       if (cens[i] == 0 && wav[i]>1)
                   5325:        A=-x[1]/(x[2])*(exp(x[2]*(agedc[i]-agegomp))-exp(x[2]*(ageexmed[i]-agegomp)))
                   5326:             +log(x[1]/YEARM)+x[2]*(agedc[i]-agegomp)+log(YEARM);  
                   5327:       
                   5328:       /*if (wav[i] > 1 && agecens[i] > 15) {*/ /* ??? */
                   5329:       if (wav[i] > 1 ) { /* ??? */
                   5330:        L=L+A*weight[i];
                   5331:        /*      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]);*/
                   5332:       }
                   5333:     }
                   5334: 
                   5335:  /*printf("x1=%2.9f x2=%2.9f x3=%2.9f L=%f\n",x[1],x[2],x[3],L);*/
                   5336:  
                   5337:   return -2*L*num/sump;
                   5338: }
                   5339: 
1.136     brouard  5340: #ifdef GSL
                   5341: /******************* Gompertz_f Likelihood ******************************/
                   5342: double gompertz_f(const gsl_vector *v, void *params)
                   5343: { 
                   5344:   double A,B,LL=0.0,sump=0.,num=0.;
                   5345:   double *x= (double *) v->data;
                   5346:   int i,n=0; /* n is the size of the sample */
                   5347: 
                   5348:   for (i=0;i<=imx-1 ; i++) {
                   5349:     sump=sump+weight[i];
                   5350:     /*    sump=sump+1;*/
                   5351:     num=num+1;
                   5352:   }
                   5353:  
                   5354:  
                   5355:   /* for (i=0; i<=imx; i++) 
                   5356:      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]);*/
                   5357:   printf("x[0]=%lf x[1]=%lf\n",x[0],x[1]);
                   5358:   for (i=1;i<=imx ; i++)
                   5359:     {
                   5360:       if (cens[i] == 1 && wav[i]>1)
                   5361:        A=-x[0]/(x[1])*(exp(x[1]*(agecens[i]-agegomp))-exp(x[1]*(ageexmed[i]-agegomp)));
                   5362:       
                   5363:       if (cens[i] == 0 && wav[i]>1)
                   5364:        A=-x[0]/(x[1])*(exp(x[1]*(agedc[i]-agegomp))-exp(x[1]*(ageexmed[i]-agegomp)))
                   5365:             +log(x[0]/YEARM)+x[1]*(agedc[i]-agegomp)+log(YEARM);  
                   5366:       
                   5367:       /*if (wav[i] > 1 && agecens[i] > 15) {*/ /* ??? */
                   5368:       if (wav[i] > 1 ) { /* ??? */
                   5369:        LL=LL+A*weight[i];
                   5370:        /*      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]);*/
                   5371:       }
                   5372:     }
                   5373: 
                   5374:  /*printf("x1=%2.9f x2=%2.9f x3=%2.9f L=%f\n",x[1],x[2],x[3],L);*/
                   5375:   printf("x[0]=%lf x[1]=%lf -2*LL*num/sump=%lf\n",x[0],x[1],-2*LL*num/sump);
                   5376:  
                   5377:   return -2*LL*num/sump;
                   5378: }
                   5379: #endif
                   5380: 
1.126     brouard  5381: /******************* Printing html file ***********/
                   5382: void printinghtmlmort(char fileres[], char title[], char datafile[], int firstpass, \
                   5383:                  int lastpass, int stepm, int weightopt, char model[],\
                   5384:                  int imx,  double p[],double **matcov,double agemortsup){
                   5385:   int i,k;
                   5386: 
                   5387:   fprintf(fichtm,"<ul><li><h4>Result files </h4>\n Force of mortality. Parameters of the Gompertz fit (with confidence interval in brackets):<br>");
                   5388:   fprintf(fichtm,"  mu(age) =%lf*exp(%lf*(age-%d)) per year<br><br>",p[1],p[2],agegomp);
                   5389:   for (i=1;i<=2;i++) 
                   5390:     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]));
                   5391:   fprintf(fichtm,"<br><br><img src=\"graphmort.png\">");
                   5392:   fprintf(fichtm,"</ul>");
                   5393: 
                   5394: fprintf(fichtm,"<ul><li><h4>Life table</h4>\n <br>");
                   5395: 
                   5396:  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>");
                   5397: 
                   5398:  for (k=agegomp;k<(agemortsup-2);k++) 
                   5399:    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]);
                   5400: 
                   5401:  
                   5402:   fflush(fichtm);
                   5403: }
                   5404: 
                   5405: /******************* Gnuplot file **************/
                   5406: void printinggnuplotmort(char fileres[], char optionfilefiname[], double ageminpar, double agemaxpar, double fage , char pathc[], double p[]){
                   5407: 
                   5408:   char dirfileres[132],optfileres[132];
1.164     brouard  5409: 
1.126     brouard  5410:   int ng;
                   5411: 
                   5412: 
                   5413:   /*#ifdef windows */
                   5414:   fprintf(ficgp,"cd \"%s\" \n",pathc);
                   5415:     /*#endif */
                   5416: 
                   5417: 
                   5418:   strcpy(dirfileres,optionfilefiname);
                   5419:   strcpy(optfileres,"vpl");
                   5420:   fprintf(ficgp,"set out \"graphmort.png\"\n "); 
                   5421:   fprintf(ficgp,"set xlabel \"Age\"\n set ylabel \"Force of mortality (per year)\" \n "); 
1.145     brouard  5422:   fprintf(ficgp, "set ter png small size 320, 240\n set log y\n"); 
                   5423:   /* fprintf(ficgp, "set size 0.65,0.65\n"); */
1.126     brouard  5424:   fprintf(ficgp,"plot [%d:100] %lf*exp(%lf*(x-%d))",agegomp,p[1],p[2],agegomp);
                   5425: 
                   5426: } 
                   5427: 
1.136     brouard  5428: int readdata(char datafile[], int firstobs, int lastobs, int *imax)
                   5429: {
1.126     brouard  5430: 
1.136     brouard  5431:   /*-------- data file ----------*/
                   5432:   FILE *fic;
                   5433:   char dummy[]="                         ";
1.164     brouard  5434:   int i=0, j=0, n=0;
1.136     brouard  5435:   int linei, month, year,iout;
                   5436:   char line[MAXLINE], linetmp[MAXLINE];
1.164     brouard  5437:   char stra[MAXLINE], strb[MAXLINE];
1.136     brouard  5438:   char *stratrunc;
                   5439:   int lstra;
1.126     brouard  5440: 
                   5441: 
1.136     brouard  5442:   if((fic=fopen(datafile,"r"))==NULL)    {
1.195   ! brouard  5443:     printf("Problem while opening datafile: %s\n", datafile);fflush(stdout);
        !          5444:     fprintf(ficlog,"Problem while opening datafile: %s\n", datafile);fflush(ficlog);return 1;
1.136     brouard  5445:   }
1.126     brouard  5446: 
1.136     brouard  5447:   i=1;
                   5448:   linei=0;
                   5449:   while ((fgets(line, MAXLINE, fic) != NULL) &&((i >= firstobs) && (i <=lastobs))) {
                   5450:     linei=linei+1;
                   5451:     for(j=strlen(line); j>=0;j--){  /* Untabifies line */
                   5452:       if(line[j] == '\t')
                   5453:        line[j] = ' ';
                   5454:     }
                   5455:     for(j=strlen(line)-1; (line[j]==' ')||(line[j]==10)||(line[j]==13);j--){
                   5456:       ;
                   5457:     };
                   5458:     line[j+1]=0;  /* Trims blanks at end of line */
                   5459:     if(line[0]=='#'){
                   5460:       fprintf(ficlog,"Comment line\n%s\n",line);
                   5461:       printf("Comment line\n%s\n",line);
                   5462:       continue;
                   5463:     }
                   5464:     trimbb(linetmp,line); /* Trims multiple blanks in line */
1.164     brouard  5465:     strcpy(line, linetmp);
1.136     brouard  5466:   
1.126     brouard  5467: 
1.136     brouard  5468:     for (j=maxwav;j>=1;j--){
1.137     brouard  5469:       cutv(stra, strb, line, ' '); 
1.136     brouard  5470:       if(strb[0]=='.') { /* Missing status */
                   5471:        lval=-1;
                   5472:       }else{
                   5473:        errno=0;
                   5474:        lval=strtol(strb,&endptr,10); 
                   5475:       /*       if (errno == ERANGE && (lval == LONG_MAX || lval == LONG_MIN))*/
                   5476:        if( strb[0]=='\0' || (*endptr != '\0')){
1.141     brouard  5477:          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);
                   5478:          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  5479:          return 1;
                   5480:        }
                   5481:       }
                   5482:       s[j][i]=lval;
                   5483:       
                   5484:       strcpy(line,stra);
                   5485:       cutv(stra, strb,line,' ');
1.169     brouard  5486:       if( (iout=sscanf(strb,"%d/%d",&month, &year)) != 0){
1.136     brouard  5487:       }
1.169     brouard  5488:       else  if( (iout=sscanf(strb,"%s.",dummy)) != 0){
1.136     brouard  5489:        month=99;
                   5490:        year=9999;
                   5491:       }else{
1.141     brouard  5492:        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);
                   5493:        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  5494:        return 1;
                   5495:       }
                   5496:       anint[j][i]= (double) year; 
                   5497:       mint[j][i]= (double)month; 
                   5498:       strcpy(line,stra);
                   5499:     } /* ENd Waves */
                   5500:     
                   5501:     cutv(stra, strb,line,' '); 
1.169     brouard  5502:     if( (iout=sscanf(strb,"%d/%d",&month, &year)) != 0){
1.136     brouard  5503:     }
1.169     brouard  5504:     else  if( (iout=sscanf(strb,"%s.",dummy)) != 0){
1.136     brouard  5505:       month=99;
                   5506:       year=9999;
                   5507:     }else{
1.141     brouard  5508:       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);
                   5509:        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  5510:        return 1;
                   5511:     }
                   5512:     andc[i]=(double) year; 
                   5513:     moisdc[i]=(double) month; 
                   5514:     strcpy(line,stra);
                   5515:     
                   5516:     cutv(stra, strb,line,' '); 
1.169     brouard  5517:     if( (iout=sscanf(strb,"%d/%d",&month, &year)) != 0){
1.136     brouard  5518:     }
1.169     brouard  5519:     else  if( (iout=sscanf(strb,"%s.", dummy)) != 0){
1.136     brouard  5520:       month=99;
                   5521:       year=9999;
                   5522:     }else{
1.141     brouard  5523:       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);
                   5524:       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  5525:        return 1;
                   5526:     }
                   5527:     if (year==9999) {
1.141     brouard  5528:       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);
                   5529:       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  5530:        return 1;
1.126     brouard  5531: 
1.136     brouard  5532:     }
                   5533:     annais[i]=(double)(year);
                   5534:     moisnais[i]=(double)(month); 
                   5535:     strcpy(line,stra);
                   5536:     
                   5537:     cutv(stra, strb,line,' '); 
                   5538:     errno=0;
                   5539:     dval=strtod(strb,&endptr); 
                   5540:     if( strb[0]=='\0' || (*endptr != '\0')){
1.141     brouard  5541:       printf("Error reading data around '%f' at line number %d, \"%s\" for individual %d\nShould be a weight.  Exiting.\n",dval, i,line,linei);
                   5542:       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  5543:       fflush(ficlog);
                   5544:       return 1;
                   5545:     }
                   5546:     weight[i]=dval; 
                   5547:     strcpy(line,stra);
                   5548:     
                   5549:     for (j=ncovcol;j>=1;j--){
                   5550:       cutv(stra, strb,line,' '); 
                   5551:       if(strb[0]=='.') { /* Missing status */
                   5552:        lval=-1;
                   5553:       }else{
                   5554:        errno=0;
                   5555:        lval=strtol(strb,&endptr,10); 
                   5556:        if( strb[0]=='\0' || (*endptr != '\0')){
1.141     brouard  5557:          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);
                   5558:          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  5559:          return 1;
                   5560:        }
                   5561:       }
                   5562:       if(lval <-1 || lval >1){
1.141     brouard  5563:        printf("Error reading data around '%ld' at line number %d for individual %d, '%s'\n \
1.136     brouard  5564:  Should be a value of %d(nth) covariate (0 should be the value for the reference and 1\n \
                   5565:  for the alternative. IMaCh does not build design variables automatically, do it yourself.\n \
                   5566:  For example, for multinomial values like 1, 2 and 3,\n \
                   5567:  build V1=0 V2=0 for the reference value (1),\n \
                   5568:         V1=1 V2=0 for (2) \n \
                   5569:  and V1=0 V2=1 for (3). V1=1 V2=1 should not exist and the corresponding\n \
                   5570:  output of IMaCh is often meaningless.\n \
                   5571:  Exiting.\n",lval,linei, i,line,j);
1.141     brouard  5572:        fprintf(ficlog,"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);fflush(ficlog);
                   5581:        return 1;
                   5582:       }
                   5583:       covar[j][i]=(double)(lval);
                   5584:       strcpy(line,stra);
                   5585:     }  
                   5586:     lstra=strlen(stra);
                   5587:      
                   5588:     if(lstra > 9){ /* More than 2**32 or max of what printf can write with %ld */
                   5589:       stratrunc = &(stra[lstra-9]);
                   5590:       num[i]=atol(stratrunc);
                   5591:     }
                   5592:     else
                   5593:       num[i]=atol(stra);
                   5594:     /*if((s[2][i]==2) && (s[3][i]==-1)&&(s[4][i]==9)){
                   5595:       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;}*/
                   5596:     
                   5597:     i=i+1;
                   5598:   } /* End loop reading  data */
1.126     brouard  5599: 
1.136     brouard  5600:   *imax=i-1; /* Number of individuals */
                   5601:   fclose(fic);
                   5602:  
                   5603:   return (0);
1.164     brouard  5604:   /* endread: */
1.136     brouard  5605:     printf("Exiting readdata: ");
                   5606:     fclose(fic);
                   5607:     return (1);
1.126     brouard  5608: 
                   5609: 
                   5610: 
1.136     brouard  5611: }
1.145     brouard  5612: void removespace(char *str) {
                   5613:   char *p1 = str, *p2 = str;
                   5614:   do
                   5615:     while (*p2 == ' ')
                   5616:       p2++;
1.169     brouard  5617:   while (*p1++ == *p2++);
1.145     brouard  5618: }
                   5619: 
                   5620: int decodemodel ( char model[], int lastobs) /**< This routine decode the model and returns:
1.187     brouard  5621:    * Model  V1+V2+V3+V8+V7*V8+V5*V6+V8*age+V3*age+age*age
                   5622:    * - nagesqr = 1 if age*age in the model, otherwise 0.
                   5623:    * - cptcovt total number of covariates of the model nbocc(+)+1 = 8 excepting constant and age and age*age
                   5624:    * - cptcovn or number of covariates k of the models excluding age*products =6 and age*age
1.145     brouard  5625:    * - cptcovage number of covariates with age*products =2
                   5626:    * - cptcovs number of simple covariates
                   5627:    * - 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
                   5628:    *     which is a new column after the 9 (ncovcol) variables. 
                   5629:    * - if k is a product Vn*Vm covar[k][i] is filled with correct values for each individual
                   5630:    * - Tprod[l] gives the kth covariates of the product Vn*Vm l=1 to cptcovprod-cptcovage
                   5631:    *    Tprod[1]@2 {5, 6}: position of first product V7*V8 is 5, and second V5*V6 is 6.
                   5632:    * - Tvard[k]  p Tvard[1][1]@4 {7, 8, 5, 6} for V7*V8 and V5*V6 .
                   5633:  */
1.136     brouard  5634: {
1.145     brouard  5635:   int i, j, k, ks;
1.164     brouard  5636:   int  j1, k1, k2;
1.136     brouard  5637:   char modelsav[80];
1.145     brouard  5638:   char stra[80], strb[80], strc[80], strd[80],stre[80];
1.187     brouard  5639:   char *strpt;
1.136     brouard  5640: 
1.145     brouard  5641:   /*removespace(model);*/
1.136     brouard  5642:   if (strlen(model) >1){ /* If there is at least 1 covariate */
1.145     brouard  5643:     j=0, j1=0, k1=0, k2=-1, ks=0, cptcovn=0;
1.137     brouard  5644:     if (strstr(model,"AGE") !=0){
1.192     brouard  5645:       printf("Error. AGE must be in lower case 'age' model=1+age+%s. ",model);
                   5646:       fprintf(ficlog,"Error. AGE must be in lower case model=1+age+%s. ",model);fflush(ficlog);
1.136     brouard  5647:       return 1;
                   5648:     }
1.141     brouard  5649:     if (strstr(model,"v") !=0){
                   5650:       printf("Error. 'v' must be in upper case 'V' model=%s ",model);
                   5651:       fprintf(ficlog,"Error. 'v' must be in upper case model=%s ",model);fflush(ficlog);
                   5652:       return 1;
                   5653:     }
1.187     brouard  5654:     strcpy(modelsav,model); 
                   5655:     if ((strpt=strstr(model,"age*age")) !=0){
                   5656:       printf(" strpt=%s, model=%s\n",strpt, model);
                   5657:       if(strpt != model){
                   5658:       printf("Error in model: 'model=%s'; 'age*age' should in first place before other covariates\n \
1.192     brouard  5659:  'model=1+age+age*age+V1.' or 'model=1+age+age*age+V1+V1*age.', please swap as well as \n \
1.187     brouard  5660:  corresponding column of parameters.\n",model);
                   5661:       fprintf(ficlog,"Error in model: 'model=%s'; 'age*age' should in first place before other covariates\n \
1.192     brouard  5662:  'model=1+age+age*age+V1.' or 'model=1+age+age*age+V1+V1*age.', please swap as well as \n \
1.187     brouard  5663:  corresponding column of parameters.\n",model); fflush(ficlog);
                   5664:       return 1;
                   5665:     }
                   5666: 
                   5667:       nagesqr=1;
                   5668:       if (strstr(model,"+age*age") !=0)
                   5669:        substrchaine(modelsav, model, "+age*age");
                   5670:       else if (strstr(model,"age*age+") !=0)
                   5671:        substrchaine(modelsav, model, "age*age+");
                   5672:       else 
                   5673:        substrchaine(modelsav, model, "age*age");
                   5674:     }else
                   5675:       nagesqr=0;
                   5676:     if (strlen(modelsav) >1){
                   5677:       j=nbocc(modelsav,'+'); /**< j=Number of '+' */
                   5678:       j1=nbocc(modelsav,'*'); /**< j1=Number of '*' */
                   5679:       cptcovs=j+1-j1; /**<  Number of simple covariates V1+V1*age+V3 +V3*V4+age*age=> V1 + V3 =2  */
                   5680:       cptcovt= j+1; /* Number of total covariates in the model, not including
                   5681:                   * cst, age and age*age 
                   5682:                   * V1+V1*age+ V3 + V3*V4+age*age=> 4*/
                   5683:                   /* including age products which are counted in cptcovage.
                   5684:                  * but the covariates which are products must be treated 
                   5685:                  * separately: ncovn=4- 2=2 (V1+V3). */
                   5686:       cptcovprod=j1; /**< Number of products  V1*V2 +v3*age = 2 */
                   5687:       cptcovprodnoage=0; /**< Number of covariate products without age: V3*V4 =1  */
                   5688: 
                   5689:     
                   5690:       /*   Design
                   5691:        *  V1   V2   V3   V4  V5  V6  V7  V8  V9 Weight
                   5692:        *  <          ncovcol=8                >
                   5693:        * Model V2 + V1 + V3*age + V3 + V5*V6 + V7*V8 + V8*age + V8
                   5694:        *   k=  1    2      3       4     5       6      7        8
                   5695:        *  cptcovn number of covariates (not including constant and age ) = # of + plus 1 = 7+1=8
                   5696:        *  covar[k,i], value of kth covariate if not including age for individual i:
                   5697:        *       covar[1][i]= (V2), covar[4][i]=(V3), covar[8][i]=(V8)
                   5698:        *  Tvar[k] # of the kth covariate:  Tvar[1]=2  Tvar[4]=3 Tvar[8]=8
                   5699:        *       if multiplied by age: V3*age Tvar[3=V3*age]=3 (V3) Tvar[7]=8 and 
                   5700:        *  Tage[++cptcovage]=k
                   5701:        *       if products, new covar are created after ncovcol with k1
                   5702:        *  Tvar[k]=ncovcol+k1; # of the kth covariate product:  Tvar[5]=ncovcol+1=10  Tvar[6]=ncovcol+1=11
                   5703:        *  Tprod[k1]=k; Tprod[1]=5 Tprod[2]= 6; gives the position of the k1th product
                   5704:        *  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
                   5705:        *  Tvar[cptcovn+k2]=Tvard[k1][1];Tvar[cptcovn+k2+1]=Tvard[k1][2];
                   5706:        *  Tvar[8+1]=5;Tvar[8+2]=6;Tvar[8+3]=7;Tvar[8+4]=8 inverted
                   5707:        *  V1   V2   V3   V4  V5  V6  V7  V8  V9  V10  V11
                   5708:        *  <          ncovcol=8                >
                   5709:        *       Model V2 + V1 + V3*age + V3 + V5*V6 + V7*V8 + V8*age + V8    d1   d1   d2  d2
                   5710:        *          k=  1    2      3       4     5       6      7        8    9   10   11  12
                   5711:        *     Tvar[k]= 2    1      3       3    10      11      8        8    5    6    7   8
                   5712:        * p Tvar[1]@12={2,   1,     3,      3,   11,     10,     8,       8,   7,   8,   5,  6}
                   5713:        * p Tprod[1]@2={                         6, 5}
                   5714:        *p Tvard[1][1]@4= {7, 8, 5, 6}
                   5715:        * covar[k][i]= V2   V1      ?      V3    V5*V6?   V7*V8?  ?       V8   
                   5716:        *  cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*cov[2];
                   5717:        *How to reorganize?
                   5718:        * Model V1 + V2 + V3 + V8 + V5*V6 + V7*V8 + V3*age + V8*age
                   5719:        * Tvars {2,   1,     3,      3,   11,     10,     8,       8,   7,   8,   5,  6}
                   5720:        *       {2,   1,     4,      8,    5,      6,     3,       7}
                   5721:        * Struct []
                   5722:        */
1.145     brouard  5723: 
1.187     brouard  5724:       /* This loop fills the array Tvar from the string 'model'.*/
                   5725:       /* j is the number of + signs in the model V1+V2+V3 j=2 i=3 to 1 */
                   5726:       /*   modelsav=V2+V1+V4+age*V3 strb=age*V3 stra=V2+V1+V4  */
                   5727:       /*       k=4 (age*V3) Tvar[k=4]= 3 (from V3) Tage[cptcovage=1]=4 */
                   5728:       /*       k=3 V4 Tvar[k=3]= 4 (from V4) */
                   5729:       /*       k=2 V1 Tvar[k=2]= 1 (from V1) */
                   5730:       /*       k=1 Tvar[1]=2 (from V2) */
                   5731:       /*       k=5 Tvar[5] */
                   5732:       /* for (k=1; k<=cptcovn;k++) { */
                   5733:       /*       cov[2+k]=nbcode[Tvar[k]][codtab[ij][Tvar[k]]]; */
                   5734:       /*       } */
                   5735:       /* for (k=1; k<=cptcovage;k++) cov[2+Tage[k]]=nbcode[Tvar[Tage[k]]][codtab[ij][Tvar[Tage[k]]]]*cov[2]; */
                   5736:       /*
                   5737:        * Treating invertedly V2+V1+V3*age+V2*V4 is as if written V2*V4 +V3*age + V1 + V2 */
                   5738:       for(k=cptcovt; k>=1;k--) /**< Number of covariates */
1.145     brouard  5739:         Tvar[k]=0;
1.187     brouard  5740:       cptcovage=0;
                   5741:       for(k=1; k<=cptcovt;k++){ /* Loop on total covariates of the model */
                   5742:        cutl(stra,strb,modelsav,'+'); /* keeps in strb after the first '+' 
                   5743:                                         modelsav==V2+V1+V4+V3*age strb=V3*age stra=V2+V1+V4 */ 
                   5744:        if (nbocc(modelsav,'+')==0) strcpy(strb,modelsav); /* and analyzes it */
                   5745:        /*      printf("i=%d a=%s b=%s sav=%s\n",i, stra,strb,modelsav);*/
                   5746:        /*scanf("%d",i);*/
                   5747:        if (strchr(strb,'*')) {  /**< Model includes a product V2+V1+V4+V3*age strb=V3*age */
                   5748:          cutl(strc,strd,strb,'*'); /**< strd*strc  Vm*Vn: strb=V3*age(input) strc=age strd=V3 ; V3*V2 strc=V2, strd=V3 */
                   5749:          if (strcmp(strc,"age")==0) { /**< Model includes age: Vn*age */
                   5750:            /* covar is not filled and then is empty */
                   5751:            cptcovprod--;
                   5752:            cutl(stre,strb,strd,'V'); /* strd=V3(input): stre="3" */
                   5753:            Tvar[k]=atoi(stre);  /* V2+V1+V4+V3*age Tvar[4]=3 ; V1+V2*age Tvar[2]=2; V1+V1*age Tvar[2]=1 */
                   5754:            cptcovage++; /* Sums the number of covariates which include age as a product */
                   5755:            Tage[cptcovage]=k;  /* Tvar[4]=3, Tage[1] = 4 or V1+V1*age Tvar[2]=1, Tage[1]=2 */
                   5756:            /*printf("stre=%s ", stre);*/
                   5757:          } else if (strcmp(strd,"age")==0) { /* or age*Vn */
                   5758:            cptcovprod--;
                   5759:            cutl(stre,strb,strc,'V');
                   5760:            Tvar[k]=atoi(stre);
                   5761:            cptcovage++;
                   5762:            Tage[cptcovage]=k;
                   5763:          } else {  /* Age is not in the model product V2+V1+V1*V4+V3*age+V3*V2  strb=V3*V2*/
                   5764:            /* loops on k1=1 (V3*V2) and k1=2 V4*V3 */
                   5765:            cptcovn++;
                   5766:            cptcovprodnoage++;k1++;
                   5767:            cutl(stre,strb,strc,'V'); /* strc= Vn, stre is n; strb=V3*V2 stre=3 strc=*/
                   5768:            Tvar[k]=ncovcol+k1; /* For model-covariate k tells which data-covariate to use but
                   5769:                                   because this model-covariate is a construction we invent a new column
                   5770:                                   ncovcol + k1
                   5771:                                   If already ncovcol=4 and model=V2+V1+V1*V4+age*V3+V3*V2
                   5772:                                   Tvar[3=V1*V4]=4+1 Tvar[5=V3*V2]=4 + 2= 6, etc */
                   5773:            cutl(strc,strb,strd,'V'); /* strd was Vm, strc is m */
                   5774:            Tprod[k1]=k;  /* Tprod[1]=3(=V1*V4) for V2+V1+V1*V4+age*V3+V3*V2  */
                   5775:            Tvard[k1][1] =atoi(strc); /* m 1 for V1*/
                   5776:            Tvard[k1][2] =atoi(stre); /* n 4 for V4*/
                   5777:            k2=k2+2;
                   5778:            Tvar[cptcovt+k2]=Tvard[k1][1]; /* Tvar[(cptcovt=4+k2=1)=5]= 1 (V1) */
                   5779:            Tvar[cptcovt+k2+1]=Tvard[k1][2];  /* Tvar[(cptcovt=4+(k2=1)+1)=6]= 4 (V4) */
                   5780:            for (i=1; i<=lastobs;i++){
                   5781:              /* Computes the new covariate which is a product of
                   5782:                 covar[n][i]* covar[m][i] and stores it at ncovol+k1 May not be defined */
                   5783:              covar[ncovcol+k1][i]=covar[atoi(stre)][i]*covar[atoi(strc)][i];
                   5784:            }
                   5785:          } /* End age is not in the model */
                   5786:        } /* End if model includes a product */
                   5787:        else { /* no more sum */
                   5788:          /*printf("d=%s c=%s b=%s\n", strd,strc,strb);*/
                   5789:          /*  scanf("%d",i);*/
                   5790:          cutl(strd,strc,strb,'V');
                   5791:          ks++; /**< Number of simple covariates */
1.145     brouard  5792:          cptcovn++;
1.187     brouard  5793:          Tvar[k]=atoi(strd);
                   5794:        }
                   5795:        strcpy(modelsav,stra);  /* modelsav=V2+V1+V4 stra=V2+V1+V4 */ 
                   5796:        /*printf("a=%s b=%s sav=%s\n", stra,strb,modelsav);
                   5797:          scanf("%d",i);*/
                   5798:       } /* end of loop + on total covariates */
                   5799:     } /* end if strlen(modelsave == 0) age*age might exist */
                   5800:   } /* end if strlen(model == 0) */
1.136     brouard  5801:   
                   5802:   /*The number n of Vn is stored in Tvar. cptcovage =number of age covariate. Tage gives the position of age. cptcovprod= number of products.
                   5803:     If model=V1+V1*age then Tvar[1]=1 Tvar[2]=1 cptcovage=1 Tage[1]=2 cptcovprod=0*/
                   5804: 
                   5805:   /* printf("tvar1=%d tvar2=%d tvar3=%d cptcovage=%d Tage=%d",Tvar[1],Tvar[2],Tvar[3],cptcovage,Tage[1]);
                   5806:   printf("cptcovprod=%d ", cptcovprod);
                   5807:   fprintf(ficlog,"cptcovprod=%d ", cptcovprod);
                   5808: 
                   5809:   scanf("%d ",i);*/
                   5810: 
                   5811: 
1.137     brouard  5812:   return (0); /* with covar[new additional covariate if product] and Tage if age */ 
1.164     brouard  5813:   /*endread:*/
1.136     brouard  5814:     printf("Exiting decodemodel: ");
                   5815:     return (1);
                   5816: }
                   5817: 
1.169     brouard  5818: int calandcheckages(int imx, int maxwav, double *agemin, double *agemax, int *nberr, int *nbwarn )
1.136     brouard  5819: {
                   5820:   int i, m;
                   5821: 
                   5822:   for (i=1; i<=imx; i++) {
                   5823:     for(m=2; (m<= maxwav); m++) {
                   5824:       if (((int)mint[m][i]== 99) && (s[m][i] <= nlstate)){
                   5825:        anint[m][i]=9999;
                   5826:        s[m][i]=-1;
                   5827:       }
                   5828:       if((int)moisdc[i]==99 && (int)andc[i]==9999 && s[m][i]>nlstate){
1.169     brouard  5829:        *nberr = *nberr + 1;
                   5830:        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);
                   5831:        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  5832:        s[m][i]=-1;
                   5833:       }
                   5834:       if((int)moisdc[i]==99 && (int)andc[i]!=9999 && s[m][i]>nlstate){
1.169     brouard  5835:        (*nberr)++;
1.136     brouard  5836:        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]); 
                   5837:        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]); 
                   5838:        s[m][i]=-1; /* We prefer to skip it (and to skip it in version 0.8a1 too */
                   5839:       }
                   5840:     }
                   5841:   }
                   5842: 
                   5843:   for (i=1; i<=imx; i++)  {
                   5844:     agedc[i]=(moisdc[i]/12.+andc[i])-(moisnais[i]/12.+annais[i]);
                   5845:     for(m=firstpass; (m<= lastpass); m++){
                   5846:       if(s[m][i] >0 || s[m][i]==-2 || s[m][i]==-4 || s[m][i]==-5){
                   5847:        if (s[m][i] >= nlstate+1) {
1.169     brouard  5848:          if(agedc[i]>0){
                   5849:            if((int)moisdc[i]!=99 && (int)andc[i]!=9999){
1.136     brouard  5850:              agev[m][i]=agedc[i];
                   5851:          /*if(moisdc[i]==99 && andc[i]==9999) s[m][i]=-1;*/
1.169     brouard  5852:            }else {
1.136     brouard  5853:              if ((int)andc[i]!=9999){
                   5854:                nbwarn++;
                   5855:                printf("Warning negative age at death: %ld line:%d\n",num[i],i);
                   5856:                fprintf(ficlog,"Warning negative age at death: %ld line:%d\n",num[i],i);
                   5857:                agev[m][i]=-1;
                   5858:              }
                   5859:            }
1.169     brouard  5860:          } /* agedc > 0 */
1.136     brouard  5861:        }
                   5862:        else if(s[m][i] !=9){ /* Standard case, age in fractional
                   5863:                                 years but with the precision of a month */
                   5864:          agev[m][i]=(mint[m][i]/12.+1./24.+anint[m][i])-(moisnais[i]/12.+1./24.+annais[i]);
                   5865:          if((int)mint[m][i]==99 || (int)anint[m][i]==9999)
                   5866:            agev[m][i]=1;
                   5867:          else if(agev[m][i] < *agemin){ 
                   5868:            *agemin=agev[m][i];
                   5869:            printf(" Min anint[%d][%d]=%.2f annais[%d]=%.2f, agemin=%.2f\n",m,i,anint[m][i], i,annais[i], *agemin);
                   5870:          }
                   5871:          else if(agev[m][i] >*agemax){
                   5872:            *agemax=agev[m][i];
1.156     brouard  5873:            /* printf(" Max anint[%d][%d]=%.0f annais[%d]=%.0f, agemax=%.2f\n",m,i,anint[m][i], i,annais[i], *agemax);*/
1.136     brouard  5874:          }
                   5875:          /*agev[m][i]=anint[m][i]-annais[i];*/
                   5876:          /*     agev[m][i] = age[i]+2*m;*/
                   5877:        }
                   5878:        else { /* =9 */
                   5879:          agev[m][i]=1;
                   5880:          s[m][i]=-1;
                   5881:        }
                   5882:       }
                   5883:       else /*= 0 Unknown */
                   5884:        agev[m][i]=1;
                   5885:     }
                   5886:     
                   5887:   }
                   5888:   for (i=1; i<=imx; i++)  {
                   5889:     for(m=firstpass; (m<=lastpass); m++){
                   5890:       if (s[m][i] > (nlstate+ndeath)) {
1.169     brouard  5891:        (*nberr)++;
1.136     brouard  5892:        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);     
                   5893:        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);     
                   5894:        return 1;
                   5895:       }
                   5896:     }
                   5897:   }
                   5898: 
                   5899:   /*for (i=1; i<=imx; i++){
                   5900:   for (m=firstpass; (m<lastpass); m++){
                   5901:      printf("%ld %d %.lf %d %d\n", num[i],(covar[1][i]),agev[m][i],s[m][i],s[m+1][i]);
                   5902: }
                   5903: 
                   5904: }*/
                   5905: 
                   5906: 
1.139     brouard  5907:   printf("Total number of individuals= %d, Agemin = %.2f, Agemax= %.2f\n\n", imx, *agemin, *agemax);
                   5908:   fprintf(ficlog,"Total number of individuals= %d, Agemin = %.2f, Agemax= %.2f\n\n", imx, *agemin, *agemax); 
1.136     brouard  5909: 
                   5910:   return (0);
1.164     brouard  5911:  /* endread:*/
1.136     brouard  5912:     printf("Exiting calandcheckages: ");
                   5913:     return (1);
                   5914: }
                   5915: 
1.172     brouard  5916: #if defined(_MSC_VER)
                   5917: /*printf("Visual C++ compiler: %s \n;", _MSC_FULL_VER);*/
                   5918: /*fprintf(ficlog, "Visual C++ compiler: %s \n;", _MSC_FULL_VER);*/
                   5919: //#include "stdafx.h"
                   5920: //#include <stdio.h>
                   5921: //#include <tchar.h>
                   5922: //#include <windows.h>
                   5923: //#include <iostream>
                   5924: typedef BOOL(WINAPI *LPFN_ISWOW64PROCESS) (HANDLE, PBOOL);
                   5925: 
                   5926: LPFN_ISWOW64PROCESS fnIsWow64Process;
                   5927: 
                   5928: BOOL IsWow64()
                   5929: {
                   5930:        BOOL bIsWow64 = FALSE;
                   5931: 
                   5932:        //typedef BOOL (APIENTRY *LPFN_ISWOW64PROCESS)
                   5933:        //  (HANDLE, PBOOL);
                   5934: 
                   5935:        //LPFN_ISWOW64PROCESS fnIsWow64Process;
                   5936: 
                   5937:        HMODULE module = GetModuleHandle(_T("kernel32"));
                   5938:        const char funcName[] = "IsWow64Process";
                   5939:        fnIsWow64Process = (LPFN_ISWOW64PROCESS)
                   5940:                GetProcAddress(module, funcName);
                   5941: 
                   5942:        if (NULL != fnIsWow64Process)
                   5943:        {
                   5944:                if (!fnIsWow64Process(GetCurrentProcess(),
                   5945:                        &bIsWow64))
                   5946:                        //throw std::exception("Unknown error");
                   5947:                        printf("Unknown error\n");
                   5948:        }
                   5949:        return bIsWow64 != FALSE;
                   5950: }
                   5951: #endif
1.177     brouard  5952: 
1.191     brouard  5953: void syscompilerinfo(int logged)
1.167     brouard  5954:  {
                   5955:    /* #include "syscompilerinfo.h"*/
1.185     brouard  5956:    /* command line Intel compiler 32bit windows, XP compatible:*/
                   5957:    /* /GS /W3 /Gy
                   5958:       /Zc:wchar_t /Zi /O2 /Fd"Release\vc120.pdb" /D "WIN32" /D "NDEBUG" /D
                   5959:       "_CONSOLE" /D "_LIB" /D "_USING_V110_SDK71_" /D "_UNICODE" /D
                   5960:       "UNICODE" /Qipo /Zc:forScope /Gd /Oi /MT /Fa"Release\" /EHsc /nologo
1.186     brouard  5961:       /Fo"Release\" /Qprof-dir "Release\" /Fp"Release\IMaCh.pch"
                   5962:    */ 
                   5963:    /* 64 bits */
1.185     brouard  5964:    /*
                   5965:      /GS /W3 /Gy
                   5966:      /Zc:wchar_t /Zi /O2 /Fd"x64\Release\vc120.pdb" /D "WIN32" /D "NDEBUG"
                   5967:      /D "_CONSOLE" /D "_LIB" /D "_UNICODE" /D "UNICODE" /Qipo /Zc:forScope
                   5968:      /Oi /MD /Fa"x64\Release\" /EHsc /nologo /Fo"x64\Release\" /Qprof-dir
                   5969:      "x64\Release\" /Fp"x64\Release\IMaCh.pch" */
                   5970:    /* Optimization are useless and O3 is slower than O2 */
                   5971:    /*
                   5972:      /GS /W3 /Gy /Zc:wchar_t /Zi /O3 /Fd"x64\Release\vc120.pdb" /D "WIN32" 
                   5973:      /D "NDEBUG" /D "_CONSOLE" /D "_LIB" /D "_UNICODE" /D "UNICODE" /Qipo 
                   5974:      /Zc:forScope /Oi /MD /Fa"x64\Release\" /EHsc /nologo /Qparallel 
                   5975:      /Fo"x64\Release\" /Qprof-dir "x64\Release\" /Fp"x64\Release\IMaCh.pch" 
                   5976:    */
1.186     brouard  5977:    /* Link is */ /* /OUT:"visual studio
1.185     brouard  5978:       2013\Projects\IMaCh\Release\IMaCh.exe" /MANIFEST /NXCOMPAT
                   5979:       /PDB:"visual studio
                   5980:       2013\Projects\IMaCh\Release\IMaCh.pdb" /DYNAMICBASE
                   5981:       "kernel32.lib" "user32.lib" "gdi32.lib" "winspool.lib"
                   5982:       "comdlg32.lib" "advapi32.lib" "shell32.lib" "ole32.lib"
                   5983:       "oleaut32.lib" "uuid.lib" "odbc32.lib" "odbccp32.lib"
                   5984:       /MACHINE:X86 /OPT:REF /SAFESEH /INCREMENTAL:NO
                   5985:       /SUBSYSTEM:CONSOLE",5.01" /MANIFESTUAC:"level='asInvoker'
                   5986:       uiAccess='false'"
                   5987:       /ManifestFile:"Release\IMaCh.exe.intermediate.manifest" /OPT:ICF
                   5988:       /NOLOGO /TLBID:1
                   5989:    */
1.177     brouard  5990: #if defined __INTEL_COMPILER
1.178     brouard  5991: #if defined(__GNUC__)
                   5992:        struct utsname sysInfo;  /* For Intel on Linux and OS/X */
                   5993: #endif
1.177     brouard  5994: #elif defined(__GNUC__) 
1.179     brouard  5995: #ifndef  __APPLE__
1.174     brouard  5996: #include <gnu/libc-version.h>  /* Only on gnu */
1.179     brouard  5997: #endif
1.177     brouard  5998:    struct utsname sysInfo;
1.178     brouard  5999:    int cross = CROSS;
                   6000:    if (cross){
                   6001:           printf("Cross-");
1.191     brouard  6002:           if(logged) fprintf(ficlog, "Cross-");
1.178     brouard  6003:    }
1.174     brouard  6004: #endif
                   6005: 
1.171     brouard  6006: #include <stdint.h>
1.178     brouard  6007: 
1.191     brouard  6008:    printf("Compiled with:");if(logged)fprintf(ficlog,"Compiled with:");
1.169     brouard  6009: #if defined(__clang__)
1.191     brouard  6010:    printf(" Clang/LLVM");if(logged)fprintf(ficlog," Clang/LLVM");      /* Clang/LLVM. ---------------------------------------------- */
1.169     brouard  6011: #endif
                   6012: #if defined(__ICC) || defined(__INTEL_COMPILER)
1.191     brouard  6013:    printf(" Intel ICC/ICPC");if(logged)fprintf(ficlog," Intel ICC/ICPC");/* Intel ICC/ICPC. ------------------------------------------ */
1.169     brouard  6014: #endif
                   6015: #if defined(__GNUC__) || defined(__GNUG__)
1.191     brouard  6016:    printf(" GNU GCC/G++");if(logged)fprintf(ficlog," GNU GCC/G++");/* GNU GCC/G++. --------------------------------------------- */
1.169     brouard  6017: #endif
                   6018: #if defined(__HP_cc) || defined(__HP_aCC)
1.191     brouard  6019:    printf(" Hewlett-Packard C/aC++");if(logged)fprintf(fcilog," Hewlett-Packard C/aC++"); /* Hewlett-Packard C/aC++. ---------------------------------- */
1.169     brouard  6020: #endif
                   6021: #if defined(__IBMC__) || defined(__IBMCPP__)
1.191     brouard  6022:    printf(" IBM XL C/C++"); if(logged) fprintf(ficlog," IBM XL C/C++");/* IBM XL C/C++. -------------------------------------------- */
1.169     brouard  6023: #endif
                   6024: #if defined(_MSC_VER)
1.191     brouard  6025:    printf(" Microsoft Visual Studio");if(logged)fprintf(ficlog," Microsoft Visual Studio");/* Microsoft Visual Studio. --------------------------------- */
1.169     brouard  6026: #endif
                   6027: #if defined(__PGI)
1.191     brouard  6028:    printf(" Portland Group PGCC/PGCPP");if(logged) fprintf(ficlog," Portland Group PGCC/PGCPP");/* Portland Group PGCC/PGCPP. ------------------------------- */
1.169     brouard  6029: #endif
                   6030: #if defined(__SUNPRO_C) || defined(__SUNPRO_CC)
1.191     brouard  6031:    printf(" Oracle Solaris Studio");if(logged)fprintf(ficlog," Oracle Solaris Studio\n");/* Oracle Solaris Studio. ----------------------------------- */
1.167     brouard  6032: #endif
1.191     brouard  6033:    printf(" for "); if (logged) fprintf(ficlog, " for ");
1.169     brouard  6034:    
1.167     brouard  6035: // http://stackoverflow.com/questions/4605842/how-to-identify-platform-compiler-from-preprocessor-macros
                   6036: #ifdef _WIN32 // note the underscore: without it, it's not msdn official!
                   6037:     // Windows (x64 and x86)
1.191     brouard  6038:    printf("Windows (x64 and x86) ");if(logged) fprintf(ficlog,"Windows (x64 and x86) ");
1.167     brouard  6039: #elif __unix__ // all unices, not all compilers
                   6040:     // Unix
1.191     brouard  6041:    printf("Unix ");if(logged) fprintf(ficlog,"Unix ");
1.167     brouard  6042: #elif __linux__
                   6043:     // linux
1.191     brouard  6044:    printf("linux ");if(logged) fprintf(ficlog,"linux ");
1.167     brouard  6045: #elif __APPLE__
1.174     brouard  6046:     // Mac OS, not sure if this is covered by __posix__ and/or __unix__ though..
1.191     brouard  6047:    printf("Mac OS ");if(logged) fprintf(ficlog,"Mac OS ");
1.167     brouard  6048: #endif
                   6049: 
                   6050: /*  __MINGW32__          */
                   6051: /*  __CYGWIN__  */
                   6052: /* __MINGW64__  */
                   6053: // http://msdn.microsoft.com/en-us/library/b0084kay.aspx
                   6054: /* _MSC_VER  //the Visual C++ compiler is 17.00.51106.1, the _MSC_VER macro evaluates to 1700. Type cl /?  */
                   6055: /* _MSC_FULL_VER //the Visual C++ compiler is 15.00.20706.01, the _MSC_FULL_VER macro evaluates to 150020706 */
                   6056: /* _WIN64  // Defined for applications for Win64. */
                   6057: /* _M_X64 // Defined for compilations that target x64 processors. */
                   6058: /* _DEBUG // Defined when you compile with /LDd, /MDd, and /MTd. */
1.171     brouard  6059: 
1.167     brouard  6060: #if UINTPTR_MAX == 0xffffffff
1.191     brouard  6061:    printf(" 32-bit"); if(logged) fprintf(ficlog," 32-bit");/* 32-bit */
1.167     brouard  6062: #elif UINTPTR_MAX == 0xffffffffffffffff
1.191     brouard  6063:    printf(" 64-bit"); if(logged) fprintf(ficlog," 64-bit");/* 64-bit */
1.167     brouard  6064: #else
1.191     brouard  6065:    printf(" wtf-bit"); if(logged) fprintf(ficlog," wtf-bit");/* wtf */
1.167     brouard  6066: #endif
                   6067: 
1.169     brouard  6068: #if defined(__GNUC__)
                   6069: # if defined(__GNUC_PATCHLEVEL__)
                   6070: #  define __GNUC_VERSION__ (__GNUC__ * 10000 \
                   6071:                             + __GNUC_MINOR__ * 100 \
                   6072:                             + __GNUC_PATCHLEVEL__)
                   6073: # else
                   6074: #  define __GNUC_VERSION__ (__GNUC__ * 10000 \
                   6075:                             + __GNUC_MINOR__ * 100)
                   6076: # endif
1.174     brouard  6077:    printf(" using GNU C version %d.\n", __GNUC_VERSION__);
1.191     brouard  6078:    if(logged) fprintf(ficlog, " using GNU C version %d.\n", __GNUC_VERSION__);
1.176     brouard  6079: 
                   6080:    if (uname(&sysInfo) != -1) {
                   6081:      printf("Running on: %s %s %s %s %s\n",sysInfo.sysname, sysInfo.nodename, sysInfo.release, sysInfo.version, sysInfo.machine);
1.191     brouard  6082:         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  6083:    }
                   6084:    else
                   6085:       perror("uname() error");
1.179     brouard  6086:    //#ifndef __INTEL_COMPILER 
                   6087: #if !defined (__INTEL_COMPILER) && !defined(__APPLE__)
1.174     brouard  6088:    printf("GNU libc version: %s\n", gnu_get_libc_version()); 
1.191     brouard  6089:    if(logged) fprintf(ficlog,"GNU libc version: %s\n", gnu_get_libc_version());
1.177     brouard  6090: #endif
1.169     brouard  6091: #endif
1.172     brouard  6092: 
                   6093:    //   void main()
                   6094:    //   {
1.169     brouard  6095: #if defined(_MSC_VER)
1.174     brouard  6096:    if (IsWow64()){
1.191     brouard  6097:           printf("\nThe program (probably compiled for 32bit) is running under WOW64 (64bit) emulation.\n");
                   6098:           if (logged) fprintf(ficlog, "\nThe program (probably compiled for 32bit) is running under WOW64 (64bit) emulation.\n");
1.174     brouard  6099:    }
                   6100:    else{
1.191     brouard  6101:           printf("\nThe program is not running under WOW64 (i.e probably on a 64bit Windows).\n");
                   6102:           if (logged) fprintf(ficlog, "\nThe programm is not running under WOW64 (i.e probably on a 64bit Windows).\n");
1.174     brouard  6103:    }
1.172     brouard  6104:    //     printf("\nPress Enter to continue...");
                   6105:    //     getchar();
                   6106:    //   }
                   6107: 
1.169     brouard  6108: #endif
                   6109:    
1.167     brouard  6110: 
                   6111:  }
1.136     brouard  6112: 
1.180     brouard  6113: int prevalence_limit(double *p, double **prlim, double ageminpar, double agemaxpar){
                   6114:   /*--------------- Prevalence limit  (period or stable prevalence) --------------*/
                   6115:   int i, j, k, i1 ;
                   6116:   double ftolpl = 1.e-10;
                   6117:   double age, agebase, agelim;
                   6118: 
                   6119:     strcpy(filerespl,"pl");
                   6120:     strcat(filerespl,fileres);
                   6121:     if((ficrespl=fopen(filerespl,"w"))==NULL) {
                   6122:       printf("Problem with period (stable) prevalence resultfile: %s\n", filerespl);return 1;
                   6123:       fprintf(ficlog,"Problem with period (stable) prevalence resultfile: %s\n", filerespl);return 1;
                   6124:     }
                   6125:     printf("Computing period (stable) prevalence: result on file '%s' \n", filerespl);
                   6126:     fprintf(ficlog,"Computing period (stable) prevalence: result on file '%s' \n", filerespl);
                   6127:     pstamp(ficrespl);
                   6128:     fprintf(ficrespl,"# Period (stable) prevalence \n");
                   6129:     fprintf(ficrespl,"#Age ");
                   6130:     for(i=1; i<=nlstate;i++) fprintf(ficrespl,"%d-%d ",i,i);
                   6131:     fprintf(ficrespl,"\n");
                   6132:   
                   6133:     /* prlim=matrix(1,nlstate,1,nlstate);*/ /* back in main */
                   6134: 
                   6135:     agebase=ageminpar;
                   6136:     agelim=agemaxpar;
                   6137: 
                   6138:     i1=pow(2,cptcoveff);
                   6139:     if (cptcovn < 1){i1=1;}
                   6140: 
                   6141:     for(cptcov=1,k=0;cptcov<=i1;cptcov++){
                   6142:     /* for(cptcov=1,k=0;cptcov<=1;cptcov++){ */
                   6143:       //for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){
                   6144:        k=k+1;
                   6145:        /* to clean */
                   6146:        //printf("cptcov=%d cptcod=%d codtab=%d\n",cptcov, cptcod,codtab[cptcod][cptcov]);
                   6147:        fprintf(ficrespl,"\n#******");
                   6148:        printf("\n#******");
                   6149:        fprintf(ficlog,"\n#******");
                   6150:        for(j=1;j<=cptcoveff;j++) {
                   6151:          fprintf(ficrespl," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
                   6152:          printf(" V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
                   6153:          fprintf(ficlog," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
                   6154:        }
                   6155:        fprintf(ficrespl,"******\n");
                   6156:        printf("******\n");
                   6157:        fprintf(ficlog,"******\n");
                   6158: 
                   6159:        fprintf(ficrespl,"#Age ");
                   6160:        for(j=1;j<=cptcoveff;j++) {
                   6161:          fprintf(ficrespl,"V%d %d",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
                   6162:        }
                   6163:        for(i=1; i<=nlstate;i++) fprintf(ficrespl,"%d-%d ",i,i);
                   6164:        fprintf(ficrespl,"\n");
                   6165:        
                   6166:        for (age=agebase; age<=agelim; age++){
                   6167:        /* for (age=agebase; age<=agebase; age++){ */
                   6168:          prevalim(prlim, nlstate, p, age, oldm, savm,ftolpl,k);
                   6169:          fprintf(ficrespl,"%.0f ",age );
                   6170:          for(j=1;j<=cptcoveff;j++)
                   6171:            fprintf(ficrespl,"%d %d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
                   6172:          for(i=1; i<=nlstate;i++)
                   6173:            fprintf(ficrespl," %.5f", prlim[i][i]);
                   6174:          fprintf(ficrespl,"\n");
                   6175:        } /* Age */
                   6176:        /* was end of cptcod */
                   6177:     } /* cptcov */
1.184     brouard  6178:        return 0;
1.180     brouard  6179: }
                   6180: 
                   6181: int hPijx(double *p, int bage, int fage){
                   6182:     /*------------- h Pij x at various ages ------------*/
                   6183: 
                   6184:   int stepsize;
                   6185:   int agelim;
                   6186:   int hstepm;
                   6187:   int nhstepm;
                   6188:   int h, i, i1, j, k;
                   6189: 
                   6190:   double agedeb;
                   6191:   double ***p3mat;
                   6192: 
                   6193:     strcpy(filerespij,"pij");  strcat(filerespij,fileres);
                   6194:     if((ficrespij=fopen(filerespij,"w"))==NULL) {
                   6195:       printf("Problem with Pij resultfile: %s\n", filerespij); return 1;
                   6196:       fprintf(ficlog,"Problem with Pij resultfile: %s\n", filerespij); return 1;
                   6197:     }
                   6198:     printf("Computing pij: result on file '%s' \n", filerespij);
                   6199:     fprintf(ficlog,"Computing pij: result on file '%s' \n", filerespij);
                   6200:   
                   6201:     stepsize=(int) (stepm+YEARM-1)/YEARM;
                   6202:     /*if (stepm<=24) stepsize=2;*/
                   6203: 
                   6204:     agelim=AGESUP;
                   6205:     hstepm=stepsize*YEARM; /* Every year of age */
                   6206:     hstepm=hstepm/stepm; /* Typically 2 years, = 2/6 months = 4 */ 
                   6207: 
                   6208:     /* hstepm=1;   aff par mois*/
                   6209:     pstamp(ficrespij);
                   6210:     fprintf(ficrespij,"#****** h Pij x Probability to be in state j at age x+h being in i at x ");
                   6211:     i1= pow(2,cptcoveff);
1.183     brouard  6212:    /* for(cptcov=1,k=0;cptcov<=i1;cptcov++){ */
                   6213:    /*    /\*for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){*\/ */
                   6214:    /*          k=k+1;  */
                   6215:     for (k=1; k <= (int) pow(2,cptcoveff); k++){
                   6216:       fprintf(ficrespij,"\n#****** ");
                   6217:       for(j=1;j<=cptcoveff;j++) 
                   6218:        fprintf(ficrespij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
                   6219:       fprintf(ficrespij,"******\n");
                   6220:       
                   6221:       for (agedeb=fage; agedeb>=bage; agedeb--){ /* If stepm=6 months */
                   6222:        nhstepm=(int) rint((agelim-agedeb)*YEARM/stepm); /* Typically 20 years = 20*12/6=40 */ 
                   6223:        nhstepm = nhstepm/hstepm; /* Typically 40/4=10 */
                   6224:        
                   6225:        /*        nhstepm=nhstepm*YEARM; aff par mois*/
1.180     brouard  6226:        
1.183     brouard  6227:        p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   6228:        oldm=oldms;savm=savms;
                   6229:        hpxij(p3mat,nhstepm,agedeb,hstepm,p,nlstate,stepm,oldm,savm, k);  
                   6230:        fprintf(ficrespij,"# Cov Agex agex+h hpijx with i,j=");
                   6231:        for(i=1; i<=nlstate;i++)
                   6232:          for(j=1; j<=nlstate+ndeath;j++)
                   6233:            fprintf(ficrespij," %1d-%1d",i,j);
                   6234:        fprintf(ficrespij,"\n");
                   6235:        for (h=0; h<=nhstepm; h++){
                   6236:          /*agedebphstep = agedeb + h*hstepm/YEARM*stepm;*/
                   6237:          fprintf(ficrespij,"%d %3.f %3.f",k, agedeb, agedeb + h*hstepm/YEARM*stepm );
1.180     brouard  6238:          for(i=1; i<=nlstate;i++)
                   6239:            for(j=1; j<=nlstate+ndeath;j++)
1.183     brouard  6240:              fprintf(ficrespij," %.5f", p3mat[i][j][h]);
1.180     brouard  6241:          fprintf(ficrespij,"\n");
                   6242:        }
1.183     brouard  6243:        free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   6244:        fprintf(ficrespij,"\n");
                   6245:       }
1.180     brouard  6246:       /*}*/
                   6247:     }
1.184     brouard  6248:        return 0;
1.180     brouard  6249: }
                   6250: 
                   6251: 
1.136     brouard  6252: /***********************************************/
                   6253: /**************** Main Program *****************/
                   6254: /***********************************************/
                   6255: 
                   6256: int main(int argc, char *argv[])
                   6257: {
                   6258: #ifdef GSL
                   6259:   const gsl_multimin_fminimizer_type *T;
                   6260:   size_t iteri = 0, it;
                   6261:   int rval = GSL_CONTINUE;
                   6262:   int status = GSL_SUCCESS;
                   6263:   double ssval;
                   6264: #endif
                   6265:   int movingaverage(double ***probs, double bage,double fage, double ***mobaverage, int mobilav);
1.164     brouard  6266:   int i,j, k, n=MAXN,iter=0,m,size=100, cptcod;
                   6267: 
                   6268:   int jj, ll, li, lj, lk;
1.136     brouard  6269:   int numlinepar=0; /* Current linenumber of parameter file */
                   6270:   int itimes;
                   6271:   int NDIM=2;
                   6272:   int vpopbased=0;
                   6273: 
1.164     brouard  6274:   char ca[32], cb[32];
1.136     brouard  6275:   /*  FILE *fichtm; *//* Html File */
                   6276:   /* FILE *ficgp;*/ /*Gnuplot File */
                   6277:   struct stat info;
1.191     brouard  6278:   double agedeb=0.;
1.194     brouard  6279: 
                   6280:   double ageminpar=AGEOVERFLOW,agemin=AGEOVERFLOW, agemaxpar=-AGEOVERFLOW, agemax=-AGEOVERFLOW;
1.136     brouard  6281: 
1.165     brouard  6282:   double fret;
1.191     brouard  6283:   double dum=0.; /* Dummy variable */
1.136     brouard  6284:   double ***p3mat;
                   6285:   double ***mobaverage;
1.164     brouard  6286: 
                   6287:   char line[MAXLINE];
1.136     brouard  6288:   char path[MAXLINE],pathc[MAXLINE],pathcd[MAXLINE],pathtot[MAXLINE],model[MAXLINE];
                   6289:   char pathr[MAXLINE], pathimach[MAXLINE]; 
1.164     brouard  6290:   char *tok, *val; /* pathtot */
1.136     brouard  6291:   int firstobs=1, lastobs=10;
1.195   ! brouard  6292:   int c,  h , cpt, c2;
1.191     brouard  6293:   int jl=0;
                   6294:   int i1, j1, jk, stepsize=0;
1.194     brouard  6295:   int count=0;
                   6296: 
1.164     brouard  6297:   int *tab; 
1.136     brouard  6298:   int mobilavproj=0 , prevfcast=0 ; /* moving average of prev, If prevfcast=1 prevalence projection */
                   6299:   int mobilav=0,popforecast=0;
1.191     brouard  6300:   int hstepm=0, nhstepm=0;
1.136     brouard  6301:   int agemortsup;
                   6302:   float  sumlpop=0.;
                   6303:   double jprev1=1, mprev1=1,anprev1=2000,jprev2=1, mprev2=1,anprev2=2000;
                   6304:   double jpyram=1, mpyram=1,anpyram=2000,jpyram1=1, mpyram1=1,anpyram1=2000;
                   6305: 
1.191     brouard  6306:   double bage=0, fage=110., age, agelim=0., agebase=0.;
1.136     brouard  6307:   double ftolpl=FTOL;
                   6308:   double **prlim;
                   6309:   double ***param; /* Matrix of parameters */
                   6310:   double  *p;
                   6311:   double **matcov; /* Matrix of covariance */
                   6312:   double ***delti3; /* Scale */
                   6313:   double *delti; /* Scale */
                   6314:   double ***eij, ***vareij;
                   6315:   double **varpl; /* Variances of prevalence limits by age */
                   6316:   double *epj, vepp;
1.164     brouard  6317: 
1.136     brouard  6318:   double dateprev1, dateprev2,jproj1=1,mproj1=1,anproj1=2000,jproj2=1,mproj2=1,anproj2=2000;
                   6319:   double **ximort;
1.145     brouard  6320:   char *alph[]={"a","a","b","c","d","e"}, str[4]="1234";
1.136     brouard  6321:   int *dcwave;
                   6322: 
1.164     brouard  6323:   char z[1]="c";
1.136     brouard  6324: 
                   6325:   /*char  *strt;*/
                   6326:   char strtend[80];
1.126     brouard  6327: 
1.164     brouard  6328: 
1.126     brouard  6329: /*   setlocale (LC_ALL, ""); */
                   6330: /*   bindtextdomain (PACKAGE, LOCALEDIR); */
                   6331: /*   textdomain (PACKAGE); */
                   6332: /*   setlocale (LC_CTYPE, ""); */
                   6333: /*   setlocale (LC_MESSAGES, ""); */
                   6334: 
                   6335:   /*   gettimeofday(&start_time, (struct timezone*)0); */ /* at first time */
1.157     brouard  6336:   rstart_time = time(NULL);  
                   6337:   /*  (void) gettimeofday(&start_time,&tzp);*/
                   6338:   start_time = *localtime(&rstart_time);
1.126     brouard  6339:   curr_time=start_time;
1.157     brouard  6340:   /*tml = *localtime(&start_time.tm_sec);*/
                   6341:   /* strcpy(strstart,asctime(&tml)); */
                   6342:   strcpy(strstart,asctime(&start_time));
1.126     brouard  6343: 
                   6344: /*  printf("Localtime (at start)=%s",strstart); */
1.157     brouard  6345: /*  tp.tm_sec = tp.tm_sec +86400; */
                   6346: /*  tm = *localtime(&start_time.tm_sec); */
1.126     brouard  6347: /*   tmg.tm_year=tmg.tm_year +dsign*dyear; */
                   6348: /*   tmg.tm_mon=tmg.tm_mon +dsign*dmonth; */
                   6349: /*   tmg.tm_hour=tmg.tm_hour + 1; */
1.157     brouard  6350: /*   tp.tm_sec = mktime(&tmg); */
1.126     brouard  6351: /*   strt=asctime(&tmg); */
                   6352: /*   printf("Time(after) =%s",strstart);  */
                   6353: /*  (void) time (&time_value);
                   6354: *  printf("time=%d,t-=%d\n",time_value,time_value-86400);
                   6355: *  tm = *localtime(&time_value);
                   6356: *  strstart=asctime(&tm);
                   6357: *  printf("tim_value=%d,asctime=%s\n",time_value,strstart); 
                   6358: */
                   6359: 
                   6360:   nberr=0; /* Number of errors and warnings */
                   6361:   nbwarn=0;
1.184     brouard  6362: #ifdef WIN32
                   6363:   _getcwd(pathcd, size);
                   6364: #else
1.126     brouard  6365:   getcwd(pathcd, size);
1.184     brouard  6366: #endif
1.191     brouard  6367:   syscompilerinfo(0);
1.126     brouard  6368:   printf("\n%s\n%s",version,fullversion);
                   6369:   if(argc <=1){
                   6370:     printf("\nEnter the parameter file name: ");
                   6371:     fgets(pathr,FILENAMELENGTH,stdin);
                   6372:     i=strlen(pathr);
                   6373:     if(pathr[i-1]=='\n')
                   6374:       pathr[i-1]='\0';
1.156     brouard  6375:     i=strlen(pathr);
                   6376:     if(pathr[i-1]==' ') /* This may happen when dragging on oS/X! */
                   6377:       pathr[i-1]='\0';
1.126     brouard  6378:    for (tok = pathr; tok != NULL; ){
                   6379:       printf("Pathr |%s|\n",pathr);
                   6380:       while ((val = strsep(&tok, "\"" )) != NULL && *val == '\0');
                   6381:       printf("val= |%s| pathr=%s\n",val,pathr);
                   6382:       strcpy (pathtot, val);
                   6383:       if(pathr[0] == '\0') break; /* Dirty */
                   6384:     }
                   6385:   }
                   6386:   else{
                   6387:     strcpy(pathtot,argv[1]);
                   6388:   }
                   6389:   /*if(getcwd(pathcd, MAXLINE)!= NULL)printf ("Error pathcd\n");*/
                   6390:   /*cygwin_split_path(pathtot,path,optionfile);
                   6391:     printf("pathtot=%s, path=%s, optionfile=%s\n",pathtot,path,optionfile);*/
                   6392:   /* cutv(path,optionfile,pathtot,'\\');*/
                   6393: 
                   6394:   /* Split argv[0], imach program to get pathimach */
                   6395:   printf("\nargv[0]=%s argv[1]=%s, \n",argv[0],argv[1]);
                   6396:   split(argv[0],pathimach,optionfile,optionfilext,optionfilefiname);
                   6397:   printf("\nargv[0]=%s pathimach=%s, \noptionfile=%s \noptionfilext=%s \noptionfilefiname=%s\n",argv[0],pathimach,optionfile,optionfilext,optionfilefiname);
                   6398:  /*   strcpy(pathimach,argv[0]); */
                   6399:   /* Split argv[1]=pathtot, parameter file name to get path, optionfile, extension and name */
                   6400:   split(pathtot,path,optionfile,optionfilext,optionfilefiname);
                   6401:   printf("\npathtot=%s,\npath=%s,\noptionfile=%s \noptionfilext=%s \noptionfilefiname=%s\n",pathtot,path,optionfile,optionfilext,optionfilefiname);
1.184     brouard  6402: #ifdef WIN32
                   6403:   _chdir(path); /* Can be a relative path */
                   6404:   if(_getcwd(pathcd,MAXLINE) > 0) /* So pathcd is the full path */
                   6405: #else
1.126     brouard  6406:   chdir(path); /* Can be a relative path */
1.184     brouard  6407:   if (getcwd(pathcd, MAXLINE) > 0) /* So pathcd is the full path */
                   6408: #endif
                   6409:   printf("Current directory %s!\n",pathcd);
1.126     brouard  6410:   strcpy(command,"mkdir ");
                   6411:   strcat(command,optionfilefiname);
                   6412:   if((outcmd=system(command)) != 0){
1.169     brouard  6413:     printf("Directory already exists (or can't create it) %s%s, err=%d\n",path,optionfilefiname,outcmd);
1.126     brouard  6414:     /* fprintf(ficlog,"Problem creating directory %s%s\n",path,optionfilefiname); */
                   6415:     /* fclose(ficlog); */
                   6416: /*     exit(1); */
                   6417:   }
                   6418: /*   if((imk=mkdir(optionfilefiname))<0){ */
                   6419: /*     perror("mkdir"); */
                   6420: /*   } */
                   6421: 
                   6422:   /*-------- arguments in the command line --------*/
                   6423: 
1.186     brouard  6424:   /* Main Log file */
1.126     brouard  6425:   strcat(filelog, optionfilefiname);
                   6426:   strcat(filelog,".log");    /* */
                   6427:   if((ficlog=fopen(filelog,"w"))==NULL)    {
                   6428:     printf("Problem with logfile %s\n",filelog);
                   6429:     goto end;
                   6430:   }
                   6431:   fprintf(ficlog,"Log filename:%s\n",filelog);
                   6432:   fprintf(ficlog,"\n%s\n%s",version,fullversion);
                   6433:   fprintf(ficlog,"\nEnter the parameter file name: \n");
                   6434:   fprintf(ficlog,"pathimach=%s\npathtot=%s\n\
                   6435:  path=%s \n\
                   6436:  optionfile=%s\n\
                   6437:  optionfilext=%s\n\
1.156     brouard  6438:  optionfilefiname='%s'\n",pathimach,pathtot,path,optionfile,optionfilext,optionfilefiname);
1.126     brouard  6439: 
1.191     brouard  6440:   syscompilerinfo(0);
1.167     brouard  6441: 
1.126     brouard  6442:   printf("Local time (at start):%s",strstart);
                   6443:   fprintf(ficlog,"Local time (at start): %s",strstart);
                   6444:   fflush(ficlog);
                   6445: /*   (void) gettimeofday(&curr_time,&tzp); */
1.157     brouard  6446: /*   printf("Elapsed time %d\n", asc_diff_time(curr_time.tm_sec-start_time.tm_sec,tmpout)); */
1.126     brouard  6447: 
                   6448:   /* */
                   6449:   strcpy(fileres,"r");
                   6450:   strcat(fileres, optionfilefiname);
                   6451:   strcat(fileres,".txt");    /* Other files have txt extension */
                   6452: 
1.186     brouard  6453:   /* Main ---------arguments file --------*/
1.126     brouard  6454: 
                   6455:   if((ficpar=fopen(optionfile,"r"))==NULL)    {
1.155     brouard  6456:     printf("Problem with optionfile '%s' with errno='%s'\n",optionfile,strerror(errno));
                   6457:     fprintf(ficlog,"Problem with optionfile '%s' with errno='%s'\n",optionfile,strerror(errno));
1.126     brouard  6458:     fflush(ficlog);
1.149     brouard  6459:     /* goto end; */
                   6460:     exit(70); 
1.126     brouard  6461:   }
                   6462: 
                   6463: 
                   6464: 
                   6465:   strcpy(filereso,"o");
                   6466:   strcat(filereso,fileres);
                   6467:   if((ficparo=fopen(filereso,"w"))==NULL) { /* opened on subdirectory */
                   6468:     printf("Problem with Output resultfile: %s\n", filereso);
                   6469:     fprintf(ficlog,"Problem with Output resultfile: %s\n", filereso);
                   6470:     fflush(ficlog);
                   6471:     goto end;
                   6472:   }
                   6473: 
                   6474:   /* Reads comments: lines beginning with '#' */
                   6475:   numlinepar=0;
                   6476:   while((c=getc(ficpar))=='#' && c!= EOF){
                   6477:     ungetc(c,ficpar);
                   6478:     fgets(line, MAXLINE, ficpar);
                   6479:     numlinepar++;
1.141     brouard  6480:     fputs(line,stdout);
1.126     brouard  6481:     fputs(line,ficparo);
                   6482:     fputs(line,ficlog);
                   6483:   }
                   6484:   ungetc(c,ficpar);
                   6485: 
1.187     brouard  6486:   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  6487:   numlinepar=numlinepar+3; /* In general */
1.187     brouard  6488:   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);
                   6489:   if(model[strlen(model)-1]=='.') /* Suppressing leading dot in the model */
                   6490:     model[strlen(model)-1]='\0';
                   6491:   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);
                   6492:   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  6493:   fflush(ficlog);
1.190     brouard  6494:   /* if(model[0]=='#'|| model[0]== '\0'){ */
                   6495:   if(model[0]=='#'){
1.187     brouard  6496:     printf("Error in 'model' line: model should start with 'model=1+age+' and end with '.' \n \
                   6497:  'model=1+age+.' or 'model=1+age+V1.' or 'model=1+age+age*age+V1+V1*age.' or \n \
                   6498:  'model=1+age+V1+V2.' or 'model=1+age+V1+V2+V1*V2.' etc. \n");         \
                   6499:     if(mle != -1){
                   6500:       printf("Fix the model line and run imach with mle=-1 to get a correct template of the parameter file.\n");
                   6501:       exit(1);
                   6502:     }
                   6503:   }
1.126     brouard  6504:   while((c=getc(ficpar))=='#' && c!= EOF){
                   6505:     ungetc(c,ficpar);
                   6506:     fgets(line, MAXLINE, ficpar);
                   6507:     numlinepar++;
1.195   ! brouard  6508:     if(line[1]=='q'){ /* This #q will quit imach (the answer is q) */
        !          6509:       z[0]=line[1];
        !          6510:     }
        !          6511:     /* printf("****line [1] = %c \n",line[1]); */
1.141     brouard  6512:     fputs(line, stdout);
                   6513:     //puts(line);
1.126     brouard  6514:     fputs(line,ficparo);
                   6515:     fputs(line,ficlog);
                   6516:   }
                   6517:   ungetc(c,ficpar);
                   6518: 
                   6519:    
1.145     brouard  6520:   covar=matrix(0,NCOVMAX,1,n);  /**< used in readdata */
1.136     brouard  6521:   cptcovn=0; /*Number of covariates, i.e. number of '+' in model statement plus one, indepently of n in Vn*/
                   6522:   /* v1+v2+v3+v2*v4+v5*age makes cptcovn = 5
                   6523:      v1+v2*age+v2*v3 makes cptcovn = 3
                   6524:   */
                   6525:   if (strlen(model)>1) 
1.187     brouard  6526:     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  6527:   else
1.187     brouard  6528:     ncovmodel=2; /* Constant and age */
1.133     brouard  6529:   nforce= (nlstate+ndeath-1)*nlstate; /* Number of forces ij from state i to j */
                   6530:   npar= nforce*ncovmodel; /* Number of parameters like aij*/
1.131     brouard  6531:   if(npar >MAXPARM || nlstate >NLSTATEMAX || ndeath >NDEATHMAX || ncovmodel>NCOVMAX){
                   6532:     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);
                   6533:     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);
                   6534:     fflush(stdout);
                   6535:     fclose (ficlog);
                   6536:     goto end;
                   6537:   }
1.126     brouard  6538:   delti3= ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel);
                   6539:   delti=delti3[1][1];
                   6540:   /*delti=vector(1,npar); *//* Scale of each paramater (output from hesscov)*/
                   6541:   if(mle==-1){ /* Print a wizard for help writing covariance matrix */
                   6542:     prwizard(ncovmodel, nlstate, ndeath, model, ficparo);
1.191     brouard  6543:     printf(" You chose mle=-1, look at file %s for a template of covariance matrix \n",filereso);
                   6544:     fprintf(ficlog," You chose mle=-1, look at file %s for a template of covariance matrix \n",filereso);
1.126     brouard  6545:     free_ma3x(delti3,1,nlstate,1, nlstate+ndeath-1,1,ncovmodel); 
                   6546:     fclose (ficparo);
                   6547:     fclose (ficlog);
                   6548:     goto end;
                   6549:     exit(0);
                   6550:   }
1.186     brouard  6551:   else if(mle==-3) { /* Main Wizard */
1.126     brouard  6552:     prwizard(ncovmodel, nlstate, ndeath, model, ficparo);
1.192     brouard  6553:     printf(" You chose mle=-3, look at file %s for a template of covariance matrix \n",filereso);
                   6554:     fprintf(ficlog," You chose mle=-3, look at file %s for a template of covariance matrix \n",filereso);
1.126     brouard  6555:     param= ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel);
                   6556:     matcov=matrix(1,npar,1,npar);
                   6557:   }
                   6558:   else{
1.145     brouard  6559:     /* Read guessed parameters */
1.126     brouard  6560:     /* Reads comments: lines beginning with '#' */
                   6561:     while((c=getc(ficpar))=='#' && c!= EOF){
                   6562:       ungetc(c,ficpar);
                   6563:       fgets(line, MAXLINE, ficpar);
                   6564:       numlinepar++;
1.141     brouard  6565:       fputs(line,stdout);
1.126     brouard  6566:       fputs(line,ficparo);
                   6567:       fputs(line,ficlog);
                   6568:     }
                   6569:     ungetc(c,ficpar);
                   6570:     
                   6571:     param= ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel);
                   6572:     for(i=1; i <=nlstate; i++){
                   6573:       j=0;
                   6574:       for(jj=1; jj <=nlstate+ndeath; jj++){
                   6575:        if(jj==i) continue;
                   6576:        j++;
                   6577:        fscanf(ficpar,"%1d%1d",&i1,&j1);
1.193     brouard  6578:        if ((i1 != i) || (j1 != jj)){
1.126     brouard  6579:          printf("Error in line parameters number %d, %1d%1d instead of %1d%1d \n \
                   6580: It might be a problem of design; if ncovcol and the model are correct\n \
                   6581: run imach with mle=-1 to get a correct template of the parameter file.\n",numlinepar, i,j, i1, j1);
                   6582:          exit(1);
                   6583:        }
                   6584:        fprintf(ficparo,"%1d%1d",i1,j1);
                   6585:        if(mle==1)
1.193     brouard  6586:          printf("%1d%1d",i,jj);
                   6587:        fprintf(ficlog,"%1d%1d",i,jj);
1.126     brouard  6588:        for(k=1; k<=ncovmodel;k++){
                   6589:          fscanf(ficpar," %lf",&param[i][j][k]);
                   6590:          if(mle==1){
                   6591:            printf(" %lf",param[i][j][k]);
                   6592:            fprintf(ficlog," %lf",param[i][j][k]);
                   6593:          }
                   6594:          else
                   6595:            fprintf(ficlog," %lf",param[i][j][k]);
                   6596:          fprintf(ficparo," %lf",param[i][j][k]);
                   6597:        }
                   6598:        fscanf(ficpar,"\n");
                   6599:        numlinepar++;
                   6600:        if(mle==1)
                   6601:          printf("\n");
                   6602:        fprintf(ficlog,"\n");
                   6603:        fprintf(ficparo,"\n");
                   6604:       }
                   6605:     }  
                   6606:     fflush(ficlog);
                   6607: 
1.145     brouard  6608:     /* Reads scales values */
1.126     brouard  6609:     p=param[1][1];
                   6610:     
                   6611:     /* Reads comments: lines beginning with '#' */
                   6612:     while((c=getc(ficpar))=='#' && c!= EOF){
                   6613:       ungetc(c,ficpar);
                   6614:       fgets(line, MAXLINE, ficpar);
                   6615:       numlinepar++;
1.141     brouard  6616:       fputs(line,stdout);
1.126     brouard  6617:       fputs(line,ficparo);
                   6618:       fputs(line,ficlog);
                   6619:     }
                   6620:     ungetc(c,ficpar);
                   6621: 
                   6622:     for(i=1; i <=nlstate; i++){
                   6623:       for(j=1; j <=nlstate+ndeath-1; j++){
                   6624:        fscanf(ficpar,"%1d%1d",&i1,&j1);
1.164     brouard  6625:        if ( (i1-i) * (j1-j) != 0){
1.126     brouard  6626:          printf("Error in line parameters number %d, %1d%1d instead of %1d%1d \n",numlinepar, i,j, i1, j1);
                   6627:          exit(1);
                   6628:        }
                   6629:        printf("%1d%1d",i,j);
                   6630:        fprintf(ficparo,"%1d%1d",i1,j1);
                   6631:        fprintf(ficlog,"%1d%1d",i1,j1);
                   6632:        for(k=1; k<=ncovmodel;k++){
                   6633:          fscanf(ficpar,"%le",&delti3[i][j][k]);
                   6634:          printf(" %le",delti3[i][j][k]);
                   6635:          fprintf(ficparo," %le",delti3[i][j][k]);
                   6636:          fprintf(ficlog," %le",delti3[i][j][k]);
                   6637:        }
                   6638:        fscanf(ficpar,"\n");
                   6639:        numlinepar++;
                   6640:        printf("\n");
                   6641:        fprintf(ficparo,"\n");
                   6642:        fprintf(ficlog,"\n");
                   6643:       }
                   6644:     }
                   6645:     fflush(ficlog);
                   6646: 
1.145     brouard  6647:     /* Reads covariance matrix */
1.126     brouard  6648:     delti=delti3[1][1];
                   6649: 
                   6650: 
                   6651:     /* free_ma3x(delti3,1,nlstate,1,nlstate+ndeath-1,1,ncovmodel); */ /* Hasn't to to freed here otherwise delti is no more allocated */
                   6652:   
                   6653:     /* Reads comments: lines beginning with '#' */
                   6654:     while((c=getc(ficpar))=='#' && c!= EOF){
                   6655:       ungetc(c,ficpar);
                   6656:       fgets(line, MAXLINE, ficpar);
                   6657:       numlinepar++;
1.141     brouard  6658:       fputs(line,stdout);
1.126     brouard  6659:       fputs(line,ficparo);
                   6660:       fputs(line,ficlog);
                   6661:     }
                   6662:     ungetc(c,ficpar);
                   6663:   
                   6664:     matcov=matrix(1,npar,1,npar);
1.131     brouard  6665:     for(i=1; i <=npar; i++)
                   6666:       for(j=1; j <=npar; j++) matcov[i][j]=0.;
                   6667:       
1.194     brouard  6668:     /* Scans npar lines */
1.126     brouard  6669:     for(i=1; i <=npar; i++){
1.194     brouard  6670:       count=fscanf(ficpar,"%1d%1d%1d",&i1,&j1,&jk);
                   6671:       if(count != 3){
                   6672:        printf("Error! Error in parameter file %s at line %d after line starting with %1d%1d%1d\n\
                   6673: This is probably because your covariance matrix doesn't \n  contain exactly %d lines corresponding to your model line '1+age+%s'.\n\
                   6674: Please run with mle=-1 to get a correct covariance matrix.\n",optionfile,numlinepar, i1,j1,jk, npar, model);
                   6675:        fprintf(ficlog,"Error! Error in parameter file %s at line %d after line starting with %1d%1d%1d\n\
                   6676: This is probably because your covariance matrix doesn't \n  contain exactly %d lines corresponding to your model line '1+age+%s'.\n\
                   6677: Please run with mle=-1 to get a correct covariance matrix.\n",optionfile,numlinepar, i1,j1,jk, npar, model);
                   6678:        exit(1);
                   6679:       }else
1.126     brouard  6680:       if(mle==1)
1.194     brouard  6681:        printf("%1d%1d%1d",i1,j1,jk);
                   6682:       fprintf(ficlog,"%1d%1d%1d",i1,j1,jk);
                   6683:       fprintf(ficparo,"%1d%1d%1d",i1,j1,jk);
1.126     brouard  6684:       for(j=1; j <=i; j++){
                   6685:        fscanf(ficpar," %le",&matcov[i][j]);
                   6686:        if(mle==1){
                   6687:          printf(" %.5le",matcov[i][j]);
                   6688:        }
                   6689:        fprintf(ficlog," %.5le",matcov[i][j]);
                   6690:        fprintf(ficparo," %.5le",matcov[i][j]);
                   6691:       }
                   6692:       fscanf(ficpar,"\n");
                   6693:       numlinepar++;
                   6694:       if(mle==1)
                   6695:        printf("\n");
                   6696:       fprintf(ficlog,"\n");
                   6697:       fprintf(ficparo,"\n");
                   6698:     }
1.194     brouard  6699:     /* End of read covariance matrix npar lines */
1.126     brouard  6700:     for(i=1; i <=npar; i++)
                   6701:       for(j=i+1;j<=npar;j++)
                   6702:        matcov[i][j]=matcov[j][i];
                   6703:     
                   6704:     if(mle==1)
                   6705:       printf("\n");
                   6706:     fprintf(ficlog,"\n");
                   6707:     
                   6708:     fflush(ficlog);
                   6709:     
                   6710:     /*-------- Rewriting parameter file ----------*/
                   6711:     strcpy(rfileres,"r");    /* "Rparameterfile */
                   6712:     strcat(rfileres,optionfilefiname);    /* Parameter file first name*/
                   6713:     strcat(rfileres,".");    /* */
                   6714:     strcat(rfileres,optionfilext);    /* Other files have txt extension */
                   6715:     if((ficres =fopen(rfileres,"w"))==NULL) {
                   6716:       printf("Problem writing new parameter file: %s\n", fileres);goto end;
                   6717:       fprintf(ficlog,"Problem writing new parameter file: %s\n", fileres);goto end;
                   6718:     }
                   6719:     fprintf(ficres,"#%s\n",version);
                   6720:   }    /* End of mle != -3 */
                   6721: 
1.186     brouard  6722:   /*  Main data
                   6723:    */
1.126     brouard  6724:   n= lastobs;
                   6725:   num=lvector(1,n);
                   6726:   moisnais=vector(1,n);
                   6727:   annais=vector(1,n);
                   6728:   moisdc=vector(1,n);
                   6729:   andc=vector(1,n);
                   6730:   agedc=vector(1,n);
                   6731:   cod=ivector(1,n);
                   6732:   weight=vector(1,n);
                   6733:   for(i=1;i<=n;i++) weight[i]=1.0; /* Equal weights, 1 by default */
                   6734:   mint=matrix(1,maxwav,1,n);
                   6735:   anint=matrix(1,maxwav,1,n);
1.131     brouard  6736:   s=imatrix(1,maxwav+1,1,n); /* s[i][j] health state for wave i and individual j */ 
1.126     brouard  6737:   tab=ivector(1,NCOVMAX);
1.144     brouard  6738:   ncodemax=ivector(1,NCOVMAX); /* Number of code per covariate; if O and 1 only, 2**ncov; V1+V2+V3+V4=>16 */
1.192     brouard  6739:   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  6740: 
1.136     brouard  6741:   /* Reads data from file datafile */
                   6742:   if (readdata(datafile, firstobs, lastobs, &imx)==1)
                   6743:     goto end;
                   6744: 
                   6745:   /* Calculation of the number of parameters from char model */
1.137     brouard  6746:     /*    modelsav=V2+V1+V4+age*V3 strb=age*V3 stra=V2+V1+V4 
                   6747:        k=4 (age*V3) Tvar[k=4]= 3 (from V3) Tag[cptcovage=1]=4
                   6748:        k=3 V4 Tvar[k=3]= 4 (from V4)
                   6749:        k=2 V1 Tvar[k=2]= 1 (from V1)
                   6750:        k=1 Tvar[1]=2 (from V2)
                   6751:     */
                   6752:   Tvar=ivector(1,NCOVMAX); /* Was 15 changed to NCOVMAX. */
                   6753:   /*  V2+V1+V4+age*V3 is a model with 4 covariates (3 plus signs). 
                   6754:       For each model-covariate stores the data-covariate id. Tvar[1]=2, Tvar[2]=1, Tvar[3]=4, 
                   6755:       Tvar[4=age*V3] is 3 and 'age' is recorded in Tage.
                   6756:   */
                   6757:   /* For model-covariate k tells which data-covariate to use but
                   6758:     because this model-covariate is a construction we invent a new column
                   6759:     ncovcol + k1
                   6760:     If already ncovcol=4 and model=V2+V1+V1*V4+age*V3
                   6761:     Tvar[3=V1*V4]=4+1 etc */
1.145     brouard  6762:   Tprod=ivector(1,NCOVMAX); /* Gives the position of a product */
1.137     brouard  6763:   /* Tprod[k1=1]=3(=V1*V4) for V2+V1+V1*V4+age*V3
                   6764:      if  V2+V1+V1*V4+age*V3+V3*V2   TProd[k1=2]=5 (V3*V2)
                   6765:   */
1.145     brouard  6766:   Tvaraff=ivector(1,NCOVMAX); /* Unclear */
                   6767:   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  6768:                            * For V3*V2 (in V2+V1+V1*V4+age*V3+V3*V2), V3*V2 position is 2nd. 
                   6769:                            * Tvard[k1=2][1]=3 (V3) Tvard[k1=2][2]=2(V2) */
1.145     brouard  6770:   Tage=ivector(1,NCOVMAX); /* Gives the covariate id of covariates associated with age: V2 + V1 + age*V4 + V3*age
1.137     brouard  6771:                         4 covariates (3 plus signs)
                   6772:                         Tage[1=V3*age]= 4; Tage[2=age*V4] = 3
                   6773:                      */  
1.136     brouard  6774: 
1.186     brouard  6775: /* Main decodemodel */
                   6776: 
1.187     brouard  6777: 
1.136     brouard  6778:   if(decodemodel(model, lastobs) == 1)
                   6779:     goto end;
                   6780: 
1.137     brouard  6781:   if((double)(lastobs-imx)/(double)imx > 1.10){
                   6782:     nbwarn++;
                   6783:     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); 
                   6784:     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); 
                   6785:   }
1.136     brouard  6786:     /*  if(mle==1){*/
1.137     brouard  6787:   if (weightopt != 1) { /* Maximisation without weights. We can have weights different from 1 but want no weight*/
                   6788:     for(i=1;i<=imx;i++) weight[i]=1.0; /* changed to imx */
1.136     brouard  6789:   }
                   6790: 
                   6791:     /*-calculation of age at interview from date of interview and age at death -*/
                   6792:   agev=matrix(1,maxwav,1,imx);
                   6793: 
                   6794:   if(calandcheckages(imx, maxwav, &agemin, &agemax, &nberr, &nbwarn) == 1)
                   6795:     goto end;
                   6796: 
1.126     brouard  6797: 
1.136     brouard  6798:   agegomp=(int)agemin;
                   6799:   free_vector(moisnais,1,n);
                   6800:   free_vector(annais,1,n);
1.126     brouard  6801:   /* free_matrix(mint,1,maxwav,1,n);
                   6802:      free_matrix(anint,1,maxwav,1,n);*/
                   6803:   free_vector(moisdc,1,n);
                   6804:   free_vector(andc,1,n);
1.145     brouard  6805:   /* */
                   6806:   
1.126     brouard  6807:   wav=ivector(1,imx);
                   6808:   dh=imatrix(1,lastpass-firstpass+1,1,imx);
                   6809:   bh=imatrix(1,lastpass-firstpass+1,1,imx);
                   6810:   mw=imatrix(1,lastpass-firstpass+1,1,imx);
                   6811:    
                   6812:   /* Concatenates waves */
                   6813:   concatwav(wav, dh, bh, mw, s, agedc, agev,  firstpass, lastpass, imx, nlstate, stepm);
1.145     brouard  6814:   /* */
                   6815:  
1.126     brouard  6816:   /* Routine tricode is to calculate cptcoveff (real number of unique covariates) and to associate covariable number and modality */
                   6817: 
                   6818:   nbcode=imatrix(0,NCOVMAX,0,NCOVMAX); 
                   6819:   ncodemax[1]=1;
1.145     brouard  6820:   Ndum =ivector(-1,NCOVMAX);  
1.187     brouard  6821:   if (ncovmodel-nagesqr > 2 ) /* That is if covariate other than cst, age and age*age */
1.145     brouard  6822:     tricode(Tvar,nbcode,imx, Ndum); /**< Fills nbcode[Tvar[j]][l]; */
1.186     brouard  6823:   /* Nbcode gives the value of the lth modality of jth covariate, in
                   6824:      V2+V1*age, there are 3 covariates Tvar[2]=1 (V1).*/
                   6825:   /* 1 to ncodemax[j] is the maximum value of this jth covariate */
1.145     brouard  6826: 
                   6827:   codtab=imatrix(1,100,1,10); /* codtab[h,k]=( (h-1) - mod(k-1,2**(k-1) )/2**(k-1) */
                   6828:   /*printf(" codtab[1,1],codtab[100,10]=%d,%d\n", codtab[1][1],codtab[100][10]);*/
1.186     brouard  6829:   /* codtab gives the value 1 or 2 of the hth combination of k covariates (1 or 2).*/
1.145     brouard  6830:   h=0;
                   6831: 
                   6832: 
                   6833:   /*if (cptcovn > 0) */
1.126     brouard  6834:       
1.145     brouard  6835:  
1.126     brouard  6836:   m=pow(2,cptcoveff);
                   6837:  
1.131     brouard  6838:   for(k=1;k<=cptcoveff; k++){ /* scans any effective covariate */
1.143     brouard  6839:     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 */ 
                   6840:       for(j=1; j <= ncodemax[k]; j++){ /* For each modality of this covariate ncodemax=2*/
                   6841:        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  6842:          h++;
1.141     brouard  6843:          if (h>m) 
1.136     brouard  6844:            h=1;
1.144     brouard  6845:          /**< codtab(h,k)  k   = codtab[h,k]=( (h-1) - mod(k-1,2**(k-1) )/2**(k-1) + 1
1.186     brouard  6846:           * For k=4 covariates, h goes from 1 to 2**k
                   6847:           * codtabm(h,k)=  1 & (h-1) >> (k-1) ;
                   6848:           *     h\k   1     2     3     4
1.143     brouard  6849:           *______________________________  
                   6850:           *     1 i=1 1 i=1 1 i=1 1 i=1 1
                   6851:           *     2     2     1     1     1
                   6852:           *     3 i=2 1     2     1     1
                   6853:           *     4     2     2     1     1
                   6854:           *     5 i=3 1 i=2 1     2     1
                   6855:           *     6     2     1     2     1
                   6856:           *     7 i=4 1     2     2     1
                   6857:           *     8     2     2     2     1
                   6858:           *     9 i=5 1 i=3 1 i=2 1     1
                   6859:           *    10     2     1     1     1
                   6860:           *    11 i=6 1     2     1     1
                   6861:           *    12     2     2     1     1
                   6862:           *    13 i=7 1 i=4 1     2     1    
                   6863:           *    14     2     1     2     1
                   6864:           *    15 i=8 1     2     2     1
                   6865:           *    16     2     2     2     1
                   6866:           */
1.141     brouard  6867:          codtab[h][k]=j;
1.186     brouard  6868:          /* codtab[12][3]=1; */
1.145     brouard  6869:          /*codtab[h][Tvar[k]]=j;*/
1.130     brouard  6870:          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  6871:        } 
                   6872:       }
                   6873:     }
                   6874:   } 
                   6875:   /* printf("codtab[1][2]=%d codtab[2][2]=%d",codtab[1][2],codtab[2][2]); 
                   6876:      codtab[1][2]=1;codtab[2][2]=2; */
                   6877:   /* for(i=1; i <=m ;i++){ 
                   6878:      for(k=1; k <=cptcovn; k++){
1.131     brouard  6879:        printf("i=%d k=%d %d %d ",i,k,codtab[i][k], cptcoveff);
1.126     brouard  6880:      }
                   6881:      printf("\n");
                   6882:      }
                   6883:      scanf("%d",i);*/
1.145     brouard  6884: 
                   6885:  free_ivector(Ndum,-1,NCOVMAX);
                   6886: 
                   6887: 
1.126     brouard  6888:     
1.186     brouard  6889:   /* Initialisation of ----------- gnuplot -------------*/
1.126     brouard  6890:   strcpy(optionfilegnuplot,optionfilefiname);
                   6891:   if(mle==-3)
                   6892:     strcat(optionfilegnuplot,"-mort");
                   6893:   strcat(optionfilegnuplot,".gp");
                   6894: 
                   6895:   if((ficgp=fopen(optionfilegnuplot,"w"))==NULL) {
                   6896:     printf("Problem with file %s",optionfilegnuplot);
                   6897:   }
                   6898:   else{
                   6899:     fprintf(ficgp,"\n# %s\n", version); 
                   6900:     fprintf(ficgp,"# %s\n", optionfilegnuplot); 
1.141     brouard  6901:     //fprintf(ficgp,"set missing 'NaNq'\n");
                   6902:     fprintf(ficgp,"set datafile missing 'NaNq'\n");
1.126     brouard  6903:   }
                   6904:   /*  fclose(ficgp);*/
1.186     brouard  6905: 
                   6906: 
                   6907:   /* Initialisation of --------- index.htm --------*/
1.126     brouard  6908: 
                   6909:   strcpy(optionfilehtm,optionfilefiname); /* Main html file */
                   6910:   if(mle==-3)
                   6911:     strcat(optionfilehtm,"-mort");
                   6912:   strcat(optionfilehtm,".htm");
                   6913:   if((fichtm=fopen(optionfilehtm,"w"))==NULL)    {
1.131     brouard  6914:     printf("Problem with %s \n",optionfilehtm);
                   6915:     exit(0);
1.126     brouard  6916:   }
                   6917: 
                   6918:   strcpy(optionfilehtmcov,optionfilefiname); /* Only for matrix of covariance */
                   6919:   strcat(optionfilehtmcov,"-cov.htm");
                   6920:   if((fichtmcov=fopen(optionfilehtmcov,"w"))==NULL)    {
                   6921:     printf("Problem with %s \n",optionfilehtmcov), exit(0);
                   6922:   }
                   6923:   else{
                   6924:   fprintf(fichtmcov,"<html><head>\n<title>IMaCh Cov %s</title></head>\n <body><font size=\"2\">%s <br> %s</font> \
                   6925: <hr size=\"2\" color=\"#EC5E5E\"> \n\
                   6926: Title=%s <br>Datafile=%s Firstpass=%d Lastpass=%d Stepm=%d Weight=%d Model=%s<br>\n",\
                   6927:          optionfilehtmcov,version,fullversion,title,datafile,firstpass,lastpass,stepm, weightopt, model);
                   6928:   }
                   6929: 
                   6930:   fprintf(fichtm,"<html><head>\n<title>IMaCh %s</title></head>\n <body><font size=\"2\">%s <br> %s</font> \
                   6931: <hr size=\"2\" color=\"#EC5E5E\"> \n\
                   6932: Title=%s <br>Datafile=%s Firstpass=%d Lastpass=%d Stepm=%d Weight=%d Model=%s<br>\n\
                   6933: \n\
                   6934: <hr  size=\"2\" color=\"#EC5E5E\">\
                   6935:  <ul><li><h4>Parameter files</h4>\n\
                   6936:  - Parameter file: <a href=\"%s.%s\">%s.%s</a><br>\n\
                   6937:  - Copy of the parameter file: <a href=\"o%s\">o%s</a><br>\n\
                   6938:  - Log file of the run: <a href=\"%s\">%s</a><br>\n\
                   6939:  - Gnuplot file name: <a href=\"%s\">%s</a><br>\n\
                   6940:  - Date and time at start: %s</ul>\n",\
                   6941:          optionfilehtm,version,fullversion,title,datafile,firstpass,lastpass,stepm, weightopt, model,\
                   6942:          optionfilefiname,optionfilext,optionfilefiname,optionfilext,\
                   6943:          fileres,fileres,\
                   6944:          filelog,filelog,optionfilegnuplot,optionfilegnuplot,strstart);
                   6945:   fflush(fichtm);
                   6946: 
                   6947:   strcpy(pathr,path);
                   6948:   strcat(pathr,optionfilefiname);
1.184     brouard  6949: #ifdef WIN32
                   6950:   _chdir(optionfilefiname); /* Move to directory named optionfile */
                   6951: #else
1.126     brouard  6952:   chdir(optionfilefiname); /* Move to directory named optionfile */
1.184     brouard  6953: #endif
                   6954:          
1.126     brouard  6955:   
                   6956:   /* Calculates basic frequencies. Computes observed prevalence at single age
                   6957:      and prints on file fileres'p'. */
                   6958:   freqsummary(fileres, agemin, agemax, s, agev, nlstate, imx,Tvaraff,nbcode, ncodemax,mint,anint,strstart);
                   6959: 
                   6960:   fprintf(fichtm,"\n");
                   6961:   fprintf(fichtm,"<br>Total number of observations=%d <br>\n\
                   6962: Youngest age at first (selected) pass %.2f, oldest age %.2f<br>\n\
                   6963: Interval (in months) between two waves: Min=%d Max=%d Mean=%.2lf<br>\n",\
                   6964:          imx,agemin,agemax,jmin,jmax,jmean);
                   6965:   pmmij= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
                   6966:     oldms= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
                   6967:     newms= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
                   6968:     savms= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
                   6969:     oldm=oldms; newm=newms; savm=savms; /* Keeps fixed addresses to free */
                   6970:     
                   6971:    
                   6972:   /* For Powell, parameters are in a vector p[] starting at p[1]
                   6973:      so we point p on param[1][1] so that p[1] maps on param[1][1][1] */
                   6974:   p=param[1][1]; /* *(*(*(param +1)+1)+0) */
                   6975: 
                   6976:   globpr=0; /* To get the number ipmx of contributions and the sum of weights*/
1.186     brouard  6977:   /* For mortality only */
1.126     brouard  6978:   if (mle==-3){
1.136     brouard  6979:     ximort=matrix(1,NDIM,1,NDIM); 
1.186     brouard  6980:     /*     ximort=gsl_matrix_alloc(1,NDIM,1,NDIM); */
1.126     brouard  6981:     cens=ivector(1,n);
                   6982:     ageexmed=vector(1,n);
                   6983:     agecens=vector(1,n);
                   6984:     dcwave=ivector(1,n);
                   6985:  
                   6986:     for (i=1; i<=imx; i++){
                   6987:       dcwave[i]=-1;
                   6988:       for (m=firstpass; m<=lastpass; m++)
                   6989:        if (s[m][i]>nlstate) {
                   6990:          dcwave[i]=m;
                   6991:          /*    printf("i=%d j=%d s=%d dcwave=%d\n",i,j, s[j][i],dcwave[i]);*/
                   6992:          break;
                   6993:        }
                   6994:     }
                   6995: 
                   6996:     for (i=1; i<=imx; i++) {
                   6997:       if (wav[i]>0){
                   6998:        ageexmed[i]=agev[mw[1][i]][i];
                   6999:        j=wav[i];
                   7000:        agecens[i]=1.; 
                   7001: 
                   7002:        if (ageexmed[i]> 1 && wav[i] > 0){
                   7003:          agecens[i]=agev[mw[j][i]][i];
                   7004:          cens[i]= 1;
                   7005:        }else if (ageexmed[i]< 1) 
                   7006:          cens[i]= -1;
                   7007:        if (agedc[i]< AGESUP && agedc[i]>1 && dcwave[i]>firstpass && dcwave[i]<=lastpass)
                   7008:          cens[i]=0 ;
                   7009:       }
                   7010:       else cens[i]=-1;
                   7011:     }
                   7012:     
                   7013:     for (i=1;i<=NDIM;i++) {
                   7014:       for (j=1;j<=NDIM;j++)
                   7015:        ximort[i][j]=(i == j ? 1.0 : 0.0);
                   7016:     }
                   7017:     
1.145     brouard  7018:     /*p[1]=0.0268; p[NDIM]=0.083;*/
1.126     brouard  7019:     /*printf("%lf %lf", p[1], p[2]);*/
                   7020:     
                   7021:     
1.136     brouard  7022: #ifdef GSL
                   7023:     printf("GSL optimization\n");  fprintf(ficlog,"Powell\n");
1.162     brouard  7024: #else
1.126     brouard  7025:     printf("Powell\n");  fprintf(ficlog,"Powell\n");
1.136     brouard  7026: #endif
1.126     brouard  7027:     strcpy(filerespow,"pow-mort"); 
                   7028:     strcat(filerespow,fileres);
                   7029:     if((ficrespow=fopen(filerespow,"w"))==NULL) {
                   7030:       printf("Problem with resultfile: %s\n", filerespow);
                   7031:       fprintf(ficlog,"Problem with resultfile: %s\n", filerespow);
                   7032:     }
1.136     brouard  7033: #ifdef GSL
                   7034:     fprintf(ficrespow,"# GSL optimization\n# iter -2*LL");
1.162     brouard  7035: #else
1.126     brouard  7036:     fprintf(ficrespow,"# Powell\n# iter -2*LL");
1.136     brouard  7037: #endif
1.126     brouard  7038:     /*  for (i=1;i<=nlstate;i++)
                   7039:        for(j=1;j<=nlstate+ndeath;j++)
                   7040:        if(j!=i)fprintf(ficrespow," p%1d%1d",i,j);
                   7041:     */
                   7042:     fprintf(ficrespow,"\n");
1.136     brouard  7043: #ifdef GSL
                   7044:     /* gsl starts here */ 
                   7045:     T = gsl_multimin_fminimizer_nmsimplex;
                   7046:     gsl_multimin_fminimizer *sfm = NULL;
                   7047:     gsl_vector *ss, *x;
                   7048:     gsl_multimin_function minex_func;
                   7049: 
                   7050:     /* Initial vertex size vector */
                   7051:     ss = gsl_vector_alloc (NDIM);
                   7052:     
                   7053:     if (ss == NULL){
                   7054:       GSL_ERROR_VAL ("failed to allocate space for ss", GSL_ENOMEM, 0);
                   7055:     }
                   7056:     /* Set all step sizes to 1 */
                   7057:     gsl_vector_set_all (ss, 0.001);
                   7058: 
                   7059:     /* Starting point */
1.126     brouard  7060:     
1.136     brouard  7061:     x = gsl_vector_alloc (NDIM);
                   7062:     
                   7063:     if (x == NULL){
                   7064:       gsl_vector_free(ss);
                   7065:       GSL_ERROR_VAL ("failed to allocate space for x", GSL_ENOMEM, 0);
                   7066:     }
                   7067:   
                   7068:     /* Initialize method and iterate */
                   7069:     /*     p[1]=0.0268; p[NDIM]=0.083; */
1.186     brouard  7070:     /*     gsl_vector_set(x, 0, 0.0268); */
                   7071:     /*     gsl_vector_set(x, 1, 0.083); */
1.136     brouard  7072:     gsl_vector_set(x, 0, p[1]);
                   7073:     gsl_vector_set(x, 1, p[2]);
                   7074: 
                   7075:     minex_func.f = &gompertz_f;
                   7076:     minex_func.n = NDIM;
                   7077:     minex_func.params = (void *)&p; /* ??? */
                   7078:     
                   7079:     sfm = gsl_multimin_fminimizer_alloc (T, NDIM);
                   7080:     gsl_multimin_fminimizer_set (sfm, &minex_func, x, ss);
                   7081:     
                   7082:     printf("Iterations beginning .....\n\n");
                   7083:     printf("Iter. #    Intercept       Slope     -Log Likelihood     Simplex size\n");
                   7084: 
                   7085:     iteri=0;
                   7086:     while (rval == GSL_CONTINUE){
                   7087:       iteri++;
                   7088:       status = gsl_multimin_fminimizer_iterate(sfm);
                   7089:       
                   7090:       if (status) printf("error: %s\n", gsl_strerror (status));
                   7091:       fflush(0);
                   7092:       
                   7093:       if (status) 
                   7094:         break;
                   7095:       
                   7096:       rval = gsl_multimin_test_size (gsl_multimin_fminimizer_size (sfm), 1e-6);
                   7097:       ssval = gsl_multimin_fminimizer_size (sfm);
                   7098:       
                   7099:       if (rval == GSL_SUCCESS)
                   7100:         printf ("converged to a local maximum at\n");
                   7101:       
                   7102:       printf("%5d ", iteri);
                   7103:       for (it = 0; it < NDIM; it++){
                   7104:        printf ("%10.5f ", gsl_vector_get (sfm->x, it));
                   7105:       }
                   7106:       printf("f() = %-10.5f ssize = %.7f\n", sfm->fval, ssval);
                   7107:     }
                   7108:     
                   7109:     printf("\n\n Please note: Program should be run many times with varying starting points to detemine global maximum\n\n");
                   7110:     
                   7111:     gsl_vector_free(x); /* initial values */
                   7112:     gsl_vector_free(ss); /* inital step size */
                   7113:     for (it=0; it<NDIM; it++){
                   7114:       p[it+1]=gsl_vector_get(sfm->x,it);
                   7115:       fprintf(ficrespow," %.12lf", p[it]);
                   7116:     }
                   7117:     gsl_multimin_fminimizer_free (sfm); /* p *(sfm.x.data) et p *(sfm.x.data+1)  */
                   7118: #endif
                   7119: #ifdef POWELL
                   7120:      powell(p,ximort,NDIM,ftol,&iter,&fret,gompertz);
                   7121: #endif  
1.126     brouard  7122:     fclose(ficrespow);
                   7123:     
                   7124:     hesscov(matcov, p, NDIM, delti, 1e-4, gompertz); 
                   7125: 
                   7126:     for(i=1; i <=NDIM; i++)
                   7127:       for(j=i+1;j<=NDIM;j++)
                   7128:        matcov[i][j]=matcov[j][i];
                   7129:     
                   7130:     printf("\nCovariance matrix\n ");
                   7131:     for(i=1; i <=NDIM; i++) {
                   7132:       for(j=1;j<=NDIM;j++){ 
                   7133:        printf("%f ",matcov[i][j]);
                   7134:       }
                   7135:       printf("\n ");
                   7136:     }
                   7137:     
                   7138:     printf("iter=%d MLE=%f Eq=%lf*exp(%lf*(age-%d))\n",iter,-gompertz(p),p[1],p[2],agegomp);
1.193     brouard  7139:     for (i=1;i<=NDIM;i++) {
1.126     brouard  7140:       printf("%f [%f ; %f]\n",p[i],p[i]-2*sqrt(matcov[i][i]),p[i]+2*sqrt(matcov[i][i]));
1.193     brouard  7141:       fprintf(ficlog,"%f [%f ; %f]\n",p[i],p[i]-2*sqrt(matcov[i][i]),p[i]+2*sqrt(matcov[i][i]));
                   7142:     }
1.126     brouard  7143:     lsurv=vector(1,AGESUP);
                   7144:     lpop=vector(1,AGESUP);
                   7145:     tpop=vector(1,AGESUP);
                   7146:     lsurv[agegomp]=100000;
                   7147:     
                   7148:     for (k=agegomp;k<=AGESUP;k++) {
                   7149:       agemortsup=k;
                   7150:       if (p[1]*exp(p[2]*(k-agegomp))>1) break;
                   7151:     }
                   7152:     
                   7153:     for (k=agegomp;k<agemortsup;k++)
                   7154:       lsurv[k+1]=lsurv[k]-lsurv[k]*(p[1]*exp(p[2]*(k-agegomp)));
                   7155:     
                   7156:     for (k=agegomp;k<agemortsup;k++){
                   7157:       lpop[k]=(lsurv[k]+lsurv[k+1])/2.;
                   7158:       sumlpop=sumlpop+lpop[k];
                   7159:     }
                   7160:     
                   7161:     tpop[agegomp]=sumlpop;
                   7162:     for (k=agegomp;k<(agemortsup-3);k++){
                   7163:       /*  tpop[k+1]=2;*/
                   7164:       tpop[k+1]=tpop[k]-lpop[k];
                   7165:     }
                   7166:     
                   7167:     
                   7168:     printf("\nAge   lx     qx    dx    Lx     Tx     e(x)\n");
                   7169:     for (k=agegomp;k<(agemortsup-2);k++) 
                   7170:       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]);
                   7171:     
                   7172:     
                   7173:     replace_back_to_slash(pathc,pathcd); /* Even gnuplot wants a / */
1.194     brouard  7174:     if(ageminpar == AGEOVERFLOW ||agemaxpar == AGEOVERFLOW){
                   7175:        printf("Warning! Error in gnuplot file with ageminpar %f or agemaxpar %f overflow\n\
                   7176: This is probably because your parameter file doesn't \n  contain the exact number of lines (or columns) corresponding to your model line.\n\
                   7177: Please run with mle=-1 to get a correct covariance matrix.\n",ageminpar,agemaxpar);
                   7178:        fprintf(ficlog,"Warning! Error in gnuplot file with ageminpar %f or agemaxpar %f overflow\n\
                   7179: This is probably because your parameter file doesn't \n  contain the exact number of lines (or columns) corresponding to your model line.\n\
                   7180: Please run with mle=-1 to get a correct covariance matrix.\n",ageminpar,agemaxpar);
                   7181:     }else
                   7182:       printinggnuplotmort(fileres, optionfilefiname,ageminpar,agemaxpar,fage, pathc,p);
1.126     brouard  7183:     printinghtmlmort(fileres,title,datafile, firstpass, lastpass, \
                   7184:                     stepm, weightopt,\
                   7185:                     model,imx,p,matcov,agemortsup);
                   7186:     
                   7187:     free_vector(lsurv,1,AGESUP);
                   7188:     free_vector(lpop,1,AGESUP);
                   7189:     free_vector(tpop,1,AGESUP);
1.136     brouard  7190: #ifdef GSL
                   7191:     free_ivector(cens,1,n);
                   7192:     free_vector(agecens,1,n);
                   7193:     free_ivector(dcwave,1,n);
                   7194:     free_matrix(ximort,1,NDIM,1,NDIM);
                   7195: #endif
1.186     brouard  7196:   } /* Endof if mle==-3 mortality only */
                   7197:   /* Standard maximisation */
1.126     brouard  7198:   else{ /* For mle >=1 */
1.132     brouard  7199:     globpr=0;/* debug */
1.186     brouard  7200:     /* Computes likelihood for initial parameters */
1.132     brouard  7201:     likelione(ficres, p, npar, nlstate, &globpr, &ipmx, &sw, &fretone, funcone); /* Prints the contributions to the likelihood */
1.126     brouard  7202:     printf("First Likeli=%12.6f ipmx=%ld sw=%12.6f",fretone,ipmx,sw);
                   7203:     for (k=1; k<=npar;k++)
                   7204:       printf(" %d %8.5f",k,p[k]);
                   7205:     printf("\n");
1.186     brouard  7206:     globpr=1; /* again, to print the contributions */
1.126     brouard  7207:     likelione(ficres, p, npar, nlstate, &globpr, &ipmx, &sw, &fretone, funcone); /* Prints the contributions to the likelihood */
                   7208:     printf("Second Likeli=%12.6f ipmx=%ld sw=%12.6f",fretone,ipmx,sw);
                   7209:     for (k=1; k<=npar;k++)
                   7210:       printf(" %d %8.5f",k,p[k]);
                   7211:     printf("\n");
1.186     brouard  7212:     if(mle>=1){ /* Could be 1 or 2, Real Maximisation */
1.126     brouard  7213:       mlikeli(ficres,p, npar, ncovmodel, nlstate, ftol, func);
                   7214:     }
                   7215:     
                   7216:     /*--------- results files --------------*/
1.192     brouard  7217:     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  7218:     
                   7219:     
                   7220:     fprintf(ficres,"# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
                   7221:     printf("# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
                   7222:     fprintf(ficlog,"# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
                   7223:     for(i=1,jk=1; i <=nlstate; i++){
                   7224:       for(k=1; k <=(nlstate+ndeath); k++){
                   7225:        if (k != i) {
                   7226:          printf("%d%d ",i,k);
                   7227:          fprintf(ficlog,"%d%d ",i,k);
                   7228:          fprintf(ficres,"%1d%1d ",i,k);
                   7229:          for(j=1; j <=ncovmodel; j++){
1.190     brouard  7230:            printf("%12.7f ",p[jk]);
                   7231:            fprintf(ficlog,"%12.7f ",p[jk]);
                   7232:            fprintf(ficres,"%12.7f ",p[jk]);
1.126     brouard  7233:            jk++; 
                   7234:          }
                   7235:          printf("\n");
                   7236:          fprintf(ficlog,"\n");
                   7237:          fprintf(ficres,"\n");
                   7238:        }
                   7239:       }
                   7240:     }
                   7241:     if(mle!=0){
                   7242:       /* Computing hessian and covariance matrix */
                   7243:       ftolhess=ftol; /* Usually correct */
                   7244:       hesscov(matcov, p, npar, delti, ftolhess, func);
                   7245:     }
1.193     brouard  7246:     printf("Parameters and 95%% confidence intervals\n");
                   7247:     fprintf(ficlog, "Parameters, T and confidence intervals\n");
                   7248:     for(i=1,jk=1; i <=nlstate; i++){
                   7249:       for(k=1; k <=(nlstate+ndeath); k++){
                   7250:        if (k != i) {
                   7251:          printf("%d%d ",i,k);
                   7252:          fprintf(ficlog,"%d%d ",i,k);
                   7253:          for(j=1; j <=ncovmodel; j++){
                   7254:            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]));
                   7255:            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]));
                   7256:            jk++; 
                   7257:          }
                   7258:          printf("\n");
                   7259:          fprintf(ficlog,"\n");
                   7260:        }
                   7261:       }
                   7262:     }
                   7263: 
1.126     brouard  7264:     fprintf(ficres,"# Scales (for hessian or gradient estimation)\n");
                   7265:     printf("# Scales (for hessian or gradient estimation)\n");
                   7266:     fprintf(ficlog,"# Scales (for hessian or gradient estimation)\n");
                   7267:     for(i=1,jk=1; i <=nlstate; i++){
                   7268:       for(j=1; j <=nlstate+ndeath; j++){
                   7269:        if (j!=i) {
                   7270:          fprintf(ficres,"%1d%1d",i,j);
                   7271:          printf("%1d%1d",i,j);
                   7272:          fprintf(ficlog,"%1d%1d",i,j);
                   7273:          for(k=1; k<=ncovmodel;k++){
                   7274:            printf(" %.5e",delti[jk]);
                   7275:            fprintf(ficlog," %.5e",delti[jk]);
                   7276:            fprintf(ficres," %.5e",delti[jk]);
                   7277:            jk++;
                   7278:          }
                   7279:          printf("\n");
                   7280:          fprintf(ficlog,"\n");
                   7281:          fprintf(ficres,"\n");
                   7282:        }
                   7283:       }
                   7284:     }
                   7285:     
                   7286:     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");
                   7287:     if(mle>=1)
                   7288:       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");
                   7289:     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");
                   7290:     /* # 121 Var(a12)\n\ */
                   7291:     /* # 122 Cov(b12,a12) Var(b12)\n\ */
                   7292:     /* # 131 Cov(a13,a12) Cov(a13,b12, Var(a13)\n\ */
                   7293:     /* # 132 Cov(b13,a12) Cov(b13,b12, Cov(b13,a13) Var(b13)\n\ */
                   7294:     /* # 212 Cov(a21,a12) Cov(a21,b12, Cov(a21,a13) Cov(a21,b13) Var(a21)\n\ */
                   7295:     /* # 212 Cov(b21,a12) Cov(b21,b12, Cov(b21,a13) Cov(b21,b13) Cov(b21,a21) Var(b21)\n\ */
                   7296:     /* # 232 Cov(a23,a12) Cov(a23,b12, Cov(a23,a13) Cov(a23,b13) Cov(a23,a21) Cov(a23,b21) Var(a23)\n\ */
                   7297:     /* # 232 Cov(b23,a12) Cov(b23,b12) ... Var (b23)\n" */
                   7298:     
                   7299:     
                   7300:     /* Just to have a covariance matrix which will be more understandable
                   7301:        even is we still don't want to manage dictionary of variables
                   7302:     */
                   7303:     for(itimes=1;itimes<=2;itimes++){
                   7304:       jj=0;
                   7305:       for(i=1; i <=nlstate; i++){
                   7306:        for(j=1; j <=nlstate+ndeath; j++){
                   7307:          if(j==i) continue;
                   7308:          for(k=1; k<=ncovmodel;k++){
                   7309:            jj++;
                   7310:            ca[0]= k+'a'-1;ca[1]='\0';
                   7311:            if(itimes==1){
                   7312:              if(mle>=1)
                   7313:                printf("#%1d%1d%d",i,j,k);
                   7314:              fprintf(ficlog,"#%1d%1d%d",i,j,k);
                   7315:              fprintf(ficres,"#%1d%1d%d",i,j,k);
                   7316:            }else{
                   7317:              if(mle>=1)
                   7318:                printf("%1d%1d%d",i,j,k);
                   7319:              fprintf(ficlog,"%1d%1d%d",i,j,k);
                   7320:              fprintf(ficres,"%1d%1d%d",i,j,k);
                   7321:            }
                   7322:            ll=0;
                   7323:            for(li=1;li <=nlstate; li++){
                   7324:              for(lj=1;lj <=nlstate+ndeath; lj++){
                   7325:                if(lj==li) continue;
                   7326:                for(lk=1;lk<=ncovmodel;lk++){
                   7327:                  ll++;
                   7328:                  if(ll<=jj){
                   7329:                    cb[0]= lk +'a'-1;cb[1]='\0';
                   7330:                    if(ll<jj){
                   7331:                      if(itimes==1){
                   7332:                        if(mle>=1)
                   7333:                          printf(" Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
                   7334:                        fprintf(ficlog," Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
                   7335:                        fprintf(ficres," Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
                   7336:                      }else{
                   7337:                        if(mle>=1)
                   7338:                          printf(" %.5e",matcov[jj][ll]); 
                   7339:                        fprintf(ficlog," %.5e",matcov[jj][ll]); 
                   7340:                        fprintf(ficres," %.5e",matcov[jj][ll]); 
                   7341:                      }
                   7342:                    }else{
                   7343:                      if(itimes==1){
                   7344:                        if(mle>=1)
                   7345:                          printf(" Var(%s%1d%1d)",ca,i,j);
                   7346:                        fprintf(ficlog," Var(%s%1d%1d)",ca,i,j);
                   7347:                        fprintf(ficres," Var(%s%1d%1d)",ca,i,j);
                   7348:                      }else{
                   7349:                        if(mle>=1)
                   7350:                          printf(" %.5e",matcov[jj][ll]); 
                   7351:                        fprintf(ficlog," %.5e",matcov[jj][ll]); 
                   7352:                        fprintf(ficres," %.5e",matcov[jj][ll]); 
                   7353:                      }
                   7354:                    }
                   7355:                  }
                   7356:                } /* end lk */
                   7357:              } /* end lj */
                   7358:            } /* end li */
                   7359:            if(mle>=1)
                   7360:              printf("\n");
                   7361:            fprintf(ficlog,"\n");
                   7362:            fprintf(ficres,"\n");
                   7363:            numlinepar++;
                   7364:          } /* end k*/
                   7365:        } /*end j */
                   7366:       } /* end i */
                   7367:     } /* end itimes */
                   7368:     
                   7369:     fflush(ficlog);
                   7370:     fflush(ficres);
                   7371:     
                   7372:     while((c=getc(ficpar))=='#' && c!= EOF){
                   7373:       ungetc(c,ficpar);
                   7374:       fgets(line, MAXLINE, ficpar);
1.141     brouard  7375:       fputs(line,stdout);
1.126     brouard  7376:       fputs(line,ficparo);
                   7377:     }
                   7378:     ungetc(c,ficpar);
                   7379:     
                   7380:     estepm=0;
                   7381:     fscanf(ficpar,"agemin=%lf agemax=%lf bage=%lf fage=%lf estepm=%d\n",&ageminpar,&agemaxpar, &bage, &fage, &estepm);
                   7382:     if (estepm==0 || estepm < stepm) estepm=stepm;
                   7383:     if (fage <= 2) {
                   7384:       bage = ageminpar;
                   7385:       fage = agemaxpar;
                   7386:     }
                   7387:     
                   7388:     fprintf(ficres,"# agemin agemax for life expectancy, bage fage (if mle==0 ie no data nor Max likelihood).\n");
                   7389:     fprintf(ficres,"agemin=%.0f agemax=%.0f bage=%.0f fage=%.0f estepm=%d\n",ageminpar,agemaxpar,bage,fage, estepm);
                   7390:     fprintf(ficparo,"agemin=%.0f agemax=%.0f bage=%.0f fage=%.0f estepm=%d\n",ageminpar,agemaxpar,bage,fage, estepm);
1.186     brouard  7391: 
                   7392:     /* Other stuffs, more or less useful */    
1.126     brouard  7393:     while((c=getc(ficpar))=='#' && c!= EOF){
                   7394:       ungetc(c,ficpar);
                   7395:       fgets(line, MAXLINE, ficpar);
1.141     brouard  7396:       fputs(line,stdout);
1.126     brouard  7397:       fputs(line,ficparo);
                   7398:     }
                   7399:     ungetc(c,ficpar);
                   7400:     
                   7401:     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);
                   7402:     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);
                   7403:     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);
                   7404:     printf("begin-prev-date=%.lf/%.lf/%.lf end-prev-date=%.lf/%.lf/%.lf mov_average=%d\n",jprev1, mprev1,anprev1,jprev2, mprev2,anprev2,mobilav);
                   7405:     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);
                   7406:     
                   7407:     while((c=getc(ficpar))=='#' && c!= EOF){
                   7408:       ungetc(c,ficpar);
                   7409:       fgets(line, MAXLINE, ficpar);
1.141     brouard  7410:       fputs(line,stdout);
1.126     brouard  7411:       fputs(line,ficparo);
                   7412:     }
                   7413:     ungetc(c,ficpar);
                   7414:     
                   7415:     
                   7416:     dateprev1=anprev1+(mprev1-1)/12.+(jprev1-1)/365.;
                   7417:     dateprev2=anprev2+(mprev2-1)/12.+(jprev2-1)/365.;
                   7418:     
                   7419:     fscanf(ficpar,"pop_based=%d\n",&popbased);
1.193     brouard  7420:     fprintf(ficlog,"pop_based=%d\n",popbased);
1.126     brouard  7421:     fprintf(ficparo,"pop_based=%d\n",popbased);   
                   7422:     fprintf(ficres,"pop_based=%d\n",popbased);   
                   7423:     
                   7424:     while((c=getc(ficpar))=='#' && c!= EOF){
                   7425:       ungetc(c,ficpar);
                   7426:       fgets(line, MAXLINE, ficpar);
1.141     brouard  7427:       fputs(line,stdout);
1.126     brouard  7428:       fputs(line,ficparo);
                   7429:     }
                   7430:     ungetc(c,ficpar);
                   7431:     
                   7432:     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);
                   7433:     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);
                   7434:     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);
                   7435:     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);
                   7436:     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);
                   7437:     /* day and month of proj2 are not used but only year anproj2.*/
                   7438:     
                   7439:     
                   7440:     
1.145     brouard  7441:      /* freqsummary(fileres, agemin, agemax, s, agev, nlstate, imx,Tvaraff,nbcode, ncodemax,mint,anint); */
                   7442:     /* ,dateprev1,dateprev2,jprev1, mprev1,anprev1,jprev2, mprev2,anprev2); */
1.126     brouard  7443:     
                   7444:     replace_back_to_slash(pathc,pathcd); /* Even gnuplot wants a / */
1.194     brouard  7445:     if(ageminpar == AGEOVERFLOW ||agemaxpar == -AGEOVERFLOW){
                   7446:        printf("Warning! Error in gnuplot file with ageminpar %f or agemaxpar %f overflow\n\
                   7447: This is probably because your parameter file doesn't \n  contain the exact number of lines (or columns) corresponding to your model line.\n\
                   7448: Please run with mle=-1 to get a correct covariance matrix.\n",ageminpar,agemaxpar);
                   7449:        fprintf(ficlog,"Warning! Error in gnuplot file with ageminpar %f or agemaxpar %f overflow\n\
                   7450: This is probably because your parameter file doesn't \n  contain the exact number of lines (or columns) corresponding to your model line.\n\
                   7451: Please run with mle=-1 to get a correct covariance matrix.\n",ageminpar,agemaxpar);
                   7452:     }else
                   7453:       printinggnuplot(fileres, optionfilefiname,ageminpar,agemaxpar,fage, pathc,p);
1.126     brouard  7454:     
                   7455:     printinghtml(fileres,title,datafile, firstpass, lastpass, stepm, weightopt,\
                   7456:                 model,imx,jmin,jmax,jmean,rfileres,popforecast,estepm,\
                   7457:                 jprev1,mprev1,anprev1,jprev2,mprev2,anprev2);
                   7458:       
                   7459:    /*------------ free_vector  -------------*/
                   7460:    /*  chdir(path); */
                   7461:  
                   7462:     free_ivector(wav,1,imx);
                   7463:     free_imatrix(dh,1,lastpass-firstpass+1,1,imx);
                   7464:     free_imatrix(bh,1,lastpass-firstpass+1,1,imx);
                   7465:     free_imatrix(mw,1,lastpass-firstpass+1,1,imx);   
                   7466:     free_lvector(num,1,n);
                   7467:     free_vector(agedc,1,n);
                   7468:     /*free_matrix(covar,0,NCOVMAX,1,n);*/
                   7469:     /*free_matrix(covar,1,NCOVMAX,1,n);*/
                   7470:     fclose(ficparo);
                   7471:     fclose(ficres);
                   7472: 
                   7473: 
1.186     brouard  7474:     /* Other results (useful)*/
                   7475: 
                   7476: 
1.126     brouard  7477:     /*--------------- Prevalence limit  (period or stable prevalence) --------------*/
1.180     brouard  7478:     /*#include "prevlim.h"*/  /* Use ficrespl, ficlog */
                   7479:     prlim=matrix(1,nlstate,1,nlstate);
                   7480:     prevalence_limit(p, prlim,  ageminpar, agemaxpar);
1.126     brouard  7481:     fclose(ficrespl);
                   7482: 
1.145     brouard  7483: #ifdef FREEEXIT2
                   7484: #include "freeexit2.h"
                   7485: #endif
                   7486: 
1.126     brouard  7487:     /*------------- h Pij x at various ages ------------*/
1.180     brouard  7488:     /*#include "hpijx.h"*/
                   7489:     hPijx(p, bage, fage);
1.145     brouard  7490:     fclose(ficrespij);
1.126     brouard  7491: 
1.145     brouard  7492:   /*-------------- Variance of one-step probabilities---*/
                   7493:     k=1;
1.126     brouard  7494:     varprob(optionfilefiname, matcov, p, delti, nlstate, bage, fage,k,Tvar,nbcode, ncodemax,strstart);
                   7495: 
                   7496: 
                   7497:     probs= ma3x(1,AGESUP,1,NCOVMAX, 1,NCOVMAX);
                   7498:     for(i=1;i<=AGESUP;i++)
                   7499:       for(j=1;j<=NCOVMAX;j++)
                   7500:        for(k=1;k<=NCOVMAX;k++)
                   7501:          probs[i][j][k]=0.;
                   7502: 
                   7503:     /*---------- Forecasting ------------------*/
                   7504:     /*if((stepm == 1) && (strcmp(model,".")==0)){*/
                   7505:     if(prevfcast==1){
                   7506:       /*    if(stepm ==1){*/
                   7507:       prevforecast(fileres, anproj1, mproj1, jproj1, agemin, agemax, dateprev1, dateprev2, mobilavproj, bage, fage, firstpass, lastpass, anproj2, p, cptcoveff);
                   7508:       /* (popforecast==1) populforecast(fileres, anpyram,mpyram,jpyram, agemin,agemax, dateprev1, dateprev2,mobilav, agedeb, fage, popforecast, popfile, anpyram1,p, i1);*/
                   7509:       /*      }  */
                   7510:       /*      else{ */
                   7511:       /*        erreur=108; */
                   7512:       /*        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); */
                   7513:       /*        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); */
                   7514:       /*      } */
                   7515:     }
1.186     brouard  7516:  
                   7517:     /* ------ Other prevalence ratios------------ */
1.126     brouard  7518: 
1.127     brouard  7519:     /* Computes prevalence between agemin (i.e minimal age computed) and no more ageminpar */
                   7520: 
                   7521:     prevalence(probs, agemin, agemax, s, agev, nlstate, imx, Tvar, nbcode, ncodemax, mint, anint, dateprev1, dateprev2, firstpass, lastpass);
                   7522:     /*  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",\
                   7523:        ageminpar, agemax, s[lastpass][imx], agev[lastpass][imx], nlstate, imx, mint[lastpass][imx],anint[lastpass][imx], dateprev1, dateprev2, firstpass, lastpass);
                   7524:     */
1.126     brouard  7525: 
1.127     brouard  7526:     if (mobilav!=0) {
                   7527:       mobaverage= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
                   7528:       if (movingaverage(probs, bage, fage, mobaverage,mobilav)!=0){
                   7529:        fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav);
                   7530:        printf(" Error in movingaverage mobilav=%d\n",mobilav);
                   7531:       }
1.126     brouard  7532:     }
                   7533: 
                   7534: 
1.127     brouard  7535:     /*---------- Health expectancies, no variances ------------*/
                   7536: 
1.126     brouard  7537:     strcpy(filerese,"e");
                   7538:     strcat(filerese,fileres);
                   7539:     if((ficreseij=fopen(filerese,"w"))==NULL) {
                   7540:       printf("Problem with Health Exp. resultfile: %s\n", filerese); exit(0);
                   7541:       fprintf(ficlog,"Problem with Health Exp. resultfile: %s\n", filerese); exit(0);
                   7542:     }
                   7543:     printf("Computing Health Expectancies: result on file '%s' \n", filerese);
                   7544:     fprintf(ficlog,"Computing Health Expectancies: result on file '%s' \n", filerese);
1.145     brouard  7545:     /*for(cptcov=1,k=0;cptcov<=i1;cptcov++){
                   7546:       for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){*/
                   7547:           
                   7548:     for (k=1; k <= (int) pow(2,cptcoveff); k++){
1.127     brouard  7549:        fprintf(ficreseij,"\n#****** ");
                   7550:        for(j=1;j<=cptcoveff;j++) {
                   7551:          fprintf(ficreseij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
                   7552:        }
                   7553:        fprintf(ficreseij,"******\n");
                   7554: 
                   7555:        eij=ma3x(1,nlstate,1,nlstate,(int) bage, (int) fage);
                   7556:        oldm=oldms;savm=savms;
                   7557:        evsij(eij, p, nlstate, stepm, (int) bage, (int)fage, oldm, savm, k, estepm, strstart);  
                   7558:       
                   7559:        free_ma3x(eij,1,nlstate,1,nlstate,(int) bage, (int)fage);
1.145     brouard  7560:       /*}*/
1.127     brouard  7561:     }
                   7562:     fclose(ficreseij);
                   7563: 
                   7564: 
                   7565:     /*---------- Health expectancies and variances ------------*/
                   7566: 
                   7567: 
                   7568:     strcpy(filerest,"t");
                   7569:     strcat(filerest,fileres);
                   7570:     if((ficrest=fopen(filerest,"w"))==NULL) {
                   7571:       printf("Problem with total LE resultfile: %s\n", filerest);goto end;
                   7572:       fprintf(ficlog,"Problem with total LE resultfile: %s\n", filerest);goto end;
                   7573:     }
                   7574:     printf("Computing Total Life expectancies with their standard errors: file '%s' \n", filerest); 
                   7575:     fprintf(ficlog,"Computing Total Life expectancies with their standard errors: file '%s' \n", filerest); 
                   7576: 
1.126     brouard  7577: 
                   7578:     strcpy(fileresstde,"stde");
                   7579:     strcat(fileresstde,fileres);
                   7580:     if((ficresstdeij=fopen(fileresstde,"w"))==NULL) {
                   7581:       printf("Problem with Health Exp. and std errors resultfile: %s\n", fileresstde); exit(0);
                   7582:       fprintf(ficlog,"Problem with Health Exp. and std errors resultfile: %s\n", fileresstde); exit(0);
                   7583:     }
                   7584:     printf("Computing Health Expectancies and standard errors: result on file '%s' \n", fileresstde);
                   7585:     fprintf(ficlog,"Computing Health Expectancies and standard errors: result on file '%s' \n", fileresstde);
                   7586: 
                   7587:     strcpy(filerescve,"cve");
                   7588:     strcat(filerescve,fileres);
                   7589:     if((ficrescveij=fopen(filerescve,"w"))==NULL) {
                   7590:       printf("Problem with Covar. Health Exp. resultfile: %s\n", filerescve); exit(0);
                   7591:       fprintf(ficlog,"Problem with Covar. Health Exp. resultfile: %s\n", filerescve); exit(0);
                   7592:     }
                   7593:     printf("Computing Covar. of Health Expectancies: result on file '%s' \n", filerescve);
                   7594:     fprintf(ficlog,"Computing Covar. of Health Expectancies: result on file '%s' \n", filerescve);
                   7595: 
                   7596:     strcpy(fileresv,"v");
                   7597:     strcat(fileresv,fileres);
                   7598:     if((ficresvij=fopen(fileresv,"w"))==NULL) {
                   7599:       printf("Problem with variance resultfile: %s\n", fileresv);exit(0);
                   7600:       fprintf(ficlog,"Problem with variance resultfile: %s\n", fileresv);exit(0);
                   7601:     }
                   7602:     printf("Computing Variance-covariance of DFLEs: file '%s' \n", fileresv);
                   7603:     fprintf(ficlog,"Computing Variance-covariance of DFLEs: file '%s' \n", fileresv);
                   7604: 
1.145     brouard  7605:     /*for(cptcov=1,k=0;cptcov<=i1;cptcov++){
                   7606:       for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){*/
                   7607:           
                   7608:     for (k=1; k <= (int) pow(2,cptcoveff); k++){
                   7609:        fprintf(ficrest,"\n#****** ");
1.126     brouard  7610:        for(j=1;j<=cptcoveff;j++) 
                   7611:          fprintf(ficrest,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
                   7612:        fprintf(ficrest,"******\n");
                   7613: 
                   7614:        fprintf(ficresstdeij,"\n#****** ");
                   7615:        fprintf(ficrescveij,"\n#****** ");
                   7616:        for(j=1;j<=cptcoveff;j++) {
                   7617:          fprintf(ficresstdeij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
                   7618:          fprintf(ficrescveij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
                   7619:        }
                   7620:        fprintf(ficresstdeij,"******\n");
                   7621:        fprintf(ficrescveij,"******\n");
                   7622: 
                   7623:        fprintf(ficresvij,"\n#****** ");
                   7624:        for(j=1;j<=cptcoveff;j++) 
                   7625:          fprintf(ficresvij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
                   7626:        fprintf(ficresvij,"******\n");
                   7627: 
                   7628:        eij=ma3x(1,nlstate,1,nlstate,(int) bage, (int) fage);
                   7629:        oldm=oldms;savm=savms;
1.127     brouard  7630:        cvevsij(eij, p, nlstate, stepm, (int) bage, (int)fage, oldm, savm, k, estepm, delti, matcov, strstart);  
1.145     brouard  7631:        /*
                   7632:         */
                   7633:        /* goto endfree; */
1.126     brouard  7634:  
                   7635:        vareij=ma3x(1,nlstate,1,nlstate,(int) bage, (int) fage);
                   7636:        pstamp(ficrest);
1.145     brouard  7637: 
                   7638: 
1.128     brouard  7639:        for(vpopbased=0; vpopbased <= popbased; vpopbased++){ /* Done for vpopbased=0 and vpopbased=1 if popbased==1*/
1.145     brouard  7640:          oldm=oldms;savm=savms; /* Segmentation fault */
1.161     brouard  7641:          cptcod= 0; /* To be deleted */
                   7642:          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  7643:          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  7644:          if(vpopbased==1)
                   7645:            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);
                   7646:          else
                   7647:            fprintf(ficrest,"the age specific period (stable) prevalences in each health state \n");
                   7648:          fprintf(ficrest,"# Age e.. (std) ");
                   7649:          for (i=1;i<=nlstate;i++) fprintf(ficrest,"e.%d (std) ",i);
                   7650:          fprintf(ficrest,"\n");
1.126     brouard  7651: 
1.128     brouard  7652:          epj=vector(1,nlstate+1);
                   7653:          for(age=bage; age <=fage ;age++){
                   7654:            prevalim(prlim, nlstate, p, age, oldm, savm,ftolpl,k);
                   7655:            if (vpopbased==1) {
                   7656:              if(mobilav ==0){
                   7657:                for(i=1; i<=nlstate;i++)
                   7658:                  prlim[i][i]=probs[(int)age][i][k];
                   7659:              }else{ /* mobilav */ 
                   7660:                for(i=1; i<=nlstate;i++)
                   7661:                  prlim[i][i]=mobaverage[(int)age][i][k];
                   7662:              }
1.126     brouard  7663:            }
                   7664:        
1.128     brouard  7665:            fprintf(ficrest," %4.0f",age);
                   7666:            for(j=1, epj[nlstate+1]=0.;j <=nlstate;j++){
                   7667:              for(i=1, epj[j]=0.;i <=nlstate;i++) {
                   7668:                epj[j] += prlim[i][i]*eij[i][j][(int)age];
                   7669:                /*  printf("%lf %lf ", prlim[i][i] ,eij[i][j][(int)age]);*/
                   7670:              }
                   7671:              epj[nlstate+1] +=epj[j];
1.126     brouard  7672:            }
                   7673: 
1.128     brouard  7674:            for(i=1, vepp=0.;i <=nlstate;i++)
                   7675:              for(j=1;j <=nlstate;j++)
                   7676:                vepp += vareij[i][j][(int)age];
                   7677:            fprintf(ficrest," %7.3f (%7.3f)", epj[nlstate+1],sqrt(vepp));
                   7678:            for(j=1;j <=nlstate;j++){
                   7679:              fprintf(ficrest," %7.3f (%7.3f)", epj[j],sqrt(vareij[j][j][(int)age]));
                   7680:            }
                   7681:            fprintf(ficrest,"\n");
1.126     brouard  7682:          }
                   7683:        }
                   7684:        free_ma3x(eij,1,nlstate,1,nlstate,(int) bage, (int)fage);
                   7685:        free_ma3x(vareij,1,nlstate,1,nlstate,(int) bage, (int)fage);
                   7686:        free_vector(epj,1,nlstate+1);
1.145     brouard  7687:       /*}*/
1.126     brouard  7688:     }
                   7689:     free_vector(weight,1,n);
1.145     brouard  7690:     free_imatrix(Tvard,1,NCOVMAX,1,2);
1.126     brouard  7691:     free_imatrix(s,1,maxwav+1,1,n);
                   7692:     free_matrix(anint,1,maxwav,1,n); 
                   7693:     free_matrix(mint,1,maxwav,1,n);
                   7694:     free_ivector(cod,1,n);
                   7695:     free_ivector(tab,1,NCOVMAX);
                   7696:     fclose(ficresstdeij);
                   7697:     fclose(ficrescveij);
                   7698:     fclose(ficresvij);
                   7699:     fclose(ficrest);
                   7700:     fclose(ficpar);
                   7701:   
                   7702:     /*------- Variance of period (stable) prevalence------*/   
                   7703: 
                   7704:     strcpy(fileresvpl,"vpl");
                   7705:     strcat(fileresvpl,fileres);
                   7706:     if((ficresvpl=fopen(fileresvpl,"w"))==NULL) {
                   7707:       printf("Problem with variance of period (stable) prevalence  resultfile: %s\n", fileresvpl);
                   7708:       exit(0);
                   7709:     }
                   7710:     printf("Computing Variance-covariance of period (stable) prevalence: file '%s' \n", fileresvpl);
                   7711: 
1.145     brouard  7712:     /*for(cptcov=1,k=0;cptcov<=i1;cptcov++){
                   7713:       for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){*/
                   7714:           
                   7715:     for (k=1; k <= (int) pow(2,cptcoveff); k++){
                   7716:        fprintf(ficresvpl,"\n#****** ");
1.126     brouard  7717:        for(j=1;j<=cptcoveff;j++) 
                   7718:          fprintf(ficresvpl,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
                   7719:        fprintf(ficresvpl,"******\n");
                   7720:       
                   7721:        varpl=matrix(1,nlstate,(int) bage, (int) fage);
                   7722:        oldm=oldms;savm=savms;
                   7723:        varprevlim(fileres, varpl, matcov, p, delti, nlstate, stepm, (int) bage, (int) fage, oldm, savm, prlim, ftolpl,k,strstart);
                   7724:        free_matrix(varpl,1,nlstate,(int) bage, (int)fage);
1.145     brouard  7725:       /*}*/
1.126     brouard  7726:     }
                   7727: 
                   7728:     fclose(ficresvpl);
                   7729: 
                   7730:     /*---------- End : free ----------------*/
                   7731:     if (mobilav!=0) free_ma3x(mobaverage,1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
                   7732:     free_ma3x(probs,1,AGESUP,1,NCOVMAX, 1,NCOVMAX);
                   7733:   }  /* mle==-3 arrives here for freeing */
1.164     brouard  7734:  /* endfree:*/
1.141     brouard  7735:     free_matrix(prlim,1,nlstate,1,nlstate); /*here or after loop ? */
1.126     brouard  7736:     free_matrix(pmmij,1,nlstate+ndeath,1,nlstate+ndeath);
                   7737:     free_matrix(oldms, 1,nlstate+ndeath,1,nlstate+ndeath);
                   7738:     free_matrix(newms, 1,nlstate+ndeath,1,nlstate+ndeath);
                   7739:     free_matrix(savms, 1,nlstate+ndeath,1,nlstate+ndeath);
                   7740:     free_matrix(covar,0,NCOVMAX,1,n);
                   7741:     free_matrix(matcov,1,npar,1,npar);
                   7742:     /*free_vector(delti,1,npar);*/
                   7743:     free_ma3x(delti3,1,nlstate,1, nlstate+ndeath-1,1,ncovmodel); 
                   7744:     free_matrix(agev,1,maxwav,1,imx);
                   7745:     free_ma3x(param,1,nlstate,1, nlstate+ndeath-1,1,ncovmodel);
                   7746: 
1.145     brouard  7747:     free_ivector(ncodemax,1,NCOVMAX);
1.192     brouard  7748:     free_ivector(ncodemaxwundef,1,NCOVMAX);
1.145     brouard  7749:     free_ivector(Tvar,1,NCOVMAX);
                   7750:     free_ivector(Tprod,1,NCOVMAX);
                   7751:     free_ivector(Tvaraff,1,NCOVMAX);
                   7752:     free_ivector(Tage,1,NCOVMAX);
1.126     brouard  7753: 
                   7754:     free_imatrix(nbcode,0,NCOVMAX,0,NCOVMAX);
                   7755:     free_imatrix(codtab,1,100,1,10);
                   7756:   fflush(fichtm);
                   7757:   fflush(ficgp);
                   7758:   
                   7759: 
                   7760:   if((nberr >0) || (nbwarn>0)){
                   7761:     printf("End of Imach with %d errors and/or %d warnings\n",nberr,nbwarn);
                   7762:     fprintf(ficlog,"End of Imach with %d errors and/or warnings %d\n",nberr,nbwarn);
                   7763:   }else{
                   7764:     printf("End of Imach\n");
                   7765:     fprintf(ficlog,"End of Imach\n");
                   7766:   }
                   7767:   printf("See log file on %s\n",filelog);
                   7768:   /*  gettimeofday(&end_time, (struct timezone*)0);*/  /* after time */
1.157     brouard  7769:   /*(void) gettimeofday(&end_time,&tzp);*/
                   7770:   rend_time = time(NULL);  
                   7771:   end_time = *localtime(&rend_time);
                   7772:   /* tml = *localtime(&end_time.tm_sec); */
                   7773:   strcpy(strtend,asctime(&end_time));
1.126     brouard  7774:   printf("Local time at start %s\nLocal time at end   %s",strstart, strtend); 
                   7775:   fprintf(ficlog,"Local time at start %s\nLocal time at end   %s\n",strstart, strtend); 
1.157     brouard  7776:   printf("Total time used %s\n", asc_diff_time(rend_time -rstart_time,tmpout));
1.126     brouard  7777: 
1.157     brouard  7778:   printf("Total time was %.0lf Sec.\n", difftime(rend_time,rstart_time));
                   7779:   fprintf(ficlog,"Total time used %s\n", asc_diff_time(rend_time -rstart_time,tmpout));
                   7780:   fprintf(ficlog,"Total time was %.0lf Sec.\n", difftime(rend_time,rstart_time));
1.126     brouard  7781:   /*  printf("Total time was %d uSec.\n", total_usecs);*/
                   7782: /*   if(fileappend(fichtm,optionfilehtm)){ */
                   7783:   fprintf(fichtm,"<br>Local time at start %s<br>Local time at end   %s<br>\n</body></html>",strstart, strtend);
                   7784:   fclose(fichtm);
                   7785:   fprintf(fichtmcov,"<br>Local time at start %s<br>Local time at end   %s<br>\n</body></html>",strstart, strtend);
                   7786:   fclose(fichtmcov);
                   7787:   fclose(ficgp);
                   7788:   fclose(ficlog);
                   7789:   /*------ End -----------*/
                   7790: 
                   7791: 
                   7792:    printf("Before Current directory %s!\n",pathcd);
1.184     brouard  7793: #ifdef WIN32
                   7794:    if (_chdir(pathcd) != 0)
                   7795:           printf("Can't move to directory %s!\n",path);
                   7796:    if(_getcwd(pathcd,MAXLINE) > 0)
                   7797: #else
1.126     brouard  7798:    if(chdir(pathcd) != 0)
1.184     brouard  7799:           printf("Can't move to directory %s!\n", path);
                   7800:    if (getcwd(pathcd, MAXLINE) > 0)
                   7801: #endif 
1.126     brouard  7802:     printf("Current directory %s!\n",pathcd);
                   7803:   /*strcat(plotcmd,CHARSEPARATOR);*/
                   7804:   sprintf(plotcmd,"gnuplot");
1.157     brouard  7805: #ifdef _WIN32
1.126     brouard  7806:   sprintf(plotcmd,"\"%sgnuplot.exe\"",pathimach);
                   7807: #endif
                   7808:   if(!stat(plotcmd,&info)){
1.158     brouard  7809:     printf("Error or gnuplot program not found: '%s'\n",plotcmd);fflush(stdout);
1.126     brouard  7810:     if(!stat(getenv("GNUPLOTBIN"),&info)){
1.158     brouard  7811:       printf("Error or gnuplot program not found: '%s' Environment GNUPLOTBIN not set.\n",plotcmd);fflush(stdout);
1.126     brouard  7812:     }else
                   7813:       strcpy(pplotcmd,plotcmd);
1.157     brouard  7814: #ifdef __unix
1.126     brouard  7815:     strcpy(plotcmd,GNUPLOTPROGRAM);
                   7816:     if(!stat(plotcmd,&info)){
1.158     brouard  7817:       printf("Error gnuplot program not found: '%s'\n",plotcmd);fflush(stdout);
1.126     brouard  7818:     }else
                   7819:       strcpy(pplotcmd,plotcmd);
                   7820: #endif
                   7821:   }else
                   7822:     strcpy(pplotcmd,plotcmd);
                   7823:   
                   7824:   sprintf(plotcmd,"%s %s",pplotcmd, optionfilegnuplot);
1.158     brouard  7825:   printf("Starting graphs with: '%s'\n",plotcmd);fflush(stdout);
1.126     brouard  7826: 
                   7827:   if((outcmd=system(plotcmd)) != 0){
1.158     brouard  7828:     printf("gnuplot command might not be in your path: '%s', err=%d\n", plotcmd, outcmd);
1.154     brouard  7829:     printf("\n Trying if gnuplot resides on the same directory that IMaCh\n");
1.152     brouard  7830:     sprintf(plotcmd,"%sgnuplot %s", pathimach, optionfilegnuplot);
1.150     brouard  7831:     if((outcmd=system(plotcmd)) != 0)
1.153     brouard  7832:       printf("\n Still a problem with gnuplot command %s, err=%d\n", plotcmd, outcmd);
1.126     brouard  7833:   }
1.158     brouard  7834:   printf(" Successful, please wait...");
1.126     brouard  7835:   while (z[0] != 'q') {
                   7836:     /* chdir(path); */
1.154     brouard  7837:     printf("\nType e to edit results with your browser, g to graph again and q for exit: ");
1.126     brouard  7838:     scanf("%s",z);
                   7839: /*     if (z[0] == 'c') system("./imach"); */
                   7840:     if (z[0] == 'e') {
1.158     brouard  7841: #ifdef __APPLE__
1.152     brouard  7842:       sprintf(pplotcmd, "open %s", optionfilehtm);
1.157     brouard  7843: #elif __linux
                   7844:       sprintf(pplotcmd, "xdg-open %s", optionfilehtm);
1.153     brouard  7845: #else
1.152     brouard  7846:       sprintf(pplotcmd, "%s", optionfilehtm);
1.153     brouard  7847: #endif
                   7848:       printf("Starting browser with: %s",pplotcmd);fflush(stdout);
                   7849:       system(pplotcmd);
1.126     brouard  7850:     }
                   7851:     else if (z[0] == 'g') system(plotcmd);
                   7852:     else if (z[0] == 'q') exit(0);
                   7853:   }
                   7854:   end:
                   7855:   while (z[0] != 'q') {
1.195   ! brouard  7856:     printf("\nType  q for exiting: "); fflush(stdout);
1.126     brouard  7857:     scanf("%s",z);
                   7858:   }
                   7859: }

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