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

1.188   ! brouard     1: /* $Id: imach.c,v 1.187 2015/04/29 09:11:15 brouard Exp $
1.126     brouard     2:   $State: Exp $
1.163     brouard     3:   $Log: imach.c,v $
1.188   ! brouard     4:   Revision 1.187  2015/04/29 09:11:15  brouard
        !             5:   *** empty log message ***
        !             6: 
1.187     brouard     7:   Revision 1.186  2015/04/23 12:01:52  brouard
                      8:   Summary: V1*age is working now, version 0.98q1
                      9: 
                     10:   Some codes had been disabled in order to simplify and Vn*age was
                     11:   working in the optimization phase, ie, giving correct MLE parameters,
                     12:   but, as usual, outputs were not correct and program core dumped.
                     13: 
1.186     brouard    14:   Revision 1.185  2015/03/11 13:26:42  brouard
                     15:   Summary: Inclusion of compile and links command line for Intel Compiler
                     16: 
1.185     brouard    17:   Revision 1.184  2015/03/11 11:52:39  brouard
                     18:   Summary: Back from Windows 8. Intel Compiler
                     19: 
1.184     brouard    20:   Revision 1.183  2015/03/10 20:34:32  brouard
                     21:   Summary: 0.98q0, trying with directest, mnbrak fixed
                     22: 
                     23:   We use directest instead of original Powell test; probably no
                     24:   incidence on the results, but better justifications;
                     25:   We fixed Numerical Recipes mnbrak routine which was wrong and gave
                     26:   wrong results.
                     27: 
1.183     brouard    28:   Revision 1.182  2015/02/12 08:19:57  brouard
                     29:   Summary: Trying to keep directest which seems simpler and more general
                     30:   Author: Nicolas Brouard
                     31: 
1.182     brouard    32:   Revision 1.181  2015/02/11 23:22:24  brouard
                     33:   Summary: Comments on Powell added
                     34: 
                     35:   Author:
                     36: 
1.181     brouard    37:   Revision 1.180  2015/02/11 17:33:45  brouard
                     38:   Summary: Finishing move from main to function (hpijx and prevalence_limit)
                     39: 
1.180     brouard    40:   Revision 1.179  2015/01/04 09:57:06  brouard
                     41:   Summary: back to OS/X
                     42: 
1.179     brouard    43:   Revision 1.178  2015/01/04 09:35:48  brouard
                     44:   *** empty log message ***
                     45: 
1.178     brouard    46:   Revision 1.177  2015/01/03 18:40:56  brouard
                     47:   Summary: Still testing ilc32 on OSX
                     48: 
1.177     brouard    49:   Revision 1.176  2015/01/03 16:45:04  brouard
                     50:   *** empty log message ***
                     51: 
1.176     brouard    52:   Revision 1.175  2015/01/03 16:33:42  brouard
                     53:   *** empty log message ***
                     54: 
1.175     brouard    55:   Revision 1.174  2015/01/03 16:15:49  brouard
                     56:   Summary: Still in cross-compilation
                     57: 
1.174     brouard    58:   Revision 1.173  2015/01/03 12:06:26  brouard
                     59:   Summary: trying to detect cross-compilation
                     60: 
1.173     brouard    61:   Revision 1.172  2014/12/27 12:07:47  brouard
                     62:   Summary: Back from Visual Studio and Intel, options for compiling for Windows XP
                     63: 
1.172     brouard    64:   Revision 1.171  2014/12/23 13:26:59  brouard
                     65:   Summary: Back from Visual C
                     66: 
                     67:   Still problem with utsname.h on Windows
                     68: 
1.171     brouard    69:   Revision 1.170  2014/12/23 11:17:12  brouard
                     70:   Summary: Cleaning some \%% back to %%
                     71: 
                     72:   The escape was mandatory for a specific compiler (which one?), but too many warnings.
                     73: 
1.170     brouard    74:   Revision 1.169  2014/12/22 23:08:31  brouard
                     75:   Summary: 0.98p
                     76: 
                     77:   Outputs some informations on compiler used, OS etc. Testing on different platforms.
                     78: 
1.169     brouard    79:   Revision 1.168  2014/12/22 15:17:42  brouard
1.170     brouard    80:   Summary: update
1.169     brouard    81: 
1.168     brouard    82:   Revision 1.167  2014/12/22 13:50:56  brouard
                     83:   Summary: Testing uname and compiler version and if compiled 32 or 64
                     84: 
                     85:   Testing on Linux 64
                     86: 
1.167     brouard    87:   Revision 1.166  2014/12/22 11:40:47  brouard
                     88:   *** empty log message ***
                     89: 
1.166     brouard    90:   Revision 1.165  2014/12/16 11:20:36  brouard
                     91:   Summary: After compiling on Visual C
                     92: 
                     93:   * imach.c (Module): Merging 1.61 to 1.162
                     94: 
1.165     brouard    95:   Revision 1.164  2014/12/16 10:52:11  brouard
                     96:   Summary: Merging with Visual C after suppressing some warnings for unused variables. Also fixing Saito's bug 0.98Xn
                     97: 
                     98:   * imach.c (Module): Merging 1.61 to 1.162
                     99: 
1.164     brouard   100:   Revision 1.163  2014/12/16 10:30:11  brouard
                    101:   * imach.c (Module): Merging 1.61 to 1.162
                    102: 
1.163     brouard   103:   Revision 1.162  2014/09/25 11:43:39  brouard
                    104:   Summary: temporary backup 0.99!
                    105: 
1.162     brouard   106:   Revision 1.1  2014/09/16 11:06:58  brouard
                    107:   Summary: With some code (wrong) for nlopt
                    108: 
                    109:   Author:
                    110: 
                    111:   Revision 1.161  2014/09/15 20:41:41  brouard
                    112:   Summary: Problem with macro SQR on Intel compiler
                    113: 
1.161     brouard   114:   Revision 1.160  2014/09/02 09:24:05  brouard
                    115:   *** empty log message ***
                    116: 
1.160     brouard   117:   Revision 1.159  2014/09/01 10:34:10  brouard
                    118:   Summary: WIN32
                    119:   Author: Brouard
                    120: 
1.159     brouard   121:   Revision 1.158  2014/08/27 17:11:51  brouard
                    122:   *** empty log message ***
                    123: 
1.158     brouard   124:   Revision 1.157  2014/08/27 16:26:55  brouard
                    125:   Summary: Preparing windows Visual studio version
                    126:   Author: Brouard
                    127: 
                    128:   In order to compile on Visual studio, time.h is now correct and time_t
                    129:   and tm struct should be used. difftime should be used but sometimes I
                    130:   just make the differences in raw time format (time(&now).
                    131:   Trying to suppress #ifdef LINUX
                    132:   Add xdg-open for __linux in order to open default browser.
                    133: 
1.157     brouard   134:   Revision 1.156  2014/08/25 20:10:10  brouard
                    135:   *** empty log message ***
                    136: 
1.156     brouard   137:   Revision 1.155  2014/08/25 18:32:34  brouard
                    138:   Summary: New compile, minor changes
                    139:   Author: Brouard
                    140: 
1.155     brouard   141:   Revision 1.154  2014/06/20 17:32:08  brouard
                    142:   Summary: Outputs now all graphs of convergence to period prevalence
                    143: 
1.154     brouard   144:   Revision 1.153  2014/06/20 16:45:46  brouard
                    145:   Summary: If 3 live state, convergence to period prevalence on same graph
                    146:   Author: Brouard
                    147: 
1.153     brouard   148:   Revision 1.152  2014/06/18 17:54:09  brouard
                    149:   Summary: open browser, use gnuplot on same dir than imach if not found in the path
                    150: 
1.152     brouard   151:   Revision 1.151  2014/06/18 16:43:30  brouard
                    152:   *** empty log message ***
                    153: 
1.151     brouard   154:   Revision 1.150  2014/06/18 16:42:35  brouard
                    155:   Summary: If gnuplot is not in the path try on same directory than imach binary (OSX)
                    156:   Author: brouard
                    157: 
1.150     brouard   158:   Revision 1.149  2014/06/18 15:51:14  brouard
                    159:   Summary: Some fixes in parameter files errors
                    160:   Author: Nicolas Brouard
                    161: 
1.149     brouard   162:   Revision 1.148  2014/06/17 17:38:48  brouard
                    163:   Summary: Nothing new
                    164:   Author: Brouard
                    165: 
                    166:   Just a new packaging for OS/X version 0.98nS
                    167: 
1.148     brouard   168:   Revision 1.147  2014/06/16 10:33:11  brouard
                    169:   *** empty log message ***
                    170: 
1.147     brouard   171:   Revision 1.146  2014/06/16 10:20:28  brouard
                    172:   Summary: Merge
                    173:   Author: Brouard
                    174: 
                    175:   Merge, before building revised version.
                    176: 
1.146     brouard   177:   Revision 1.145  2014/06/10 21:23:15  brouard
                    178:   Summary: Debugging with valgrind
                    179:   Author: Nicolas Brouard
                    180: 
                    181:   Lot of changes in order to output the results with some covariates
                    182:   After the Edimburgh REVES conference 2014, it seems mandatory to
                    183:   improve the code.
                    184:   No more memory valgrind error but a lot has to be done in order to
                    185:   continue the work of splitting the code into subroutines.
                    186:   Also, decodemodel has been improved. Tricode is still not
                    187:   optimal. nbcode should be improved. Documentation has been added in
                    188:   the source code.
                    189: 
1.144     brouard   190:   Revision 1.143  2014/01/26 09:45:38  brouard
                    191:   Summary: Version 0.98nR (to be improved, but gives same optimization results as 0.98k. Nice, promising
                    192: 
                    193:   * imach.c (Module): Trying to merge old staffs together while being at Tokyo. Not tested...
                    194:   (Module): Version 0.98nR Running ok, but output format still only works for three covariates.
                    195: 
1.143     brouard   196:   Revision 1.142  2014/01/26 03:57:36  brouard
                    197:   Summary: gnuplot changed plot w l 1 has to be changed to plot w l lt 2
                    198: 
                    199:   * imach.c (Module): Trying to merge old staffs together while being at Tokyo. Not tested...
                    200: 
1.142     brouard   201:   Revision 1.141  2014/01/26 02:42:01  brouard
                    202:   * imach.c (Module): Trying to merge old staffs together while being at Tokyo. Not tested...
                    203: 
1.141     brouard   204:   Revision 1.140  2011/09/02 10:37:54  brouard
                    205:   Summary: times.h is ok with mingw32 now.
                    206: 
1.140     brouard   207:   Revision 1.139  2010/06/14 07:50:17  brouard
                    208:   After the theft of my laptop, I probably lost some lines of codes which were not uploaded to the CVS tree.
                    209:   I remember having already fixed agemin agemax which are pointers now but not cvs saved.
                    210: 
1.139     brouard   211:   Revision 1.138  2010/04/30 18:19:40  brouard
                    212:   *** empty log message ***
                    213: 
1.138     brouard   214:   Revision 1.137  2010/04/29 18:11:38  brouard
                    215:   (Module): Checking covariates for more complex models
                    216:   than V1+V2. A lot of change to be done. Unstable.
                    217: 
1.137     brouard   218:   Revision 1.136  2010/04/26 20:30:53  brouard
                    219:   (Module): merging some libgsl code. Fixing computation
                    220:   of likelione (using inter/intrapolation if mle = 0) in order to
                    221:   get same likelihood as if mle=1.
                    222:   Some cleaning of code and comments added.
                    223: 
1.136     brouard   224:   Revision 1.135  2009/10/29 15:33:14  brouard
                    225:   (Module): Now imach stops if date of birth, at least year of birth, is not given. Some cleaning of the code.
                    226: 
1.135     brouard   227:   Revision 1.134  2009/10/29 13:18:53  brouard
                    228:   (Module): Now imach stops if date of birth, at least year of birth, is not given. Some cleaning of the code.
                    229: 
1.134     brouard   230:   Revision 1.133  2009/07/06 10:21:25  brouard
                    231:   just nforces
                    232: 
1.133     brouard   233:   Revision 1.132  2009/07/06 08:22:05  brouard
                    234:   Many tings
                    235: 
1.132     brouard   236:   Revision 1.131  2009/06/20 16:22:47  brouard
                    237:   Some dimensions resccaled
                    238: 
1.131     brouard   239:   Revision 1.130  2009/05/26 06:44:34  brouard
                    240:   (Module): Max Covariate is now set to 20 instead of 8. A
                    241:   lot of cleaning with variables initialized to 0. Trying to make
                    242:   V2+V3*age+V1+V4 strb=V3*age+V1+V4 working better.
                    243: 
1.130     brouard   244:   Revision 1.129  2007/08/31 13:49:27  lievre
                    245:   Modification of the way of exiting when the covariate is not binary in order to see on the window the error message before exiting
                    246: 
1.129     lievre    247:   Revision 1.128  2006/06/30 13:02:05  brouard
                    248:   (Module): Clarifications on computing e.j
                    249: 
1.128     brouard   250:   Revision 1.127  2006/04/28 18:11:50  brouard
                    251:   (Module): Yes the sum of survivors was wrong since
                    252:   imach-114 because nhstepm was no more computed in the age
                    253:   loop. Now we define nhstepma in the age loop.
                    254:   (Module): In order to speed up (in case of numerous covariates) we
                    255:   compute health expectancies (without variances) in a first step
                    256:   and then all the health expectancies with variances or standard
                    257:   deviation (needs data from the Hessian matrices) which slows the
                    258:   computation.
                    259:   In the future we should be able to stop the program is only health
                    260:   expectancies and graph are needed without standard deviations.
                    261: 
1.127     brouard   262:   Revision 1.126  2006/04/28 17:23:28  brouard
                    263:   (Module): Yes the sum of survivors was wrong since
                    264:   imach-114 because nhstepm was no more computed in the age
                    265:   loop. Now we define nhstepma in the age loop.
                    266:   Version 0.98h
                    267: 
1.126     brouard   268:   Revision 1.125  2006/04/04 15:20:31  lievre
                    269:   Errors in calculation of health expectancies. Age was not initialized.
                    270:   Forecasting file added.
                    271: 
                    272:   Revision 1.124  2006/03/22 17:13:53  lievre
                    273:   Parameters are printed with %lf instead of %f (more numbers after the comma).
                    274:   The log-likelihood is printed in the log file
                    275: 
                    276:   Revision 1.123  2006/03/20 10:52:43  brouard
                    277:   * imach.c (Module): <title> changed, corresponds to .htm file
                    278:   name. <head> headers where missing.
                    279: 
                    280:   * imach.c (Module): Weights can have a decimal point as for
                    281:   English (a comma might work with a correct LC_NUMERIC environment,
                    282:   otherwise the weight is truncated).
                    283:   Modification of warning when the covariates values are not 0 or
                    284:   1.
                    285:   Version 0.98g
                    286: 
                    287:   Revision 1.122  2006/03/20 09:45:41  brouard
                    288:   (Module): Weights can have a decimal point as for
                    289:   English (a comma might work with a correct LC_NUMERIC environment,
                    290:   otherwise the weight is truncated).
                    291:   Modification of warning when the covariates values are not 0 or
                    292:   1.
                    293:   Version 0.98g
                    294: 
                    295:   Revision 1.121  2006/03/16 17:45:01  lievre
                    296:   * imach.c (Module): Comments concerning covariates added
                    297: 
                    298:   * imach.c (Module): refinements in the computation of lli if
                    299:   status=-2 in order to have more reliable computation if stepm is
                    300:   not 1 month. Version 0.98f
                    301: 
                    302:   Revision 1.120  2006/03/16 15:10:38  lievre
                    303:   (Module): refinements in the computation of lli if
                    304:   status=-2 in order to have more reliable computation if stepm is
                    305:   not 1 month. Version 0.98f
                    306: 
                    307:   Revision 1.119  2006/03/15 17:42:26  brouard
                    308:   (Module): Bug if status = -2, the loglikelihood was
                    309:   computed as likelihood omitting the logarithm. Version O.98e
                    310: 
                    311:   Revision 1.118  2006/03/14 18:20:07  brouard
                    312:   (Module): varevsij Comments added explaining the second
                    313:   table of variances if popbased=1 .
                    314:   (Module): Covariances of eij, ekl added, graphs fixed, new html link.
                    315:   (Module): Function pstamp added
                    316:   (Module): Version 0.98d
                    317: 
                    318:   Revision 1.117  2006/03/14 17:16:22  brouard
                    319:   (Module): varevsij Comments added explaining the second
                    320:   table of variances if popbased=1 .
                    321:   (Module): Covariances of eij, ekl added, graphs fixed, new html link.
                    322:   (Module): Function pstamp added
                    323:   (Module): Version 0.98d
                    324: 
                    325:   Revision 1.116  2006/03/06 10:29:27  brouard
                    326:   (Module): Variance-covariance wrong links and
                    327:   varian-covariance of ej. is needed (Saito).
                    328: 
                    329:   Revision 1.115  2006/02/27 12:17:45  brouard
                    330:   (Module): One freematrix added in mlikeli! 0.98c
                    331: 
                    332:   Revision 1.114  2006/02/26 12:57:58  brouard
                    333:   (Module): Some improvements in processing parameter
                    334:   filename with strsep.
                    335: 
                    336:   Revision 1.113  2006/02/24 14:20:24  brouard
                    337:   (Module): Memory leaks checks with valgrind and:
                    338:   datafile was not closed, some imatrix were not freed and on matrix
                    339:   allocation too.
                    340: 
                    341:   Revision 1.112  2006/01/30 09:55:26  brouard
                    342:   (Module): Back to gnuplot.exe instead of wgnuplot.exe
                    343: 
                    344:   Revision 1.111  2006/01/25 20:38:18  brouard
                    345:   (Module): Lots of cleaning and bugs added (Gompertz)
                    346:   (Module): Comments can be added in data file. Missing date values
                    347:   can be a simple dot '.'.
                    348: 
                    349:   Revision 1.110  2006/01/25 00:51:50  brouard
                    350:   (Module): Lots of cleaning and bugs added (Gompertz)
                    351: 
                    352:   Revision 1.109  2006/01/24 19:37:15  brouard
                    353:   (Module): Comments (lines starting with a #) are allowed in data.
                    354: 
                    355:   Revision 1.108  2006/01/19 18:05:42  lievre
                    356:   Gnuplot problem appeared...
                    357:   To be fixed
                    358: 
                    359:   Revision 1.107  2006/01/19 16:20:37  brouard
                    360:   Test existence of gnuplot in imach path
                    361: 
                    362:   Revision 1.106  2006/01/19 13:24:36  brouard
                    363:   Some cleaning and links added in html output
                    364: 
                    365:   Revision 1.105  2006/01/05 20:23:19  lievre
                    366:   *** empty log message ***
                    367: 
                    368:   Revision 1.104  2005/09/30 16:11:43  lievre
                    369:   (Module): sump fixed, loop imx fixed, and simplifications.
                    370:   (Module): If the status is missing at the last wave but we know
                    371:   that the person is alive, then we can code his/her status as -2
                    372:   (instead of missing=-1 in earlier versions) and his/her
                    373:   contributions to the likelihood is 1 - Prob of dying from last
                    374:   health status (= 1-p13= p11+p12 in the easiest case of somebody in
                    375:   the healthy state at last known wave). Version is 0.98
                    376: 
                    377:   Revision 1.103  2005/09/30 15:54:49  lievre
                    378:   (Module): sump fixed, loop imx fixed, and simplifications.
                    379: 
                    380:   Revision 1.102  2004/09/15 17:31:30  brouard
                    381:   Add the possibility to read data file including tab characters.
                    382: 
                    383:   Revision 1.101  2004/09/15 10:38:38  brouard
                    384:   Fix on curr_time
                    385: 
                    386:   Revision 1.100  2004/07/12 18:29:06  brouard
                    387:   Add version for Mac OS X. Just define UNIX in Makefile
                    388: 
                    389:   Revision 1.99  2004/06/05 08:57:40  brouard
                    390:   *** empty log message ***
                    391: 
                    392:   Revision 1.98  2004/05/16 15:05:56  brouard
                    393:   New version 0.97 . First attempt to estimate force of mortality
                    394:   directly from the data i.e. without the need of knowing the health
                    395:   state at each age, but using a Gompertz model: log u =a + b*age .
                    396:   This is the basic analysis of mortality and should be done before any
                    397:   other analysis, in order to test if the mortality estimated from the
                    398:   cross-longitudinal survey is different from the mortality estimated
                    399:   from other sources like vital statistic data.
                    400: 
                    401:   The same imach parameter file can be used but the option for mle should be -3.
                    402: 
1.133     brouard   403:   Agnès, who wrote this part of the code, tried to keep most of the
1.126     brouard   404:   former routines in order to include the new code within the former code.
                    405: 
                    406:   The output is very simple: only an estimate of the intercept and of
                    407:   the slope with 95% confident intervals.
                    408: 
                    409:   Current limitations:
                    410:   A) Even if you enter covariates, i.e. with the
                    411:   model= V1+V2 equation for example, the programm does only estimate a unique global model without covariates.
                    412:   B) There is no computation of Life Expectancy nor Life Table.
                    413: 
                    414:   Revision 1.97  2004/02/20 13:25:42  lievre
                    415:   Version 0.96d. Population forecasting command line is (temporarily)
                    416:   suppressed.
                    417: 
                    418:   Revision 1.96  2003/07/15 15:38:55  brouard
                    419:   * imach.c (Repository): Errors in subdirf, 2, 3 while printing tmpout is
                    420:   rewritten within the same printf. Workaround: many printfs.
                    421: 
                    422:   Revision 1.95  2003/07/08 07:54:34  brouard
                    423:   * imach.c (Repository):
                    424:   (Repository): Using imachwizard code to output a more meaningful covariance
                    425:   matrix (cov(a12,c31) instead of numbers.
                    426: 
                    427:   Revision 1.94  2003/06/27 13:00:02  brouard
                    428:   Just cleaning
                    429: 
                    430:   Revision 1.93  2003/06/25 16:33:55  brouard
                    431:   (Module): On windows (cygwin) function asctime_r doesn't
                    432:   exist so I changed back to asctime which exists.
                    433:   (Module): Version 0.96b
                    434: 
                    435:   Revision 1.92  2003/06/25 16:30:45  brouard
                    436:   (Module): On windows (cygwin) function asctime_r doesn't
                    437:   exist so I changed back to asctime which exists.
                    438: 
                    439:   Revision 1.91  2003/06/25 15:30:29  brouard
                    440:   * imach.c (Repository): Duplicated warning errors corrected.
                    441:   (Repository): Elapsed time after each iteration is now output. It
                    442:   helps to forecast when convergence will be reached. Elapsed time
                    443:   is stamped in powell.  We created a new html file for the graphs
                    444:   concerning matrix of covariance. It has extension -cov.htm.
                    445: 
                    446:   Revision 1.90  2003/06/24 12:34:15  brouard
                    447:   (Module): Some bugs corrected for windows. Also, when
                    448:   mle=-1 a template is output in file "or"mypar.txt with the design
                    449:   of the covariance matrix to be input.
                    450: 
                    451:   Revision 1.89  2003/06/24 12:30:52  brouard
                    452:   (Module): Some bugs corrected for windows. Also, when
                    453:   mle=-1 a template is output in file "or"mypar.txt with the design
                    454:   of the covariance matrix to be input.
                    455: 
                    456:   Revision 1.88  2003/06/23 17:54:56  brouard
                    457:   * 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.
                    458: 
                    459:   Revision 1.87  2003/06/18 12:26:01  brouard
                    460:   Version 0.96
                    461: 
                    462:   Revision 1.86  2003/06/17 20:04:08  brouard
                    463:   (Module): Change position of html and gnuplot routines and added
                    464:   routine fileappend.
                    465: 
                    466:   Revision 1.85  2003/06/17 13:12:43  brouard
                    467:   * imach.c (Repository): Check when date of death was earlier that
                    468:   current date of interview. It may happen when the death was just
                    469:   prior to the death. In this case, dh was negative and likelihood
                    470:   was wrong (infinity). We still send an "Error" but patch by
                    471:   assuming that the date of death was just one stepm after the
                    472:   interview.
                    473:   (Repository): Because some people have very long ID (first column)
                    474:   we changed int to long in num[] and we added a new lvector for
                    475:   memory allocation. But we also truncated to 8 characters (left
                    476:   truncation)
                    477:   (Repository): No more line truncation errors.
                    478: 
                    479:   Revision 1.84  2003/06/13 21:44:43  brouard
                    480:   * imach.c (Repository): Replace "freqsummary" at a correct
                    481:   place. It differs from routine "prevalence" which may be called
                    482:   many times. Probs is memory consuming and must be used with
                    483:   parcimony.
                    484:   Version 0.95a3 (should output exactly the same maximization than 0.8a2)
                    485: 
                    486:   Revision 1.83  2003/06/10 13:39:11  lievre
                    487:   *** empty log message ***
                    488: 
                    489:   Revision 1.82  2003/06/05 15:57:20  brouard
                    490:   Add log in  imach.c and  fullversion number is now printed.
                    491: 
                    492: */
                    493: /*
                    494:    Interpolated Markov Chain
                    495: 
                    496:   Short summary of the programme:
                    497:   
                    498:   This program computes Healthy Life Expectancies from
                    499:   cross-longitudinal data. Cross-longitudinal data consist in: -1- a
                    500:   first survey ("cross") where individuals from different ages are
                    501:   interviewed on their health status or degree of disability (in the
                    502:   case of a health survey which is our main interest) -2- at least a
                    503:   second wave of interviews ("longitudinal") which measure each change
                    504:   (if any) in individual health status.  Health expectancies are
                    505:   computed from the time spent in each health state according to a
                    506:   model. More health states you consider, more time is necessary to reach the
                    507:   Maximum Likelihood of the parameters involved in the model.  The
                    508:   simplest model is the multinomial logistic model where pij is the
                    509:   probability to be observed in state j at the second wave
                    510:   conditional to be observed in state i at the first wave. Therefore
                    511:   the model is: log(pij/pii)= aij + bij*age+ cij*sex + etc , where
                    512:   'age' is age and 'sex' is a covariate. If you want to have a more
                    513:   complex model than "constant and age", you should modify the program
                    514:   where the markup *Covariates have to be included here again* invites
                    515:   you to do it.  More covariates you add, slower the
                    516:   convergence.
                    517: 
                    518:   The advantage of this computer programme, compared to a simple
                    519:   multinomial logistic model, is clear when the delay between waves is not
                    520:   identical for each individual. Also, if a individual missed an
                    521:   intermediate interview, the information is lost, but taken into
                    522:   account using an interpolation or extrapolation.  
                    523: 
                    524:   hPijx is the probability to be observed in state i at age x+h
                    525:   conditional to the observed state i at age x. The delay 'h' can be
                    526:   split into an exact number (nh*stepm) of unobserved intermediate
                    527:   states. This elementary transition (by month, quarter,
                    528:   semester or year) is modelled as a multinomial logistic.  The hPx
                    529:   matrix is simply the matrix product of nh*stepm elementary matrices
                    530:   and the contribution of each individual to the likelihood is simply
                    531:   hPijx.
                    532: 
                    533:   Also this programme outputs the covariance matrix of the parameters but also
                    534:   of the life expectancies. It also computes the period (stable) prevalence. 
                    535:   
1.133     brouard   536:   Authors: Nicolas Brouard (brouard@ined.fr) and Agnès Lièvre (lievre@ined.fr).
                    537:            Institut national d'études démographiques, Paris.
1.126     brouard   538:   This software have been partly granted by Euro-REVES, a concerted action
                    539:   from the European Union.
                    540:   It is copyrighted identically to a GNU software product, ie programme and
                    541:   software can be distributed freely for non commercial use. Latest version
                    542:   can be accessed at http://euroreves.ined.fr/imach .
                    543: 
                    544:   Help to debug: LD_PRELOAD=/usr/local/lib/libnjamd.so ./imach foo.imach
                    545:   or better on gdb : set env LD_PRELOAD=/usr/local/lib/libnjamd.so
                    546:   
                    547:   **********************************************************************/
                    548: /*
                    549:   main
                    550:   read parameterfile
                    551:   read datafile
                    552:   concatwav
                    553:   freqsummary
                    554:   if (mle >= 1)
                    555:     mlikeli
                    556:   print results files
                    557:   if mle==1 
                    558:      computes hessian
                    559:   read end of parameter file: agemin, agemax, bage, fage, estepm
                    560:       begin-prev-date,...
                    561:   open gnuplot file
                    562:   open html file
1.145     brouard   563:   period (stable) prevalence      | pl_nom    1-1 2-2 etc by covariate
                    564:    for age prevalim()             | #****** V1=0  V2=1  V3=1  V4=0 ******
                    565:                                   | 65 1 0 2 1 3 1 4 0  0.96326 0.03674
                    566:     freexexit2 possible for memory heap.
                    567: 
                    568:   h Pij x                         | pij_nom  ficrestpij
                    569:    # Cov Agex agex+h hpijx with i,j= 1-1 1-2     1-3     2-1     2-2     2-3
                    570:        1  85   85    1.00000             0.00000 0.00000 0.00000 1.00000 0.00000
                    571:        1  85   86    0.68299             0.22291 0.09410 0.71093 0.00000 0.28907
                    572: 
                    573:        1  65   99    0.00364             0.00322 0.99314 0.00350 0.00310 0.99340
                    574:        1  65  100    0.00214             0.00204 0.99581 0.00206 0.00196 0.99597
                    575:   variance of p one-step probabilities varprob  | prob_nom   ficresprob #One-step probabilities and stand. devi in ()
                    576:    Standard deviation of one-step probabilities | probcor_nom   ficresprobcor #One-step probabilities and correlation matrix
                    577:    Matrix of variance covariance of one-step probabilities |  probcov_nom ficresprobcov #One-step probabilities and covariance matrix
                    578: 
1.126     brouard   579:   forecasting if prevfcast==1 prevforecast call prevalence()
                    580:   health expectancies
                    581:   Variance-covariance of DFLE
                    582:   prevalence()
                    583:    movingaverage()
                    584:   varevsij() 
                    585:   if popbased==1 varevsij(,popbased)
                    586:   total life expectancies
                    587:   Variance of period (stable) prevalence
                    588:  end
                    589: */
                    590: 
1.187     brouard   591: /* #define DEBUG */
                    592: /* #define DEBUGBRENT */
1.165     brouard   593: #define POWELL /* Instead of NLOPT */
1.186     brouard   594: /* #define POWELLORIGINAL /\* Don't use Directest to decide new direction but original Powell test *\/ */
                    595: /* #define MNBRAKORIGINAL /\* Don't use mnbrak fix *\/ */
1.126     brouard   596: 
                    597: #include <math.h>
                    598: #include <stdio.h>
                    599: #include <stdlib.h>
                    600: #include <string.h>
1.159     brouard   601: 
                    602: #ifdef _WIN32
                    603: #include <io.h>
1.172     brouard   604: #include <windows.h>
                    605: #include <tchar.h>
1.159     brouard   606: #else
1.126     brouard   607: #include <unistd.h>
1.159     brouard   608: #endif
1.126     brouard   609: 
                    610: #include <limits.h>
                    611: #include <sys/types.h>
1.171     brouard   612: 
                    613: #if defined(__GNUC__)
                    614: #include <sys/utsname.h> /* Doesn't work on Windows */
                    615: #endif
                    616: 
1.126     brouard   617: #include <sys/stat.h>
                    618: #include <errno.h>
1.159     brouard   619: /* extern int errno; */
1.126     brouard   620: 
1.157     brouard   621: /* #ifdef LINUX */
                    622: /* #include <time.h> */
                    623: /* #include "timeval.h" */
                    624: /* #else */
                    625: /* #include <sys/time.h> */
                    626: /* #endif */
                    627: 
1.126     brouard   628: #include <time.h>
                    629: 
1.136     brouard   630: #ifdef GSL
                    631: #include <gsl/gsl_errno.h>
                    632: #include <gsl/gsl_multimin.h>
                    633: #endif
                    634: 
1.167     brouard   635: 
1.162     brouard   636: #ifdef NLOPT
                    637: #include <nlopt.h>
                    638: typedef struct {
                    639:   double (* function)(double [] );
                    640: } myfunc_data ;
                    641: #endif
                    642: 
1.126     brouard   643: /* #include <libintl.h> */
                    644: /* #define _(String) gettext (String) */
                    645: 
1.141     brouard   646: #define MAXLINE 1024 /* Was 256. Overflow with 312 with 2 states and 4 covariates. Should be ok */
1.126     brouard   647: 
                    648: #define GNUPLOTPROGRAM "gnuplot"
                    649: /*#define GNUPLOTPROGRAM "..\\gp37mgw\\wgnuplot"*/
                    650: #define FILENAMELENGTH 132
                    651: 
                    652: #define        GLOCK_ERROR_NOPATH              -1      /* empty path */
                    653: #define        GLOCK_ERROR_GETCWD              -2      /* cannot get cwd */
                    654: 
1.144     brouard   655: #define MAXPARM 128 /**< Maximum number of parameters for the optimization */
                    656: #define NPARMAX 64 /**< (nlstate+ndeath-1)*nlstate*ncovmodel */
1.126     brouard   657: 
                    658: #define NINTERVMAX 8
1.144     brouard   659: #define NLSTATEMAX 8 /**< Maximum number of live states (for func) */
                    660: #define NDEATHMAX 8 /**< Maximum number of dead states (for func) */
                    661: #define NCOVMAX 20 /**< Maximum number of covariates, including generated covariates V1*V2 */
1.145     brouard   662: #define codtabm(h,k)  1 & (h-1) >> (k-1) ;
1.126     brouard   663: #define MAXN 20000
1.144     brouard   664: #define YEARM 12. /**< Number of months per year */
1.126     brouard   665: #define AGESUP 130
                    666: #define AGEBASE 40
1.164     brouard   667: #define AGEGOMP 10 /**< Minimal age for Gompertz adjustment */
1.157     brouard   668: #ifdef _WIN32
                    669: #define DIRSEPARATOR '\\'
                    670: #define CHARSEPARATOR "\\"
                    671: #define ODIRSEPARATOR '/'
                    672: #else
1.126     brouard   673: #define DIRSEPARATOR '/'
                    674: #define CHARSEPARATOR "/"
                    675: #define ODIRSEPARATOR '\\'
                    676: #endif
                    677: 
1.188   ! brouard   678: /* $Id: imach.c,v 1.187 2015/04/29 09:11:15 brouard Exp $ */
1.126     brouard   679: /* $State: Exp $ */
                    680: 
1.186     brouard   681: char version[]="Imach version 0.98q1, April 2015,INED-EUROREVES-Institut de longevite-Japan Society for the Promotion of Science (Grant-in-Aid for Scientific Research 25293121), Intel Software 2015";
1.188   ! brouard   682: char fullversion[]="$Revision: 1.187 $ $Date: 2015/04/29 09:11:15 $"; 
1.126     brouard   683: char strstart[80];
                    684: char optionfilext[10], optionfilefiname[FILENAMELENGTH];
1.130     brouard   685: int erreur=0, nberr=0, nbwarn=0; /* Error number, number of errors number of warnings  */
1.187     brouard   686: int nagesqr=0, nforce=0; /* nagesqr=1 if model is including age*age, number of forces */
1.145     brouard   687: /* Number of covariates model=V2+V1+ V3*age+V2*V4 */
                    688: int cptcovn=0; /**< cptcovn number of covariates added in the model (excepting constant and age and age*product) */
                    689: int cptcovt=0; /**< cptcovt number of covariates added in the model (excepting constant and age) */
                    690: int cptcovs=0; /**< cptcovs number of simple covariates V2+V1 =2 */
                    691: int cptcovage=0; /**< Number of covariates with age: V3*age only =1 */
                    692: int cptcovprodnoage=0; /**< Number of covariate products without age */   
                    693: int cptcoveff=0; /* Total number of covariates to vary for printing results */
                    694: int cptcov=0; /* Working variable */
1.126     brouard   695: int npar=NPARMAX;
                    696: int nlstate=2; /* Number of live states */
                    697: int ndeath=1; /* Number of dead states */
1.130     brouard   698: int ncovmodel=0, ncovcol=0;     /* Total number of covariables including constant a12*1 +b12*x ncovmodel=2 */
1.126     brouard   699: int popbased=0;
                    700: 
                    701: int *wav; /* Number of waves for this individuual 0 is possible */
1.130     brouard   702: int maxwav=0; /* Maxim number of waves */
                    703: int jmin=0, jmax=0; /* min, max spacing between 2 waves */
                    704: int ijmin=0, ijmax=0; /* Individuals having jmin and jmax */ 
                    705: int gipmx=0, gsw=0; /* Global variables on the number of contributions 
1.126     brouard   706:                   to the likelihood and the sum of weights (done by funcone)*/
1.130     brouard   707: int mle=1, weightopt=0;
1.126     brouard   708: int **mw; /* mw[mi][i] is number of the mi wave for this individual */
                    709: int **dh; /* dh[mi][i] is number of steps between mi,mi+1 for this individual */
                    710: int **bh; /* bh[mi][i] is the bias (+ or -) for this individual if the delay between
                    711:           * wave mi and wave mi+1 is not an exact multiple of stepm. */
1.162     brouard   712: int countcallfunc=0;  /* Count the number of calls to func */
1.130     brouard   713: double jmean=1; /* Mean space between 2 waves */
1.145     brouard   714: double **matprod2(); /* test */
1.126     brouard   715: double **oldm, **newm, **savm; /* Working pointers to matrices */
                    716: double **oldms, **newms, **savms; /* Fixed working pointers to matrices */
1.136     brouard   717: /*FILE *fic ; */ /* Used in readdata only */
                    718: FILE *ficpar, *ficparo,*ficres, *ficresp, *ficrespl, *ficrespij, *ficrest,*ficresf,*ficrespop;
1.126     brouard   719: FILE *ficlog, *ficrespow;
1.130     brouard   720: int globpr=0; /* Global variable for printing or not */
1.126     brouard   721: double fretone; /* Only one call to likelihood */
1.130     brouard   722: long ipmx=0; /* Number of contributions */
1.126     brouard   723: double sw; /* Sum of weights */
                    724: char filerespow[FILENAMELENGTH];
                    725: char fileresilk[FILENAMELENGTH]; /* File of individual contributions to the likelihood */
                    726: FILE *ficresilk;
                    727: FILE *ficgp,*ficresprob,*ficpop, *ficresprobcov, *ficresprobcor;
                    728: FILE *ficresprobmorprev;
                    729: FILE *fichtm, *fichtmcov; /* Html File */
                    730: FILE *ficreseij;
                    731: char filerese[FILENAMELENGTH];
                    732: FILE *ficresstdeij;
                    733: char fileresstde[FILENAMELENGTH];
                    734: FILE *ficrescveij;
                    735: char filerescve[FILENAMELENGTH];
                    736: FILE  *ficresvij;
                    737: char fileresv[FILENAMELENGTH];
                    738: FILE  *ficresvpl;
                    739: char fileresvpl[FILENAMELENGTH];
                    740: char title[MAXLINE];
                    741: char optionfile[FILENAMELENGTH], datafile[FILENAMELENGTH],  filerespl[FILENAMELENGTH];
                    742: char plotcmd[FILENAMELENGTH], pplotcmd[FILENAMELENGTH];
                    743: char tmpout[FILENAMELENGTH],  tmpout2[FILENAMELENGTH]; 
                    744: char command[FILENAMELENGTH];
                    745: int  outcmd=0;
                    746: 
                    747: char fileres[FILENAMELENGTH], filerespij[FILENAMELENGTH], filereso[FILENAMELENGTH], rfileres[FILENAMELENGTH];
                    748: 
                    749: char filelog[FILENAMELENGTH]; /* Log file */
                    750: char filerest[FILENAMELENGTH];
                    751: char fileregp[FILENAMELENGTH];
                    752: char popfile[FILENAMELENGTH];
                    753: 
                    754: char optionfilegnuplot[FILENAMELENGTH], optionfilehtm[FILENAMELENGTH], optionfilehtmcov[FILENAMELENGTH] ;
                    755: 
1.157     brouard   756: /* struct timeval start_time, end_time, curr_time, last_time, forecast_time; */
                    757: /* struct timezone tzp; */
                    758: /* extern int gettimeofday(); */
                    759: struct tm tml, *gmtime(), *localtime();
                    760: 
                    761: extern time_t time();
                    762: 
                    763: struct tm start_time, end_time, curr_time, last_time, forecast_time;
                    764: time_t  rstart_time, rend_time, rcurr_time, rlast_time, rforecast_time; /* raw time */
                    765: struct tm tm;
                    766: 
1.126     brouard   767: char strcurr[80], strfor[80];
                    768: 
                    769: char *endptr;
                    770: long lval;
                    771: double dval;
                    772: 
                    773: #define NR_END 1
                    774: #define FREE_ARG char*
                    775: #define FTOL 1.0e-10
                    776: 
                    777: #define NRANSI 
                    778: #define ITMAX 200 
                    779: 
                    780: #define TOL 2.0e-4 
                    781: 
                    782: #define CGOLD 0.3819660 
                    783: #define ZEPS 1.0e-10 
                    784: #define SHFT(a,b,c,d) (a)=(b);(b)=(c);(c)=(d); 
                    785: 
                    786: #define GOLD 1.618034 
                    787: #define GLIMIT 100.0 
                    788: #define TINY 1.0e-20 
                    789: 
                    790: static double maxarg1,maxarg2;
                    791: #define FMAX(a,b) (maxarg1=(a),maxarg2=(b),(maxarg1)>(maxarg2)? (maxarg1):(maxarg2))
                    792: #define FMIN(a,b) (maxarg1=(a),maxarg2=(b),(maxarg1)<(maxarg2)? (maxarg1):(maxarg2))
                    793:   
                    794: #define SIGN(a,b) ((b)>0.0 ? fabs(a) : -fabs(a))
                    795: #define rint(a) floor(a+0.5)
1.166     brouard   796: /* http://www.thphys.uni-heidelberg.de/~robbers/cmbeasy/doc/html/myutils_8h-source.html */
1.183     brouard   797: #define mytinydouble 1.0e-16
1.166     brouard   798: /* #define DEQUAL(a,b) (fabs((a)-(b))<mytinydouble) */
                    799: /* http://www.thphys.uni-heidelberg.de/~robbers/cmbeasy/doc/html/mynrutils_8h-source.html */
                    800: /* static double dsqrarg; */
                    801: /* #define DSQR(a) (DEQUAL((dsqrarg=(a)),0.0) ? 0.0 : dsqrarg*dsqrarg) */
1.126     brouard   802: static double sqrarg;
                    803: #define SQR(a) ((sqrarg=(a)) == 0.0 ? 0.0 :sqrarg*sqrarg)
                    804: #define SWAP(a,b) {temp=(a);(a)=(b);(b)=temp;} 
                    805: int agegomp= AGEGOMP;
                    806: 
                    807: int imx; 
                    808: int stepm=1;
                    809: /* Stepm, step in month: minimum step interpolation*/
                    810: 
                    811: int estepm;
                    812: /* Estepm, step in month to interpolate survival function in order to approximate Life Expectancy*/
                    813: 
                    814: int m,nb;
                    815: long *num;
                    816: int firstpass=0, lastpass=4,*cod, *ncodemax, *Tage,*cens;
                    817: double **agev,*moisnais, *annais, *moisdc, *andc,**mint, **anint;
                    818: double **pmmij, ***probs;
                    819: double *ageexmed,*agecens;
                    820: double dateintmean=0;
                    821: 
                    822: double *weight;
                    823: int **s; /* Status */
1.141     brouard   824: double *agedc;
1.145     brouard   825: double  **covar; /**< covar[j,i], value of jth covariate for individual i,
1.141     brouard   826:                  * covar=matrix(0,NCOVMAX,1,n); 
1.187     brouard   827:                  * cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*age; */
1.141     brouard   828: double  idx; 
                    829: int **nbcode, *Tvar; /**< model=V2 => Tvar[1]= 2 */
1.145     brouard   830: int *Ndum; /** Freq of modality (tricode */
1.141     brouard   831: int **codtab; /**< codtab=imatrix(1,100,1,10); */
                    832: int **Tvard, *Tprod, cptcovprod, *Tvaraff;
1.126     brouard   833: double *lsurv, *lpop, *tpop;
                    834: 
1.143     brouard   835: double ftol=FTOL; /**< Tolerance for computing Max Likelihood */
                    836: double ftolhess; /**< Tolerance for computing hessian */
1.126     brouard   837: 
                    838: /**************** split *************************/
                    839: static int split( char *path, char *dirc, char *name, char *ext, char *finame )
                    840: {
                    841:   /* From a file name with (full) path (either Unix or Windows) we extract the directory (dirc)
                    842:      the name of the file (name), its extension only (ext) and its first part of the name (finame)
                    843:   */ 
                    844:   char *ss;                            /* pointer */
1.186     brouard   845:   int  l1=0, l2=0;                             /* length counters */
1.126     brouard   846: 
                    847:   l1 = strlen(path );                  /* length of path */
                    848:   if ( l1 == 0 ) return( GLOCK_ERROR_NOPATH );
                    849:   ss= strrchr( path, DIRSEPARATOR );           /* find last / */
                    850:   if ( ss == NULL ) {                  /* no directory, so determine current directory */
                    851:     strcpy( name, path );              /* we got the fullname name because no directory */
                    852:     /*if(strrchr(path, ODIRSEPARATOR )==NULL)
                    853:       printf("Warning you should use %s as a separator\n",DIRSEPARATOR);*/
                    854:     /* get current working directory */
                    855:     /*    extern  char* getcwd ( char *buf , int len);*/
1.184     brouard   856: #ifdef WIN32
                    857:     if (_getcwd( dirc, FILENAME_MAX ) == NULL ) {
                    858: #else
                    859:        if (getcwd(dirc, FILENAME_MAX) == NULL) {
                    860: #endif
1.126     brouard   861:       return( GLOCK_ERROR_GETCWD );
                    862:     }
                    863:     /* got dirc from getcwd*/
                    864:     printf(" DIRC = %s \n",dirc);
                    865:   } else {                             /* strip direcotry from path */
                    866:     ss++;                              /* after this, the filename */
                    867:     l2 = strlen( ss );                 /* length of filename */
                    868:     if ( l2 == 0 ) return( GLOCK_ERROR_NOPATH );
                    869:     strcpy( name, ss );                /* save file name */
                    870:     strncpy( dirc, path, l1 - l2 );    /* now the directory */
1.186     brouard   871:     dirc[l1-l2] = '\0';                        /* add zero */
1.126     brouard   872:     printf(" DIRC2 = %s \n",dirc);
                    873:   }
                    874:   /* We add a separator at the end of dirc if not exists */
                    875:   l1 = strlen( dirc );                 /* length of directory */
                    876:   if( dirc[l1-1] != DIRSEPARATOR ){
                    877:     dirc[l1] =  DIRSEPARATOR;
                    878:     dirc[l1+1] = 0; 
                    879:     printf(" DIRC3 = %s \n",dirc);
                    880:   }
                    881:   ss = strrchr( name, '.' );           /* find last / */
                    882:   if (ss >0){
                    883:     ss++;
                    884:     strcpy(ext,ss);                    /* save extension */
                    885:     l1= strlen( name);
                    886:     l2= strlen(ss)+1;
                    887:     strncpy( finame, name, l1-l2);
                    888:     finame[l1-l2]= 0;
                    889:   }
                    890: 
                    891:   return( 0 );                         /* we're done */
                    892: }
                    893: 
                    894: 
                    895: /******************************************/
                    896: 
                    897: void replace_back_to_slash(char *s, char*t)
                    898: {
                    899:   int i;
                    900:   int lg=0;
                    901:   i=0;
                    902:   lg=strlen(t);
                    903:   for(i=0; i<= lg; i++) {
                    904:     (s[i] = t[i]);
                    905:     if (t[i]== '\\') s[i]='/';
                    906:   }
                    907: }
                    908: 
1.132     brouard   909: char *trimbb(char *out, char *in)
1.137     brouard   910: { /* Trim multiple blanks in line but keeps first blanks if line starts with blanks */
1.132     brouard   911:   char *s;
                    912:   s=out;
                    913:   while (*in != '\0'){
1.137     brouard   914:     while( *in == ' ' && *(in+1) == ' '){ /* && *(in+1) != '\0'){*/
1.132     brouard   915:       in++;
                    916:     }
                    917:     *out++ = *in++;
                    918:   }
                    919:   *out='\0';
                    920:   return s;
                    921: }
                    922: 
1.187     brouard   923: /* char *substrchaine(char *out, char *in, char *chain) */
                    924: /* { */
                    925: /*   /\* Substract chain 'chain' from 'in', return and output 'out' *\/ */
                    926: /*   char *s, *t; */
                    927: /*   t=in;s=out; */
                    928: /*   while ((*in != *chain) && (*in != '\0')){ */
                    929: /*     *out++ = *in++; */
                    930: /*   } */
                    931: 
                    932: /*   /\* *in matches *chain *\/ */
                    933: /*   while ((*in++ == *chain++) && (*in != '\0')){ */
                    934: /*     printf("*in = %c, *out= %c *chain= %c \n", *in, *out, *chain);  */
                    935: /*   } */
                    936: /*   in--; chain--; */
                    937: /*   while ( (*in != '\0')){ */
                    938: /*     printf("Bef *in = %c, *out= %c *chain= %c \n", *in, *out, *chain);  */
                    939: /*     *out++ = *in++; */
                    940: /*     printf("Aft *in = %c, *out= %c *chain= %c \n", *in, *out, *chain);  */
                    941: /*   } */
                    942: /*   *out='\0'; */
                    943: /*   out=s; */
                    944: /*   return out; */
                    945: /* } */
                    946: char *substrchaine(char *out, char *in, char *chain)
                    947: {
                    948:   /* Substract chain 'chain' from 'in', return and output 'out' */
                    949:   /* in="V1+V1*age+age*age+V2", chain="age*age" */
                    950: 
                    951:   char *strloc;
                    952: 
                    953:   strcpy (out, in); 
                    954:   strloc = strstr(out, chain); /* strloc points to out at age*age+V2 */
                    955:   printf("Bef strloc=%s chain=%s out=%s \n", strloc, chain, out);
                    956:   if(strloc != NULL){ 
                    957:     /* will affect out */ /* strloc+strlenc(chain)=+V2 */ /* Will also work in Unicode */
                    958:     memmove(strloc,strloc+strlen(chain), strlen(strloc+strlen(chain))+1);
                    959:     /* strcpy (strloc, strloc +strlen(chain));*/
                    960:   }
                    961:   printf("Aft strloc=%s chain=%s in=%s out=%s \n", strloc, chain, in, out);
                    962:   return out;
                    963: }
                    964: 
                    965: 
1.145     brouard   966: char *cutl(char *blocc, char *alocc, char *in, char occ)
                    967: {
1.187     brouard   968:   /* cuts string in into blocc and alocc where blocc ends before FIRST occurence of char 'occ' 
1.145     brouard   969:      and alocc starts after first occurence of char 'occ' : ex cutv(blocc,alocc,"abcdef2ghi2j",'2')
1.187     brouard   970:      gives blocc="abcdef" and alocc="ghi2j".
1.145     brouard   971:      If occ is not found blocc is null and alocc is equal to in. Returns blocc
                    972:   */
1.160     brouard   973:   char *s, *t;
1.145     brouard   974:   t=in;s=in;
                    975:   while ((*in != occ) && (*in != '\0')){
                    976:     *alocc++ = *in++;
                    977:   }
                    978:   if( *in == occ){
                    979:     *(alocc)='\0';
                    980:     s=++in;
                    981:   }
                    982:  
                    983:   if (s == t) {/* occ not found */
                    984:     *(alocc-(in-s))='\0';
                    985:     in=s;
                    986:   }
                    987:   while ( *in != '\0'){
                    988:     *blocc++ = *in++;
                    989:   }
                    990: 
                    991:   *blocc='\0';
                    992:   return t;
                    993: }
1.137     brouard   994: char *cutv(char *blocc, char *alocc, char *in, char occ)
                    995: {
1.187     brouard   996:   /* cuts string in into blocc and alocc where blocc ends before LAST occurence of char 'occ' 
1.137     brouard   997:      and alocc starts after last occurence of char 'occ' : ex cutv(blocc,alocc,"abcdef2ghi2j",'2')
                    998:      gives blocc="abcdef2ghi" and alocc="j".
                    999:      If occ is not found blocc is null and alocc is equal to in. Returns alocc
                   1000:   */
                   1001:   char *s, *t;
                   1002:   t=in;s=in;
                   1003:   while (*in != '\0'){
                   1004:     while( *in == occ){
                   1005:       *blocc++ = *in++;
                   1006:       s=in;
                   1007:     }
                   1008:     *blocc++ = *in++;
                   1009:   }
                   1010:   if (s == t) /* occ not found */
                   1011:     *(blocc-(in-s))='\0';
                   1012:   else
                   1013:     *(blocc-(in-s)-1)='\0';
                   1014:   in=s;
                   1015:   while ( *in != '\0'){
                   1016:     *alocc++ = *in++;
                   1017:   }
                   1018: 
                   1019:   *alocc='\0';
                   1020:   return s;
                   1021: }
                   1022: 
1.126     brouard  1023: int nbocc(char *s, char occ)
                   1024: {
                   1025:   int i,j=0;
                   1026:   int lg=20;
                   1027:   i=0;
                   1028:   lg=strlen(s);
                   1029:   for(i=0; i<= lg; i++) {
                   1030:   if  (s[i] == occ ) j++;
                   1031:   }
                   1032:   return j;
                   1033: }
                   1034: 
1.137     brouard  1035: /* void cutv(char *u,char *v, char*t, char occ) */
                   1036: /* { */
                   1037: /*   /\* cuts string t into u and v where u ends before last occurence of char 'occ'  */
                   1038: /*      and v starts after last occurence of char 'occ' : ex cutv(u,v,"abcdef2ghi2j",'2') */
                   1039: /*      gives u="abcdef2ghi" and v="j" *\/ */
                   1040: /*   int i,lg,j,p=0; */
                   1041: /*   i=0; */
                   1042: /*   lg=strlen(t); */
                   1043: /*   for(j=0; j<=lg-1; j++) { */
                   1044: /*     if((t[j]!= occ) && (t[j+1]== occ)) p=j+1; */
                   1045: /*   } */
1.126     brouard  1046: 
1.137     brouard  1047: /*   for(j=0; j<p; j++) { */
                   1048: /*     (u[j] = t[j]); */
                   1049: /*   } */
                   1050: /*      u[p]='\0'; */
1.126     brouard  1051: 
1.137     brouard  1052: /*    for(j=0; j<= lg; j++) { */
                   1053: /*     if (j>=(p+1))(v[j-p-1] = t[j]); */
                   1054: /*   } */
                   1055: /* } */
1.126     brouard  1056: 
1.160     brouard  1057: #ifdef _WIN32
                   1058: char * strsep(char **pp, const char *delim)
                   1059: {
                   1060:   char *p, *q;
                   1061:          
                   1062:   if ((p = *pp) == NULL)
                   1063:     return 0;
                   1064:   if ((q = strpbrk (p, delim)) != NULL)
                   1065:   {
                   1066:     *pp = q + 1;
                   1067:     *q = '\0';
                   1068:   }
                   1069:   else
                   1070:     *pp = 0;
                   1071:   return p;
                   1072: }
                   1073: #endif
                   1074: 
1.126     brouard  1075: /********************** nrerror ********************/
                   1076: 
                   1077: void nrerror(char error_text[])
                   1078: {
                   1079:   fprintf(stderr,"ERREUR ...\n");
                   1080:   fprintf(stderr,"%s\n",error_text);
                   1081:   exit(EXIT_FAILURE);
                   1082: }
                   1083: /*********************** vector *******************/
                   1084: double *vector(int nl, int nh)
                   1085: {
                   1086:   double *v;
                   1087:   v=(double *) malloc((size_t)((nh-nl+1+NR_END)*sizeof(double)));
                   1088:   if (!v) nrerror("allocation failure in vector");
                   1089:   return v-nl+NR_END;
                   1090: }
                   1091: 
                   1092: /************************ free vector ******************/
                   1093: void free_vector(double*v, int nl, int nh)
                   1094: {
                   1095:   free((FREE_ARG)(v+nl-NR_END));
                   1096: }
                   1097: 
                   1098: /************************ivector *******************************/
                   1099: int *ivector(long nl,long nh)
                   1100: {
                   1101:   int *v;
                   1102:   v=(int *) malloc((size_t)((nh-nl+1+NR_END)*sizeof(int)));
                   1103:   if (!v) nrerror("allocation failure in ivector");
                   1104:   return v-nl+NR_END;
                   1105: }
                   1106: 
                   1107: /******************free ivector **************************/
                   1108: void free_ivector(int *v, long nl, long nh)
                   1109: {
                   1110:   free((FREE_ARG)(v+nl-NR_END));
                   1111: }
                   1112: 
                   1113: /************************lvector *******************************/
                   1114: long *lvector(long nl,long nh)
                   1115: {
                   1116:   long *v;
                   1117:   v=(long *) malloc((size_t)((nh-nl+1+NR_END)*sizeof(long)));
                   1118:   if (!v) nrerror("allocation failure in ivector");
                   1119:   return v-nl+NR_END;
                   1120: }
                   1121: 
                   1122: /******************free lvector **************************/
                   1123: void free_lvector(long *v, long nl, long nh)
                   1124: {
                   1125:   free((FREE_ARG)(v+nl-NR_END));
                   1126: }
                   1127: 
                   1128: /******************* imatrix *******************************/
                   1129: int **imatrix(long nrl, long nrh, long ncl, long nch) 
                   1130:      /* allocate a int matrix with subscript range m[nrl..nrh][ncl..nch] */ 
                   1131: { 
                   1132:   long i, nrow=nrh-nrl+1,ncol=nch-ncl+1; 
                   1133:   int **m; 
                   1134:   
                   1135:   /* allocate pointers to rows */ 
                   1136:   m=(int **) malloc((size_t)((nrow+NR_END)*sizeof(int*))); 
                   1137:   if (!m) nrerror("allocation failure 1 in matrix()"); 
                   1138:   m += NR_END; 
                   1139:   m -= nrl; 
                   1140:   
                   1141:   
                   1142:   /* allocate rows and set pointers to them */ 
                   1143:   m[nrl]=(int *) malloc((size_t)((nrow*ncol+NR_END)*sizeof(int))); 
                   1144:   if (!m[nrl]) nrerror("allocation failure 2 in matrix()"); 
                   1145:   m[nrl] += NR_END; 
                   1146:   m[nrl] -= ncl; 
                   1147:   
                   1148:   for(i=nrl+1;i<=nrh;i++) m[i]=m[i-1]+ncol; 
                   1149:   
                   1150:   /* return pointer to array of pointers to rows */ 
                   1151:   return m; 
                   1152: } 
                   1153: 
                   1154: /****************** free_imatrix *************************/
                   1155: void free_imatrix(m,nrl,nrh,ncl,nch)
                   1156:       int **m;
                   1157:       long nch,ncl,nrh,nrl; 
                   1158:      /* free an int matrix allocated by imatrix() */ 
                   1159: { 
                   1160:   free((FREE_ARG) (m[nrl]+ncl-NR_END)); 
                   1161:   free((FREE_ARG) (m+nrl-NR_END)); 
                   1162: } 
                   1163: 
                   1164: /******************* matrix *******************************/
                   1165: double **matrix(long nrl, long nrh, long ncl, long nch)
                   1166: {
                   1167:   long i, nrow=nrh-nrl+1, ncol=nch-ncl+1;
                   1168:   double **m;
                   1169: 
                   1170:   m=(double **) malloc((size_t)((nrow+NR_END)*sizeof(double*)));
                   1171:   if (!m) nrerror("allocation failure 1 in matrix()");
                   1172:   m += NR_END;
                   1173:   m -= nrl;
                   1174: 
                   1175:   m[nrl]=(double *) malloc((size_t)((nrow*ncol+NR_END)*sizeof(double)));
                   1176:   if (!m[nrl]) nrerror("allocation failure 2 in matrix()");
                   1177:   m[nrl] += NR_END;
                   1178:   m[nrl] -= ncl;
                   1179: 
                   1180:   for (i=nrl+1; i<=nrh; i++) m[i]=m[i-1]+ncol;
                   1181:   return m;
1.145     brouard  1182:   /* print *(*(m+1)+70) or print m[1][70]; print m+1 or print &(m[1]) or &(m[1][0])
                   1183: m[i] = address of ith row of the table. &(m[i]) is its value which is another adress
                   1184: that of m[i][0]. In order to get the value p m[i][0] but it is unitialized.
1.126     brouard  1185:    */
                   1186: }
                   1187: 
                   1188: /*************************free matrix ************************/
                   1189: void free_matrix(double **m, long nrl, long nrh, long ncl, long nch)
                   1190: {
                   1191:   free((FREE_ARG)(m[nrl]+ncl-NR_END));
                   1192:   free((FREE_ARG)(m+nrl-NR_END));
                   1193: }
                   1194: 
                   1195: /******************* ma3x *******************************/
                   1196: double ***ma3x(long nrl, long nrh, long ncl, long nch, long nll, long nlh)
                   1197: {
                   1198:   long i, j, nrow=nrh-nrl+1, ncol=nch-ncl+1, nlay=nlh-nll+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: 
                   1213:   m[nrl][ncl]=(double *) malloc((size_t)((nrow*ncol*nlay+NR_END)*sizeof(double)));
                   1214:   if (!m[nrl][ncl]) nrerror("allocation failure 3 in matrix()");
                   1215:   m[nrl][ncl] += NR_END;
                   1216:   m[nrl][ncl] -= nll;
                   1217:   for (j=ncl+1; j<=nch; j++) 
                   1218:     m[nrl][j]=m[nrl][j-1]+nlay;
                   1219:   
                   1220:   for (i=nrl+1; i<=nrh; i++) {
                   1221:     m[i][ncl]=m[i-1l][ncl]+ncol*nlay;
                   1222:     for (j=ncl+1; j<=nch; j++) 
                   1223:       m[i][j]=m[i][j-1]+nlay;
                   1224:   }
                   1225:   return m; 
                   1226:   /*  gdb: p *(m+1) <=> p m[1] and p (m+1) <=> p (m+1) <=> p &(m[1])
                   1227:            &(m[i][j][k]) <=> *((*(m+i) + j)+k)
                   1228:   */
                   1229: }
                   1230: 
                   1231: /*************************free ma3x ************************/
                   1232: void free_ma3x(double ***m, long nrl, long nrh, long ncl, long nch,long nll, long nlh)
                   1233: {
                   1234:   free((FREE_ARG)(m[nrl][ncl]+ nll-NR_END));
                   1235:   free((FREE_ARG)(m[nrl]+ncl-NR_END));
                   1236:   free((FREE_ARG)(m+nrl-NR_END));
                   1237: }
                   1238: 
                   1239: /*************** function subdirf ***********/
                   1240: char *subdirf(char fileres[])
                   1241: {
                   1242:   /* Caution optionfilefiname is hidden */
                   1243:   strcpy(tmpout,optionfilefiname);
                   1244:   strcat(tmpout,"/"); /* Add to the right */
                   1245:   strcat(tmpout,fileres);
                   1246:   return tmpout;
                   1247: }
                   1248: 
                   1249: /*************** function subdirf2 ***********/
                   1250: char *subdirf2(char fileres[], char *preop)
                   1251: {
                   1252:   
                   1253:   /* Caution optionfilefiname is hidden */
                   1254:   strcpy(tmpout,optionfilefiname);
                   1255:   strcat(tmpout,"/");
                   1256:   strcat(tmpout,preop);
                   1257:   strcat(tmpout,fileres);
                   1258:   return tmpout;
                   1259: }
                   1260: 
                   1261: /*************** function subdirf3 ***********/
                   1262: char *subdirf3(char fileres[], char *preop, char *preop2)
                   1263: {
                   1264:   
                   1265:   /* Caution optionfilefiname is hidden */
                   1266:   strcpy(tmpout,optionfilefiname);
                   1267:   strcat(tmpout,"/");
                   1268:   strcat(tmpout,preop);
                   1269:   strcat(tmpout,preop2);
                   1270:   strcat(tmpout,fileres);
                   1271:   return tmpout;
                   1272: }
                   1273: 
1.162     brouard  1274: char *asc_diff_time(long time_sec, char ascdiff[])
                   1275: {
                   1276:   long sec_left, days, hours, minutes;
                   1277:   days = (time_sec) / (60*60*24);
                   1278:   sec_left = (time_sec) % (60*60*24);
                   1279:   hours = (sec_left) / (60*60) ;
                   1280:   sec_left = (sec_left) %(60*60);
                   1281:   minutes = (sec_left) /60;
                   1282:   sec_left = (sec_left) % (60);
                   1283:   sprintf(ascdiff,"%ld day(s) %ld hour(s) %ld minute(s) %ld second(s)",days, hours, minutes, sec_left);  
                   1284:   return ascdiff;
                   1285: }
                   1286: 
1.126     brouard  1287: /***************** f1dim *************************/
                   1288: extern int ncom; 
                   1289: extern double *pcom,*xicom;
                   1290: extern double (*nrfunc)(double []); 
                   1291:  
                   1292: double f1dim(double x) 
                   1293: { 
                   1294:   int j; 
                   1295:   double f;
                   1296:   double *xt; 
                   1297:  
                   1298:   xt=vector(1,ncom); 
                   1299:   for (j=1;j<=ncom;j++) xt[j]=pcom[j]+x*xicom[j]; 
                   1300:   f=(*nrfunc)(xt); 
                   1301:   free_vector(xt,1,ncom); 
                   1302:   return f; 
                   1303: } 
                   1304: 
                   1305: /*****************brent *************************/
                   1306: double brent(double ax, double bx, double cx, double (*f)(double), double tol,         double *xmin) 
1.187     brouard  1307: {
                   1308:   /* Given a function f, and given a bracketing triplet of abscissas ax, bx, cx (such that bx is
                   1309:    * between ax and cx, and f(bx) is less than both f(ax) and f(cx) ), this routine isolates
                   1310:    * the minimum to a fractional precision of about tol using Brent’s method. The abscissa of
                   1311:    * the minimum is returned as xmin, and the minimum function value is returned as brent , the
                   1312:    * returned function value. 
                   1313:   */
1.126     brouard  1314:   int iter; 
                   1315:   double a,b,d,etemp;
1.159     brouard  1316:   double fu=0,fv,fw,fx;
1.164     brouard  1317:   double ftemp=0.;
1.126     brouard  1318:   double p,q,r,tol1,tol2,u,v,w,x,xm; 
                   1319:   double e=0.0; 
                   1320:  
                   1321:   a=(ax < cx ? ax : cx); 
                   1322:   b=(ax > cx ? ax : cx); 
                   1323:   x=w=v=bx; 
                   1324:   fw=fv=fx=(*f)(x); 
                   1325:   for (iter=1;iter<=ITMAX;iter++) { 
                   1326:     xm=0.5*(a+b); 
                   1327:     tol2=2.0*(tol1=tol*fabs(x)+ZEPS); 
                   1328:     /*         if (2.0*fabs(fp-(*fret)) <= ftol*(fabs(fp)+fabs(*fret)))*/
                   1329:     printf(".");fflush(stdout);
                   1330:     fprintf(ficlog,".");fflush(ficlog);
1.162     brouard  1331: #ifdef DEBUGBRENT
1.126     brouard  1332:     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);
                   1333:     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);
                   1334:     /*         if ((fabs(x-xm) <= (tol2-0.5*(b-a)))||(2.0*fabs(fu-ftemp) <= ftol*1.e-2*(fabs(fu)+fabs(ftemp)))) { */
                   1335: #endif
                   1336:     if (fabs(x-xm) <= (tol2-0.5*(b-a))){ 
                   1337:       *xmin=x; 
                   1338:       return fx; 
                   1339:     } 
                   1340:     ftemp=fu;
                   1341:     if (fabs(e) > tol1) { 
                   1342:       r=(x-w)*(fx-fv); 
                   1343:       q=(x-v)*(fx-fw); 
                   1344:       p=(x-v)*q-(x-w)*r; 
                   1345:       q=2.0*(q-r); 
                   1346:       if (q > 0.0) p = -p; 
                   1347:       q=fabs(q); 
                   1348:       etemp=e; 
                   1349:       e=d; 
                   1350:       if (fabs(p) >= fabs(0.5*q*etemp) || p <= q*(a-x) || p >= q*(b-x)) 
                   1351:        d=CGOLD*(e=(x >= xm ? a-x : b-x)); 
                   1352:       else { 
                   1353:        d=p/q; 
                   1354:        u=x+d; 
                   1355:        if (u-a < tol2 || b-u < tol2) 
                   1356:          d=SIGN(tol1,xm-x); 
                   1357:       } 
                   1358:     } else { 
                   1359:       d=CGOLD*(e=(x >= xm ? a-x : b-x)); 
                   1360:     } 
                   1361:     u=(fabs(d) >= tol1 ? x+d : x+SIGN(tol1,d)); 
                   1362:     fu=(*f)(u); 
                   1363:     if (fu <= fx) { 
                   1364:       if (u >= x) a=x; else b=x; 
                   1365:       SHFT(v,w,x,u) 
1.183     brouard  1366:       SHFT(fv,fw,fx,fu) 
                   1367:     } else { 
                   1368:       if (u < x) a=u; else b=u; 
                   1369:       if (fu <= fw || w == x) { 
                   1370:        v=w; 
                   1371:        w=u; 
                   1372:        fv=fw; 
                   1373:        fw=fu; 
                   1374:       } else if (fu <= fv || v == x || v == w) { 
                   1375:        v=u; 
                   1376:        fv=fu; 
                   1377:       } 
                   1378:     } 
1.126     brouard  1379:   } 
                   1380:   nrerror("Too many iterations in brent"); 
                   1381:   *xmin=x; 
                   1382:   return fx; 
                   1383: } 
                   1384: 
                   1385: /****************** mnbrak ***********************/
                   1386: 
                   1387: void mnbrak(double *ax, double *bx, double *cx, double *fa, double *fb, double *fc, 
                   1388:            double (*func)(double)) 
1.183     brouard  1389: { /* Given a function func , and given distinct initial points ax and bx , this routine searches in
                   1390: the downhill direction (defined by the function as evaluated at the initial points) and returns
                   1391: new points ax , bx , cx that bracket a minimum of the function. Also returned are the function
                   1392: values at the three points, fa, fb , and fc such that fa > fb and fb < fc.
                   1393:    */
1.126     brouard  1394:   double ulim,u,r,q, dum;
                   1395:   double fu; 
1.187     brouard  1396: 
                   1397:   double scale=10.;
                   1398:   int iterscale=0;
                   1399: 
                   1400:   *fa=(*func)(*ax); /*  xta[j]=pcom[j]+(*ax)*xicom[j]; fa=f(xta[j])*/
                   1401:   *fb=(*func)(*bx); /*  xtb[j]=pcom[j]+(*bx)*xicom[j]; fb=f(xtb[j]) */
                   1402: 
                   1403: 
                   1404:   /* while(*fb != *fb){ /\* *ax should be ok, reducing distance to *ax *\/ */
                   1405:   /*   printf("Warning mnbrak *fb = %lf, *bx=%lf *ax=%lf *fa==%lf iter=%d\n",*fb, *bx, *ax, *fa, iterscale++); */
                   1406:   /*   *bx = *ax - (*ax - *bx)/scale; */
                   1407:   /*   *fb=(*func)(*bx);  /\*  xtb[j]=pcom[j]+(*bx)*xicom[j]; fb=f(xtb[j]) *\/ */
                   1408:   /* } */
                   1409: 
1.126     brouard  1410:   if (*fb > *fa) { 
                   1411:     SHFT(dum,*ax,*bx,dum) 
1.183     brouard  1412:     SHFT(dum,*fb,*fa,dum) 
                   1413:   } 
1.126     brouard  1414:   *cx=(*bx)+GOLD*(*bx-*ax); 
                   1415:   *fc=(*func)(*cx); 
1.183     brouard  1416: #ifdef DEBUG
                   1417:   printf("mnbrak0 *fb=%.12e *fc=%.12e\n",*fb,*fc);
                   1418:   fprintf(ficlog,"mnbrak0 *fb=%.12e *fc=%.12e\n",*fb,*fc);
                   1419: #endif
                   1420:   while (*fb > *fc) { /* Declining a,b,c with fa> fb > fc */
1.126     brouard  1421:     r=(*bx-*ax)*(*fb-*fc); 
                   1422:     q=(*bx-*cx)*(*fb-*fa); 
                   1423:     u=(*bx)-((*bx-*cx)*q-(*bx-*ax)*r)/ 
1.183     brouard  1424:       (2.0*SIGN(FMAX(fabs(q-r),TINY),q-r)); /* Minimum abscissa of a parabolic estimated from (a,fa), (b,fb) and (c,fc). */
                   1425:     ulim=(*bx)+GLIMIT*(*cx-*bx); /* Maximum abscissa where function should be evaluated */
                   1426:     if ((*bx-u)*(u-*cx) > 0.0) { /* if u_p is between b and c */
1.126     brouard  1427:       fu=(*func)(u); 
1.163     brouard  1428: #ifdef DEBUG
                   1429:       /* f(x)=A(x-u)**2+f(u) */
                   1430:       double A, fparabu; 
                   1431:       A= (*fb - *fa)/(*bx-*ax)/(*bx+*ax-2*u);
                   1432:       fparabu= *fa - A*(*ax-u)*(*ax-u);
                   1433:       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);
                   1434:       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  1435:       /* And thus,it can be that fu > *fc even if fparabu < *fc */
                   1436:       /* mnbrak (*ax=7.666299858533, *fa=299039.693133272231), (*bx=8.595447774979, *fb=298976.598289369489),
                   1437:         (*cx=10.098840694817, *fc=298946.631474258087),  (*u=9.852501168332, fu=298948.773013752128, fparabu=298945.434711494134) */
                   1438:       /* In that case, there is no bracket in the output! Routine is wrong with many consequences.*/
1.163     brouard  1439: #endif 
1.184     brouard  1440: #ifdef MNBRAKORIGINAL
1.183     brouard  1441: #else
                   1442:       if (fu > *fc) {
                   1443: #ifdef DEBUG
                   1444:       printf("mnbrak4  fu > fc \n");
                   1445:       fprintf(ficlog, "mnbrak4 fu > fc\n");
                   1446: #endif
                   1447:        /* 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 *\/  */
                   1448:        /* SHFT(*fa,*fc,fu,*fc) /\* (b, u, c) is a bracket while test fb > fc will be fu > fc  will exit *\/ */
                   1449:        dum=u; /* Shifting c and u */
                   1450:        u = *cx;
                   1451:        *cx = dum;
                   1452:        dum = fu;
                   1453:        fu = *fc;
                   1454:        *fc =dum;
                   1455:       } else { /* end */
                   1456: #ifdef DEBUG
                   1457:       printf("mnbrak3  fu < fc \n");
                   1458:       fprintf(ficlog, "mnbrak3 fu < fc\n");
                   1459: #endif
                   1460:        dum=u; /* Shifting c and u */
                   1461:        u = *cx;
                   1462:        *cx = dum;
                   1463:        dum = fu;
                   1464:        fu = *fc;
                   1465:        *fc =dum;
                   1466:       }
                   1467: #endif
1.162     brouard  1468:     } else if ((*cx-u)*(u-ulim) > 0.0) { /* u is after c but before ulim */
1.183     brouard  1469: #ifdef DEBUG
                   1470:       printf("mnbrak2  u after c but before ulim\n");
                   1471:       fprintf(ficlog, "mnbrak2 u after c but before ulim\n");
                   1472: #endif
1.126     brouard  1473:       fu=(*func)(u); 
                   1474:       if (fu < *fc) { 
1.183     brouard  1475: #ifdef DEBUG
                   1476:       printf("mnbrak2  u after c but before ulim AND fu < fc\n");
                   1477:       fprintf(ficlog, "mnbrak2 u after c but before ulim AND fu <fc \n");
                   1478: #endif
1.126     brouard  1479:        SHFT(*bx,*cx,u,*cx+GOLD*(*cx-*bx)) 
1.183     brouard  1480:        SHFT(*fb,*fc,fu,(*func)(u)) 
                   1481:       } 
1.162     brouard  1482:     } else if ((u-ulim)*(ulim-*cx) >= 0.0) { /* u outside ulim (verifying that ulim is beyond c) */
1.183     brouard  1483: #ifdef DEBUG
                   1484:       printf("mnbrak2  u outside ulim (verifying that ulim is beyond c)\n");
                   1485:       fprintf(ficlog, "mnbrak2 u outside ulim (verifying that ulim is beyond c)\n");
                   1486: #endif
1.126     brouard  1487:       u=ulim; 
                   1488:       fu=(*func)(u); 
1.183     brouard  1489:     } else { /* u could be left to b (if r > q parabola has a maximum) */
                   1490: #ifdef DEBUG
                   1491:       printf("mnbrak2  u could be left to b (if r > q parabola has a maximum)\n");
                   1492:       fprintf(ficlog, "mnbrak2  u could be left to b (if r > q parabola has a maximum)\n");
                   1493: #endif
1.126     brouard  1494:       u=(*cx)+GOLD*(*cx-*bx); 
                   1495:       fu=(*func)(u); 
1.183     brouard  1496:     } /* end tests */
1.126     brouard  1497:     SHFT(*ax,*bx,*cx,u) 
1.183     brouard  1498:     SHFT(*fa,*fb,*fc,fu) 
                   1499: #ifdef DEBUG
                   1500:       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);
                   1501:       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);
                   1502: #endif
                   1503:   } /* 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  1504: } 
                   1505: 
                   1506: /*************** linmin ************************/
1.162     brouard  1507: /* Given an n -dimensional point p[1..n] and an n -dimensional direction xi[1..n] , moves and
                   1508: resets p to where the function func(p) takes on a minimum along the direction xi from p ,
                   1509: and replaces xi by the actual vector displacement that p was moved. Also returns as fret
                   1510: the value of func at the returned location p . This is actually all accomplished by calling the
                   1511: routines mnbrak and brent .*/
1.126     brouard  1512: int ncom; 
                   1513: double *pcom,*xicom;
                   1514: double (*nrfunc)(double []); 
                   1515:  
                   1516: void linmin(double p[], double xi[], int n, double *fret,double (*func)(double [])) 
                   1517: { 
                   1518:   double brent(double ax, double bx, double cx, 
                   1519:               double (*f)(double), double tol, double *xmin); 
                   1520:   double f1dim(double x); 
                   1521:   void mnbrak(double *ax, double *bx, double *cx, double *fa, double *fb, 
                   1522:              double *fc, double (*func)(double)); 
                   1523:   int j; 
                   1524:   double xx,xmin,bx,ax; 
                   1525:   double fx,fb,fa;
1.187     brouard  1526: 
                   1527:   double scale=10., axs, xxs, xxss; /* Scale added for infinity */
1.126     brouard  1528:  
                   1529:   ncom=n; 
                   1530:   pcom=vector(1,n); 
                   1531:   xicom=vector(1,n); 
                   1532:   nrfunc=func; 
                   1533:   for (j=1;j<=n;j++) { 
                   1534:     pcom[j]=p[j]; 
                   1535:     xicom[j]=xi[j]; 
                   1536:   } 
1.187     brouard  1537: 
                   1538:   axs=0.0;
                   1539:   xxss=1; /* 1 and using scale */
                   1540:   xxs=1;
                   1541:   do{
                   1542:     ax=0.;
                   1543:     xx= xxs;
                   1544:     mnbrak(&ax,&xx,&bx,&fa,&fx,&fb,f1dim);  /* Outputs: xtx[j]=pcom[j]+(*xx)*xicom[j]; fx=f(xtx[j]) */
                   1545:     /* brackets with inputs ax=0 and xx=1, but points, pcom=p, and directions values, xicom=xi, are sent via f1dim(x) */
                   1546:     /* 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))   */
                   1547:     /* Outputs: fa=f(p(j)) and fx=f(p(j) + xxs * xi(j) ) and f(bx)= f(p(j)+ bx* xi(j)) */
                   1548:     /* Given input ax=axs and xx=xxs, xx might be too far from ax to get a finite f(xx) */
                   1549:     /* Searches on line, outputs (ax, xx, bx) such that fx < min(fa and fb) */
                   1550:     /* 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]]*/
                   1551:     if (fx != fx){
                   1552:        xxs=xxs/scale; /* Trying a smaller xx, closer to initial ax=0 */
                   1553:        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);
                   1554:     }
                   1555:   }while(fx != fx);
                   1556: 
                   1557:   *fret=brent(ax,xx,bx,f1dim,TOL,&xmin); /* Giving a bracketting triplet (ax, xx, bx), find a minimum, xmin, according to f1dim, *fret(xmin),*/
                   1558:   /* fa = f(p[j] + ax * xi[j]), fx = f(p[j] + xx * xi[j]), fb = f(p[j] + bx * xi[j]) */
                   1559:   /* fmin = f(p[j] + xmin * xi[j]) */
                   1560:   /* P+lambda n in that direction (lambdamin), with TOL between abscisses */
                   1561:   /* f1dim(xmin): for (j=1;j<=ncom;j++) xt[j]=pcom[j]+xmin*xicom[j]; */
1.126     brouard  1562: #ifdef DEBUG
                   1563:   printf("retour brent fret=%.12e xmin=%.12e\n",*fret,xmin);
                   1564:   fprintf(ficlog,"retour brent fret=%.12e xmin=%.12e\n",*fret,xmin);
                   1565: #endif
1.187     brouard  1566:   printf("linmin end ");
1.126     brouard  1567:   for (j=1;j<=n;j++) { 
1.188   ! brouard  1568:     /* printf(" before xi[%d]=%12.8f", j,xi[j]); */
1.187     brouard  1569:     xi[j] *= xmin; /* xi rescaled by xmin: if xmin=-1.237 and xi=(1,0,...,0) xi=(-1.237,0,...,0) */
                   1570:     if(xxs <1.0)
                   1571:       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 );
                   1572:     p[j] += xi[j]; /* Parameters values are updated accordingly */
1.126     brouard  1573:   } 
1.187     brouard  1574:   printf("\n");
1.188   ! brouard  1575:   printf("Comparing last *frec(xmin)=%12.8f from Brent and frec(0.)=%12.8f \n", (*func)(p));
1.126     brouard  1576:   free_vector(xicom,1,n); 
                   1577:   free_vector(pcom,1,n); 
                   1578: } 
                   1579: 
                   1580: 
                   1581: /*************** powell ************************/
1.162     brouard  1582: /*
                   1583: Minimization of a function func of n variables. Input consists of an initial starting point
                   1584: p[1..n] ; an initial matrix xi[1..n][1..n] , whose columns contain the initial set of di-
                   1585: rections (usually the n unit vectors); and ftol , the fractional tolerance in the function value
                   1586: such that failure to decrease by more than this amount on one iteration signals doneness. On
                   1587: output, p is set to the best point found, xi is the then-current direction set, fret is the returned
                   1588: function value at p , and iter is the number of iterations taken. The routine linmin is used.
                   1589:  */
1.126     brouard  1590: void powell(double p[], double **xi, int n, double ftol, int *iter, double *fret, 
                   1591:            double (*func)(double [])) 
                   1592: { 
                   1593:   void linmin(double p[], double xi[], int n, double *fret, 
                   1594:              double (*func)(double [])); 
                   1595:   int i,ibig,j; 
                   1596:   double del,t,*pt,*ptt,*xit;
1.181     brouard  1597:   double directest;
1.126     brouard  1598:   double fp,fptt;
                   1599:   double *xits;
                   1600:   int niterf, itmp;
                   1601: 
                   1602:   pt=vector(1,n); 
                   1603:   ptt=vector(1,n); 
                   1604:   xit=vector(1,n); 
                   1605:   xits=vector(1,n); 
                   1606:   *fret=(*func)(p); 
                   1607:   for (j=1;j<=n;j++) pt[j]=p[j]; 
1.157     brouard  1608:     rcurr_time = time(NULL);  
1.126     brouard  1609:   for (*iter=1;;++(*iter)) { 
1.187     brouard  1610:     fp=(*fret); /* From former iteration or initial value */
1.126     brouard  1611:     ibig=0; 
                   1612:     del=0.0; 
1.157     brouard  1613:     rlast_time=rcurr_time;
                   1614:     /* (void) gettimeofday(&curr_time,&tzp); */
                   1615:     rcurr_time = time(NULL);  
                   1616:     curr_time = *localtime(&rcurr_time);
                   1617:     printf("\nPowell iter=%d -2*LL=%.12f %ld sec. %ld sec.",*iter,*fret, rcurr_time-rlast_time, rcurr_time-rstart_time);fflush(stdout);
                   1618:     fprintf(ficlog,"\nPowell iter=%d -2*LL=%.12f %ld sec. %ld sec.",*iter,*fret,rcurr_time-rlast_time, rcurr_time-rstart_time); fflush(ficlog);
                   1619: /*     fprintf(ficrespow,"%d %.12f %ld",*iter,*fret,curr_time.tm_sec-start_time.tm_sec); */
1.126     brouard  1620:    for (i=1;i<=n;i++) {
                   1621:       printf(" %d %.12f",i, p[i]);
                   1622:       fprintf(ficlog," %d %.12lf",i, p[i]);
                   1623:       fprintf(ficrespow," %.12lf", p[i]);
                   1624:     }
                   1625:     printf("\n");
                   1626:     fprintf(ficlog,"\n");
                   1627:     fprintf(ficrespow,"\n");fflush(ficrespow);
                   1628:     if(*iter <=3){
1.157     brouard  1629:       tml = *localtime(&rcurr_time);
                   1630:       strcpy(strcurr,asctime(&tml));
                   1631:       rforecast_time=rcurr_time; 
1.126     brouard  1632:       itmp = strlen(strcurr);
                   1633:       if(strcurr[itmp-1]=='\n')  /* Windows outputs with a new line */
                   1634:        strcurr[itmp-1]='\0';
1.162     brouard  1635:       printf("\nConsidering the time needed for the last iteration #%d: %ld seconds,\n",*iter,rcurr_time-rlast_time);
1.157     brouard  1636:       fprintf(ficlog,"\nConsidering the time needed for this last iteration #%d: %ld seconds,\n",*iter,rcurr_time-rlast_time);
1.126     brouard  1637:       for(niterf=10;niterf<=30;niterf+=10){
1.157     brouard  1638:        rforecast_time=rcurr_time+(niterf-*iter)*(rcurr_time-rlast_time);
                   1639:        forecast_time = *localtime(&rforecast_time);
                   1640:        strcpy(strfor,asctime(&forecast_time));
1.126     brouard  1641:        itmp = strlen(strfor);
                   1642:        if(strfor[itmp-1]=='\n')
                   1643:        strfor[itmp-1]='\0';
1.157     brouard  1644:        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);
                   1645:        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  1646:       }
                   1647:     }
1.187     brouard  1648:     for (i=1;i<=n;i++) { /* For each direction i */
                   1649:       for (j=1;j<=n;j++) xit[j]=xi[j][i]; /* Directions stored from previous iteration with previous scales */
1.126     brouard  1650:       fptt=(*fret); 
                   1651: #ifdef DEBUG
1.164     brouard  1652:          printf("fret=%lf, %lf, %lf \n", *fret, *fret, *fret);
                   1653:          fprintf(ficlog, "fret=%lf, %lf, %lf \n", *fret, *fret, *fret);
1.126     brouard  1654: #endif
1.187     brouard  1655:          printf("%d",i);fflush(stdout); /* print direction (parameter) i */
1.126     brouard  1656:       fprintf(ficlog,"%d",i);fflush(ficlog);
1.188   ! brouard  1657:       linmin(p,xit,n,fret,func); /* Point p[n]. xit[n] has been loaded for direction i as input.*/
        !          1658:                                    /* Outputs are fret(new point p) p is updated and xit rescaled */
        !          1659:       if (fabs(fptt-(*fret)) > del) { /* We are keeping the max gain on each of the n directions */
        !          1660:        /* because that direction will be replaced unless the gain del is small */
        !          1661:        /* in comparison with the 'probable' gain, mu^2, with the last average direction. */
        !          1662:        /* Unless the n directions are conjugate some gain in the determinant may be obtained */
        !          1663:        /* with the new direction. */
1.126     brouard  1664:        del=fabs(fptt-(*fret)); 
                   1665:        ibig=i; 
                   1666:       } 
                   1667: #ifdef DEBUG
                   1668:       printf("%d %.12e",i,(*fret));
                   1669:       fprintf(ficlog,"%d %.12e",i,(*fret));
                   1670:       for (j=1;j<=n;j++) {
                   1671:        xits[j]=FMAX(fabs(p[j]-pt[j]),1.e-5);
                   1672:        printf(" x(%d)=%.12e",j,xit[j]);
                   1673:        fprintf(ficlog," x(%d)=%.12e",j,xit[j]);
                   1674:       }
                   1675:       for(j=1;j<=n;j++) {
1.162     brouard  1676:        printf(" p(%d)=%.12e",j,p[j]);
                   1677:        fprintf(ficlog," p(%d)=%.12e",j,p[j]);
1.126     brouard  1678:       }
                   1679:       printf("\n");
                   1680:       fprintf(ficlog,"\n");
                   1681: #endif
1.187     brouard  1682:     } /* end loop on each direction i */
                   1683:     /* Convergence test will use last linmin estimation (fret) and compare former iteration (fp) */ 
1.188   ! brouard  1684:     /* But p and xit have been updated at the end of linmin, *fret corresponds to new p, xit  */
1.187     brouard  1685:     /* New value of last point Pn is not computed, P(n-1) */
1.182     brouard  1686:     if (2.0*fabs(fp-(*fret)) <= ftol*(fabs(fp)+fabs(*fret))) { /* Did we reach enough precision? */
1.188   ! brouard  1687:       /* We could compare with a chi^2. chisquare(0.95,ddl=1)=3.84 */
        !          1688:       /* By adding age*age in a model, the new -2LL should be lower and the difference follows a */
        !          1689:       /* a chisquare statistics with 1 degree. To be significant at the 95% level, it should have */
        !          1690:       /* decreased of more than 3.84  */
        !          1691:       /* By adding age*age and V1*age the gain (-2LL) should be more than 5.99 (ddl=2) */
        !          1692:       /* By using V1+V2+V3, the gain should be  7.82, compared with basic 1+age. */
        !          1693:       /* By adding 10 parameters more the gain should be 18.31 */
        !          1694: 
        !          1695:       /* Starting the program with initial values given by a former maximization will simply change */
        !          1696:       /* the scales of the directions and the directions, because the are reset to canonical directions */
        !          1697:       /* Thus the first calls to linmin will give new points and better maximizations until fp-(*fret) is */
        !          1698:       /* under the tolerance value. If the tolerance is very small 1.e-9, it could last long.  */
1.126     brouard  1699: #ifdef DEBUG
                   1700:       int k[2],l;
                   1701:       k[0]=1;
                   1702:       k[1]=-1;
                   1703:       printf("Max: %.12e",(*func)(p));
                   1704:       fprintf(ficlog,"Max: %.12e",(*func)(p));
                   1705:       for (j=1;j<=n;j++) {
                   1706:        printf(" %.12e",p[j]);
                   1707:        fprintf(ficlog," %.12e",p[j]);
                   1708:       }
                   1709:       printf("\n");
                   1710:       fprintf(ficlog,"\n");
                   1711:       for(l=0;l<=1;l++) {
                   1712:        for (j=1;j<=n;j++) {
                   1713:          ptt[j]=p[j]+(p[j]-pt[j])*k[l];
                   1714:          printf("l=%d j=%d ptt=%.12e, xits=%.12e, p=%.12e, xit=%.12e", l,j,ptt[j],xits[j],p[j],xit[j]);
                   1715:          fprintf(ficlog,"l=%d j=%d ptt=%.12e, xits=%.12e, p=%.12e, xit=%.12e", l,j,ptt[j],xits[j],p[j],xit[j]);
                   1716:        }
                   1717:        printf("func(ptt)=%.12e, deriv=%.12e\n",(*func)(ptt),(ptt[j]-p[j])/((*func)(ptt)-(*func)(p)));
                   1718:        fprintf(ficlog,"func(ptt)=%.12e, deriv=%.12e\n",(*func)(ptt),(ptt[j]-p[j])/((*func)(ptt)-(*func)(p)));
                   1719:       }
                   1720: #endif
                   1721: 
                   1722: 
                   1723:       free_vector(xit,1,n); 
                   1724:       free_vector(xits,1,n); 
                   1725:       free_vector(ptt,1,n); 
                   1726:       free_vector(pt,1,n); 
                   1727:       return; 
                   1728:     } 
                   1729:     if (*iter == ITMAX) nrerror("powell exceeding maximum iterations."); 
1.181     brouard  1730:     for (j=1;j<=n;j++) { /* Computes the extrapolated point P_0 + 2 (P_n-P_0) */
1.126     brouard  1731:       ptt[j]=2.0*p[j]-pt[j]; 
                   1732:       xit[j]=p[j]-pt[j]; 
                   1733:       pt[j]=p[j]; 
                   1734:     } 
1.181     brouard  1735:     fptt=(*func)(ptt); /* f_3 */
1.161     brouard  1736:     if (fptt < fp) { /* If extrapolated point is better, decide if we keep that new direction or not */
1.162     brouard  1737:       /* (x1 f1=fp), (x2 f2=*fret), (x3 f3=fptt), (xm fm) */
1.161     brouard  1738:       /* From x1 (P0) distance of x2 is at h and x3 is 2h */
1.162     brouard  1739:       /* Let f"(x2) be the 2nd derivative equal everywhere.  */
                   1740:       /* Then the parabolic through (x1,f1), (x2,f2) and (x3,f3) */
                   1741:       /* will reach at f3 = fm + h^2/2 f"m  ; f" = (f1 -2f2 +f3 ) / h**2 */
1.181     brouard  1742:       /* Conditional for using this new direction is that mu^2 = (f1-2f2+f3)^2 /2 < del */
1.161     brouard  1743:       /* t=2.0*(fp-2.0*(*fret)+fptt)*SQR(fp-(*fret)-del)-del*SQR(fp-fptt); */
1.183     brouard  1744: #ifdef NRCORIGINAL
                   1745:       t=2.0*(fp-2.0*(*fret)+fptt)*SQR(fp-(*fret)-del)- del*SQR(fp-fptt); /* Original Numerical Recipes in C*/
                   1746: #else
                   1747:       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  1748:       t= t- del*SQR(fp-fptt);
1.183     brouard  1749: #endif
1.182     brouard  1750:       directest = fp-2.0*(*fret)+fptt - 2.0 * del; /* If del was big enough we change it for a new direction */
1.161     brouard  1751: #ifdef DEBUG
1.181     brouard  1752:       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);
                   1753:       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  1754:       printf("t3= %.12lf, t4= %.12lf, t3*= %.12lf, t4*= %.12lf\n",SQR(fp-(*fret)-del),SQR(fp-fptt),
                   1755:             (fp-(*fret)-del)*(fp-(*fret)-del),(fp-fptt)*(fp-fptt));
                   1756:       fprintf(ficlog,"t3= %.12lf, t4= %.12lf, t3*= %.12lf, t4*= %.12lf\n",SQR(fp-(*fret)-del),SQR(fp-fptt),
                   1757:             (fp-(*fret)-del)*(fp-(*fret)-del),(fp-fptt)*(fp-fptt));
                   1758:       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);
                   1759:       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);
                   1760: #endif
1.183     brouard  1761: #ifdef POWELLORIGINAL
                   1762:       if (t < 0.0) { /* Then we use it for new direction */
                   1763: #else
1.182     brouard  1764:       if (directest*t < 0.0) { /* Contradiction between both tests */
1.184     brouard  1765:       printf("directest= %.12lf, t= %.12lf, f1= %.12lf,f2= %.12lf,f3= %.12lf, del= %.12lf\n",directest, t, fp,(*fret),fptt,del);
1.182     brouard  1766:       printf("f1-2f2+f3= %.12lf, f1-f2-del= %.12lf, f1-f3= %.12lf\n",fp-2.0*(*fret)+fptt, fp -(*fret) -del, fp-fptt);
1.184     brouard  1767:       fprintf(ficlog,"directest= %.12lf, t= %.12lf, f1= %.12lf,f2= %.12lf,f3= %.12lf, del= %.12lf\n",directest, t, fp,(*fret),fptt, del);
1.182     brouard  1768:       fprintf(ficlog,"f1-2f2+f3= %.12lf, f1-f2-del= %.12lf, f1-f3= %.12lf\n",fp-2.0*(*fret)+fptt, fp -(*fret) -del, fp-fptt);
                   1769:     } 
1.181     brouard  1770:       if (directest < 0.0) { /* Then we use it for new direction */
                   1771: #endif
1.187     brouard  1772:        linmin(p,xit,n,fret,func); /* computes minimum on the extrapolated direction: changes p and rescales xit.*/
1.126     brouard  1773:        for (j=1;j<=n;j++) { 
1.181     brouard  1774:          xi[j][ibig]=xi[j][n]; /* Replace direction with biggest decrease by last direction n */
                   1775:          xi[j][n]=xit[j];      /* and this nth direction by the by the average p_0 p_n */
1.126     brouard  1776:        }
1.181     brouard  1777:        printf("Gaining to use new average direction of P0 P%d instead of biggest increase direction %d :\n",n,ibig);
                   1778:        fprintf(ficlog,"Gaining to use new average direction of P0 P%d instead of biggest increase direction %d :\n",n,ibig);
1.161     brouard  1779: 
1.126     brouard  1780: #ifdef DEBUG
1.164     brouard  1781:        printf("Direction changed  last moved %d in place of ibig=%d, new last is the average:\n",n,ibig);
                   1782:        fprintf(ficlog,"Direction changed  last moved %d in place of ibig=%d, new last is the average:\n",n,ibig);
1.126     brouard  1783:        for(j=1;j<=n;j++){
                   1784:          printf(" %.12e",xit[j]);
                   1785:          fprintf(ficlog," %.12e",xit[j]);
                   1786:        }
                   1787:        printf("\n");
                   1788:        fprintf(ficlog,"\n");
                   1789: #endif
1.162     brouard  1790:       } /* end of t negative */
                   1791:     } /* end if (fptt < fp)  */
1.126     brouard  1792:   } 
                   1793: } 
                   1794: 
                   1795: /**** Prevalence limit (stable or period prevalence)  ****************/
                   1796: 
                   1797: double **prevalim(double **prlim, int nlstate, double x[], double age, double **oldm, double **savm, double ftolpl, int ij)
                   1798: {
                   1799:   /* Computes the prevalence limit in each live state at age x by left multiplying the unit
                   1800:      matrix by transitions matrix until convergence is reached */
1.169     brouard  1801:   
1.126     brouard  1802:   int i, ii,j,k;
                   1803:   double min, max, maxmin, maxmax,sumnew=0.;
1.145     brouard  1804:   /* double **matprod2(); */ /* test */
1.131     brouard  1805:   double **out, cov[NCOVMAX+1], **pmij();
1.126     brouard  1806:   double **newm;
                   1807:   double agefin, delaymax=50 ; /* Max number of years to converge */
1.169     brouard  1808:   
1.126     brouard  1809:   for (ii=1;ii<=nlstate+ndeath;ii++)
                   1810:     for (j=1;j<=nlstate+ndeath;j++){
                   1811:       oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   1812:     }
1.169     brouard  1813:   
                   1814:   cov[1]=1.;
                   1815:   
                   1816:   /* Even if hstepm = 1, at least one multiplication by the unit matrix */
1.126     brouard  1817:   for(agefin=age-stepm/YEARM; agefin>=age-delaymax; agefin=agefin-stepm/YEARM){
                   1818:     newm=savm;
                   1819:     /* Covariates have to be included here again */
1.138     brouard  1820:     cov[2]=agefin;
1.187     brouard  1821:     if(nagesqr==1)
                   1822:       cov[3]= agefin*agefin;;
1.138     brouard  1823:     for (k=1; k<=cptcovn;k++) {
1.187     brouard  1824:       cov[2+nagesqr+k]=nbcode[Tvar[k]][codtab[ij][Tvar[k]]];
1.145     brouard  1825:       /*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  1826:     }
1.186     brouard  1827:     /*wrong? for (k=1; k<=cptcovage;k++) cov[2+Tage[k]]=cov[2+Tage[k]]*cov[2]; */
1.187     brouard  1828:     for (k=1; k<=cptcovage;k++) cov[2+nagesqr+Tage[k]]=nbcode[Tvar[k]][codtab[ij][Tvar[k]]]*cov[2];
1.186     brouard  1829:     for (k=1; k<=cptcovprod;k++) /* Useless */
1.187     brouard  1830:       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  1831:     
                   1832:     /*printf("ij=%d cptcovprod=%d tvar=%d ", ij, cptcovprod, Tvar[1]);*/
                   1833:     /*printf("ij=%d cov[3]=%lf cov[4]=%lf \n",ij, cov[3],cov[4]);*/
                   1834:     /*printf("ij=%d cov[3]=%lf \n",ij, cov[3]);*/
1.145     brouard  1835:     /* savm=pmij(pmmij,cov,ncovmodel,x,nlstate); */
                   1836:     /* out=matprod2(newm, pmij(pmmij,cov,ncovmodel,x,nlstate),1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, oldm); /\* Bug Valgrind *\/ */
1.142     brouard  1837:     out=matprod2(newm, pmij(pmmij,cov,ncovmodel,x,nlstate),1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, oldm); /* Bug Valgrind */
1.138     brouard  1838:     
1.126     brouard  1839:     savm=oldm;
                   1840:     oldm=newm;
                   1841:     maxmax=0.;
                   1842:     for(j=1;j<=nlstate;j++){
                   1843:       min=1.;
                   1844:       max=0.;
                   1845:       for(i=1; i<=nlstate; i++) {
                   1846:        sumnew=0;
                   1847:        for(k=1; k<=ndeath; k++) sumnew+=newm[i][nlstate+k];
                   1848:        prlim[i][j]= newm[i][j]/(1-sumnew);
1.145     brouard  1849:         /*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  1850:        max=FMAX(max,prlim[i][j]);
                   1851:        min=FMIN(min,prlim[i][j]);
                   1852:       }
                   1853:       maxmin=max-min;
                   1854:       maxmax=FMAX(maxmax,maxmin);
1.169     brouard  1855:     } /* j loop */
1.126     brouard  1856:     if(maxmax < ftolpl){
                   1857:       return prlim;
                   1858:     }
1.169     brouard  1859:   } /* age loop */
                   1860:   return prlim; /* should not reach here */
1.126     brouard  1861: }
                   1862: 
                   1863: /*************** transition probabilities ***************/ 
                   1864: 
                   1865: double **pmij(double **ps, double *cov, int ncovmodel, double *x, int nlstate )
                   1866: {
1.138     brouard  1867:   /* According to parameters values stored in x and the covariate's values stored in cov,
                   1868:      computes the probability to be observed in state j being in state i by appying the
                   1869:      model to the ncovmodel covariates (including constant and age).
                   1870:      lnpijopii=ln(pij/pii)= aij+bij*age+cij*v1+dij*v2+... = sum_nc=1^ncovmodel xij(nc)*cov[nc]
                   1871:      and, according on how parameters are entered, the position of the coefficient xij(nc) of the
                   1872:      ncth covariate in the global vector x is given by the formula:
                   1873:      j<i nc+((i-1)*(nlstate+ndeath-1)+j-1)*ncovmodel
                   1874:      j>=i nc + ((i-1)*(nlstate+ndeath-1)+(j-2))*ncovmodel
                   1875:      Computes ln(pij/pii) (lnpijopii), deduces pij/pii by exponentiation,
                   1876:      sums on j different of i to get 1-pii/pii, deduces pii, and then all pij.
                   1877:      Outputs ps[i][j] the probability to be observed in j being in j according to
                   1878:      the values of the covariates cov[nc] and corresponding parameter values x[nc+shiftij]
                   1879:   */
                   1880:   double s1, lnpijopii;
1.126     brouard  1881:   /*double t34;*/
1.164     brouard  1882:   int i,j, nc, ii, jj;
1.126     brouard  1883: 
                   1884:     for(i=1; i<= nlstate; i++){
                   1885:       for(j=1; j<i;j++){
1.138     brouard  1886:        for (nc=1, lnpijopii=0.;nc <=ncovmodel; nc++){
                   1887:          /*lnpijopii += param[i][j][nc]*cov[nc];*/
                   1888:          lnpijopii += x[nc+((i-1)*(nlstate+ndeath-1)+j-1)*ncovmodel]*cov[nc];
                   1889: /*      printf("Int j<i s1=%.17e, lnpijopii=%.17e\n",s1,lnpijopii); */
1.126     brouard  1890:        }
1.138     brouard  1891:        ps[i][j]=lnpijopii; /* In fact ln(pij/pii) */
                   1892: /*     printf("s1=%.17e, lnpijopii=%.17e\n",s1,lnpijopii); */
1.126     brouard  1893:       }
                   1894:       for(j=i+1; j<=nlstate+ndeath;j++){
1.138     brouard  1895:        for (nc=1, lnpijopii=0.;nc <=ncovmodel; nc++){
                   1896:          /*lnpijopii += x[(i-1)*nlstate*ncovmodel+(j-2)*ncovmodel+nc+(i-1)*(ndeath-1)*ncovmodel]*cov[nc];*/
                   1897:          lnpijopii += x[nc + ((i-1)*(nlstate+ndeath-1)+(j-2))*ncovmodel]*cov[nc];
                   1898: /*       printf("Int j>i s1=%.17e, lnpijopii=%.17e %lx %lx\n",s1,lnpijopii,s1,lnpijopii); */
1.126     brouard  1899:        }
1.138     brouard  1900:        ps[i][j]=lnpijopii; /* In fact ln(pij/pii) */
1.126     brouard  1901:       }
                   1902:     }
                   1903:     
                   1904:     for(i=1; i<= nlstate; i++){
                   1905:       s1=0;
1.131     brouard  1906:       for(j=1; j<i; j++){
1.138     brouard  1907:        s1+=exp(ps[i][j]); /* In fact sums pij/pii */
1.131     brouard  1908:        /*printf("debug1 %d %d ps=%lf exp(ps)=%lf s1+=%lf\n",i,j,ps[i][j],exp(ps[i][j]),s1); */
                   1909:       }
                   1910:       for(j=i+1; j<=nlstate+ndeath; j++){
1.138     brouard  1911:        s1+=exp(ps[i][j]); /* In fact sums pij/pii */
1.131     brouard  1912:        /*printf("debug2 %d %d ps=%lf exp(ps)=%lf s1+=%lf\n",i,j,ps[i][j],exp(ps[i][j]),s1); */
                   1913:       }
1.138     brouard  1914:       /* s1= sum_{j<>i} pij/pii=(1-pii)/pii and thus pii is known from s1 */
1.126     brouard  1915:       ps[i][i]=1./(s1+1.);
1.138     brouard  1916:       /* Computing other pijs */
1.126     brouard  1917:       for(j=1; j<i; j++)
                   1918:        ps[i][j]= exp(ps[i][j])*ps[i][i];
                   1919:       for(j=i+1; j<=nlstate+ndeath; j++)
                   1920:        ps[i][j]= exp(ps[i][j])*ps[i][i];
                   1921:       /* ps[i][nlstate+1]=1.-s1- ps[i][i];*/ /* Sum should be 1 */
                   1922:     } /* end i */
                   1923:     
                   1924:     for(ii=nlstate+1; ii<= nlstate+ndeath; ii++){
                   1925:       for(jj=1; jj<= nlstate+ndeath; jj++){
                   1926:        ps[ii][jj]=0;
                   1927:        ps[ii][ii]=1;
                   1928:       }
                   1929:     }
                   1930:     
1.145     brouard  1931:     
                   1932:     /* for(ii=1; ii<= nlstate+ndeath; ii++){ */
                   1933:     /*   for(jj=1; jj<= nlstate+ndeath; jj++){ */
                   1934:     /*         printf(" pmij  ps[%d][%d]=%lf ",ii,jj,ps[ii][jj]); */
                   1935:     /*   } */
                   1936:     /*   printf("\n "); */
                   1937:     /* } */
                   1938:     /* printf("\n ");printf("%lf ",cov[2]);*/
                   1939:     /*
1.126     brouard  1940:       for(i=1; i<= npar; i++) printf("%f ",x[i]);
                   1941:       goto end;*/
                   1942:     return ps;
                   1943: }
                   1944: 
                   1945: /**************** Product of 2 matrices ******************/
                   1946: 
1.145     brouard  1947: double **matprod2(double **out, double **in,int nrl, int nrh, int ncl, int nch, int ncolol, int ncoloh, double **b)
1.126     brouard  1948: {
                   1949:   /* Computes the matrix product of in(1,nrh-nrl+1)(1,nch-ncl+1) times
                   1950:      b(1,nch-ncl+1)(1,ncoloh-ncolol+1) into out(...) */
                   1951:   /* in, b, out are matrice of pointers which should have been initialized 
                   1952:      before: only the contents of out is modified. The function returns
                   1953:      a pointer to pointers identical to out */
1.145     brouard  1954:   int i, j, k;
1.126     brouard  1955:   for(i=nrl; i<= nrh; i++)
1.145     brouard  1956:     for(k=ncolol; k<=ncoloh; k++){
                   1957:       out[i][k]=0.;
                   1958:       for(j=ncl; j<=nch; j++)
                   1959:        out[i][k] +=in[i][j]*b[j][k];
                   1960:     }
1.126     brouard  1961:   return out;
                   1962: }
                   1963: 
                   1964: 
                   1965: /************* Higher Matrix Product ***************/
                   1966: 
                   1967: double ***hpxij(double ***po, int nhstepm, double age, int hstepm, double *x, int nlstate, int stepm, double **oldm, double **savm, int ij )
                   1968: {
                   1969:   /* Computes the transition matrix starting at age 'age' over 
                   1970:      'nhstepm*hstepm*stepm' months (i.e. until
                   1971:      age (in years)  age+nhstepm*hstepm*stepm/12) by multiplying 
                   1972:      nhstepm*hstepm matrices. 
                   1973:      Output is stored in matrix po[i][j][h] for h every 'hstepm' step 
                   1974:      (typically every 2 years instead of every month which is too big 
                   1975:      for the memory).
                   1976:      Model is determined by parameters x and covariates have to be 
                   1977:      included manually here. 
                   1978: 
                   1979:      */
                   1980: 
                   1981:   int i, j, d, h, k;
1.131     brouard  1982:   double **out, cov[NCOVMAX+1];
1.126     brouard  1983:   double **newm;
1.187     brouard  1984:   double agexact;
1.126     brouard  1985: 
                   1986:   /* Hstepm could be zero and should return the unit matrix */
                   1987:   for (i=1;i<=nlstate+ndeath;i++)
                   1988:     for (j=1;j<=nlstate+ndeath;j++){
                   1989:       oldm[i][j]=(i==j ? 1.0 : 0.0);
                   1990:       po[i][j][0]=(i==j ? 1.0 : 0.0);
                   1991:     }
                   1992:   /* Even if hstepm = 1, at least one multiplication by the unit matrix */
                   1993:   for(h=1; h <=nhstepm; h++){
                   1994:     for(d=1; d <=hstepm; d++){
                   1995:       newm=savm;
                   1996:       /* Covariates have to be included here again */
                   1997:       cov[1]=1.;
1.187     brouard  1998:       agexact=age+((h-1)*hstepm + (d-1))*stepm/YEARM;
                   1999:       cov[2]=agexact;
                   2000:       if(nagesqr==1)
                   2001:        cov[3]= agexact*agexact;
1.131     brouard  2002:       for (k=1; k<=cptcovn;k++) 
1.187     brouard  2003:        cov[2+nagesqr+k]=nbcode[Tvar[k]][codtab[ij][Tvar[k]]];
1.186     brouard  2004:       for (k=1; k<=cptcovage;k++) /* Should start at cptcovn+1 */
                   2005:        /* cov[2+Tage[k]]=cov[2+Tage[k]]*cov[2]; */
1.187     brouard  2006:        cov[2+nagesqr+Tage[k]]=nbcode[Tvar[Tage[k]]][codtab[ij][Tvar[Tage[k]]]]*cov[2];
1.145     brouard  2007:       for (k=1; k<=cptcovprod;k++) /* Useless because included in cptcovn */
1.187     brouard  2008:        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  2009: 
                   2010: 
                   2011:       /*printf("hxi cptcov=%d cptcode=%d\n",cptcov,cptcode);*/
                   2012:       /*printf("h=%d d=%d age=%f cov=%f\n",h,d,age,cov[2]);*/
                   2013:       out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, 
                   2014:                   pmij(pmmij,cov,ncovmodel,x,nlstate));
                   2015:       savm=oldm;
                   2016:       oldm=newm;
                   2017:     }
                   2018:     for(i=1; i<=nlstate+ndeath; i++)
                   2019:       for(j=1;j<=nlstate+ndeath;j++) {
                   2020:        po[i][j][h]=newm[i][j];
1.128     brouard  2021:        /*if(h==nhstepm) printf("po[%d][%d][%d]=%f ",i,j,h,po[i][j][h]);*/
1.126     brouard  2022:       }
1.128     brouard  2023:     /*printf("h=%d ",h);*/
1.126     brouard  2024:   } /* end h */
1.128     brouard  2025: /*     printf("\n H=%d \n",h); */
1.126     brouard  2026:   return po;
                   2027: }
                   2028: 
1.162     brouard  2029: #ifdef NLOPT
                   2030:   double  myfunc(unsigned n, const double *p1, double *grad, void *pd){
                   2031:   double fret;
                   2032:   double *xt;
                   2033:   int j;
                   2034:   myfunc_data *d2 = (myfunc_data *) pd;
                   2035: /* xt = (p1-1); */
                   2036:   xt=vector(1,n); 
                   2037:   for (j=1;j<=n;j++)   xt[j]=p1[j-1]; /* xt[1]=p1[0] */
                   2038: 
                   2039:   fret=(d2->function)(xt); /*  p xt[1]@8 is fine */
                   2040:   /* fret=(*func)(xt); /\*  p xt[1]@8 is fine *\/ */
                   2041:   printf("Function = %.12lf ",fret);
                   2042:   for (j=1;j<=n;j++) printf(" %d %.8lf", j, xt[j]); 
                   2043:   printf("\n");
                   2044:  free_vector(xt,1,n);
                   2045:   return fret;
                   2046: }
                   2047: #endif
1.126     brouard  2048: 
                   2049: /*************** log-likelihood *************/
                   2050: double func( double *x)
                   2051: {
                   2052:   int i, ii, j, k, mi, d, kk;
1.131     brouard  2053:   double l, ll[NLSTATEMAX+1], cov[NCOVMAX+1];
1.126     brouard  2054:   double **out;
                   2055:   double sw; /* Sum of weights */
                   2056:   double lli; /* Individual log likelihood */
                   2057:   int s1, s2;
                   2058:   double bbh, survp;
                   2059:   long ipmx;
1.187     brouard  2060:   double agexact;
1.126     brouard  2061:   /*extern weight */
                   2062:   /* We are differentiating ll according to initial status */
                   2063:   /*  for (i=1;i<=npar;i++) printf("%f ", x[i]);*/
                   2064:   /*for(i=1;i<imx;i++) 
                   2065:     printf(" %d\n",s[4][i]);
                   2066:   */
1.162     brouard  2067: 
                   2068:   ++countcallfunc;
                   2069: 
1.126     brouard  2070:   cov[1]=1.;
                   2071: 
                   2072:   for(k=1; k<=nlstate; k++) ll[k]=0.;
                   2073: 
                   2074:   if(mle==1){
                   2075:     for (i=1,ipmx=0, sw=0.; i<=imx; i++){
1.138     brouard  2076:       /* Computes the values of the ncovmodel covariates of the model
                   2077:         depending if the covariates are fixed or variying (age dependent) and stores them in cov[]
                   2078:         Then computes with function pmij which return a matrix p[i][j] giving the elementary probability
                   2079:         to be observed in j being in i according to the model.
                   2080:        */
1.145     brouard  2081:       for (k=1; k<=cptcovn;k++){ /* Simple and product covariates without age* products */
1.187     brouard  2082:          cov[2+nagesqr+k]=covar[Tvar[k]][i];
1.145     brouard  2083:       }
1.137     brouard  2084:       /* In model V2+V1*V4+age*V3+V3*V2 Tvar[1] is V2, Tvar[2=V1*V4] 
1.138     brouard  2085:         is 6, Tvar[3=age*V3] should not be computed because of age Tvar[4=V3*V2] 
1.137     brouard  2086:         has been calculated etc */
1.126     brouard  2087:       for(mi=1; mi<= wav[i]-1; mi++){
                   2088:        for (ii=1;ii<=nlstate+ndeath;ii++)
                   2089:          for (j=1;j<=nlstate+ndeath;j++){
                   2090:            oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   2091:            savm[ii][j]=(ii==j ? 1.0 : 0.0);
                   2092:          }
                   2093:        for(d=0; d<dh[mi][i]; d++){
                   2094:          newm=savm;
1.187     brouard  2095:          agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;
                   2096:          cov[2]=agexact;
                   2097:          if(nagesqr==1)
                   2098:            cov[3]= agexact*agexact;
1.126     brouard  2099:          for (kk=1; kk<=cptcovage;kk++) {
1.187     brouard  2100:            cov[Tage[kk]+2+nagesqr]=covar[Tvar[Tage[kk]]][i]*agexact; /* Tage[kk] gives the data-covariate associated with age */
1.126     brouard  2101:          }
                   2102:          out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
                   2103:                       1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
                   2104:          savm=oldm;
                   2105:          oldm=newm;
                   2106:        } /* end mult */
                   2107:       
                   2108:        /*lli=log(out[s[mw[mi][i]][i]][s[mw[mi+1][i]][i]]);*/ /* Original formula */
                   2109:        /* But now since version 0.9 we anticipate for bias at large stepm.
                   2110:         * If stepm is larger than one month (smallest stepm) and if the exact delay 
                   2111:         * (in months) between two waves is not a multiple of stepm, we rounded to 
                   2112:         * the nearest (and in case of equal distance, to the lowest) interval but now
                   2113:         * we keep into memory the bias bh[mi][i] and also the previous matrix product
                   2114:         * (i.e to dh[mi][i]-1) saved in 'savm'. Then we inter(extra)polate the
                   2115:         * probability in order to take into account the bias as a fraction of the way
                   2116:         * from savm to out if bh is negative or even beyond if bh is positive. bh varies
                   2117:         * -stepm/2 to stepm/2 .
                   2118:         * For stepm=1 the results are the same as for previous versions of Imach.
                   2119:         * For stepm > 1 the results are less biased than in previous versions. 
                   2120:         */
                   2121:        s1=s[mw[mi][i]][i];
                   2122:        s2=s[mw[mi+1][i]][i];
                   2123:        bbh=(double)bh[mi][i]/(double)stepm; 
                   2124:        /* bias bh is positive if real duration
                   2125:         * is higher than the multiple of stepm and negative otherwise.
                   2126:         */
                   2127:        /* lli= (savm[s1][s2]>1.e-8 ?(1.+bbh)*log(out[s1][s2])- bbh*log(savm[s1][s2]):log((1.+bbh)*out[s1][s2]));*/
                   2128:        if( s2 > nlstate){ 
                   2129:          /* i.e. if s2 is a death state and if the date of death is known 
                   2130:             then the contribution to the likelihood is the probability to 
                   2131:             die between last step unit time and current  step unit time, 
                   2132:             which is also equal to probability to die before dh 
                   2133:             minus probability to die before dh-stepm . 
                   2134:             In version up to 0.92 likelihood was computed
                   2135:        as if date of death was unknown. Death was treated as any other
                   2136:        health state: the date of the interview describes the actual state
                   2137:        and not the date of a change in health state. The former idea was
                   2138:        to consider that at each interview the state was recorded
                   2139:        (healthy, disable or death) and IMaCh was corrected; but when we
                   2140:        introduced the exact date of death then we should have modified
                   2141:        the contribution of an exact death to the likelihood. This new
                   2142:        contribution is smaller and very dependent of the step unit
                   2143:        stepm. It is no more the probability to die between last interview
                   2144:        and month of death but the probability to survive from last
                   2145:        interview up to one month before death multiplied by the
                   2146:        probability to die within a month. Thanks to Chris
                   2147:        Jackson for correcting this bug.  Former versions increased
                   2148:        mortality artificially. The bad side is that we add another loop
                   2149:        which slows down the processing. The difference can be up to 10%
                   2150:        lower mortality.
                   2151:          */
1.183     brouard  2152:        /* If, at the beginning of the maximization mostly, the
                   2153:           cumulative probability or probability to be dead is
                   2154:           constant (ie = 1) over time d, the difference is equal to
                   2155:           0.  out[s1][3] = savm[s1][3]: probability, being at state
                   2156:           s1 at precedent wave, to be dead a month before current
                   2157:           wave is equal to probability, being at state s1 at
                   2158:           precedent wave, to be dead at mont of the current
                   2159:           wave. Then the observed probability (that this person died)
                   2160:           is null according to current estimated parameter. In fact,
                   2161:           it should be very low but not zero otherwise the log go to
                   2162:           infinity.
                   2163:        */
                   2164: /* #ifdef INFINITYORIGINAL */
                   2165: /*         lli=log(out[s1][s2] - savm[s1][s2]); */
                   2166: /* #else */
                   2167: /*       if ((out[s1][s2] - savm[s1][s2]) < mytinydouble)  */
                   2168: /*         lli=log(mytinydouble); */
                   2169: /*       else */
                   2170: /*         lli=log(out[s1][s2] - savm[s1][s2]); */
                   2171: /* #endif */
                   2172:            lli=log(out[s1][s2] - savm[s1][s2]);
1.126     brouard  2173: 
                   2174:        } else if  (s2==-2) {
                   2175:          for (j=1,survp=0. ; j<=nlstate; j++) 
                   2176:            survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j];
                   2177:          /*survp += out[s1][j]; */
                   2178:          lli= log(survp);
                   2179:        }
                   2180:        
                   2181:        else if  (s2==-4) { 
                   2182:          for (j=3,survp=0. ; j<=nlstate; j++)  
                   2183:            survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j];
                   2184:          lli= log(survp); 
                   2185:        } 
                   2186: 
                   2187:        else if  (s2==-5) { 
                   2188:          for (j=1,survp=0. ; j<=2; j++)  
                   2189:            survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j];
                   2190:          lli= log(survp); 
                   2191:        } 
                   2192:        
                   2193:        else{
                   2194:          lli= log((1.+bbh)*out[s1][s2]- bbh*savm[s1][s2]); /* linear interpolation */
                   2195:          /*  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 */
                   2196:        } 
                   2197:        /*lli=(1.+bbh)*log(out[s1][s2])- bbh*log(savm[s1][s2]);*/
                   2198:        /*if(lli ==000.0)*/
                   2199:        /*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); */
                   2200:        ipmx +=1;
                   2201:        sw += weight[i];
                   2202:        ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
1.183     brouard  2203:        /* if (lli < log(mytinydouble)){ */
                   2204:        /*   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); */
                   2205:        /*   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]); */
                   2206:        /* } */
1.126     brouard  2207:       } /* end of wave */
                   2208:     } /* end of individual */
                   2209:   }  else if(mle==2){
                   2210:     for (i=1,ipmx=0, sw=0.; i<=imx; i++){
1.187     brouard  2211:       for (k=1; k<=cptcovn;k++) cov[2+nagesqr+k]=covar[Tvar[k]][i];
1.126     brouard  2212:       for(mi=1; mi<= wav[i]-1; mi++){
                   2213:        for (ii=1;ii<=nlstate+ndeath;ii++)
                   2214:          for (j=1;j<=nlstate+ndeath;j++){
                   2215:            oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   2216:            savm[ii][j]=(ii==j ? 1.0 : 0.0);
                   2217:          }
                   2218:        for(d=0; d<=dh[mi][i]; d++){
                   2219:          newm=savm;
1.187     brouard  2220:          agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;
                   2221:          cov[2]=agexact;
                   2222:          if(nagesqr==1)
                   2223:            cov[3]= agexact*agexact;
1.126     brouard  2224:          for (kk=1; kk<=cptcovage;kk++) {
1.187     brouard  2225:            cov[Tage[kk]+2+nagesqr]=covar[Tvar[Tage[kk]]][i]*agexact;
1.126     brouard  2226:          }
                   2227:          out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
                   2228:                       1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
                   2229:          savm=oldm;
                   2230:          oldm=newm;
                   2231:        } /* end mult */
                   2232:       
                   2233:        s1=s[mw[mi][i]][i];
                   2234:        s2=s[mw[mi+1][i]][i];
                   2235:        bbh=(double)bh[mi][i]/(double)stepm; 
                   2236:        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 */
                   2237:        ipmx +=1;
                   2238:        sw += weight[i];
                   2239:        ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
                   2240:       } /* end of wave */
                   2241:     } /* end of individual */
                   2242:   }  else if(mle==3){  /* exponential inter-extrapolation */
                   2243:     for (i=1,ipmx=0, sw=0.; i<=imx; i++){
1.187     brouard  2244:       for (k=1; k<=cptcovn;k++) cov[2+nagesqr+k]=covar[Tvar[k]][i];
1.126     brouard  2245:       for(mi=1; mi<= wav[i]-1; mi++){
                   2246:        for (ii=1;ii<=nlstate+ndeath;ii++)
                   2247:          for (j=1;j<=nlstate+ndeath;j++){
                   2248:            oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   2249:            savm[ii][j]=(ii==j ? 1.0 : 0.0);
                   2250:          }
                   2251:        for(d=0; d<dh[mi][i]; d++){
                   2252:          newm=savm;
1.187     brouard  2253:          agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;
                   2254:          cov[2]=agexact;
                   2255:          if(nagesqr==1)
                   2256:            cov[3]= agexact*agexact;
1.126     brouard  2257:          for (kk=1; kk<=cptcovage;kk++) {
1.187     brouard  2258:            cov[Tage[kk]+2+nagesqr]=covar[Tvar[Tage[kk]]][i]*agexact;
1.126     brouard  2259:          }
                   2260:          out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
                   2261:                       1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
                   2262:          savm=oldm;
                   2263:          oldm=newm;
                   2264:        } /* end mult */
                   2265:       
                   2266:        s1=s[mw[mi][i]][i];
                   2267:        s2=s[mw[mi+1][i]][i];
                   2268:        bbh=(double)bh[mi][i]/(double)stepm; 
                   2269:        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 */
                   2270:        ipmx +=1;
                   2271:        sw += weight[i];
                   2272:        ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
                   2273:       } /* end of wave */
                   2274:     } /* end of individual */
                   2275:   }else if (mle==4){  /* ml=4 no inter-extrapolation */
                   2276:     for (i=1,ipmx=0, sw=0.; i<=imx; i++){
1.187     brouard  2277:       for (k=1; k<=cptcovn;k++) cov[2+nagesqr+k]=covar[Tvar[k]][i];
1.126     brouard  2278:       for(mi=1; mi<= wav[i]-1; mi++){
                   2279:        for (ii=1;ii<=nlstate+ndeath;ii++)
                   2280:          for (j=1;j<=nlstate+ndeath;j++){
                   2281:            oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   2282:            savm[ii][j]=(ii==j ? 1.0 : 0.0);
                   2283:          }
                   2284:        for(d=0; d<dh[mi][i]; d++){
                   2285:          newm=savm;
1.187     brouard  2286:          agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;
                   2287:          cov[2]=agexact;
                   2288:          if(nagesqr==1)
                   2289:            cov[3]= agexact*agexact;
1.126     brouard  2290:          for (kk=1; kk<=cptcovage;kk++) {
1.187     brouard  2291:            cov[Tage[kk]+2+nagesqr]=covar[Tvar[Tage[kk]]][i]*agexact;
1.126     brouard  2292:          }
                   2293:        
                   2294:          out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
                   2295:                       1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
                   2296:          savm=oldm;
                   2297:          oldm=newm;
                   2298:        } /* end mult */
                   2299:       
                   2300:        s1=s[mw[mi][i]][i];
                   2301:        s2=s[mw[mi+1][i]][i];
                   2302:        if( s2 > nlstate){ 
                   2303:          lli=log(out[s1][s2] - savm[s1][s2]);
                   2304:        }else{
                   2305:          lli=log(out[s[mw[mi][i]][i]][s[mw[mi+1][i]][i]]); /* Original formula */
                   2306:        }
                   2307:        ipmx +=1;
                   2308:        sw += weight[i];
                   2309:        ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
                   2310: /*     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]); */
                   2311:       } /* end of wave */
                   2312:     } /* end of individual */
                   2313:   }else{  /* ml=5 no inter-extrapolation no jackson =0.8a */
                   2314:     for (i=1,ipmx=0, sw=0.; i<=imx; i++){
1.187     brouard  2315:       for (k=1; k<=cptcovn;k++) cov[2+nagesqr+k]=covar[Tvar[k]][i];
1.126     brouard  2316:       for(mi=1; mi<= wav[i]-1; mi++){
                   2317:        for (ii=1;ii<=nlstate+ndeath;ii++)
                   2318:          for (j=1;j<=nlstate+ndeath;j++){
                   2319:            oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   2320:            savm[ii][j]=(ii==j ? 1.0 : 0.0);
                   2321:          }
                   2322:        for(d=0; d<dh[mi][i]; d++){
                   2323:          newm=savm;
1.187     brouard  2324:          agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;
                   2325:          cov[2]=agexact;
                   2326:          if(nagesqr==1)
                   2327:            cov[3]= agexact*agexact;
1.126     brouard  2328:          for (kk=1; kk<=cptcovage;kk++) {
1.187     brouard  2329:            cov[Tage[kk]+2+nagesqr]=covar[Tvar[Tage[kk]]][i]*agexact;
1.126     brouard  2330:          }
                   2331:        
                   2332:          out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
                   2333:                       1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
                   2334:          savm=oldm;
                   2335:          oldm=newm;
                   2336:        } /* end mult */
                   2337:       
                   2338:        s1=s[mw[mi][i]][i];
                   2339:        s2=s[mw[mi+1][i]][i];
                   2340:        lli=log(out[s[mw[mi][i]][i]][s[mw[mi+1][i]][i]]); /* Original formula */
                   2341:        ipmx +=1;
                   2342:        sw += weight[i];
                   2343:        ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
                   2344:        /*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]);*/
                   2345:       } /* end of wave */
                   2346:     } /* end of individual */
                   2347:   } /* End of if */
                   2348:   for(k=1,l=0.; k<=nlstate; k++) l += ll[k];
                   2349:   /* printf("l1=%f l2=%f ",ll[1],ll[2]); */
                   2350:   l= l*ipmx/sw; /* To get the same order of magnitude as if weight=1 for every body */
                   2351:   return -l;
                   2352: }
                   2353: 
                   2354: /*************** log-likelihood *************/
                   2355: double funcone( double *x)
                   2356: {
                   2357:   /* Same as likeli but slower because of a lot of printf and if */
                   2358:   int i, ii, j, k, mi, d, kk;
1.131     brouard  2359:   double l, ll[NLSTATEMAX+1], cov[NCOVMAX+1];
1.126     brouard  2360:   double **out;
                   2361:   double lli; /* Individual log likelihood */
                   2362:   double llt;
                   2363:   int s1, s2;
                   2364:   double bbh, survp;
1.187     brouard  2365:   double agexact;
1.126     brouard  2366:   /*extern weight */
                   2367:   /* We are differentiating ll according to initial status */
                   2368:   /*  for (i=1;i<=npar;i++) printf("%f ", x[i]);*/
                   2369:   /*for(i=1;i<imx;i++) 
                   2370:     printf(" %d\n",s[4][i]);
                   2371:   */
                   2372:   cov[1]=1.;
                   2373: 
                   2374:   for(k=1; k<=nlstate; k++) ll[k]=0.;
                   2375: 
                   2376:   for (i=1,ipmx=0, sw=0.; i<=imx; i++){
1.187     brouard  2377:     for (k=1; k<=cptcovn;k++) cov[2+nagesqr+k]=covar[Tvar[k]][i];
1.126     brouard  2378:     for(mi=1; mi<= wav[i]-1; mi++){
                   2379:       for (ii=1;ii<=nlstate+ndeath;ii++)
                   2380:        for (j=1;j<=nlstate+ndeath;j++){
                   2381:          oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   2382:          savm[ii][j]=(ii==j ? 1.0 : 0.0);
                   2383:        }
                   2384:       for(d=0; d<dh[mi][i]; d++){
                   2385:        newm=savm;
1.187     brouard  2386:        agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;
                   2387:        cov[2]=agexact;
                   2388:        if(nagesqr==1)
                   2389:          cov[3]= agexact*agexact;
1.126     brouard  2390:        for (kk=1; kk<=cptcovage;kk++) {
1.187     brouard  2391:          cov[Tage[kk]+2+nagesqr]=covar[Tvar[Tage[kk]]][i]*agexact;
1.126     brouard  2392:        }
1.187     brouard  2393: 
1.145     brouard  2394:        /* savm=pmij(pmmij,cov,ncovmodel,x,nlstate); */
1.126     brouard  2395:        out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
                   2396:                     1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
1.145     brouard  2397:        /* out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath, */
                   2398:        /*           1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate)); */
1.126     brouard  2399:        savm=oldm;
                   2400:        oldm=newm;
                   2401:       } /* end mult */
                   2402:       
                   2403:       s1=s[mw[mi][i]][i];
                   2404:       s2=s[mw[mi+1][i]][i];
                   2405:       bbh=(double)bh[mi][i]/(double)stepm; 
                   2406:       /* bias is positive if real duration
                   2407:        * is higher than the multiple of stepm and negative otherwise.
                   2408:        */
                   2409:       if( s2 > nlstate && (mle <5) ){  /* Jackson */
                   2410:        lli=log(out[s1][s2] - savm[s1][s2]);
                   2411:       } else if  (s2==-2) {
                   2412:        for (j=1,survp=0. ; j<=nlstate; j++) 
                   2413:          survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j];
                   2414:        lli= log(survp);
                   2415:       }else if (mle==1){
                   2416:        lli= log((1.+bbh)*out[s1][s2]- bbh*savm[s1][s2]); /* linear interpolation */
                   2417:       } else if(mle==2){
                   2418:        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 */
                   2419:       } else if(mle==3){  /* exponential inter-extrapolation */
                   2420:        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 */
                   2421:       } else if (mle==4){  /* mle=4 no inter-extrapolation */
                   2422:        lli=log(out[s1][s2]); /* Original formula */
1.136     brouard  2423:       } else{  /* mle=0 back to 1 */
                   2424:        lli= log((1.+bbh)*out[s1][s2]- bbh*savm[s1][s2]); /* linear interpolation */
                   2425:        /*lli=log(out[s1][s2]); */ /* Original formula */
1.126     brouard  2426:       } /* End of if */
                   2427:       ipmx +=1;
                   2428:       sw += weight[i];
                   2429:       ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
1.132     brouard  2430:       /*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  2431:       if(globpr){
1.141     brouard  2432:        fprintf(ficresilk,"%9ld %6d %2d %2d %1d %1d %3d %11.6f %8.4f\
1.126     brouard  2433:  %11.6f %11.6f %11.6f ", \
                   2434:                num[i],i,s1,s2,mi,mw[mi][i],dh[mi][i],exp(lli),weight[i],
                   2435:                2*weight[i]*lli,out[s1][s2],savm[s1][s2]);
                   2436:        for(k=1,llt=0.,l=0.; k<=nlstate; k++){
                   2437:          llt +=ll[k]*gipmx/gsw;
                   2438:          fprintf(ficresilk," %10.6f",-ll[k]*gipmx/gsw);
                   2439:        }
                   2440:        fprintf(ficresilk," %10.6f\n", -llt);
                   2441:       }
                   2442:     } /* end of wave */
                   2443:   } /* end of individual */
                   2444:   for(k=1,l=0.; k<=nlstate; k++) l += ll[k];
                   2445:   /* printf("l1=%f l2=%f ",ll[1],ll[2]); */
                   2446:   l= l*ipmx/sw; /* To get the same order of magnitude as if weight=1 for every body */
                   2447:   if(globpr==0){ /* First time we count the contributions and weights */
                   2448:     gipmx=ipmx;
                   2449:     gsw=sw;
                   2450:   }
                   2451:   return -l;
                   2452: }
                   2453: 
                   2454: 
                   2455: /*************** function likelione ***********/
                   2456: void likelione(FILE *ficres,double p[], int npar, int nlstate, int *globpri, long *ipmx, double *sw, double *fretone, double (*funcone)(double []))
                   2457: {
                   2458:   /* This routine should help understanding what is done with 
                   2459:      the selection of individuals/waves and
                   2460:      to check the exact contribution to the likelihood.
                   2461:      Plotting could be done.
                   2462:    */
                   2463:   int k;
                   2464: 
                   2465:   if(*globpri !=0){ /* Just counts and sums, no printings */
                   2466:     strcpy(fileresilk,"ilk"); 
                   2467:     strcat(fileresilk,fileres);
                   2468:     if((ficresilk=fopen(fileresilk,"w"))==NULL) {
                   2469:       printf("Problem with resultfile: %s\n", fileresilk);
                   2470:       fprintf(ficlog,"Problem with resultfile: %s\n", fileresilk);
                   2471:     }
                   2472:     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");
                   2473:     fprintf(ficresilk, "#num_i i s1 s2 mi mw dh likeli weight 2wlli out sav ");
                   2474:     /*         i,s1,s2,mi,mw[mi][i],dh[mi][i],exp(lli),weight[i],2*weight[i]*lli,out[s1][s2],savm[s1][s2]); */
                   2475:     for(k=1; k<=nlstate; k++) 
                   2476:       fprintf(ficresilk," -2*gipw/gsw*weight*ll[%d]++",k);
                   2477:     fprintf(ficresilk," -2*gipw/gsw*weight*ll(total)\n");
                   2478:   }
                   2479: 
                   2480:   *fretone=(*funcone)(p);
                   2481:   if(*globpri !=0){
                   2482:     fclose(ficresilk);
                   2483:     fprintf(fichtm,"\n<br>File of contributions to the likelihood: <a href=\"%s\">%s</a><br>\n",subdirf(fileresilk),subdirf(fileresilk));
                   2484:     fflush(fichtm); 
                   2485:   } 
                   2486:   return;
                   2487: }
                   2488: 
                   2489: 
                   2490: /*********** Maximum Likelihood Estimation ***************/
                   2491: 
                   2492: void mlikeli(FILE *ficres,double p[], int npar, int ncovmodel, int nlstate, double ftol, double (*func)(double []))
                   2493: {
1.165     brouard  2494:   int i,j, iter=0;
1.126     brouard  2495:   double **xi;
                   2496:   double fret;
                   2497:   double fretone; /* Only one call to likelihood */
                   2498:   /*  char filerespow[FILENAMELENGTH];*/
1.162     brouard  2499: 
                   2500: #ifdef NLOPT
                   2501:   int creturn;
                   2502:   nlopt_opt opt;
                   2503:   /* double lb[9] = { -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL }; /\* lower bounds *\/ */
                   2504:   double *lb;
                   2505:   double minf; /* the minimum objective value, upon return */
                   2506:   double * p1; /* Shifted parameters from 0 instead of 1 */
                   2507:   myfunc_data dinst, *d = &dinst;
                   2508: #endif
                   2509: 
                   2510: 
1.126     brouard  2511:   xi=matrix(1,npar,1,npar);
                   2512:   for (i=1;i<=npar;i++)
                   2513:     for (j=1;j<=npar;j++)
                   2514:       xi[i][j]=(i==j ? 1.0 : 0.0);
                   2515:   printf("Powell\n");  fprintf(ficlog,"Powell\n");
                   2516:   strcpy(filerespow,"pow"); 
                   2517:   strcat(filerespow,fileres);
                   2518:   if((ficrespow=fopen(filerespow,"w"))==NULL) {
                   2519:     printf("Problem with resultfile: %s\n", filerespow);
                   2520:     fprintf(ficlog,"Problem with resultfile: %s\n", filerespow);
                   2521:   }
                   2522:   fprintf(ficrespow,"# Powell\n# iter -2*LL");
                   2523:   for (i=1;i<=nlstate;i++)
                   2524:     for(j=1;j<=nlstate+ndeath;j++)
                   2525:       if(j!=i)fprintf(ficrespow," p%1d%1d",i,j);
                   2526:   fprintf(ficrespow,"\n");
1.162     brouard  2527: #ifdef POWELL
1.126     brouard  2528:   powell(p,xi,npar,ftol,&iter,&fret,func);
1.162     brouard  2529: #endif
1.126     brouard  2530: 
1.162     brouard  2531: #ifdef NLOPT
                   2532: #ifdef NEWUOA
                   2533:   opt = nlopt_create(NLOPT_LN_NEWUOA,npar);
                   2534: #else
                   2535:   opt = nlopt_create(NLOPT_LN_BOBYQA,npar);
                   2536: #endif
                   2537:   lb=vector(0,npar-1);
                   2538:   for (i=0;i<npar;i++) lb[i]= -HUGE_VAL;
                   2539:   nlopt_set_lower_bounds(opt, lb);
                   2540:   nlopt_set_initial_step1(opt, 0.1);
                   2541:   
                   2542:   p1= (p+1); /*  p *(p+1)@8 and p *(p1)@8 are equal p1[0]=p[1] */
                   2543:   d->function = func;
                   2544:   printf(" Func %.12lf \n",myfunc(npar,p1,NULL,d));
                   2545:   nlopt_set_min_objective(opt, myfunc, d);
                   2546:   nlopt_set_xtol_rel(opt, ftol);
                   2547:   if ((creturn=nlopt_optimize(opt, p1, &minf)) < 0) {
                   2548:     printf("nlopt failed! %d\n",creturn); 
                   2549:   }
                   2550:   else {
                   2551:     printf("found minimum after %d evaluations (NLOPT=%d)\n", countcallfunc ,NLOPT);
                   2552:     printf("found minimum at f(%g,%g) = %0.10g\n", p[0], p[1], minf);
                   2553:     iter=1; /* not equal */
                   2554:   }
                   2555:   nlopt_destroy(opt);
                   2556: #endif
1.126     brouard  2557:   free_matrix(xi,1,npar,1,npar);
                   2558:   fclose(ficrespow);
1.180     brouard  2559:   printf("#Number of iterations & function calls = %d & %d, -2 Log likelihood = %.12f\n",iter, countcallfunc,func(p));
                   2560:   fprintf(ficlog,"#Number of iterations & function calls = %d & %d, -2 Log likelihood = %.12f\n",iter, countcallfunc,func(p));
                   2561:   fprintf(ficres,"#Number of iterations & function calls = %d & %d, -2 Log likelihood = %.12f\n",iter, countcallfunc,func(p));
1.126     brouard  2562: 
                   2563: }
                   2564: 
                   2565: /**** Computes Hessian and covariance matrix ***/
                   2566: void hesscov(double **matcov, double p[], int npar, double delti[], double ftolhess, double (*func)(double []))
                   2567: {
                   2568:   double  **a,**y,*x,pd;
                   2569:   double **hess;
1.164     brouard  2570:   int i, j;
1.126     brouard  2571:   int *indx;
                   2572: 
                   2573:   double hessii(double p[], double delta, int theta, double delti[],double (*func)(double []),int npar);
                   2574:   double hessij(double p[], double delti[], int i, int j,double (*func)(double []),int npar);
                   2575:   void lubksb(double **a, int npar, int *indx, double b[]) ;
                   2576:   void ludcmp(double **a, int npar, int *indx, double *d) ;
                   2577:   double gompertz(double p[]);
                   2578:   hess=matrix(1,npar,1,npar);
                   2579: 
                   2580:   printf("\nCalculation of the hessian matrix. Wait...\n");
                   2581:   fprintf(ficlog,"\nCalculation of the hessian matrix. Wait...\n");
                   2582:   for (i=1;i<=npar;i++){
                   2583:     printf("%d",i);fflush(stdout);
                   2584:     fprintf(ficlog,"%d",i);fflush(ficlog);
                   2585:    
                   2586:      hess[i][i]=hessii(p,ftolhess,i,delti,func,npar);
                   2587:     
                   2588:     /*  printf(" %f ",p[i]);
                   2589:        printf(" %lf %lf %lf",hess[i][i],ftolhess,delti[i]);*/
                   2590:   }
                   2591:   
                   2592:   for (i=1;i<=npar;i++) {
                   2593:     for (j=1;j<=npar;j++)  {
                   2594:       if (j>i) { 
                   2595:        printf(".%d%d",i,j);fflush(stdout);
                   2596:        fprintf(ficlog,".%d%d",i,j);fflush(ficlog);
                   2597:        hess[i][j]=hessij(p,delti,i,j,func,npar);
                   2598:        
                   2599:        hess[j][i]=hess[i][j];    
                   2600:        /*printf(" %lf ",hess[i][j]);*/
                   2601:       }
                   2602:     }
                   2603:   }
                   2604:   printf("\n");
                   2605:   fprintf(ficlog,"\n");
                   2606: 
                   2607:   printf("\nInverting the hessian to get the covariance matrix. Wait...\n");
                   2608:   fprintf(ficlog,"\nInverting the hessian to get the covariance matrix. Wait...\n");
                   2609:   
                   2610:   a=matrix(1,npar,1,npar);
                   2611:   y=matrix(1,npar,1,npar);
                   2612:   x=vector(1,npar);
                   2613:   indx=ivector(1,npar);
                   2614:   for (i=1;i<=npar;i++)
                   2615:     for (j=1;j<=npar;j++) a[i][j]=hess[i][j];
                   2616:   ludcmp(a,npar,indx,&pd);
                   2617: 
                   2618:   for (j=1;j<=npar;j++) {
                   2619:     for (i=1;i<=npar;i++) x[i]=0;
                   2620:     x[j]=1;
                   2621:     lubksb(a,npar,indx,x);
                   2622:     for (i=1;i<=npar;i++){ 
                   2623:       matcov[i][j]=x[i];
                   2624:     }
                   2625:   }
                   2626: 
                   2627:   printf("\n#Hessian matrix#\n");
                   2628:   fprintf(ficlog,"\n#Hessian matrix#\n");
                   2629:   for (i=1;i<=npar;i++) { 
                   2630:     for (j=1;j<=npar;j++) { 
                   2631:       printf("%.3e ",hess[i][j]);
                   2632:       fprintf(ficlog,"%.3e ",hess[i][j]);
                   2633:     }
                   2634:     printf("\n");
                   2635:     fprintf(ficlog,"\n");
                   2636:   }
                   2637: 
                   2638:   /* Recompute Inverse */
                   2639:   for (i=1;i<=npar;i++)
                   2640:     for (j=1;j<=npar;j++) a[i][j]=matcov[i][j];
                   2641:   ludcmp(a,npar,indx,&pd);
                   2642: 
                   2643:   /*  printf("\n#Hessian matrix recomputed#\n");
                   2644: 
                   2645:   for (j=1;j<=npar;j++) {
                   2646:     for (i=1;i<=npar;i++) x[i]=0;
                   2647:     x[j]=1;
                   2648:     lubksb(a,npar,indx,x);
                   2649:     for (i=1;i<=npar;i++){ 
                   2650:       y[i][j]=x[i];
                   2651:       printf("%.3e ",y[i][j]);
                   2652:       fprintf(ficlog,"%.3e ",y[i][j]);
                   2653:     }
                   2654:     printf("\n");
                   2655:     fprintf(ficlog,"\n");
                   2656:   }
                   2657:   */
                   2658: 
                   2659:   free_matrix(a,1,npar,1,npar);
                   2660:   free_matrix(y,1,npar,1,npar);
                   2661:   free_vector(x,1,npar);
                   2662:   free_ivector(indx,1,npar);
                   2663:   free_matrix(hess,1,npar,1,npar);
                   2664: 
                   2665: 
                   2666: }
                   2667: 
                   2668: /*************** hessian matrix ****************/
                   2669: double hessii(double x[], double delta, int theta, double delti[], double (*func)(double []), int npar)
                   2670: {
                   2671:   int i;
                   2672:   int l=1, lmax=20;
                   2673:   double k1,k2;
1.132     brouard  2674:   double p2[MAXPARM+1]; /* identical to x */
1.126     brouard  2675:   double res;
                   2676:   double delt=0.0001, delts, nkhi=10.,nkhif=1., khi=1.e-4;
                   2677:   double fx;
                   2678:   int k=0,kmax=10;
                   2679:   double l1;
                   2680: 
                   2681:   fx=func(x);
                   2682:   for (i=1;i<=npar;i++) p2[i]=x[i];
1.145     brouard  2683:   for(l=0 ; l <=lmax; l++){  /* Enlarging the zone around the Maximum */
1.126     brouard  2684:     l1=pow(10,l);
                   2685:     delts=delt;
                   2686:     for(k=1 ; k <kmax; k=k+1){
                   2687:       delt = delta*(l1*k);
                   2688:       p2[theta]=x[theta] +delt;
1.145     brouard  2689:       k1=func(p2)-fx;   /* Might be negative if too close to the theoretical maximum */
1.126     brouard  2690:       p2[theta]=x[theta]-delt;
                   2691:       k2=func(p2)-fx;
                   2692:       /*res= (k1-2.0*fx+k2)/delt/delt; */
                   2693:       res= (k1+k2)/delt/delt/2.; /* Divided by because L and not 2*L */
                   2694:       
1.132     brouard  2695: #ifdef DEBUGHESS
1.126     brouard  2696:       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);
                   2697:       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);
                   2698: #endif
                   2699:       /*if(fabs(k1-2.0*fx+k2) <1.e-13){ */
                   2700:       if((k1 <khi/nkhi/2.) || (k2 <khi/nkhi/2.)){
                   2701:        k=kmax;
                   2702:       }
                   2703:       else if((k1 >khi/nkhif) || (k2 >khi/nkhif)){ /* Keeps lastvalue before 3.84/2 KHI2 5% 1d.f. */
1.164     brouard  2704:        k=kmax; l=lmax*10;
1.126     brouard  2705:       }
                   2706:       else if((k1 >khi/nkhi) || (k2 >khi/nkhi)){ 
                   2707:        delts=delt;
                   2708:       }
                   2709:     }
                   2710:   }
                   2711:   delti[theta]=delts;
                   2712:   return res; 
                   2713:   
                   2714: }
                   2715: 
                   2716: double hessij( double x[], double delti[], int thetai,int thetaj,double (*func)(double []),int npar)
                   2717: {
                   2718:   int i;
1.164     brouard  2719:   int l=1, lmax=20;
1.126     brouard  2720:   double k1,k2,k3,k4,res,fx;
1.132     brouard  2721:   double p2[MAXPARM+1];
1.126     brouard  2722:   int k;
                   2723: 
                   2724:   fx=func(x);
                   2725:   for (k=1; k<=2; k++) {
                   2726:     for (i=1;i<=npar;i++) p2[i]=x[i];
                   2727:     p2[thetai]=x[thetai]+delti[thetai]/k;
                   2728:     p2[thetaj]=x[thetaj]+delti[thetaj]/k;
                   2729:     k1=func(p2)-fx;
                   2730:   
                   2731:     p2[thetai]=x[thetai]+delti[thetai]/k;
                   2732:     p2[thetaj]=x[thetaj]-delti[thetaj]/k;
                   2733:     k2=func(p2)-fx;
                   2734:   
                   2735:     p2[thetai]=x[thetai]-delti[thetai]/k;
                   2736:     p2[thetaj]=x[thetaj]+delti[thetaj]/k;
                   2737:     k3=func(p2)-fx;
                   2738:   
                   2739:     p2[thetai]=x[thetai]-delti[thetai]/k;
                   2740:     p2[thetaj]=x[thetaj]-delti[thetaj]/k;
                   2741:     k4=func(p2)-fx;
                   2742:     res=(k1-k2-k3+k4)/4.0/delti[thetai]*k/delti[thetaj]*k/2.; /* Because of L not 2*L */
                   2743: #ifdef DEBUG
                   2744:     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);
                   2745:     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);
                   2746: #endif
                   2747:   }
                   2748:   return res;
                   2749: }
                   2750: 
                   2751: /************** Inverse of matrix **************/
                   2752: void ludcmp(double **a, int n, int *indx, double *d) 
                   2753: { 
                   2754:   int i,imax,j,k; 
                   2755:   double big,dum,sum,temp; 
                   2756:   double *vv; 
                   2757:  
                   2758:   vv=vector(1,n); 
                   2759:   *d=1.0; 
                   2760:   for (i=1;i<=n;i++) { 
                   2761:     big=0.0; 
                   2762:     for (j=1;j<=n;j++) 
                   2763:       if ((temp=fabs(a[i][j])) > big) big=temp; 
                   2764:     if (big == 0.0) nrerror("Singular matrix in routine ludcmp"); 
                   2765:     vv[i]=1.0/big; 
                   2766:   } 
                   2767:   for (j=1;j<=n;j++) { 
                   2768:     for (i=1;i<j;i++) { 
                   2769:       sum=a[i][j]; 
                   2770:       for (k=1;k<i;k++) sum -= a[i][k]*a[k][j]; 
                   2771:       a[i][j]=sum; 
                   2772:     } 
                   2773:     big=0.0; 
                   2774:     for (i=j;i<=n;i++) { 
                   2775:       sum=a[i][j]; 
                   2776:       for (k=1;k<j;k++) 
                   2777:        sum -= a[i][k]*a[k][j]; 
                   2778:       a[i][j]=sum; 
                   2779:       if ( (dum=vv[i]*fabs(sum)) >= big) { 
                   2780:        big=dum; 
                   2781:        imax=i; 
                   2782:       } 
                   2783:     } 
                   2784:     if (j != imax) { 
                   2785:       for (k=1;k<=n;k++) { 
                   2786:        dum=a[imax][k]; 
                   2787:        a[imax][k]=a[j][k]; 
                   2788:        a[j][k]=dum; 
                   2789:       } 
                   2790:       *d = -(*d); 
                   2791:       vv[imax]=vv[j]; 
                   2792:     } 
                   2793:     indx[j]=imax; 
                   2794:     if (a[j][j] == 0.0) a[j][j]=TINY; 
                   2795:     if (j != n) { 
                   2796:       dum=1.0/(a[j][j]); 
                   2797:       for (i=j+1;i<=n;i++) a[i][j] *= dum; 
                   2798:     } 
                   2799:   } 
                   2800:   free_vector(vv,1,n);  /* Doesn't work */
                   2801: ;
                   2802: } 
                   2803: 
                   2804: void lubksb(double **a, int n, int *indx, double b[]) 
                   2805: { 
                   2806:   int i,ii=0,ip,j; 
                   2807:   double sum; 
                   2808:  
                   2809:   for (i=1;i<=n;i++) { 
                   2810:     ip=indx[i]; 
                   2811:     sum=b[ip]; 
                   2812:     b[ip]=b[i]; 
                   2813:     if (ii) 
                   2814:       for (j=ii;j<=i-1;j++) sum -= a[i][j]*b[j]; 
                   2815:     else if (sum) ii=i; 
                   2816:     b[i]=sum; 
                   2817:   } 
                   2818:   for (i=n;i>=1;i--) { 
                   2819:     sum=b[i]; 
                   2820:     for (j=i+1;j<=n;j++) sum -= a[i][j]*b[j]; 
                   2821:     b[i]=sum/a[i][i]; 
                   2822:   } 
                   2823: } 
                   2824: 
                   2825: void pstamp(FILE *fichier)
                   2826: {
                   2827:   fprintf(fichier,"# %s.%s\n#%s\n#%s\n# %s", optionfilefiname,optionfilext,version,fullversion,strstart);
                   2828: }
                   2829: 
                   2830: /************ Frequencies ********************/
                   2831: 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[])
                   2832: {  /* Some frequencies */
                   2833:   
1.164     brouard  2834:   int i, m, jk, j1, bool, z1,j;
1.126     brouard  2835:   int first;
                   2836:   double ***freq; /* Frequencies */
                   2837:   double *pp, **prop;
                   2838:   double pos,posprop, k2, dateintsum=0,k2cpt=0;
                   2839:   char fileresp[FILENAMELENGTH];
                   2840:   
                   2841:   pp=vector(1,nlstate);
                   2842:   prop=matrix(1,nlstate,iagemin,iagemax+3);
                   2843:   strcpy(fileresp,"p");
                   2844:   strcat(fileresp,fileres);
                   2845:   if((ficresp=fopen(fileresp,"w"))==NULL) {
                   2846:     printf("Problem with prevalence resultfile: %s\n", fileresp);
                   2847:     fprintf(ficlog,"Problem with prevalence resultfile: %s\n", fileresp);
                   2848:     exit(0);
                   2849:   }
                   2850:   freq= ma3x(-5,nlstate+ndeath,-5,nlstate+ndeath,iagemin,iagemax+3);
                   2851:   j1=0;
                   2852:   
                   2853:   j=cptcoveff;
                   2854:   if (cptcovn<1) {j=1;ncodemax[1]=1;}
                   2855: 
                   2856:   first=1;
                   2857: 
1.169     brouard  2858:   /* for(k1=1; k1<=j ; k1++){ */  /* Loop on covariates */
                   2859:   /*  for(i1=1; i1<=ncodemax[k1];i1++){ */ /* Now it is 2 */
                   2860:   /*    j1++; */
1.145     brouard  2861:   for (j1 = 1; j1 <= (int) pow(2,cptcoveff); j1++){
1.126     brouard  2862:       /*printf("cptcoveff=%d Tvaraff=%d", cptcoveff,Tvaraff[1]);
                   2863:        scanf("%d", i);*/
                   2864:       for (i=-5; i<=nlstate+ndeath; i++)  
                   2865:        for (jk=-5; jk<=nlstate+ndeath; jk++)  
                   2866:          for(m=iagemin; m <= iagemax+3; m++)
                   2867:            freq[i][jk][m]=0;
1.143     brouard  2868:       
                   2869:       for (i=1; i<=nlstate; i++)  
                   2870:        for(m=iagemin; m <= iagemax+3; m++)
                   2871:          prop[i][m]=0;
1.126     brouard  2872:       
                   2873:       dateintsum=0;
                   2874:       k2cpt=0;
                   2875:       for (i=1; i<=imx; i++) {
                   2876:        bool=1;
1.144     brouard  2877:        if  (cptcovn>0) { /* Filter is here: Must be looked at for model=V1+V2+V3+V4 */
                   2878:          for (z1=1; z1<=cptcoveff; z1++)       
                   2879:             if (covar[Tvaraff[z1]][i]!= nbcode[Tvaraff[z1]][codtab[j1][z1]]){
1.145     brouard  2880:                 /* Tests if the value of each of the covariates of i is equal to filter j1 */
1.144     brouard  2881:               bool=0;
1.145     brouard  2882:               /* 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", 
                   2883:                 bool,i,z1, z1, Tvaraff[z1],i,covar[Tvaraff[z1]][i],j1,z1,codtab[j1][z1],
                   2884:                 j1,z1,nbcode[Tvaraff[z1]][codtab[j1][z1]],j1);*/
1.144     brouard  2885:               /* For j1=7 in V1+V2+V3+V4 = 0 1 1 0 and codtab[7][3]=1 and nbcde[3][?]=1*/
                   2886:             } 
1.126     brouard  2887:        }
1.144     brouard  2888:  
1.126     brouard  2889:        if (bool==1){
                   2890:          for(m=firstpass; m<=lastpass; m++){
                   2891:            k2=anint[m][i]+(mint[m][i]/12.);
                   2892:            /*if ((k2>=dateprev1) && (k2<=dateprev2)) {*/
                   2893:              if(agev[m][i]==0) agev[m][i]=iagemax+1;
                   2894:              if(agev[m][i]==1) agev[m][i]=iagemax+2;
                   2895:              if (s[m][i]>0 && s[m][i]<=nlstate) prop[s[m][i]][(int)agev[m][i]] += weight[i];
                   2896:              if (m<lastpass) {
                   2897:                freq[s[m][i]][s[m+1][i]][(int)agev[m][i]] += weight[i];
                   2898:                freq[s[m][i]][s[m+1][i]][iagemax+3] += weight[i];
                   2899:              }
                   2900:              
                   2901:              if ((agev[m][i]>1) && (agev[m][i]< (iagemax+3))) {
                   2902:                dateintsum=dateintsum+k2;
                   2903:                k2cpt++;
                   2904:              }
                   2905:              /*}*/
                   2906:          }
                   2907:        }
1.145     brouard  2908:       } /* end i */
1.126     brouard  2909:        
                   2910:       /*      fprintf(ficresp, "#Count between %.lf/%.lf/%.lf and %.lf/%.lf/%.lf\n",jprev1, mprev1,anprev1,jprev2, mprev2,anprev2);*/
                   2911:       pstamp(ficresp);
                   2912:       if  (cptcovn>0) {
                   2913:        fprintf(ficresp, "\n#********** Variable "); 
                   2914:        for (z1=1; z1<=cptcoveff; z1++) fprintf(ficresp, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtab[j1][z1]]);
                   2915:        fprintf(ficresp, "**********\n#");
1.143     brouard  2916:        fprintf(ficlog, "\n#********** Variable "); 
                   2917:        for (z1=1; z1<=cptcoveff; z1++) fprintf(ficlog, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtab[j1][z1]]);
                   2918:        fprintf(ficlog, "**********\n#");
1.126     brouard  2919:       }
                   2920:       for(i=1; i<=nlstate;i++) 
                   2921:        fprintf(ficresp, " Age Prev(%d) N(%d) N",i,i);
                   2922:       fprintf(ficresp, "\n");
                   2923:       
                   2924:       for(i=iagemin; i <= iagemax+3; i++){
                   2925:        if(i==iagemax+3){
                   2926:          fprintf(ficlog,"Total");
                   2927:        }else{
                   2928:          if(first==1){
                   2929:            first=0;
                   2930:            printf("See log file for details...\n");
                   2931:          }
                   2932:          fprintf(ficlog,"Age %d", i);
                   2933:        }
                   2934:        for(jk=1; jk <=nlstate ; jk++){
                   2935:          for(m=-1, pp[jk]=0; m <=nlstate+ndeath ; m++)
                   2936:            pp[jk] += freq[jk][m][i]; 
                   2937:        }
                   2938:        for(jk=1; jk <=nlstate ; jk++){
                   2939:          for(m=-1, pos=0; m <=0 ; m++)
                   2940:            pos += freq[jk][m][i];
                   2941:          if(pp[jk]>=1.e-10){
                   2942:            if(first==1){
1.132     brouard  2943:              printf(" %d.=%.0f loss[%d]=%.1f%%",jk,pp[jk],jk,100*pos/pp[jk]);
1.126     brouard  2944:            }
                   2945:            fprintf(ficlog," %d.=%.0f loss[%d]=%.1f%%",jk,pp[jk],jk,100*pos/pp[jk]);
                   2946:          }else{
                   2947:            if(first==1)
                   2948:              printf(" %d.=%.0f loss[%d]=NaNQ%%",jk,pp[jk],jk);
                   2949:            fprintf(ficlog," %d.=%.0f loss[%d]=NaNQ%%",jk,pp[jk],jk);
                   2950:          }
                   2951:        }
                   2952: 
                   2953:        for(jk=1; jk <=nlstate ; jk++){
                   2954:          for(m=0, pp[jk]=0; m <=nlstate+ndeath; m++)
                   2955:            pp[jk] += freq[jk][m][i];
                   2956:        }       
                   2957:        for(jk=1,pos=0,posprop=0; jk <=nlstate ; jk++){
                   2958:          pos += pp[jk];
                   2959:          posprop += prop[jk][i];
                   2960:        }
                   2961:        for(jk=1; jk <=nlstate ; jk++){
                   2962:          if(pos>=1.e-5){
                   2963:            if(first==1)
                   2964:              printf(" %d.=%.0f prev[%d]=%.1f%%",jk,pp[jk],jk,100*pp[jk]/pos);
                   2965:            fprintf(ficlog," %d.=%.0f prev[%d]=%.1f%%",jk,pp[jk],jk,100*pp[jk]/pos);
                   2966:          }else{
                   2967:            if(first==1)
                   2968:              printf(" %d.=%.0f prev[%d]=NaNQ%%",jk,pp[jk],jk);
                   2969:            fprintf(ficlog," %d.=%.0f prev[%d]=NaNQ%%",jk,pp[jk],jk);
                   2970:          }
                   2971:          if( i <= iagemax){
                   2972:            if(pos>=1.e-5){
                   2973:              fprintf(ficresp," %d %.5f %.0f %.0f",i,prop[jk][i]/posprop, prop[jk][i],posprop);
                   2974:              /*probs[i][jk][j1]= pp[jk]/pos;*/
                   2975:              /*printf("\ni=%d jk=%d j1=%d %.5f %.0f %.0f %f",i,jk,j1,pp[jk]/pos, pp[jk],pos,probs[i][jk][j1]);*/
                   2976:            }
                   2977:            else
                   2978:              fprintf(ficresp," %d NaNq %.0f %.0f",i,prop[jk][i],posprop);
                   2979:          }
                   2980:        }
                   2981:        
                   2982:        for(jk=-1; jk <=nlstate+ndeath; jk++)
                   2983:          for(m=-1; m <=nlstate+ndeath; m++)
                   2984:            if(freq[jk][m][i] !=0 ) {
                   2985:            if(first==1)
                   2986:              printf(" %d%d=%.0f",jk,m,freq[jk][m][i]);
                   2987:              fprintf(ficlog," %d%d=%.0f",jk,m,freq[jk][m][i]);
                   2988:            }
                   2989:        if(i <= iagemax)
                   2990:          fprintf(ficresp,"\n");
                   2991:        if(first==1)
                   2992:          printf("Others in log...\n");
                   2993:        fprintf(ficlog,"\n");
                   2994:       }
1.145     brouard  2995:       /*}*/
1.126     brouard  2996:   }
                   2997:   dateintmean=dateintsum/k2cpt; 
                   2998:  
                   2999:   fclose(ficresp);
                   3000:   free_ma3x(freq,-5,nlstate+ndeath,-5,nlstate+ndeath, iagemin, iagemax+3);
                   3001:   free_vector(pp,1,nlstate);
                   3002:   free_matrix(prop,1,nlstate,iagemin, iagemax+3);
                   3003:   /* End of Freq */
                   3004: }
                   3005: 
                   3006: /************ Prevalence ********************/
                   3007: 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)
                   3008: {  
                   3009:   /* Compute observed prevalence between dateprev1 and dateprev2 by counting the number of people
                   3010:      in each health status at the date of interview (if between dateprev1 and dateprev2).
                   3011:      We still use firstpass and lastpass as another selection.
                   3012:   */
                   3013:  
1.164     brouard  3014:   int i, m, jk, j1, bool, z1,j;
                   3015: 
                   3016:   double **prop;
                   3017:   double posprop; 
1.126     brouard  3018:   double  y2; /* in fractional years */
                   3019:   int iagemin, iagemax;
1.145     brouard  3020:   int first; /** to stop verbosity which is redirected to log file */
1.126     brouard  3021: 
                   3022:   iagemin= (int) agemin;
                   3023:   iagemax= (int) agemax;
                   3024:   /*pp=vector(1,nlstate);*/
                   3025:   prop=matrix(1,nlstate,iagemin,iagemax+3); 
                   3026:   /*  freq=ma3x(-1,nlstate+ndeath,-1,nlstate+ndeath,iagemin,iagemax+3);*/
                   3027:   j1=0;
                   3028:   
1.145     brouard  3029:   /*j=cptcoveff;*/
1.126     brouard  3030:   if (cptcovn<1) {j=1;ncodemax[1]=1;}
                   3031:   
1.145     brouard  3032:   first=1;
                   3033:   for(j1=1; j1<= (int) pow(2,cptcoveff);j1++){
                   3034:     /*for(i1=1; i1<=ncodemax[k1];i1++){
                   3035:       j1++;*/
1.126     brouard  3036:       
                   3037:       for (i=1; i<=nlstate; i++)  
                   3038:        for(m=iagemin; m <= iagemax+3; m++)
                   3039:          prop[i][m]=0.0;
                   3040:      
                   3041:       for (i=1; i<=imx; i++) { /* Each individual */
                   3042:        bool=1;
                   3043:        if  (cptcovn>0) {
                   3044:          for (z1=1; z1<=cptcoveff; z1++) 
                   3045:            if (covar[Tvaraff[z1]][i]!= nbcode[Tvaraff[z1]][codtab[j1][z1]]) 
                   3046:              bool=0;
                   3047:        } 
                   3048:        if (bool==1) { 
                   3049:          for(m=firstpass; m<=lastpass; m++){/* Other selection (we can limit to certain interviews*/
                   3050:            y2=anint[m][i]+(mint[m][i]/12.); /* Fractional date in year */
                   3051:            if ((y2>=dateprev1) && (y2<=dateprev2)) { /* Here is the main selection (fractional years) */
                   3052:              if(agev[m][i]==0) agev[m][i]=iagemax+1;
                   3053:              if(agev[m][i]==1) agev[m][i]=iagemax+2;
                   3054:              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); 
                   3055:              if (s[m][i]>0 && s[m][i]<=nlstate) { 
                   3056:                /*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]]);*/
                   3057:                prop[s[m][i]][(int)agev[m][i]] += weight[i];
                   3058:                prop[s[m][i]][iagemax+3] += weight[i]; 
                   3059:              } 
                   3060:            }
                   3061:          } /* end selection of waves */
                   3062:        }
                   3063:       }
                   3064:       for(i=iagemin; i <= iagemax+3; i++){  
                   3065:        for(jk=1,posprop=0; jk <=nlstate ; jk++) { 
                   3066:          posprop += prop[jk][i]; 
                   3067:        } 
1.145     brouard  3068:        
1.126     brouard  3069:        for(jk=1; jk <=nlstate ; jk++){     
                   3070:          if( i <=  iagemax){ 
                   3071:            if(posprop>=1.e-5){ 
                   3072:              probs[i][jk][j1]= prop[jk][i]/posprop;
1.145     brouard  3073:            } else{
                   3074:              if(first==1){
                   3075:                first=0;
                   3076:                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]);
                   3077:              }
                   3078:            }
1.126     brouard  3079:          } 
                   3080:        }/* end jk */ 
                   3081:       }/* end i */ 
1.145     brouard  3082:     /*} *//* end i1 */
                   3083:   } /* end j1 */
1.126     brouard  3084:   
                   3085:   /*  free_ma3x(freq,-1,nlstate+ndeath,-1,nlstate+ndeath, iagemin, iagemax+3);*/
                   3086:   /*free_vector(pp,1,nlstate);*/
                   3087:   free_matrix(prop,1,nlstate, iagemin,iagemax+3);
                   3088: }  /* End of prevalence */
                   3089: 
                   3090: /************* Waves Concatenation ***************/
                   3091: 
                   3092: 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)
                   3093: {
                   3094:   /* Concatenates waves: wav[i] is the number of effective (useful waves) of individual i.
                   3095:      Death is a valid wave (if date is known).
                   3096:      mw[mi][i] is the mi (mi=1 to wav[i])  effective wave of individual i
                   3097:      dh[m][i] or dh[mw[mi][i]][i] is the delay between two effective waves m=mw[mi][i]
                   3098:      and mw[mi+1][i]. dh depends on stepm.
                   3099:      */
                   3100: 
                   3101:   int i, mi, m;
                   3102:   /* int j, k=0,jk, ju, jl,jmin=1e+5, jmax=-1;
                   3103:      double sum=0., jmean=0.;*/
                   3104:   int first;
                   3105:   int j, k=0,jk, ju, jl;
                   3106:   double sum=0.;
                   3107:   first=0;
1.164     brouard  3108:   jmin=100000;
1.126     brouard  3109:   jmax=-1;
                   3110:   jmean=0.;
                   3111:   for(i=1; i<=imx; i++){
                   3112:     mi=0;
                   3113:     m=firstpass;
                   3114:     while(s[m][i] <= nlstate){
                   3115:       if(s[m][i]>=1 || s[m][i]==-2 || s[m][i]==-4 || s[m][i]==-5)
                   3116:        mw[++mi][i]=m;
                   3117:       if(m >=lastpass)
                   3118:        break;
                   3119:       else
                   3120:        m++;
                   3121:     }/* end while */
                   3122:     if (s[m][i] > nlstate){
                   3123:       mi++;    /* Death is another wave */
                   3124:       /* if(mi==0)  never been interviewed correctly before death */
                   3125:         /* Only death is a correct wave */
                   3126:       mw[mi][i]=m;
                   3127:     }
                   3128: 
                   3129:     wav[i]=mi;
                   3130:     if(mi==0){
                   3131:       nbwarn++;
                   3132:       if(first==0){
                   3133:        printf("Warning! No valid information for individual %ld line=%d (skipped) and may be others, see log file\n",num[i],i);
                   3134:        first=1;
                   3135:       }
                   3136:       if(first==1){
                   3137:        fprintf(ficlog,"Warning! No valid information for individual %ld line=%d (skipped)\n",num[i],i);
                   3138:       }
                   3139:     } /* end mi==0 */
                   3140:   } /* End individuals */
                   3141: 
                   3142:   for(i=1; i<=imx; i++){
                   3143:     for(mi=1; mi<wav[i];mi++){
                   3144:       if (stepm <=0)
                   3145:        dh[mi][i]=1;
                   3146:       else{
                   3147:        if (s[mw[mi+1][i]][i] > nlstate) { /* A death */
                   3148:          if (agedc[i] < 2*AGESUP) {
                   3149:            j= rint(agedc[i]*12-agev[mw[mi][i]][i]*12); 
                   3150:            if(j==0) j=1;  /* Survives at least one month after exam */
                   3151:            else if(j<0){
                   3152:              nberr++;
                   3153:              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]);
                   3154:              j=1; /* Temporary Dangerous patch */
                   3155:              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);
                   3156:              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]);
                   3157:              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);
                   3158:            }
                   3159:            k=k+1;
                   3160:            if (j >= jmax){
                   3161:              jmax=j;
                   3162:              ijmax=i;
                   3163:            }
                   3164:            if (j <= jmin){
                   3165:              jmin=j;
                   3166:              ijmin=i;
                   3167:            }
                   3168:            sum=sum+j;
                   3169:            /*if (j<0) printf("j=%d num=%d \n",j,i);*/
                   3170:            /*    printf("%d %d %d %d\n", s[mw[mi][i]][i] ,s[mw[mi+1][i]][i],j,i);*/
                   3171:          }
                   3172:        }
                   3173:        else{
                   3174:          j= rint( (agev[mw[mi+1][i]][i]*12 - agev[mw[mi][i]][i]*12));
                   3175: /*       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]); */
                   3176: 
                   3177:          k=k+1;
                   3178:          if (j >= jmax) {
                   3179:            jmax=j;
                   3180:            ijmax=i;
                   3181:          }
                   3182:          else if (j <= jmin){
                   3183:            jmin=j;
                   3184:            ijmin=i;
                   3185:          }
                   3186:          /*        if (j<10) printf("j=%d jmin=%d num=%d ",j,jmin,i); */
                   3187:          /*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]);*/
                   3188:          if(j<0){
                   3189:            nberr++;
                   3190:            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]);
                   3191:            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]);
                   3192:          }
                   3193:          sum=sum+j;
                   3194:        }
                   3195:        jk= j/stepm;
                   3196:        jl= j -jk*stepm;
                   3197:        ju= j -(jk+1)*stepm;
                   3198:        if(mle <=1){ /* only if we use a the linear-interpoloation pseudo-likelihood */
                   3199:          if(jl==0){
                   3200:            dh[mi][i]=jk;
                   3201:            bh[mi][i]=0;
                   3202:          }else{ /* We want a negative bias in order to only have interpolation ie
1.136     brouard  3203:                  * to avoid the price of an extra matrix product in likelihood */
1.126     brouard  3204:            dh[mi][i]=jk+1;
                   3205:            bh[mi][i]=ju;
                   3206:          }
                   3207:        }else{
                   3208:          if(jl <= -ju){
                   3209:            dh[mi][i]=jk;
                   3210:            bh[mi][i]=jl;       /* bias is positive if real duration
                   3211:                                 * is higher than the multiple of stepm and negative otherwise.
                   3212:                                 */
                   3213:          }
                   3214:          else{
                   3215:            dh[mi][i]=jk+1;
                   3216:            bh[mi][i]=ju;
                   3217:          }
                   3218:          if(dh[mi][i]==0){
                   3219:            dh[mi][i]=1; /* At least one step */
                   3220:            bh[mi][i]=ju; /* At least one step */
                   3221:            /*  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);*/
                   3222:          }
                   3223:        } /* end if mle */
                   3224:       }
                   3225:     } /* end wave */
                   3226:   }
                   3227:   jmean=sum/k;
                   3228:   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  3229:   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  3230:  }
                   3231: 
                   3232: /*********** Tricode ****************************/
1.145     brouard  3233: void tricode(int *Tvar, int **nbcode, int imx, int *Ndum)
1.126     brouard  3234: {
1.144     brouard  3235:   /**< Uses cptcovn+2*cptcovprod as the number of covariates */
                   3236:   /*     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  3237:    * Boring subroutine which should only output nbcode[Tvar[j]][k]
1.145     brouard  3238:    * Tvar[5] in V2+V1+V3*age+V2*V4 is 2 (V2)
1.169     brouard  3239:    * nbcode[Tvar[j]][1]= 
1.144     brouard  3240:   */
1.130     brouard  3241: 
1.145     brouard  3242:   int ij=1, k=0, j=0, i=0, maxncov=NCOVMAX;
1.136     brouard  3243:   int modmaxcovj=0; /* Modality max of covariates j */
1.145     brouard  3244:   int cptcode=0; /* Modality max of covariates j */
                   3245:   int modmincovj=0; /* Modality min of covariates j */
                   3246: 
                   3247: 
1.126     brouard  3248:   cptcoveff=0; 
                   3249:  
1.145     brouard  3250:   for (k=-1; k < maxncov; k++) Ndum[k]=0;
1.144     brouard  3251:   for (k=1; k <= maxncov; k++) ncodemax[k]=0; /* Horrible constant again replaced by NCOVMAX */
1.126     brouard  3252: 
1.145     brouard  3253:   /* Loop on covariates without age and products */
1.186     brouard  3254:   for (j=1; j<=(cptcovs); j++) { /* From model V1 + V2*age+ V3 + V3*V4 keeps V1 + V3 = 2 only */
                   3255:     for (i=1; i<=imx; i++) { /* Loop on individuals: reads the data file to get the maximum value of the 
1.136     brouard  3256:                               modality of this covariate Vj*/ 
1.145     brouard  3257:       ij=(int)(covar[Tvar[j]][i]); /* ij=0 or 1 or -1. Value of the covariate Tvar[j] for individual i
                   3258:                                    * If product of Vn*Vm, still boolean *:
                   3259:                                    * If it was coded 1, 2, 3, 4 should be splitted into 3 boolean variables
                   3260:                                    * 1 => 0 0 0, 2 => 0 0 1, 3 => 0 1 1, 4=1 0 0   */
                   3261:       /* Finds for covariate j, n=Tvar[j] of Vn . ij is the
1.136     brouard  3262:                                      modality of the nth covariate of individual i. */
1.145     brouard  3263:       if (ij > modmaxcovj)
                   3264:         modmaxcovj=ij; 
                   3265:       else if (ij < modmincovj) 
                   3266:        modmincovj=ij; 
                   3267:       if ((ij < -1) && (ij > NCOVMAX)){
                   3268:        printf( "Error: minimal is less than -1 or maximal is bigger than %d. Exiting. \n", NCOVMAX );
                   3269:        exit(1);
                   3270:       }else
1.136     brouard  3271:       Ndum[ij]++; /*counts and stores the occurence of this modality 0, 1, -1*/
1.145     brouard  3272:       /*  If coded 1, 2, 3 , counts the number of 1 Ndum[1], number of 2, Ndum[2], etc */
1.126     brouard  3273:       /*printf("i=%d ij=%d Ndum[ij]=%d imx=%d",i,ij,Ndum[ij],imx);*/
1.136     brouard  3274:       /* getting the maximum value of the modality of the covariate
                   3275:         (should be 0 or 1 now) Tvar[j]. If V=sex and male is coded 0 and
                   3276:         female is 1, then modmaxcovj=1.*/
1.187     brouard  3277:     } /* end for loop on individuals */
1.145     brouard  3278:     printf(" Minimal and maximal values of %d th covariate V%d: min=%d max=%d \n", j, Tvar[j], modmincovj, modmaxcovj);
                   3279:     cptcode=modmaxcovj;
1.137     brouard  3280:     /* Ndum[0] = frequency of 0 for model-covariate j, Ndum[1] frequency of 1 etc. */
1.145     brouard  3281:    /*for (i=0; i<=cptcode; i++) {*/
                   3282:     for (i=modmincovj;  i<=modmaxcovj; i++) { /* i=-1 ? 0 and 1*//* For each value of the modality of model-cov j */
1.187     brouard  3283:       printf("Frequencies of covariates %d ie V%d with value %d: %d\n", j, Tvar[j], i, Ndum[i]);
1.145     brouard  3284:       if( Ndum[i] != 0 ){ /* Counts if nobody answered, empty modality */
                   3285:        ncodemax[j]++;  /* ncodemax[j]= Number of non-null modalities of the j th covariate. */
                   3286:       }
                   3287:       /* In fact  ncodemax[j]=2 (dichotom. variables only) but it could be more for
                   3288:         historical reasons: 3 if coded 1, 2, 3 and 4 and Ndum[2]=0 */
1.131     brouard  3289:     } /* Ndum[-1] number of undefined modalities */
1.126     brouard  3290: 
1.136     brouard  3291:     /* j is a covariate, n=Tvar[j] of Vn; Fills nbcode */
1.186     brouard  3292:     /* For covariate j, modalities could be 1, 2, 3, 4, 5, 6, 7. 
                   3293:        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  3294:        modmincovj=3; modmaxcovj = 7;
1.186     brouard  3295:        There are only 3 modalities non empty 3, 6, 7 (or 2 if 27 is too few) : ncodemax[j]=3;
                   3296:        which will be coded 0, 1, 2 which in binary on 2=3-1 digits are 0=00 1=01, 2=10;
                   3297:        defining two dummy variables: variables V1_1 and V1_2.
1.145     brouard  3298:        nbcode[Tvar[j]][ij]=k;
                   3299:        nbcode[Tvar[j]][1]=0;
                   3300:        nbcode[Tvar[j]][2]=1;
                   3301:        nbcode[Tvar[j]][3]=2;
                   3302:     */
                   3303:     ij=1; /* ij is similar to i but can jumps over null modalities */
                   3304:     for (i=modmincovj; i<=modmaxcovj; i++) { /* i= 1 to 2 for dichotomous, or from 1 to 3 */
                   3305:       for (k=0; k<= cptcode; k++) { /* k=-1 ? k=0 to 1 *//* Could be 1 to 4 */
                   3306:        /*recode from 0 */
1.131     brouard  3307:        if (Ndum[k] != 0) { /* If at least one individual responded to this modality k */
1.186     brouard  3308:          nbcode[Tvar[j]][ij]=k;  /* stores the modality k in an array nbcode. 
1.131     brouard  3309:                                     k is a modality. If we have model=V1+V1*sex 
                   3310:                                     then: nbcode[1][1]=0 ; nbcode[1][2]=1; nbcode[2][1]=0 ; nbcode[2][2]=1; */
1.126     brouard  3311:          ij++;
                   3312:        }
                   3313:        if (ij > ncodemax[j]) break; 
1.137     brouard  3314:       }  /* end of loop on */
                   3315:     } /* end of loop on modality */ 
                   3316:   } /* end of loop on model-covariate j. nbcode[Tvarj][1]=0 and nbcode[Tvarj][2]=1 sets the value of covariate j*/  
                   3317:   
1.145     brouard  3318:  for (k=-1; k< maxncov; k++) Ndum[k]=0; 
1.137     brouard  3319:   
1.187     brouard  3320:   for (i=1; i<=ncovmodel-2-nagesqr; i++) { /* -2, cste and age and eventually age*age */ 
1.145     brouard  3321:    /* Listing of all covariables in statement model to see if some covariates appear twice. For example, V1 appears twice in V1+V1*V2.*/ 
                   3322:    ij=Tvar[i]; /* Tvar might be -1 if status was unknown */ 
1.187     brouard  3323:    Ndum[ij]++; /* Might be supersed V1 + V1*age */
1.145     brouard  3324:  } 
1.126     brouard  3325: 
                   3326:  ij=1;
1.145     brouard  3327:  for (i=0; i<=  maxncov-1; i++) { /* modmaxcovj is unknown here. Only Ndum[2(V2),3(age*V3), 5(V3*V2) 6(V1*V4) */
                   3328:    /*printf("Ndum[%d]=%d\n",i, Ndum[i]);*/
1.126     brouard  3329:    if((Ndum[i]!=0) && (i<=ncovcol)){
1.145     brouard  3330:      /*printf("diff Ndum[%d]=%d\n",i, Ndum[i]);*/
                   3331:      Tvaraff[ij]=i; /*For printing (unclear) */
1.126     brouard  3332:      ij++;
1.145     brouard  3333:    }else
                   3334:        Tvaraff[ij]=0;
1.126     brouard  3335:  }
1.131     brouard  3336:  ij--;
1.144     brouard  3337:  cptcoveff=ij; /*Number of total covariates*/
1.145     brouard  3338: 
1.126     brouard  3339: }
                   3340: 
1.145     brouard  3341: 
1.126     brouard  3342: /*********** Health Expectancies ****************/
                   3343: 
1.127     brouard  3344: 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  3345: 
                   3346: {
                   3347:   /* Health expectancies, no variances */
1.164     brouard  3348:   int i, j, nhstepm, hstepm, h, nstepm;
1.126     brouard  3349:   int nhstepma, nstepma; /* Decreasing with age */
                   3350:   double age, agelim, hf;
                   3351:   double ***p3mat;
                   3352:   double eip;
                   3353: 
                   3354:   pstamp(ficreseij);
                   3355:   fprintf(ficreseij,"# (a) Life expectancies by health status at initial age and (b) health expectancies by health status at initial age\n");
                   3356:   fprintf(ficreseij,"# Age");
                   3357:   for(i=1; i<=nlstate;i++){
                   3358:     for(j=1; j<=nlstate;j++){
                   3359:       fprintf(ficreseij," e%1d%1d ",i,j);
                   3360:     }
                   3361:     fprintf(ficreseij," e%1d. ",i);
                   3362:   }
                   3363:   fprintf(ficreseij,"\n");
                   3364: 
                   3365:   
                   3366:   if(estepm < stepm){
                   3367:     printf ("Problem %d lower than %d\n",estepm, stepm);
                   3368:   }
                   3369:   else  hstepm=estepm;   
                   3370:   /* We compute the life expectancy from trapezoids spaced every estepm months
                   3371:    * This is mainly to measure the difference between two models: for example
                   3372:    * if stepm=24 months pijx are given only every 2 years and by summing them
                   3373:    * we are calculating an estimate of the Life Expectancy assuming a linear 
                   3374:    * progression in between and thus overestimating or underestimating according
                   3375:    * to the curvature of the survival function. If, for the same date, we 
                   3376:    * estimate the model with stepm=1 month, we can keep estepm to 24 months
                   3377:    * to compare the new estimate of Life expectancy with the same linear 
                   3378:    * hypothesis. A more precise result, taking into account a more precise
                   3379:    * curvature will be obtained if estepm is as small as stepm. */
                   3380: 
                   3381:   /* For example we decided to compute the life expectancy with the smallest unit */
                   3382:   /* hstepm beeing the number of stepms, if hstepm=1 the length of hstepm is stepm. 
                   3383:      nhstepm is the number of hstepm from age to agelim 
                   3384:      nstepm is the number of stepm from age to agelin. 
                   3385:      Look at hpijx to understand the reason of that which relies in memory size
                   3386:      and note for a fixed period like estepm months */
                   3387:   /* We decided (b) to get a life expectancy respecting the most precise curvature of the
                   3388:      survival function given by stepm (the optimization length). Unfortunately it
                   3389:      means that if the survival funtion is printed only each two years of age and if
                   3390:      you sum them up and add 1 year (area under the trapezoids) you won't get the same 
                   3391:      results. So we changed our mind and took the option of the best precision.
                   3392:   */
                   3393:   hstepm=hstepm/stepm; /* Typically in stepm units, if stepm=6 & estepm=24 , = 24/6 months = 4 */ 
                   3394: 
                   3395:   agelim=AGESUP;
                   3396:   /* If stepm=6 months */
                   3397:     /* Computed by stepm unit matrices, product of hstepm matrices, stored
                   3398:        in an array of nhstepm length: nhstepm=10, hstepm=4, stepm=6 months */
                   3399:     
                   3400: /* nhstepm age range expressed in number of stepm */
                   3401:   nstepm=(int) rint((agelim-bage)*YEARM/stepm); /* Biggest nstepm */
                   3402:   /* Typically if 20 years nstepm = 20*12/6=40 stepm */ 
                   3403:   /* if (stepm >= YEARM) hstepm=1;*/
                   3404:   nhstepm = nstepm/hstepm;/* Expressed in hstepm, typically nhstepm=40/4=10 */
                   3405:   p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   3406: 
                   3407:   for (age=bage; age<=fage; age ++){ 
                   3408:     nstepma=(int) rint((agelim-bage)*YEARM/stepm); /* Biggest nstepm */
                   3409:     /* Typically if 20 years nstepm = 20*12/6=40 stepm */ 
                   3410:     /* if (stepm >= YEARM) hstepm=1;*/
                   3411:     nhstepma = nstepma/hstepm;/* Expressed in hstepm, typically nhstepma=40/4=10 */
                   3412: 
                   3413:     /* If stepm=6 months */
                   3414:     /* Computed by stepm unit matrices, product of hstepma matrices, stored
                   3415:        in an array of nhstepma length: nhstepma=10, hstepm=4, stepm=6 months */
                   3416:     
                   3417:     hpxij(p3mat,nhstepma,age,hstepm,x,nlstate,stepm,oldm, savm, cij);  
                   3418:     
                   3419:     hf=hstepm*stepm/YEARM;  /* Duration of hstepm expressed in year unit. */
                   3420:     
                   3421:     printf("%d|",(int)age);fflush(stdout);
                   3422:     fprintf(ficlog,"%d|",(int)age);fflush(ficlog);
                   3423:     
                   3424:     /* Computing expectancies */
                   3425:     for(i=1; i<=nlstate;i++)
                   3426:       for(j=1; j<=nlstate;j++)
                   3427:        for (h=0, eij[i][j][(int)age]=0; h<=nhstepm-1; h++){
                   3428:          eij[i][j][(int)age] += (p3mat[i][j][h]+p3mat[i][j][h+1])/2.0*hf;
                   3429:          
                   3430:          /* 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]);*/
                   3431: 
                   3432:        }
                   3433: 
                   3434:     fprintf(ficreseij,"%3.0f",age );
                   3435:     for(i=1; i<=nlstate;i++){
                   3436:       eip=0;
                   3437:       for(j=1; j<=nlstate;j++){
                   3438:        eip +=eij[i][j][(int)age];
                   3439:        fprintf(ficreseij,"%9.4f", eij[i][j][(int)age] );
                   3440:       }
                   3441:       fprintf(ficreseij,"%9.4f", eip );
                   3442:     }
                   3443:     fprintf(ficreseij,"\n");
                   3444:     
                   3445:   }
                   3446:   free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   3447:   printf("\n");
                   3448:   fprintf(ficlog,"\n");
                   3449:   
                   3450: }
                   3451: 
1.127     brouard  3452: 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  3453: 
                   3454: {
                   3455:   /* Covariances of health expectancies eij and of total life expectancies according
                   3456:    to initial status i, ei. .
                   3457:   */
                   3458:   int i, j, nhstepm, hstepm, h, nstepm, k, cptj, cptj2, i2, j2, ij, ji;
                   3459:   int nhstepma, nstepma; /* Decreasing with age */
                   3460:   double age, agelim, hf;
                   3461:   double ***p3matp, ***p3matm, ***varhe;
                   3462:   double **dnewm,**doldm;
                   3463:   double *xp, *xm;
                   3464:   double **gp, **gm;
                   3465:   double ***gradg, ***trgradg;
                   3466:   int theta;
                   3467: 
                   3468:   double eip, vip;
                   3469: 
                   3470:   varhe=ma3x(1,nlstate*nlstate,1,nlstate*nlstate,(int) bage, (int) fage);
                   3471:   xp=vector(1,npar);
                   3472:   xm=vector(1,npar);
                   3473:   dnewm=matrix(1,nlstate*nlstate,1,npar);
                   3474:   doldm=matrix(1,nlstate*nlstate,1,nlstate*nlstate);
                   3475:   
                   3476:   pstamp(ficresstdeij);
                   3477:   fprintf(ficresstdeij,"# Health expectancies with standard errors\n");
                   3478:   fprintf(ficresstdeij,"# Age");
                   3479:   for(i=1; i<=nlstate;i++){
                   3480:     for(j=1; j<=nlstate;j++)
                   3481:       fprintf(ficresstdeij," e%1d%1d (SE)",i,j);
                   3482:     fprintf(ficresstdeij," e%1d. ",i);
                   3483:   }
                   3484:   fprintf(ficresstdeij,"\n");
                   3485: 
                   3486:   pstamp(ficrescveij);
                   3487:   fprintf(ficrescveij,"# Subdiagonal matrix of covariances of health expectancies by age: cov(eij,ekl)\n");
                   3488:   fprintf(ficrescveij,"# Age");
                   3489:   for(i=1; i<=nlstate;i++)
                   3490:     for(j=1; j<=nlstate;j++){
                   3491:       cptj= (j-1)*nlstate+i;
                   3492:       for(i2=1; i2<=nlstate;i2++)
                   3493:        for(j2=1; j2<=nlstate;j2++){
                   3494:          cptj2= (j2-1)*nlstate+i2;
                   3495:          if(cptj2 <= cptj)
                   3496:            fprintf(ficrescveij,"  %1d%1d,%1d%1d",i,j,i2,j2);
                   3497:        }
                   3498:     }
                   3499:   fprintf(ficrescveij,"\n");
                   3500:   
                   3501:   if(estepm < stepm){
                   3502:     printf ("Problem %d lower than %d\n",estepm, stepm);
                   3503:   }
                   3504:   else  hstepm=estepm;   
                   3505:   /* We compute the life expectancy from trapezoids spaced every estepm months
                   3506:    * This is mainly to measure the difference between two models: for example
                   3507:    * if stepm=24 months pijx are given only every 2 years and by summing them
                   3508:    * we are calculating an estimate of the Life Expectancy assuming a linear 
                   3509:    * progression in between and thus overestimating or underestimating according
                   3510:    * to the curvature of the survival function. If, for the same date, we 
                   3511:    * estimate the model with stepm=1 month, we can keep estepm to 24 months
                   3512:    * to compare the new estimate of Life expectancy with the same linear 
                   3513:    * hypothesis. A more precise result, taking into account a more precise
                   3514:    * curvature will be obtained if estepm is as small as stepm. */
                   3515: 
                   3516:   /* For example we decided to compute the life expectancy with the smallest unit */
                   3517:   /* hstepm beeing the number of stepms, if hstepm=1 the length of hstepm is stepm. 
                   3518:      nhstepm is the number of hstepm from age to agelim 
                   3519:      nstepm is the number of stepm from age to agelin. 
                   3520:      Look at hpijx to understand the reason of that which relies in memory size
                   3521:      and note for a fixed period like estepm months */
                   3522:   /* We decided (b) to get a life expectancy respecting the most precise curvature of the
                   3523:      survival function given by stepm (the optimization length). Unfortunately it
                   3524:      means that if the survival funtion is printed only each two years of age and if
                   3525:      you sum them up and add 1 year (area under the trapezoids) you won't get the same 
                   3526:      results. So we changed our mind and took the option of the best precision.
                   3527:   */
                   3528:   hstepm=hstepm/stepm; /* Typically in stepm units, if stepm=6 & estepm=24 , = 24/6 months = 4 */ 
                   3529: 
                   3530:   /* If stepm=6 months */
                   3531:   /* nhstepm age range expressed in number of stepm */
                   3532:   agelim=AGESUP;
                   3533:   nstepm=(int) rint((agelim-bage)*YEARM/stepm); 
                   3534:   /* Typically if 20 years nstepm = 20*12/6=40 stepm */ 
                   3535:   /* if (stepm >= YEARM) hstepm=1;*/
                   3536:   nhstepm = nstepm/hstepm;/* Expressed in hstepm, typically nhstepm=40/4=10 */
                   3537:   
                   3538:   p3matp=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   3539:   p3matm=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   3540:   gradg=ma3x(0,nhstepm,1,npar,1,nlstate*nlstate);
                   3541:   trgradg =ma3x(0,nhstepm,1,nlstate*nlstate,1,npar);
                   3542:   gp=matrix(0,nhstepm,1,nlstate*nlstate);
                   3543:   gm=matrix(0,nhstepm,1,nlstate*nlstate);
                   3544: 
                   3545:   for (age=bage; age<=fage; age ++){ 
                   3546:     nstepma=(int) rint((agelim-bage)*YEARM/stepm); /* Biggest nstepm */
                   3547:     /* Typically if 20 years nstepm = 20*12/6=40 stepm */ 
                   3548:     /* if (stepm >= YEARM) hstepm=1;*/
                   3549:     nhstepma = nstepma/hstepm;/* Expressed in hstepm, typically nhstepma=40/4=10 */
                   3550: 
                   3551:     /* If stepm=6 months */
                   3552:     /* Computed by stepm unit matrices, product of hstepma matrices, stored
                   3553:        in an array of nhstepma length: nhstepma=10, hstepm=4, stepm=6 months */
                   3554:     
                   3555:     hf=hstepm*stepm/YEARM;  /* Duration of hstepm expressed in year unit. */
                   3556: 
                   3557:     /* Computing  Variances of health expectancies */
                   3558:     /* Gradient is computed with plus gp and minus gm. Code is duplicated in order to
                   3559:        decrease memory allocation */
                   3560:     for(theta=1; theta <=npar; theta++){
                   3561:       for(i=1; i<=npar; i++){ 
                   3562:        xp[i] = x[i] + (i==theta ?delti[theta]:0);
                   3563:        xm[i] = x[i] - (i==theta ?delti[theta]:0);
                   3564:       }
                   3565:       hpxij(p3matp,nhstepm,age,hstepm,xp,nlstate,stepm,oldm,savm, cij);  
                   3566:       hpxij(p3matm,nhstepm,age,hstepm,xm,nlstate,stepm,oldm,savm, cij);  
                   3567:   
                   3568:       for(j=1; j<= nlstate; j++){
                   3569:        for(i=1; i<=nlstate; i++){
                   3570:          for(h=0; h<=nhstepm-1; h++){
                   3571:            gp[h][(j-1)*nlstate + i] = (p3matp[i][j][h]+p3matp[i][j][h+1])/2.;
                   3572:            gm[h][(j-1)*nlstate + i] = (p3matm[i][j][h]+p3matm[i][j][h+1])/2.;
                   3573:          }
                   3574:        }
                   3575:       }
                   3576:      
                   3577:       for(ij=1; ij<= nlstate*nlstate; ij++)
                   3578:        for(h=0; h<=nhstepm-1; h++){
                   3579:          gradg[h][theta][ij]= (gp[h][ij]-gm[h][ij])/2./delti[theta];
                   3580:        }
                   3581:     }/* End theta */
                   3582:     
                   3583:     
                   3584:     for(h=0; h<=nhstepm-1; h++)
                   3585:       for(j=1; j<=nlstate*nlstate;j++)
                   3586:        for(theta=1; theta <=npar; theta++)
                   3587:          trgradg[h][j][theta]=gradg[h][theta][j];
                   3588:     
                   3589: 
                   3590:      for(ij=1;ij<=nlstate*nlstate;ij++)
                   3591:       for(ji=1;ji<=nlstate*nlstate;ji++)
                   3592:        varhe[ij][ji][(int)age] =0.;
                   3593: 
                   3594:      printf("%d|",(int)age);fflush(stdout);
                   3595:      fprintf(ficlog,"%d|",(int)age);fflush(ficlog);
                   3596:      for(h=0;h<=nhstepm-1;h++){
                   3597:       for(k=0;k<=nhstepm-1;k++){
                   3598:        matprod2(dnewm,trgradg[h],1,nlstate*nlstate,1,npar,1,npar,matcov);
                   3599:        matprod2(doldm,dnewm,1,nlstate*nlstate,1,npar,1,nlstate*nlstate,gradg[k]);
                   3600:        for(ij=1;ij<=nlstate*nlstate;ij++)
                   3601:          for(ji=1;ji<=nlstate*nlstate;ji++)
                   3602:            varhe[ij][ji][(int)age] += doldm[ij][ji]*hf*hf;
                   3603:       }
                   3604:     }
                   3605: 
                   3606:     /* Computing expectancies */
                   3607:     hpxij(p3matm,nhstepm,age,hstepm,x,nlstate,stepm,oldm, savm, cij);  
                   3608:     for(i=1; i<=nlstate;i++)
                   3609:       for(j=1; j<=nlstate;j++)
                   3610:        for (h=0, eij[i][j][(int)age]=0; h<=nhstepm-1; h++){
                   3611:          eij[i][j][(int)age] += (p3matm[i][j][h]+p3matm[i][j][h+1])/2.0*hf;
                   3612:          
                   3613:          /* 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]);*/
                   3614: 
                   3615:        }
                   3616: 
                   3617:     fprintf(ficresstdeij,"%3.0f",age );
                   3618:     for(i=1; i<=nlstate;i++){
                   3619:       eip=0.;
                   3620:       vip=0.;
                   3621:       for(j=1; j<=nlstate;j++){
                   3622:        eip += eij[i][j][(int)age];
                   3623:        for(k=1; k<=nlstate;k++) /* Sum on j and k of cov(eij,eik) */
                   3624:          vip += varhe[(j-1)*nlstate+i][(k-1)*nlstate+i][(int)age];
                   3625:        fprintf(ficresstdeij," %9.4f (%.4f)", eij[i][j][(int)age], sqrt(varhe[(j-1)*nlstate+i][(j-1)*nlstate+i][(int)age]) );
                   3626:       }
                   3627:       fprintf(ficresstdeij," %9.4f (%.4f)", eip, sqrt(vip));
                   3628:     }
                   3629:     fprintf(ficresstdeij,"\n");
                   3630: 
                   3631:     fprintf(ficrescveij,"%3.0f",age );
                   3632:     for(i=1; i<=nlstate;i++)
                   3633:       for(j=1; j<=nlstate;j++){
                   3634:        cptj= (j-1)*nlstate+i;
                   3635:        for(i2=1; i2<=nlstate;i2++)
                   3636:          for(j2=1; j2<=nlstate;j2++){
                   3637:            cptj2= (j2-1)*nlstate+i2;
                   3638:            if(cptj2 <= cptj)
                   3639:              fprintf(ficrescveij," %.4f", varhe[cptj][cptj2][(int)age]);
                   3640:          }
                   3641:       }
                   3642:     fprintf(ficrescveij,"\n");
                   3643:    
                   3644:   }
                   3645:   free_matrix(gm,0,nhstepm,1,nlstate*nlstate);
                   3646:   free_matrix(gp,0,nhstepm,1,nlstate*nlstate);
                   3647:   free_ma3x(gradg,0,nhstepm,1,npar,1,nlstate*nlstate);
                   3648:   free_ma3x(trgradg,0,nhstepm,1,nlstate*nlstate,1,npar);
                   3649:   free_ma3x(p3matm,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   3650:   free_ma3x(p3matp,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   3651:   printf("\n");
                   3652:   fprintf(ficlog,"\n");
                   3653: 
                   3654:   free_vector(xm,1,npar);
                   3655:   free_vector(xp,1,npar);
                   3656:   free_matrix(dnewm,1,nlstate*nlstate,1,npar);
                   3657:   free_matrix(doldm,1,nlstate*nlstate,1,nlstate*nlstate);
                   3658:   free_ma3x(varhe,1,nlstate*nlstate,1,nlstate*nlstate,(int) bage, (int)fage);
                   3659: }
                   3660: 
                   3661: /************ Variance ******************/
                   3662: 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[])
                   3663: {
                   3664:   /* Variance of health expectancies */
                   3665:   /*  double **prevalim(double **prlim, int nlstate, double *xp, double age, double **oldm, double ** savm,double ftolpl);*/
                   3666:   /* double **newm;*/
1.169     brouard  3667:   /* int movingaverage(double ***probs, double bage,double fage, double ***mobaverage, int mobilav)*/
                   3668:   
                   3669:   int movingaverage();
1.126     brouard  3670:   double **dnewm,**doldm;
                   3671:   double **dnewmp,**doldmp;
                   3672:   int i, j, nhstepm, hstepm, h, nstepm ;
1.164     brouard  3673:   int k;
1.126     brouard  3674:   double *xp;
                   3675:   double **gp, **gm;  /* for var eij */
                   3676:   double ***gradg, ***trgradg; /*for var eij */
                   3677:   double **gradgp, **trgradgp; /* for var p point j */
                   3678:   double *gpp, *gmp; /* for var p point j */
                   3679:   double **varppt; /* for var p point j nlstate to nlstate+ndeath */
                   3680:   double ***p3mat;
                   3681:   double age,agelim, hf;
                   3682:   double ***mobaverage;
                   3683:   int theta;
                   3684:   char digit[4];
                   3685:   char digitp[25];
                   3686: 
                   3687:   char fileresprobmorprev[FILENAMELENGTH];
                   3688: 
                   3689:   if(popbased==1){
                   3690:     if(mobilav!=0)
                   3691:       strcpy(digitp,"-populbased-mobilav-");
                   3692:     else strcpy(digitp,"-populbased-nomobil-");
                   3693:   }
                   3694:   else 
                   3695:     strcpy(digitp,"-stablbased-");
                   3696: 
                   3697:   if (mobilav!=0) {
                   3698:     mobaverage= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
                   3699:     if (movingaverage(probs, bage, fage, mobaverage,mobilav)!=0){
                   3700:       fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav);
                   3701:       printf(" Error in movingaverage mobilav=%d\n",mobilav);
                   3702:     }
                   3703:   }
                   3704: 
                   3705:   strcpy(fileresprobmorprev,"prmorprev"); 
                   3706:   sprintf(digit,"%-d",ij);
                   3707:   /*printf("DIGIT=%s, ij=%d ijr=%-d|\n",digit, ij,ij);*/
                   3708:   strcat(fileresprobmorprev,digit); /* Tvar to be done */
                   3709:   strcat(fileresprobmorprev,digitp); /* Popbased or not, mobilav or not */
                   3710:   strcat(fileresprobmorprev,fileres);
                   3711:   if((ficresprobmorprev=fopen(fileresprobmorprev,"w"))==NULL) {
                   3712:     printf("Problem with resultfile: %s\n", fileresprobmorprev);
                   3713:     fprintf(ficlog,"Problem with resultfile: %s\n", fileresprobmorprev);
                   3714:   }
                   3715:   printf("Computing total mortality p.j=w1*p1j+w2*p2j+..: result on file '%s' \n",fileresprobmorprev);
                   3716:  
                   3717:   fprintf(ficlog,"Computing total mortality p.j=w1*p1j+w2*p2j+..: result on file '%s' \n",fileresprobmorprev);
                   3718:   pstamp(ficresprobmorprev);
                   3719:   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);
                   3720:   fprintf(ficresprobmorprev,"# Age cov=%-d",ij);
                   3721:   for(j=nlstate+1; j<=(nlstate+ndeath);j++){
                   3722:     fprintf(ficresprobmorprev," p.%-d SE",j);
                   3723:     for(i=1; i<=nlstate;i++)
                   3724:       fprintf(ficresprobmorprev," w%1d p%-d%-d",i,i,j);
                   3725:   }  
                   3726:   fprintf(ficresprobmorprev,"\n");
                   3727:   fprintf(ficgp,"\n# Routine varevsij");
                   3728:   /* fprintf(fichtm, "#Local time at start: %s", strstart);*/
                   3729:   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");
                   3730:   fprintf(fichtm,"\n<br>%s  <br>\n",digitp);
                   3731: /*   } */
                   3732:   varppt = matrix(nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);
                   3733:   pstamp(ficresvij);
                   3734:   fprintf(ficresvij,"# Variance and covariance of health expectancies e.j \n#  (weighted average of eij where weights are ");
                   3735:   if(popbased==1)
1.128     brouard  3736:     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  3737:   else
                   3738:     fprintf(ficresvij,"the age specific period (stable) prevalences in each health state \n");
                   3739:   fprintf(ficresvij,"# Age");
                   3740:   for(i=1; i<=nlstate;i++)
                   3741:     for(j=1; j<=nlstate;j++)
                   3742:       fprintf(ficresvij," Cov(e.%1d, e.%1d)",i,j);
                   3743:   fprintf(ficresvij,"\n");
                   3744: 
                   3745:   xp=vector(1,npar);
                   3746:   dnewm=matrix(1,nlstate,1,npar);
                   3747:   doldm=matrix(1,nlstate,1,nlstate);
                   3748:   dnewmp= matrix(nlstate+1,nlstate+ndeath,1,npar);
                   3749:   doldmp= matrix(nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);
                   3750: 
                   3751:   gradgp=matrix(1,npar,nlstate+1,nlstate+ndeath);
                   3752:   gpp=vector(nlstate+1,nlstate+ndeath);
                   3753:   gmp=vector(nlstate+1,nlstate+ndeath);
                   3754:   trgradgp =matrix(nlstate+1,nlstate+ndeath,1,npar); /* mu or p point j*/
                   3755:   
                   3756:   if(estepm < stepm){
                   3757:     printf ("Problem %d lower than %d\n",estepm, stepm);
                   3758:   }
                   3759:   else  hstepm=estepm;   
                   3760:   /* For example we decided to compute the life expectancy with the smallest unit */
                   3761:   /* hstepm beeing the number of stepms, if hstepm=1 the length of hstepm is stepm. 
                   3762:      nhstepm is the number of hstepm from age to agelim 
                   3763:      nstepm is the number of stepm from age to agelin. 
1.128     brouard  3764:      Look at function hpijx to understand why (it is linked to memory size questions) */
1.126     brouard  3765:   /* We decided (b) to get a life expectancy respecting the most precise curvature of the
                   3766:      survival function given by stepm (the optimization length). Unfortunately it
                   3767:      means that if the survival funtion is printed every two years of age and if
                   3768:      you sum them up and add 1 year (area under the trapezoids) you won't get the same 
                   3769:      results. So we changed our mind and took the option of the best precision.
                   3770:   */
                   3771:   hstepm=hstepm/stepm; /* Typically in stepm units, if stepm=6 & estepm=24 , = 24/6 months = 4 */ 
                   3772:   agelim = AGESUP;
                   3773:   for (age=bage; age<=fage; age ++){ /* If stepm=6 months */
                   3774:     nstepm=(int) rint((agelim-age)*YEARM/stepm); /* Typically 20 years = 20*12/6=40 */ 
                   3775:     nhstepm = nstepm/hstepm;/* Expressed in hstepm, typically nhstepm=40/4=10 */
                   3776:     p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   3777:     gradg=ma3x(0,nhstepm,1,npar,1,nlstate);
                   3778:     gp=matrix(0,nhstepm,1,nlstate);
                   3779:     gm=matrix(0,nhstepm,1,nlstate);
                   3780: 
                   3781: 
                   3782:     for(theta=1; theta <=npar; theta++){
                   3783:       for(i=1; i<=npar; i++){ /* Computes gradient x + delta*/
                   3784:        xp[i] = x[i] + (i==theta ?delti[theta]:0);
                   3785:       }
                   3786:       hpxij(p3mat,nhstepm,age,hstepm,xp,nlstate,stepm,oldm,savm, ij);  
                   3787:       prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ij);
                   3788: 
                   3789:       if (popbased==1) {
                   3790:        if(mobilav ==0){
                   3791:          for(i=1; i<=nlstate;i++)
                   3792:            prlim[i][i]=probs[(int)age][i][ij];
                   3793:        }else{ /* mobilav */ 
                   3794:          for(i=1; i<=nlstate;i++)
                   3795:            prlim[i][i]=mobaverage[(int)age][i][ij];
                   3796:        }
                   3797:       }
                   3798:   
                   3799:       for(j=1; j<= nlstate; j++){
                   3800:        for(h=0; h<=nhstepm; h++){
                   3801:          for(i=1, gp[h][j]=0.;i<=nlstate;i++)
                   3802:            gp[h][j] += prlim[i][i]*p3mat[i][j][h];
                   3803:        }
                   3804:       }
                   3805:       /* This for computing probability of death (h=1 means
                   3806:          computed over hstepm matrices product = hstepm*stepm months) 
                   3807:          as a weighted average of prlim.
                   3808:       */
                   3809:       for(j=nlstate+1;j<=nlstate+ndeath;j++){
                   3810:        for(i=1,gpp[j]=0.; i<= nlstate; i++)
                   3811:          gpp[j] += prlim[i][i]*p3mat[i][j][1];
                   3812:       }    
                   3813:       /* end probability of death */
                   3814: 
                   3815:       for(i=1; i<=npar; i++) /* Computes gradient x - delta */
                   3816:        xp[i] = x[i] - (i==theta ?delti[theta]:0);
                   3817:       hpxij(p3mat,nhstepm,age,hstepm,xp,nlstate,stepm,oldm,savm, ij);  
                   3818:       prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ij);
                   3819:  
                   3820:       if (popbased==1) {
                   3821:        if(mobilav ==0){
                   3822:          for(i=1; i<=nlstate;i++)
                   3823:            prlim[i][i]=probs[(int)age][i][ij];
                   3824:        }else{ /* mobilav */ 
                   3825:          for(i=1; i<=nlstate;i++)
                   3826:            prlim[i][i]=mobaverage[(int)age][i][ij];
                   3827:        }
                   3828:       }
                   3829: 
1.128     brouard  3830:       for(j=1; j<= nlstate; j++){  /* Sum of wi * eij = e.j */
1.126     brouard  3831:        for(h=0; h<=nhstepm; h++){
                   3832:          for(i=1, gm[h][j]=0.;i<=nlstate;i++)
                   3833:            gm[h][j] += prlim[i][i]*p3mat[i][j][h];
                   3834:        }
                   3835:       }
                   3836:       /* This for computing probability of death (h=1 means
                   3837:          computed over hstepm matrices product = hstepm*stepm months) 
                   3838:          as a weighted average of prlim.
                   3839:       */
                   3840:       for(j=nlstate+1;j<=nlstate+ndeath;j++){
                   3841:        for(i=1,gmp[j]=0.; i<= nlstate; i++)
                   3842:          gmp[j] += prlim[i][i]*p3mat[i][j][1];
                   3843:       }    
                   3844:       /* end probability of death */
                   3845: 
                   3846:       for(j=1; j<= nlstate; j++) /* vareij */
                   3847:        for(h=0; h<=nhstepm; h++){
                   3848:          gradg[h][theta][j]= (gp[h][j]-gm[h][j])/2./delti[theta];
                   3849:        }
                   3850: 
                   3851:       for(j=nlstate+1; j<= nlstate+ndeath; j++){ /* var mu */
                   3852:        gradgp[theta][j]= (gpp[j]-gmp[j])/2./delti[theta];
                   3853:       }
                   3854: 
                   3855:     } /* End theta */
                   3856: 
                   3857:     trgradg =ma3x(0,nhstepm,1,nlstate,1,npar); /* veij */
                   3858: 
                   3859:     for(h=0; h<=nhstepm; h++) /* veij */
                   3860:       for(j=1; j<=nlstate;j++)
                   3861:        for(theta=1; theta <=npar; theta++)
                   3862:          trgradg[h][j][theta]=gradg[h][theta][j];
                   3863: 
                   3864:     for(j=nlstate+1; j<=nlstate+ndeath;j++) /* mu */
                   3865:       for(theta=1; theta <=npar; theta++)
                   3866:        trgradgp[j][theta]=gradgp[theta][j];
                   3867:   
                   3868: 
                   3869:     hf=hstepm*stepm/YEARM;  /* Duration of hstepm expressed in year unit. */
                   3870:     for(i=1;i<=nlstate;i++)
                   3871:       for(j=1;j<=nlstate;j++)
                   3872:        vareij[i][j][(int)age] =0.;
                   3873: 
                   3874:     for(h=0;h<=nhstepm;h++){
                   3875:       for(k=0;k<=nhstepm;k++){
                   3876:        matprod2(dnewm,trgradg[h],1,nlstate,1,npar,1,npar,matcov);
                   3877:        matprod2(doldm,dnewm,1,nlstate,1,npar,1,nlstate,gradg[k]);
                   3878:        for(i=1;i<=nlstate;i++)
                   3879:          for(j=1;j<=nlstate;j++)
                   3880:            vareij[i][j][(int)age] += doldm[i][j]*hf*hf;
                   3881:       }
                   3882:     }
                   3883:   
                   3884:     /* pptj */
                   3885:     matprod2(dnewmp,trgradgp,nlstate+1,nlstate+ndeath,1,npar,1,npar,matcov);
                   3886:     matprod2(doldmp,dnewmp,nlstate+1,nlstate+ndeath,1,npar,nlstate+1,nlstate+ndeath,gradgp);
                   3887:     for(j=nlstate+1;j<=nlstate+ndeath;j++)
                   3888:       for(i=nlstate+1;i<=nlstate+ndeath;i++)
                   3889:        varppt[j][i]=doldmp[j][i];
                   3890:     /* end ppptj */
                   3891:     /*  x centered again */
                   3892:     hpxij(p3mat,nhstepm,age,hstepm,x,nlstate,stepm,oldm,savm, ij);  
                   3893:     prevalim(prlim,nlstate,x,age,oldm,savm,ftolpl,ij);
                   3894:  
                   3895:     if (popbased==1) {
                   3896:       if(mobilav ==0){
                   3897:        for(i=1; i<=nlstate;i++)
                   3898:          prlim[i][i]=probs[(int)age][i][ij];
                   3899:       }else{ /* mobilav */ 
                   3900:        for(i=1; i<=nlstate;i++)
                   3901:          prlim[i][i]=mobaverage[(int)age][i][ij];
                   3902:       }
                   3903:     }
                   3904:              
                   3905:     /* This for computing probability of death (h=1 means
                   3906:        computed over hstepm (estepm) matrices product = hstepm*stepm months) 
                   3907:        as a weighted average of prlim.
                   3908:     */
                   3909:     for(j=nlstate+1;j<=nlstate+ndeath;j++){
                   3910:       for(i=1,gmp[j]=0.;i<= nlstate; i++) 
                   3911:        gmp[j] += prlim[i][i]*p3mat[i][j][1]; 
                   3912:     }    
                   3913:     /* end probability of death */
                   3914: 
                   3915:     fprintf(ficresprobmorprev,"%3d %d ",(int) age, ij);
                   3916:     for(j=nlstate+1; j<=(nlstate+ndeath);j++){
                   3917:       fprintf(ficresprobmorprev," %11.3e %11.3e",gmp[j], sqrt(varppt[j][j]));
                   3918:       for(i=1; i<=nlstate;i++){
                   3919:        fprintf(ficresprobmorprev," %11.3e %11.3e ",prlim[i][i],p3mat[i][j][1]);
                   3920:       }
                   3921:     } 
                   3922:     fprintf(ficresprobmorprev,"\n");
                   3923: 
                   3924:     fprintf(ficresvij,"%.0f ",age );
                   3925:     for(i=1; i<=nlstate;i++)
                   3926:       for(j=1; j<=nlstate;j++){
                   3927:        fprintf(ficresvij," %.4f", vareij[i][j][(int)age]);
                   3928:       }
                   3929:     fprintf(ficresvij,"\n");
                   3930:     free_matrix(gp,0,nhstepm,1,nlstate);
                   3931:     free_matrix(gm,0,nhstepm,1,nlstate);
                   3932:     free_ma3x(gradg,0,nhstepm,1,npar,1,nlstate);
                   3933:     free_ma3x(trgradg,0,nhstepm,1,nlstate,1,npar);
                   3934:     free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   3935:   } /* End age */
                   3936:   free_vector(gpp,nlstate+1,nlstate+ndeath);
                   3937:   free_vector(gmp,nlstate+1,nlstate+ndeath);
                   3938:   free_matrix(gradgp,1,npar,nlstate+1,nlstate+ndeath);
                   3939:   free_matrix(trgradgp,nlstate+1,nlstate+ndeath,1,npar); /* mu or p point j*/
1.145     brouard  3940:   fprintf(ficgp,"\nunset parametric;unset label; set ter png small size 320, 240");
1.126     brouard  3941:   /* for(j=nlstate+1; j<= nlstate+ndeath; j++){ *//* Only the first actually */
1.131     brouard  3942:   fprintf(ficgp,"\n set log y; unset log x;set xlabel \"Age\"; set ylabel \"Force of mortality (year-1)\";");
1.126     brouard  3943: /*   fprintf(ficgp,"\n plot \"%s\"  u 1:($3*%6.3f) not w l 1 ",fileresprobmorprev,YEARM/estepm); */
                   3944: /*   fprintf(ficgp,"\n replot \"%s\"  u 1:(($3+1.96*$4)*%6.3f) t \"95\%% interval\" w l 2 ",fileresprobmorprev,YEARM/estepm); */
                   3945: /*   fprintf(ficgp,"\n replot \"%s\"  u 1:(($3-1.96*$4)*%6.3f) not w l 2 ",fileresprobmorprev,YEARM/estepm); */
1.145     brouard  3946:   fprintf(ficgp,"\n plot \"%s\"  u 1:($3) not w l lt 1 ",subdirf(fileresprobmorprev));
1.170     brouard  3947:   fprintf(ficgp,"\n replot \"%s\"  u 1:(($3+1.96*$4)) t \"95%% interval\" w l lt 2 ",subdirf(fileresprobmorprev));
1.145     brouard  3948:   fprintf(ficgp,"\n replot \"%s\"  u 1:(($3-1.96*$4)) not w l lt 2 ",subdirf(fileresprobmorprev));
1.126     brouard  3949:   fprintf(fichtm,"\n<br> File (multiple files are possible if covariates are present): <A href=\"%s\">%s</a>\n",subdirf(fileresprobmorprev),subdirf(fileresprobmorprev));
                   3950:   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);
                   3951:   /*  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);
                   3952: */
                   3953: /*   fprintf(ficgp,"\nset out \"varmuptjgr%s%s%s.png\";replot;",digitp,optionfilefiname,digit); */
                   3954:   fprintf(ficgp,"\nset out \"%s%s.png\";replot;\n",subdirf3(optionfilefiname,"varmuptjgr",digitp),digit);
                   3955: 
                   3956:   free_vector(xp,1,npar);
                   3957:   free_matrix(doldm,1,nlstate,1,nlstate);
                   3958:   free_matrix(dnewm,1,nlstate,1,npar);
                   3959:   free_matrix(doldmp,nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);
                   3960:   free_matrix(dnewmp,nlstate+1,nlstate+ndeath,1,npar);
                   3961:   free_matrix(varppt,nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);
                   3962:   if (mobilav!=0) free_ma3x(mobaverage,1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
                   3963:   fclose(ficresprobmorprev);
                   3964:   fflush(ficgp);
                   3965:   fflush(fichtm); 
                   3966: }  /* end varevsij */
                   3967: 
                   3968: /************ Variance of prevlim ******************/
                   3969: 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[])
                   3970: {
                   3971:   /* Variance of prevalence limit */
                   3972:   /*  double **prevalim(double **prlim, int nlstate, double *xp, double age, double **oldm, double **savm,double ftolpl);*/
1.164     brouard  3973: 
1.126     brouard  3974:   double **dnewm,**doldm;
                   3975:   int i, j, nhstepm, hstepm;
                   3976:   double *xp;
                   3977:   double *gp, *gm;
                   3978:   double **gradg, **trgradg;
                   3979:   double age,agelim;
                   3980:   int theta;
                   3981:   
                   3982:   pstamp(ficresvpl);
                   3983:   fprintf(ficresvpl,"# Standard deviation of period (stable) prevalences \n");
                   3984:   fprintf(ficresvpl,"# Age");
                   3985:   for(i=1; i<=nlstate;i++)
                   3986:       fprintf(ficresvpl," %1d-%1d",i,i);
                   3987:   fprintf(ficresvpl,"\n");
                   3988: 
                   3989:   xp=vector(1,npar);
                   3990:   dnewm=matrix(1,nlstate,1,npar);
                   3991:   doldm=matrix(1,nlstate,1,nlstate);
                   3992:   
                   3993:   hstepm=1*YEARM; /* Every year of age */
                   3994:   hstepm=hstepm/stepm; /* Typically in stepm units, if j= 2 years, = 2/6 months = 4 */ 
                   3995:   agelim = AGESUP;
                   3996:   for (age=bage; age<=fage; age ++){ /* If stepm=6 months */
                   3997:     nhstepm=(int) rint((agelim-age)*YEARM/stepm); /* Typically 20 years = 20*12/6=40 */ 
                   3998:     if (stepm >= YEARM) hstepm=1;
                   3999:     nhstepm = nhstepm/hstepm; /* Typically 40/4=10 */
                   4000:     gradg=matrix(1,npar,1,nlstate);
                   4001:     gp=vector(1,nlstate);
                   4002:     gm=vector(1,nlstate);
                   4003: 
                   4004:     for(theta=1; theta <=npar; theta++){
                   4005:       for(i=1; i<=npar; i++){ /* Computes gradient */
                   4006:        xp[i] = x[i] + (i==theta ?delti[theta]:0);
                   4007:       }
                   4008:       prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ij);
                   4009:       for(i=1;i<=nlstate;i++)
                   4010:        gp[i] = prlim[i][i];
                   4011:     
                   4012:       for(i=1; i<=npar; i++) /* Computes gradient */
                   4013:        xp[i] = x[i] - (i==theta ?delti[theta]:0);
                   4014:       prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ij);
                   4015:       for(i=1;i<=nlstate;i++)
                   4016:        gm[i] = prlim[i][i];
                   4017: 
                   4018:       for(i=1;i<=nlstate;i++)
                   4019:        gradg[theta][i]= (gp[i]-gm[i])/2./delti[theta];
                   4020:     } /* End theta */
                   4021: 
                   4022:     trgradg =matrix(1,nlstate,1,npar);
                   4023: 
                   4024:     for(j=1; j<=nlstate;j++)
                   4025:       for(theta=1; theta <=npar; theta++)
                   4026:        trgradg[j][theta]=gradg[theta][j];
                   4027: 
                   4028:     for(i=1;i<=nlstate;i++)
                   4029:       varpl[i][(int)age] =0.;
                   4030:     matprod2(dnewm,trgradg,1,nlstate,1,npar,1,npar,matcov);
                   4031:     matprod2(doldm,dnewm,1,nlstate,1,npar,1,nlstate,gradg);
                   4032:     for(i=1;i<=nlstate;i++)
                   4033:       varpl[i][(int)age] = doldm[i][i]; /* Covariances are useless */
                   4034: 
                   4035:     fprintf(ficresvpl,"%.0f ",age );
                   4036:     for(i=1; i<=nlstate;i++)
                   4037:       fprintf(ficresvpl," %.5f (%.5f)",prlim[i][i],sqrt(varpl[i][(int)age]));
                   4038:     fprintf(ficresvpl,"\n");
                   4039:     free_vector(gp,1,nlstate);
                   4040:     free_vector(gm,1,nlstate);
                   4041:     free_matrix(gradg,1,npar,1,nlstate);
                   4042:     free_matrix(trgradg,1,nlstate,1,npar);
                   4043:   } /* End age */
                   4044: 
                   4045:   free_vector(xp,1,npar);
                   4046:   free_matrix(doldm,1,nlstate,1,npar);
                   4047:   free_matrix(dnewm,1,nlstate,1,nlstate);
                   4048: 
                   4049: }
                   4050: 
                   4051: /************ Variance of one-step probabilities  ******************/
                   4052: 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[])
                   4053: {
1.164     brouard  4054:   int i, j=0,  k1, l1, tj;
1.126     brouard  4055:   int k2, l2, j1,  z1;
1.164     brouard  4056:   int k=0, l;
1.145     brouard  4057:   int first=1, first1, first2;
1.126     brouard  4058:   double cv12, mu1, mu2, lc1, lc2, v12, v21, v11, v22,v1,v2, c12, tnalp;
                   4059:   double **dnewm,**doldm;
                   4060:   double *xp;
                   4061:   double *gp, *gm;
                   4062:   double **gradg, **trgradg;
                   4063:   double **mu;
1.164     brouard  4064:   double age, cov[NCOVMAX+1];
1.126     brouard  4065:   double std=2.0; /* Number of standard deviation wide of confidence ellipsoids */
                   4066:   int theta;
                   4067:   char fileresprob[FILENAMELENGTH];
                   4068:   char fileresprobcov[FILENAMELENGTH];
                   4069:   char fileresprobcor[FILENAMELENGTH];
                   4070:   double ***varpij;
                   4071: 
                   4072:   strcpy(fileresprob,"prob"); 
                   4073:   strcat(fileresprob,fileres);
                   4074:   if((ficresprob=fopen(fileresprob,"w"))==NULL) {
                   4075:     printf("Problem with resultfile: %s\n", fileresprob);
                   4076:     fprintf(ficlog,"Problem with resultfile: %s\n", fileresprob);
                   4077:   }
                   4078:   strcpy(fileresprobcov,"probcov"); 
                   4079:   strcat(fileresprobcov,fileres);
                   4080:   if((ficresprobcov=fopen(fileresprobcov,"w"))==NULL) {
                   4081:     printf("Problem with resultfile: %s\n", fileresprobcov);
                   4082:     fprintf(ficlog,"Problem with resultfile: %s\n", fileresprobcov);
                   4083:   }
                   4084:   strcpy(fileresprobcor,"probcor"); 
                   4085:   strcat(fileresprobcor,fileres);
                   4086:   if((ficresprobcor=fopen(fileresprobcor,"w"))==NULL) {
                   4087:     printf("Problem with resultfile: %s\n", fileresprobcor);
                   4088:     fprintf(ficlog,"Problem with resultfile: %s\n", fileresprobcor);
                   4089:   }
                   4090:   printf("Computing standard deviation of one-step probabilities: result on file '%s' \n",fileresprob);
                   4091:   fprintf(ficlog,"Computing standard deviation of one-step probabilities: result on file '%s' \n",fileresprob);
                   4092:   printf("Computing matrix of variance covariance of one-step probabilities: result on file '%s' \n",fileresprobcov);
                   4093:   fprintf(ficlog,"Computing matrix of variance covariance of one-step probabilities: result on file '%s' \n",fileresprobcov);
                   4094:   printf("and correlation matrix of one-step probabilities: result on file '%s' \n",fileresprobcor);
                   4095:   fprintf(ficlog,"and correlation matrix of one-step probabilities: result on file '%s' \n",fileresprobcor);
                   4096:   pstamp(ficresprob);
                   4097:   fprintf(ficresprob,"#One-step probabilities and stand. devi in ()\n");
                   4098:   fprintf(ficresprob,"# Age");
                   4099:   pstamp(ficresprobcov);
                   4100:   fprintf(ficresprobcov,"#One-step probabilities and covariance matrix\n");
                   4101:   fprintf(ficresprobcov,"# Age");
                   4102:   pstamp(ficresprobcor);
                   4103:   fprintf(ficresprobcor,"#One-step probabilities and correlation matrix\n");
                   4104:   fprintf(ficresprobcor,"# Age");
                   4105: 
                   4106: 
                   4107:   for(i=1; i<=nlstate;i++)
                   4108:     for(j=1; j<=(nlstate+ndeath);j++){
                   4109:       fprintf(ficresprob," p%1d-%1d (SE)",i,j);
                   4110:       fprintf(ficresprobcov," p%1d-%1d ",i,j);
                   4111:       fprintf(ficresprobcor," p%1d-%1d ",i,j);
                   4112:     }  
                   4113:  /* fprintf(ficresprob,"\n");
                   4114:   fprintf(ficresprobcov,"\n");
                   4115:   fprintf(ficresprobcor,"\n");
                   4116:  */
1.131     brouard  4117:   xp=vector(1,npar);
1.126     brouard  4118:   dnewm=matrix(1,(nlstate)*(nlstate+ndeath),1,npar);
                   4119:   doldm=matrix(1,(nlstate)*(nlstate+ndeath),1,(nlstate)*(nlstate+ndeath));
                   4120:   mu=matrix(1,(nlstate)*(nlstate+ndeath), (int) bage, (int)fage);
                   4121:   varpij=ma3x(1,nlstate*(nlstate+ndeath),1,nlstate*(nlstate+ndeath),(int) bage, (int) fage);
                   4122:   first=1;
                   4123:   fprintf(ficgp,"\n# Routine varprob");
                   4124:   fprintf(fichtm,"\n<li><h4> Computing and drawing one step probabilities with their confidence intervals</h4></li>\n");
                   4125:   fprintf(fichtm,"\n");
                   4126: 
                   4127:   fprintf(fichtm,"\n<li><h4> <a href=\"%s\">Matrix of variance-covariance of pairs of step probabilities (drawings)</a></h4></li>\n",optionfilehtmcov);
                   4128:   fprintf(fichtmcov,"\n<h4>Matrix of variance-covariance of pairs of step probabilities</h4>\n\
                   4129:   file %s<br>\n",optionfilehtmcov);
                   4130:   fprintf(fichtmcov,"\nEllipsoids of confidence centered on point (p<inf>ij</inf>, p<inf>kl</inf>) are estimated\
                   4131: and drawn. It helps understanding how is the covariance between two incidences.\
                   4132:  They are expressed in year<sup>-1</sup> in order to be less dependent of stepm.<br>\n");
                   4133:   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. \
                   4134: It can be understood this way: if pij and pkl where uncorrelated the (2x2) matrix of covariance \
                   4135: would have been (1/(var pij), 0 , 0, 1/(var pkl)), and the confidence interval would be 2 \
                   4136: standard deviations wide on each axis. <br>\
                   4137:  Now, if both incidences are correlated (usual case) we diagonalised the inverse of the covariance matrix\
                   4138:  and made the appropriate rotation to look at the uncorrelated principal directions.<br>\
                   4139: To be simple, these graphs help to understand the significativity of each parameter in relation to a second other one.<br> \n");
                   4140: 
                   4141:   cov[1]=1;
1.145     brouard  4142:   /* tj=cptcoveff; */
                   4143:   tj = (int) pow(2,cptcoveff);
1.126     brouard  4144:   if (cptcovn<1) {tj=1;ncodemax[1]=1;}
                   4145:   j1=0;
1.145     brouard  4146:   for(j1=1; j1<=tj;j1++){
                   4147:     /*for(i1=1; i1<=ncodemax[t];i1++){ */
                   4148:     /*j1++;*/
1.126     brouard  4149:       if  (cptcovn>0) {
                   4150:        fprintf(ficresprob, "\n#********** Variable "); 
                   4151:        for (z1=1; z1<=cptcoveff; z1++) fprintf(ficresprob, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtab[j1][z1]]);
                   4152:        fprintf(ficresprob, "**********\n#\n");
                   4153:        fprintf(ficresprobcov, "\n#********** Variable "); 
                   4154:        for (z1=1; z1<=cptcoveff; z1++) fprintf(ficresprobcov, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtab[j1][z1]]);
                   4155:        fprintf(ficresprobcov, "**********\n#\n");
                   4156:        
                   4157:        fprintf(ficgp, "\n#********** Variable "); 
                   4158:        for (z1=1; z1<=cptcoveff; z1++) fprintf(ficgp, " V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtab[j1][z1]]);
                   4159:        fprintf(ficgp, "**********\n#\n");
                   4160:        
                   4161:        
                   4162:        fprintf(fichtmcov, "\n<hr  size=\"2\" color=\"#EC5E5E\">********** Variable "); 
                   4163:        for (z1=1; z1<=cptcoveff; z1++) fprintf(fichtm, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtab[j1][z1]]);
                   4164:        fprintf(fichtmcov, "**********\n<hr size=\"2\" color=\"#EC5E5E\">");
                   4165:        
                   4166:        fprintf(ficresprobcor, "\n#********** Variable ");    
                   4167:        for (z1=1; z1<=cptcoveff; z1++) fprintf(ficresprobcor, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtab[j1][z1]]);
                   4168:        fprintf(ficresprobcor, "**********\n#");    
                   4169:       }
                   4170:       
1.145     brouard  4171:       gradg=matrix(1,npar,1,(nlstate)*(nlstate+ndeath));
                   4172:       trgradg=matrix(1,(nlstate)*(nlstate+ndeath),1,npar);
                   4173:       gp=vector(1,(nlstate)*(nlstate+ndeath));
                   4174:       gm=vector(1,(nlstate)*(nlstate+ndeath));
1.126     brouard  4175:       for (age=bage; age<=fage; age ++){ 
                   4176:        cov[2]=age;
1.187     brouard  4177:        if(nagesqr==1)
                   4178:          cov[3]= age*age;
1.126     brouard  4179:        for (k=1; k<=cptcovn;k++) {
1.187     brouard  4180:          cov[2+nagesqr+k]=nbcode[Tvar[k]][codtab[j1][Tvar[k]]];/* j1 1 2 3 4
1.145     brouard  4181:                                                         * 1  1 1 1 1
                   4182:                                                         * 2  2 1 1 1
                   4183:                                                         * 3  1 2 1 1
                   4184:                                                         */
                   4185:          /* nbcode[1][1]=0 nbcode[1][2]=1;*/
1.126     brouard  4186:        }
1.186     brouard  4187:        /* for (k=1; k<=cptcovage;k++) cov[2+Tage[k]]=cov[2+Tage[k]]*cov[2]; */
                   4188:        for (k=1; k<=cptcovage;k++) cov[2+Tage[k]]=nbcode[Tvar[Tage[k]]][codtab[ij][Tvar[Tage[k]]]]*cov[2];
1.126     brouard  4189:        for (k=1; k<=cptcovprod;k++)
1.187     brouard  4190:          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  4191:        
                   4192:     
                   4193:        for(theta=1; theta <=npar; theta++){
                   4194:          for(i=1; i<=npar; i++)
                   4195:            xp[i] = x[i] + (i==theta ?delti[theta]:(double)0);
                   4196:          
                   4197:          pmij(pmmij,cov,ncovmodel,xp,nlstate);
                   4198:          
                   4199:          k=0;
                   4200:          for(i=1; i<= (nlstate); i++){
                   4201:            for(j=1; j<=(nlstate+ndeath);j++){
                   4202:              k=k+1;
                   4203:              gp[k]=pmmij[i][j];
                   4204:            }
                   4205:          }
                   4206:          
                   4207:          for(i=1; i<=npar; i++)
                   4208:            xp[i] = x[i] - (i==theta ?delti[theta]:(double)0);
                   4209:     
                   4210:          pmij(pmmij,cov,ncovmodel,xp,nlstate);
                   4211:          k=0;
                   4212:          for(i=1; i<=(nlstate); i++){
                   4213:            for(j=1; j<=(nlstate+ndeath);j++){
                   4214:              k=k+1;
                   4215:              gm[k]=pmmij[i][j];
                   4216:            }
                   4217:          }
                   4218:      
                   4219:          for(i=1; i<= (nlstate)*(nlstate+ndeath); i++) 
                   4220:            gradg[theta][i]=(gp[i]-gm[i])/(double)2./delti[theta];  
                   4221:        }
                   4222: 
                   4223:        for(j=1; j<=(nlstate)*(nlstate+ndeath);j++)
                   4224:          for(theta=1; theta <=npar; theta++)
                   4225:            trgradg[j][theta]=gradg[theta][j];
                   4226:        
                   4227:        matprod2(dnewm,trgradg,1,(nlstate)*(nlstate+ndeath),1,npar,1,npar,matcov); 
                   4228:        matprod2(doldm,dnewm,1,(nlstate)*(nlstate+ndeath),1,npar,1,(nlstate)*(nlstate+ndeath),gradg);
                   4229: 
                   4230:        pmij(pmmij,cov,ncovmodel,x,nlstate);
                   4231:        
                   4232:        k=0;
                   4233:        for(i=1; i<=(nlstate); i++){
                   4234:          for(j=1; j<=(nlstate+ndeath);j++){
                   4235:            k=k+1;
                   4236:            mu[k][(int) age]=pmmij[i][j];
                   4237:          }
                   4238:        }
                   4239:        for(i=1;i<=(nlstate)*(nlstate+ndeath);i++)
                   4240:          for(j=1;j<=(nlstate)*(nlstate+ndeath);j++)
                   4241:            varpij[i][j][(int)age] = doldm[i][j];
                   4242: 
                   4243:        /*printf("\n%d ",(int)age);
                   4244:          for (i=1; i<=(nlstate)*(nlstate+ndeath);i++){
                   4245:          printf("%e [%e ;%e] ",gm[i],gm[i]-2*sqrt(doldm[i][i]),gm[i]+2*sqrt(doldm[i][i]));
                   4246:          fprintf(ficlog,"%e [%e ;%e] ",gm[i],gm[i]-2*sqrt(doldm[i][i]),gm[i]+2*sqrt(doldm[i][i]));
                   4247:          }*/
                   4248: 
                   4249:        fprintf(ficresprob,"\n%d ",(int)age);
                   4250:        fprintf(ficresprobcov,"\n%d ",(int)age);
                   4251:        fprintf(ficresprobcor,"\n%d ",(int)age);
                   4252: 
                   4253:        for (i=1; i<=(nlstate)*(nlstate+ndeath);i++)
                   4254:          fprintf(ficresprob,"%11.3e (%11.3e) ",mu[i][(int) age],sqrt(varpij[i][i][(int)age]));
                   4255:        for (i=1; i<=(nlstate)*(nlstate+ndeath);i++){
                   4256:          fprintf(ficresprobcov,"%11.3e ",mu[i][(int) age]);
                   4257:          fprintf(ficresprobcor,"%11.3e ",mu[i][(int) age]);
                   4258:        }
                   4259:        i=0;
                   4260:        for (k=1; k<=(nlstate);k++){
                   4261:          for (l=1; l<=(nlstate+ndeath);l++){ 
1.145     brouard  4262:            i++;
1.126     brouard  4263:            fprintf(ficresprobcov,"\n%d %d-%d",(int)age,k,l);
                   4264:            fprintf(ficresprobcor,"\n%d %d-%d",(int)age,k,l);
                   4265:            for (j=1; j<=i;j++){
1.145     brouard  4266:              /* printf(" k=%d l=%d i=%d j=%d\n",k,l,i,j);fflush(stdout); */
1.126     brouard  4267:              fprintf(ficresprobcov," %11.3e",varpij[i][j][(int)age]);
                   4268:              fprintf(ficresprobcor," %11.3e",varpij[i][j][(int) age]/sqrt(varpij[i][i][(int) age])/sqrt(varpij[j][j][(int)age]));
                   4269:            }
                   4270:          }
                   4271:        }/* end of loop for state */
                   4272:       } /* end of loop for age */
1.145     brouard  4273:       free_vector(gp,1,(nlstate+ndeath)*(nlstate+ndeath));
                   4274:       free_vector(gm,1,(nlstate+ndeath)*(nlstate+ndeath));
                   4275:       free_matrix(trgradg,1,(nlstate+ndeath)*(nlstate+ndeath),1,npar);
                   4276:       free_matrix(gradg,1,(nlstate+ndeath)*(nlstate+ndeath),1,npar);
                   4277:       
1.126     brouard  4278:       /* Confidence intervalle of pij  */
                   4279:       /*
1.131     brouard  4280:        fprintf(ficgp,"\nunset parametric;unset label");
1.126     brouard  4281:        fprintf(ficgp,"\nset log y;unset log x; set xlabel \"Age\";set ylabel \"probability (year-1)\"");
                   4282:        fprintf(ficgp,"\nset ter png small\nset size 0.65,0.65");
                   4283:        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);
                   4284:        fprintf(fichtm,"\n<br><img src=\"pijgr%s.png\"> ",optionfilefiname);
                   4285:        fprintf(ficgp,"\nset out \"pijgr%s.png\"",optionfilefiname);
                   4286:        fprintf(ficgp,"\nplot \"%s\" every :::%d::%d u 1:2 \"\%%lf",k1,k2,xfilevarprob);
                   4287:       */
                   4288: 
                   4289:       /* Drawing ellipsoids of confidence of two variables p(k1-l1,k2-l2)*/
1.145     brouard  4290:       first1=1;first2=2;
1.126     brouard  4291:       for (k2=1; k2<=(nlstate);k2++){
                   4292:        for (l2=1; l2<=(nlstate+ndeath);l2++){ 
                   4293:          if(l2==k2) continue;
                   4294:          j=(k2-1)*(nlstate+ndeath)+l2;
                   4295:          for (k1=1; k1<=(nlstate);k1++){
                   4296:            for (l1=1; l1<=(nlstate+ndeath);l1++){ 
                   4297:              if(l1==k1) continue;
                   4298:              i=(k1-1)*(nlstate+ndeath)+l1;
                   4299:              if(i<=j) continue;
                   4300:              for (age=bage; age<=fage; age ++){ 
                   4301:                if ((int)age %5==0){
                   4302:                  v1=varpij[i][i][(int)age]/stepm*YEARM/stepm*YEARM;
                   4303:                  v2=varpij[j][j][(int)age]/stepm*YEARM/stepm*YEARM;
                   4304:                  cv12=varpij[i][j][(int)age]/stepm*YEARM/stepm*YEARM;
                   4305:                  mu1=mu[i][(int) age]/stepm*YEARM ;
                   4306:                  mu2=mu[j][(int) age]/stepm*YEARM;
                   4307:                  c12=cv12/sqrt(v1*v2);
                   4308:                  /* Computing eigen value of matrix of covariance */
                   4309:                  lc1=((v1+v2)+sqrt((v1+v2)*(v1+v2) - 4*(v1*v2-cv12*cv12)))/2.;
                   4310:                  lc2=((v1+v2)-sqrt((v1+v2)*(v1+v2) - 4*(v1*v2-cv12*cv12)))/2.;
1.135     brouard  4311:                  if ((lc2 <0) || (lc1 <0) ){
1.145     brouard  4312:                    if(first2==1){
                   4313:                      first1=0;
                   4314:                    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);
                   4315:                    }
                   4316:                    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);
                   4317:                    /* lc1=fabs(lc1); */ /* If we want to have them positive */
                   4318:                    /* lc2=fabs(lc2); */
1.135     brouard  4319:                  }
                   4320: 
1.126     brouard  4321:                  /* Eigen vectors */
                   4322:                  v11=(1./sqrt(1+(v1-lc1)*(v1-lc1)/cv12/cv12));
                   4323:                  /*v21=sqrt(1.-v11*v11); *//* error */
                   4324:                  v21=(lc1-v1)/cv12*v11;
                   4325:                  v12=-v21;
                   4326:                  v22=v11;
                   4327:                  tnalp=v21/v11;
                   4328:                  if(first1==1){
                   4329:                    first1=0;
                   4330:                    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);
                   4331:                  }
                   4332:                  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);
                   4333:                  /*printf(fignu*/
                   4334:                  /* mu1+ v11*lc1*cost + v12*lc2*sin(t) */
                   4335:                  /* mu2+ v21*lc1*cost + v22*lc2*sin(t) */
                   4336:                  if(first==1){
                   4337:                    first=0;
                   4338:                    fprintf(ficgp,"\nset parametric;unset label");
                   4339:                    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  4340:                    fprintf(ficgp,"\nset ter png small size 320, 240");
1.126     brouard  4341:                    fprintf(fichtmcov,"\n<br>Ellipsoids of confidence cov(p%1d%1d,p%1d%1d) expressed in year<sup>-1</sup>\
                   4342:  :<a href=\"%s%d%1d%1d-%1d%1d.png\">\
                   4343: %s%d%1d%1d-%1d%1d.png</A>, ",k1,l1,k2,l2,\
                   4344:                            subdirf2(optionfilefiname,"varpijgr"), j1,k1,l1,k2,l2,\
                   4345:                            subdirf2(optionfilefiname,"varpijgr"), j1,k1,l1,k2,l2);
                   4346:                    fprintf(fichtmcov,"\n<br><img src=\"%s%d%1d%1d-%1d%1d.png\"> ",subdirf2(optionfilefiname,"varpijgr"), j1,k1,l1,k2,l2);
                   4347:                    fprintf(fichtmcov,"\n<br> Correlation at age %d (%.3f),",(int) age, c12);
                   4348:                    fprintf(ficgp,"\nset out \"%s%d%1d%1d-%1d%1d.png\"",subdirf2(optionfilefiname,"varpijgr"), j1,k1,l1,k2,l2);
                   4349:                    fprintf(ficgp,"\nset label \"%d\" at %11.3e,%11.3e center",(int) age, mu1,mu2);
                   4350:                    fprintf(ficgp,"\n# Age %d, p%1d%1d - p%1d%1d",(int) age, k1,l1,k2,l2);
                   4351:                    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",\
                   4352:                            mu1,std,v11,sqrt(lc1),v12,sqrt(lc2),\
                   4353:                            mu2,std,v21,sqrt(lc1),v22,sqrt(lc2));
                   4354:                  }else{
                   4355:                    first=0;
                   4356:                    fprintf(fichtmcov," %d (%.3f),",(int) age, c12);
                   4357:                    fprintf(ficgp,"\n# Age %d, p%1d%1d - p%1d%1d",(int) age, k1,l1,k2,l2);
                   4358:                    fprintf(ficgp,"\nset label \"%d\" at %11.3e,%11.3e center",(int) age, mu1,mu2);
                   4359:                    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",\
                   4360:                            mu1,std,v11,sqrt(lc1),v12,sqrt(lc2),\
                   4361:                            mu2,std,v21,sqrt(lc1),v22,sqrt(lc2));
                   4362:                  }/* if first */
                   4363:                } /* age mod 5 */
                   4364:              } /* end loop age */
                   4365:              fprintf(ficgp,"\nset out \"%s%d%1d%1d-%1d%1d.png\";replot;",subdirf2(optionfilefiname,"varpijgr"), j1,k1,l1,k2,l2);
                   4366:              first=1;
                   4367:            } /*l12 */
                   4368:          } /* k12 */
                   4369:        } /*l1 */
                   4370:       }/* k1 */
1.169     brouard  4371:       /* } */ /* loop covariates */
1.126     brouard  4372:   }
                   4373:   free_ma3x(varpij,1,nlstate,1,nlstate+ndeath,(int) bage, (int)fage);
                   4374:   free_matrix(mu,1,(nlstate+ndeath)*(nlstate+ndeath),(int) bage, (int)fage);
                   4375:   free_matrix(doldm,1,(nlstate)*(nlstate+ndeath),1,(nlstate)*(nlstate+ndeath));
                   4376:   free_matrix(dnewm,1,(nlstate)*(nlstate+ndeath),1,npar);
                   4377:   free_vector(xp,1,npar);
                   4378:   fclose(ficresprob);
                   4379:   fclose(ficresprobcov);
                   4380:   fclose(ficresprobcor);
                   4381:   fflush(ficgp);
                   4382:   fflush(fichtmcov);
                   4383: }
                   4384: 
                   4385: 
                   4386: /******************* Printing html file ***********/
                   4387: void printinghtml(char fileres[], char title[], char datafile[], int firstpass, \
                   4388:                  int lastpass, int stepm, int weightopt, char model[],\
                   4389:                  int imx,int jmin, int jmax, double jmeanint,char rfileres[],\
                   4390:                  int popforecast, int estepm ,\
                   4391:                  double jprev1, double mprev1,double anprev1, \
                   4392:                  double jprev2, double mprev2,double anprev2){
                   4393:   int jj1, k1, i1, cpt;
                   4394: 
                   4395:    fprintf(fichtm,"<ul><li><a href='#firstorder'>Result files (first order: no variance)</a>\n \
                   4396:    <li><a href='#secondorder'>Result files (second order (variance)</a>\n \
                   4397: </ul>");
                   4398:    fprintf(fichtm,"<ul><li><h4><a name='firstorder'>Result files (first order: no variance)</a></h4>\n \
                   4399:  - Observed prevalence in each state (during the period defined between %.lf/%.lf/%.lf and %.lf/%.lf/%.lf): <a href=\"%s\">%s</a> <br>\n ",
                   4400:           jprev1, mprev1,anprev1,jprev2, mprev2,anprev2,subdirf2(fileres,"p"),subdirf2(fileres,"p"));
                   4401:    fprintf(fichtm,"\
                   4402:  - Estimated transition probabilities over %d (stepm) months: <a href=\"%s\">%s</a><br>\n ",
                   4403:           stepm,subdirf2(fileres,"pij"),subdirf2(fileres,"pij"));
                   4404:    fprintf(fichtm,"\
                   4405:  - Period (stable) prevalence in each health state: <a href=\"%s\">%s</a> <br>\n",
                   4406:           subdirf2(fileres,"pl"),subdirf2(fileres,"pl"));
                   4407:    fprintf(fichtm,"\
1.128     brouard  4408:  - (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  4409:    <a href=\"%s\">%s</a> <br>\n",
                   4410:           estepm,subdirf2(fileres,"e"),subdirf2(fileres,"e"));
                   4411:    fprintf(fichtm,"\
                   4412:  - Population projections by age and states: \
                   4413:    <a href=\"%s\">%s</a> <br>\n</li>", subdirf2(fileres,"f"),subdirf2(fileres,"f"));
                   4414: 
                   4415: fprintf(fichtm," \n<ul><li><b>Graphs</b></li><p>");
                   4416: 
1.145     brouard  4417:  m=pow(2,cptcoveff);
1.126     brouard  4418:  if (cptcovn < 1) {m=1;ncodemax[1]=1;}
                   4419: 
                   4420:  jj1=0;
                   4421:  for(k1=1; k1<=m;k1++){
                   4422:    for(i1=1; i1<=ncodemax[k1];i1++){
                   4423:      jj1++;
                   4424:      if (cptcovn > 0) {
                   4425:        fprintf(fichtm,"<hr  size=\"2\" color=\"#EC5E5E\">************ Results for covariates");
                   4426:        for (cpt=1; cpt<=cptcoveff;cpt++) 
                   4427:         fprintf(fichtm," V%d=%d ",Tvaraff[cpt],nbcode[Tvaraff[cpt]][codtab[jj1][cpt]]);
                   4428:        fprintf(fichtm," ************\n<hr size=\"2\" color=\"#EC5E5E\">");
                   4429:      }
                   4430:      /* Pij */
1.145     brouard  4431:      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> \
                   4432: <img src=\"%s%d_1.png\">",stepm,subdirf2(optionfilefiname,"pe"),jj1,subdirf2(optionfilefiname,"pe"),jj1,subdirf2(optionfilefiname,"pe"),jj1);     
1.126     brouard  4433:      /* Quasi-incidences */
                   4434:      fprintf(fichtm,"<br>- Pij or Conditional probabilities to be observed in state j being in state i %d (stepm) months\
1.145     brouard  4435:  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> \
                   4436: <img src=\"%s%d_2.png\">",stepm,subdirf2(optionfilefiname,"pe"),jj1,subdirf2(optionfilefiname,"pe"),jj1,subdirf2(optionfilefiname,"pe"),jj1); 
1.126     brouard  4437:        /* Period (stable) prevalence in each health state */
1.154     brouard  4438:        for(cpt=1; cpt<=nlstate;cpt++){
1.166     brouard  4439:         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> \
                   4440: <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  4441:        }
                   4442:      for(cpt=1; cpt<=nlstate;cpt++) {
1.154     brouard  4443:         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> \
                   4444: <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  4445:      }
                   4446:    } /* end i1 */
                   4447:  }/* End k1 */
                   4448:  fprintf(fichtm,"</ul>");
                   4449: 
                   4450: 
                   4451:  fprintf(fichtm,"\
                   4452: \n<br><li><h4> <a name='secondorder'>Result files (second order: variances)</a></h4>\n\
                   4453:  - Parameter file with estimated parameters and covariance matrix: <a href=\"%s\">%s</a> <br>\n", rfileres,rfileres);
                   4454: 
                   4455:  fprintf(fichtm," - Variance of one-step probabilities: <a href=\"%s\">%s</a> <br>\n",
                   4456:         subdirf2(fileres,"prob"),subdirf2(fileres,"prob"));
                   4457:  fprintf(fichtm,"\
                   4458:  - Variance-covariance of one-step probabilities: <a href=\"%s\">%s</a> <br>\n",
                   4459:         subdirf2(fileres,"probcov"),subdirf2(fileres,"probcov"));
                   4460: 
                   4461:  fprintf(fichtm,"\
                   4462:  - Correlation matrix of one-step probabilities: <a href=\"%s\">%s</a> <br>\n",
                   4463:         subdirf2(fileres,"probcor"),subdirf2(fileres,"probcor"));
                   4464:  fprintf(fichtm,"\
                   4465:  - 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): \
                   4466:    <a href=\"%s\">%s</a> <br>\n</li>",
                   4467:           estepm,subdirf2(fileres,"cve"),subdirf2(fileres,"cve"));
                   4468:  fprintf(fichtm,"\
                   4469:  - (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): \
                   4470:    <a href=\"%s\">%s</a> <br>\n</li>",
                   4471:           estepm,subdirf2(fileres,"stde"),subdirf2(fileres,"stde"));
                   4472:  fprintf(fichtm,"\
1.128     brouard  4473:  - 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  4474:         estepm, subdirf2(fileres,"v"),subdirf2(fileres,"v"));
                   4475:  fprintf(fichtm,"\
1.128     brouard  4476:  - 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",
                   4477:         estepm, subdirf2(fileres,"t"),subdirf2(fileres,"t"));
1.126     brouard  4478:  fprintf(fichtm,"\
                   4479:  - Standard deviation of period (stable) prevalences: <a href=\"%s\">%s</a> <br>\n",\
                   4480:         subdirf2(fileres,"vpl"),subdirf2(fileres,"vpl"));
                   4481: 
                   4482: /*  if(popforecast==1) fprintf(fichtm,"\n */
                   4483: /*  - Prevalences forecasting: <a href=\"f%s\">f%s</a> <br>\n */
                   4484: /*  - Population forecasting (if popforecast=1): <a href=\"pop%s\">pop%s</a> <br>\n */
                   4485: /*     <br>",fileres,fileres,fileres,fileres); */
                   4486: /*  else  */
                   4487: /*    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); */
                   4488:  fflush(fichtm);
                   4489:  fprintf(fichtm," <ul><li><b>Graphs</b></li><p>");
                   4490: 
1.145     brouard  4491:  m=pow(2,cptcoveff);
1.126     brouard  4492:  if (cptcovn < 1) {m=1;ncodemax[1]=1;}
                   4493: 
                   4494:  jj1=0;
                   4495:  for(k1=1; k1<=m;k1++){
                   4496:    for(i1=1; i1<=ncodemax[k1];i1++){
                   4497:      jj1++;
                   4498:      if (cptcovn > 0) {
                   4499:        fprintf(fichtm,"<hr  size=\"2\" color=\"#EC5E5E\">************ Results for covariates");
                   4500:        for (cpt=1; cpt<=cptcoveff;cpt++) 
                   4501:         fprintf(fichtm," V%d=%d ",Tvaraff[cpt],nbcode[Tvaraff[cpt]][codtab[jj1][cpt]]);
                   4502:        fprintf(fichtm," ************\n<hr size=\"2\" color=\"#EC5E5E\">");
                   4503:      }
                   4504:      for(cpt=1; cpt<=nlstate;cpt++) {
                   4505:        fprintf(fichtm,"<br>- Observed (cross-sectional) and period (incidence based) \
1.145     brouard  4506: prevalence (with 95%% confidence interval) in state (%d): %s%d_%d.png <br>\
                   4507: <img src=\"%s%d_%d.png\">",cpt,subdirf2(optionfilefiname,"v"),cpt,jj1,subdirf2(optionfilefiname,"v"),cpt,jj1);  
1.126     brouard  4508:      }
                   4509:      fprintf(fichtm,"\n<br>- Total life expectancy by age and \
1.128     brouard  4510: health expectancies in states (1) and (2). If popbased=1 the smooth (due to the model) \
                   4511: true period expectancies (those weighted with period prevalences are also\
                   4512:  drawn in addition to the population based expectancies computed using\
                   4513:  observed and cahotic prevalences: %s%d.png<br>\
1.126     brouard  4514: <img src=\"%s%d.png\">",subdirf2(optionfilefiname,"e"),jj1,subdirf2(optionfilefiname,"e"),jj1);
                   4515:    } /* end i1 */
                   4516:  }/* End k1 */
                   4517:  fprintf(fichtm,"</ul>");
                   4518:  fflush(fichtm);
                   4519: }
                   4520: 
                   4521: /******************* Gnuplot file **************/
                   4522: void printinggnuplot(char fileres[], char optionfilefiname[], double ageminpar, double agemaxpar, double fage , char pathc[], double p[]){
                   4523: 
                   4524:   char dirfileres[132],optfileres[132];
1.164     brouard  4525:   int cpt=0,k1=0,i=0,k=0,j=0,jk=0,k2=0,k3=0,ij=0,l=0;
1.130     brouard  4526:   int ng=0;
1.126     brouard  4527: /*   if((ficgp=fopen(optionfilegnuplot,"a"))==NULL) { */
                   4528: /*     printf("Problem with file %s",optionfilegnuplot); */
                   4529: /*     fprintf(ficlog,"Problem with file %s",optionfilegnuplot); */
                   4530: /*   } */
                   4531: 
                   4532:   /*#ifdef windows */
                   4533:   fprintf(ficgp,"cd \"%s\" \n",pathc);
                   4534:     /*#endif */
                   4535:   m=pow(2,cptcoveff);
                   4536: 
                   4537:   strcpy(dirfileres,optionfilefiname);
                   4538:   strcpy(optfileres,"vpl");
                   4539:  /* 1eme*/
1.153     brouard  4540:   fprintf(ficgp,"\n# 1st: Period (stable) prevalence with CI: 'vpl' files\n");
1.126     brouard  4541:   for (cpt=1; cpt<= nlstate ; cpt ++) {
1.145     brouard  4542:     for (k1=1; k1<= m ; k1 ++) { /* plot [100000000000000000000:-100000000000000000000] "mysbiaspar/vplrmysbiaspar.txt to check */
                   4543:      fprintf(ficgp,"\nset out \"%s%d_%d.png\" \n",subdirf2(optionfilefiname,"v"),cpt,k1);
                   4544:      fprintf(ficgp,"\n#set out \"v%s%d_%d.png\" \n",optionfilefiname,cpt,k1);
1.126     brouard  4545:      fprintf(ficgp,"set xlabel \"Age\" \n\
                   4546: set ylabel \"Probability\" \n\
1.145     brouard  4547: set ter png small size 320, 240\n\
1.170     brouard  4548: plot [%.f:%.f] \"%s\" every :::%d::%d u 1:2 \"%%lf",ageminpar,fage,subdirf2(fileres,"vpl"),k1-1,k1-1);
1.126     brouard  4549: 
                   4550:      for (i=1; i<= nlstate ; i ++) {
1.170     brouard  4551:        if (i==cpt) fprintf(ficgp," %%lf (%%lf)");
                   4552:        else        fprintf(ficgp," %%*lf (%%*lf)");
1.126     brouard  4553:      }
1.170     brouard  4554:      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  4555:      for (i=1; i<= nlstate ; i ++) {
1.170     brouard  4556:        if (i==cpt) fprintf(ficgp," %%lf (%%lf)");
                   4557:        else fprintf(ficgp," %%*lf (%%*lf)");
1.126     brouard  4558:      } 
1.170     brouard  4559:      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  4560:      for (i=1; i<= nlstate ; i ++) {
1.170     brouard  4561:        if (i==cpt) fprintf(ficgp," %%lf (%%lf)");
                   4562:        else fprintf(ficgp," %%*lf (%%*lf)");
1.126     brouard  4563:      }  
1.145     brouard  4564:      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  4565:    }
                   4566:   }
                   4567:   /*2 eme*/
1.153     brouard  4568:   fprintf(ficgp,"\n# 2nd: Total life expectancy with CI: 't' files\n");
1.126     brouard  4569:   for (k1=1; k1<= m ; k1 ++) { 
                   4570:     fprintf(ficgp,"\nset out \"%s%d.png\" \n",subdirf2(optionfilefiname,"e"),k1);
1.145     brouard  4571:     fprintf(ficgp,"set ylabel \"Years\" \nset ter png small size 320, 240\nplot [%.f:%.f] ",ageminpar,fage);
1.126     brouard  4572:     
                   4573:     for (i=1; i<= nlstate+1 ; i ++) {
                   4574:       k=2*i;
1.170     brouard  4575:       fprintf(ficgp,"\"%s\" every :::%d::%d u 1:2 \"%%lf",subdirf2(fileres,"t"),k1-1,k1-1);
1.126     brouard  4576:       for (j=1; j<= nlstate+1 ; j ++) {
1.170     brouard  4577:        if (j==i) fprintf(ficgp," %%lf (%%lf)");
                   4578:        else fprintf(ficgp," %%*lf (%%*lf)");
1.126     brouard  4579:       }   
                   4580:       if (i== 1) fprintf(ficgp,"\" t\"TLE\" w l ,");
                   4581:       else fprintf(ficgp,"\" t\"LE in state (%d)\" w l ,",i-1);
1.170     brouard  4582:       fprintf(ficgp,"\"%s\" every :::%d::%d u 1:($2-$3*2) \"%%lf",subdirf2(fileres,"t"),k1-1,k1-1);
1.126     brouard  4583:       for (j=1; j<= nlstate+1 ; j ++) {
1.170     brouard  4584:        if (j==i) fprintf(ficgp," %%lf (%%lf)");
                   4585:        else fprintf(ficgp," %%*lf (%%*lf)");
1.126     brouard  4586:       }   
1.145     brouard  4587:       fprintf(ficgp,"\" t\"\" w l lt 0,");
1.170     brouard  4588:       fprintf(ficgp,"\"%s\" every :::%d::%d u 1:($2+$3*2) \"%%lf",subdirf2(fileres,"t"),k1-1,k1-1);
1.126     brouard  4589:       for (j=1; j<= nlstate+1 ; j ++) {
1.170     brouard  4590:        if (j==i) fprintf(ficgp," %%lf (%%lf)");
                   4591:        else fprintf(ficgp," %%*lf (%%*lf)");
1.126     brouard  4592:       }   
1.145     brouard  4593:       if (i== (nlstate+1)) fprintf(ficgp,"\" t\"\" w l lt 0");
                   4594:       else fprintf(ficgp,"\" t\"\" w l lt 0,");
1.126     brouard  4595:     }
                   4596:   }
                   4597:   
                   4598:   /*3eme*/
                   4599:   
                   4600:   for (k1=1; k1<= m ; k1 ++) { 
                   4601:     for (cpt=1; cpt<= nlstate ; cpt ++) {
                   4602:       /*       k=2+nlstate*(2*cpt-2); */
                   4603:       k=2+(nlstate+1)*(cpt-1);
                   4604:       fprintf(ficgp,"\nset out \"%s%d%d.png\" \n",subdirf2(optionfilefiname,"exp"),cpt,k1);
1.145     brouard  4605:       fprintf(ficgp,"set ter png small size 320, 240\n\
1.126     brouard  4606: 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);
                   4607:       /*fprintf(ficgp,",\"e%s\" every :::%d::%d u 1:($%d-2*$%d) \"\%%lf ",fileres,k1-1,k1-1,k,k+1);
                   4608:        for (i=1; i<= nlstate*2 ; i ++) fprintf(ficgp,"\%%lf (\%%lf) ");
                   4609:        fprintf(ficgp,"\" t \"e%d1\" w l",cpt);
                   4610:        fprintf(ficgp,",\"e%s\" every :::%d::%d u 1:($%d+2*$%d) \"\%%lf ",fileres,k1-1,k1-1,k,k+1);
                   4611:        for (i=1; i<= nlstate*2 ; i ++) fprintf(ficgp,"\%%lf (\%%lf) ");
                   4612:        fprintf(ficgp,"\" t \"e%d1\" w l",cpt);
                   4613:        
                   4614:       */
                   4615:       for (i=1; i< nlstate ; i ++) {
                   4616:        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);
                   4617:        /*      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);*/
                   4618:        
                   4619:       } 
                   4620:       fprintf(ficgp," ,\"%s\" every :::%d::%d u 1:%d t \"e%d.\" w l",subdirf2(fileres,"e"),k1-1,k1-1,k+nlstate,cpt);
                   4621:     }
                   4622:   }
                   4623:   
                   4624:   /* CV preval stable (period) */
1.153     brouard  4625:   for (k1=1; k1<= m ; k1 ++) { /* For each multivariate if any */
                   4626:     for (cpt=1; cpt<=nlstate ; cpt ++) { /* For each life state */
1.126     brouard  4627:       k=3;
1.153     brouard  4628:       fprintf(ficgp,"\n#\n#\n#CV preval stable (period): 'pij' files, cov=%d state=%d",k1, cpt);
1.145     brouard  4629:       fprintf(ficgp,"\nset out \"%s%d_%d.png\" \n",subdirf2(optionfilefiname,"p"),cpt,k1);
1.126     brouard  4630:       fprintf(ficgp,"set xlabel \"Age\" \nset ylabel \"Probability\" \n\
1.145     brouard  4631: set ter png small size 320, 240\n\
1.126     brouard  4632: unset log y\n\
1.153     brouard  4633: plot [%.f:%.f]  ", ageminpar, agemaxpar);
                   4634:       for (i=1; i<= nlstate ; i ++){
                   4635:        if(i==1)
                   4636:          fprintf(ficgp,"\"%s\"",subdirf2(fileres,"pij"));
                   4637:        else
                   4638:          fprintf(ficgp,", '' ");
1.154     brouard  4639:        l=(nlstate+ndeath)*(i-1)+1;
                   4640:        fprintf(ficgp," u ($1==%d ? ($3):1/0):($%d/($%d",k1,k+l+(cpt-1),k+l);
1.153     brouard  4641:        for (j=1; j<= (nlstate-1) ; j ++)
                   4642:          fprintf(ficgp,"+$%d",k+l+j);
                   4643:        fprintf(ficgp,")) t \"prev(%d,%d)\" w l",i,cpt);
                   4644:       } /* nlstate */
                   4645:       fprintf(ficgp,"\n");
                   4646:     } /* end cpt state*/ 
                   4647:   } /* end covariate */  
1.126     brouard  4648:   
                   4649:   /* proba elementaires */
1.187     brouard  4650:   fprintf(ficgp,"\n##############\n#MLE estimated parameters\n#############\n");
1.126     brouard  4651:   for(i=1,jk=1; i <=nlstate; i++){
1.187     brouard  4652:     fprintf(ficgp,"# initial state %d\n",i);
1.126     brouard  4653:     for(k=1; k <=(nlstate+ndeath); k++){
                   4654:       if (k != i) {
1.187     brouard  4655:        fprintf(ficgp,"#   current state %d\n",k);
1.126     brouard  4656:        for(j=1; j <=ncovmodel; j++){
1.187     brouard  4657:          fprintf(ficgp,"p%d=%f; ",jk,p[jk]);
1.126     brouard  4658:          jk++; 
                   4659:        }
1.187     brouard  4660:        fprintf(ficgp,"\n");
1.126     brouard  4661:       }
                   4662:     }
                   4663:    }
1.187     brouard  4664:   fprintf(ficgp,"##############\n#\n");
                   4665: 
1.145     brouard  4666:   /*goto avoid;*/
1.187     brouard  4667:   fprintf(ficgp,"\n##############\n#Graphics of of probabilities or incidences\n#############\n");
                   4668:   fprintf(ficgp,"# logi(p12/p11)=a12+b12*age+c12age*age+d12*V1+e12*V1*age\n");
                   4669:   fprintf(ficgp,"# logi(p12/p11)=p1 +p2*age +p3*age*age+ p4*V1+ p5*V1*age\n");
                   4670:   fprintf(ficgp,"# logi(p13/p11)=a13+b13*age+c13age*age+d13*V1+e13*V1*age\n");
                   4671:   fprintf(ficgp,"# logi(p13/p11)=p6 +p7*age +p8*age*age+ p9*V1+ p10*V1*age\n");
                   4672:   fprintf(ficgp,"# p12+p13+p14+p11=1=p11(1+exp(a12+b12*age+c12age*age+d12*V1+e12*V1*age)\n");
                   4673:   fprintf(ficgp,"#                      +exp(a13+b13*age+c13age*age+d13*V1+e13*V1*age)+...)\n");
                   4674:   fprintf(ficgp,"# p11=1/(1+exp(a12+b12*age+c12age*age+d12*V1+e12*V1*age)\n");
                   4675:   fprintf(ficgp,"#                      +exp(a13+b13*age+c13age*age+d13*V1+e13*V1*age)+...)\n");
                   4676:   fprintf(ficgp,"# p12=exp(a12+b12*age+c12age*age+d12*V1+e12*V1*age)/\n");
                   4677:   fprintf(ficgp,"#     (1+exp(a12+b12*age+c12age*age+d12*V1+e12*V1*age)\n");
                   4678:   fprintf(ficgp,"#       +exp(a13+b13*age+c13age*age+d13*V1+e13*V1*age))\n");
                   4679:   fprintf(ficgp,"#       +exp(a14+b14*age+c14age*age+d14*V1+e14*V1*age)+...)\n");
                   4680:   fprintf(ficgp,"#\n");
1.126     brouard  4681:    for(ng=1; ng<=2;ng++){ /* Number of graphics: first is probabilities second is incidence per year*/
1.187     brouard  4682:      fprintf(ficgp,"# ng=%d\n",ng);
                   4683:      fprintf(ficgp,"#   jk=1 to 2^%d=%d\n",cptcoveff,m);
1.126     brouard  4684:      for(jk=1; jk <=m; jk++) {
1.187     brouard  4685:        fprintf(ficgp,"#    jk=%d\n",jk);
1.145     brouard  4686:        fprintf(ficgp,"\nset out \"%s%d_%d.png\" \n",subdirf2(optionfilefiname,"pe"),jk,ng); 
1.126     brouard  4687:        if (ng==2)
                   4688:         fprintf(ficgp,"\nset ylabel \"Quasi-incidence per year\"\n");
                   4689:        else
                   4690:         fprintf(ficgp,"\nset title \"Probability\"\n");
1.145     brouard  4691:        fprintf(ficgp,"\nset ter png small size 320, 240\nset log y\nplot  [%.f:%.f] ",ageminpar,agemaxpar);
1.126     brouard  4692:        i=1;
                   4693:        for(k2=1; k2<=nlstate; k2++) {
                   4694:         k3=i;
                   4695:         for(k=1; k<=(nlstate+ndeath); k++) {
                   4696:           if (k != k2){
                   4697:             if(ng==2)
1.187     brouard  4698:               if(nagesqr==0)
                   4699:                 fprintf(ficgp," %f*exp(p%d+p%d*x",YEARM/stepm,i,i+1);
                   4700:               else /* nagesqr =1 */
                   4701:                 fprintf(ficgp," %f*exp(p%d+p%d*x+p%d*x*x",YEARM/stepm,i,i+1,i+1+nagesqr);
1.126     brouard  4702:             else
1.187     brouard  4703:               if(nagesqr==0)
                   4704:                 fprintf(ficgp," exp(p%d+p%d*x",i,i+1);
                   4705:               else /* nagesqr =1 */
                   4706:                 fprintf(ficgp," exp(p%d+p%d*x+p%d*x*x",i,i+1,i+1+nagesqr);
1.141     brouard  4707:             ij=1;/* To be checked else nbcode[0][0] wrong */
1.187     brouard  4708:             for(j=3; j <=ncovmodel-nagesqr; j++) {
1.186     brouard  4709:               if(((j-2)==Tage[ij]) &&(ij <=cptcovage)) { /* Bug valgrind */
1.187     brouard  4710:                 fprintf(ficgp,"+p%d*%d*x",i+j+nagesqr-1,nbcode[Tvar[j-2]][codtab[jk][Tvar[j-2]]]);
1.186     brouard  4711:                 ij++;
                   4712:               }
                   4713:               else
1.187     brouard  4714:                 fprintf(ficgp,"+p%d*%d",i+j+nagesqr-1,nbcode[Tvar[j-2]][codtab[jk][j-2]]);
1.126     brouard  4715:             }
                   4716:             fprintf(ficgp,")/(1");
                   4717:             
1.187     brouard  4718:             for(k1=1; k1 <=nlstate; k1++){ 
                   4719:               if(nagesqr==0)
                   4720:                 fprintf(ficgp,"+exp(p%d+p%d*x",k3+(k1-1)*ncovmodel,k3+(k1-1)*ncovmodel+1);
                   4721:               else /* nagesqr =1 */
                   4722:                 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);
                   4723:   
1.126     brouard  4724:               ij=1;
1.187     brouard  4725:               for(j=3; j <=ncovmodel-nagesqr; j++){
1.186     brouard  4726:                 if(((j-2)==Tage[ij]) &&(ij <=cptcovage)) {
1.187     brouard  4727:                   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  4728:                   ij++;
                   4729:                 }
                   4730:                 else
1.187     brouard  4731:                   fprintf(ficgp,"+p%d*%d",k3+(k1-1)*ncovmodel+1+j-2+nagesqr,nbcode[Tvar[j-2]][codtab[jk][j-2]]);
1.126     brouard  4732:               }
                   4733:               fprintf(ficgp,")");
                   4734:             }
                   4735:             fprintf(ficgp,") t \"p%d%d\" ", k2,k);
                   4736:             if ((k+k2)!= (nlstate*2+ndeath)) fprintf(ficgp,",");
                   4737:             i=i+ncovmodel;
                   4738:           }
                   4739:         } /* end k */
                   4740:        } /* end k2 */
                   4741:      } /* end jk */
                   4742:    } /* end ng */
1.164     brouard  4743:  /* avoid: */
1.126     brouard  4744:    fflush(ficgp); 
                   4745: }  /* end gnuplot */
                   4746: 
                   4747: 
                   4748: /*************** Moving average **************/
                   4749: int movingaverage(double ***probs, double bage,double fage, double ***mobaverage, int mobilav){
                   4750: 
                   4751:   int i, cpt, cptcod;
                   4752:   int modcovmax =1;
                   4753:   int mobilavrange, mob;
                   4754:   double age;
                   4755: 
                   4756:   modcovmax=2*cptcoveff;/* Max number of modalities. We suppose 
                   4757:                           a covariate has 2 modalities */
                   4758:   if (cptcovn<1) modcovmax=1; /* At least 1 pass */
                   4759: 
                   4760:   if(mobilav==1||mobilav ==3 ||mobilav==5 ||mobilav== 7){
                   4761:     if(mobilav==1) mobilavrange=5; /* default */
                   4762:     else mobilavrange=mobilav;
                   4763:     for (age=bage; age<=fage; age++)
                   4764:       for (i=1; i<=nlstate;i++)
                   4765:        for (cptcod=1;cptcod<=modcovmax;cptcod++)
                   4766:          mobaverage[(int)age][i][cptcod]=probs[(int)age][i][cptcod];
                   4767:     /* We keep the original values on the extreme ages bage, fage and for 
                   4768:        fage+1 and bage-1 we use a 3 terms moving average; for fage+2 bage+2
                   4769:        we use a 5 terms etc. until the borders are no more concerned. 
                   4770:     */ 
                   4771:     for (mob=3;mob <=mobilavrange;mob=mob+2){
                   4772:       for (age=bage+(mob-1)/2; age<=fage-(mob-1)/2; age++){
                   4773:        for (i=1; i<=nlstate;i++){
                   4774:          for (cptcod=1;cptcod<=modcovmax;cptcod++){
                   4775:            mobaverage[(int)age][i][cptcod] =probs[(int)age][i][cptcod];
                   4776:              for (cpt=1;cpt<=(mob-1)/2;cpt++){
                   4777:                mobaverage[(int)age][i][cptcod] +=probs[(int)age-cpt][i][cptcod];
                   4778:                mobaverage[(int)age][i][cptcod] +=probs[(int)age+cpt][i][cptcod];
                   4779:              }
                   4780:            mobaverage[(int)age][i][cptcod]=mobaverage[(int)age][i][cptcod]/mob;
                   4781:          }
                   4782:        }
                   4783:       }/* end age */
                   4784:     }/* end mob */
                   4785:   }else return -1;
                   4786:   return 0;
                   4787: }/* End movingaverage */
                   4788: 
                   4789: 
                   4790: /************** Forecasting ******************/
1.169     brouard  4791: 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  4792:   /* proj1, year, month, day of starting projection 
                   4793:      agemin, agemax range of age
                   4794:      dateprev1 dateprev2 range of dates during which prevalence is computed
                   4795:      anproj2 year of en of projection (same day and month as proj1).
                   4796:   */
1.164     brouard  4797:   int yearp, stepsize, hstepm, nhstepm, j, k, cptcod, i, h, i1;
1.126     brouard  4798:   double agec; /* generic age */
                   4799:   double agelim, ppij, yp,yp1,yp2,jprojmean,mprojmean,anprojmean;
                   4800:   double *popeffectif,*popcount;
                   4801:   double ***p3mat;
                   4802:   double ***mobaverage;
                   4803:   char fileresf[FILENAMELENGTH];
                   4804: 
                   4805:   agelim=AGESUP;
                   4806:   prevalence(probs, ageminpar, agemax, s, agev, nlstate, imx, Tvar, nbcode, ncodemax, mint, anint, dateprev1, dateprev2, firstpass, lastpass);
                   4807:  
                   4808:   strcpy(fileresf,"f"); 
                   4809:   strcat(fileresf,fileres);
                   4810:   if((ficresf=fopen(fileresf,"w"))==NULL) {
                   4811:     printf("Problem with forecast resultfile: %s\n", fileresf);
                   4812:     fprintf(ficlog,"Problem with forecast resultfile: %s\n", fileresf);
                   4813:   }
                   4814:   printf("Computing forecasting: result on file '%s' \n", fileresf);
                   4815:   fprintf(ficlog,"Computing forecasting: result on file '%s' \n", fileresf);
                   4816: 
                   4817:   if (cptcoveff==0) ncodemax[cptcoveff]=1;
                   4818: 
                   4819:   if (mobilav!=0) {
                   4820:     mobaverage= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
                   4821:     if (movingaverage(probs, ageminpar, fage, mobaverage,mobilav)!=0){
                   4822:       fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav);
                   4823:       printf(" Error in movingaverage mobilav=%d\n",mobilav);
                   4824:     }
                   4825:   }
                   4826: 
                   4827:   stepsize=(int) (stepm+YEARM-1)/YEARM;
                   4828:   if (stepm<=12) stepsize=1;
                   4829:   if(estepm < stepm){
                   4830:     printf ("Problem %d lower than %d\n",estepm, stepm);
                   4831:   }
                   4832:   else  hstepm=estepm;   
                   4833: 
                   4834:   hstepm=hstepm/stepm; 
                   4835:   yp1=modf(dateintmean,&yp);/* extracts integral of datemean in yp  and
                   4836:                                fractional in yp1 */
                   4837:   anprojmean=yp;
                   4838:   yp2=modf((yp1*12),&yp);
                   4839:   mprojmean=yp;
                   4840:   yp1=modf((yp2*30.5),&yp);
                   4841:   jprojmean=yp;
                   4842:   if(jprojmean==0) jprojmean=1;
                   4843:   if(mprojmean==0) jprojmean=1;
                   4844: 
                   4845:   i1=cptcoveff;
                   4846:   if (cptcovn < 1){i1=1;}
                   4847:   
                   4848:   fprintf(ficresf,"# Mean day of interviews %.lf/%.lf/%.lf (%.2f) between %.2f and %.2f \n",jprojmean,mprojmean,anprojmean,dateintmean,dateprev1,dateprev2); 
                   4849:   
                   4850:   fprintf(ficresf,"#****** Routine prevforecast **\n");
                   4851: 
                   4852: /*           if (h==(int)(YEARM*yearp)){ */
                   4853:   for(cptcov=1, k=0;cptcov<=i1;cptcov++){
                   4854:     for(cptcod=1;cptcod<=ncodemax[cptcoveff];cptcod++){
                   4855:       k=k+1;
                   4856:       fprintf(ficresf,"\n#******");
                   4857:       for(j=1;j<=cptcoveff;j++) {
                   4858:        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]]);
                   4859:       }
                   4860:       fprintf(ficresf,"******\n");
                   4861:       fprintf(ficresf,"# Covariate valuofcovar yearproj age");
                   4862:       for(j=1; j<=nlstate+ndeath;j++){ 
                   4863:        for(i=1; i<=nlstate;i++)              
                   4864:           fprintf(ficresf," p%d%d",i,j);
                   4865:        fprintf(ficresf," p.%d",j);
                   4866:       }
                   4867:       for (yearp=0; yearp<=(anproj2-anproj1);yearp +=stepsize) { 
                   4868:        fprintf(ficresf,"\n");
                   4869:        fprintf(ficresf,"\n# Forecasting at date %.lf/%.lf/%.lf ",jproj1,mproj1,anproj1+yearp);   
                   4870: 
                   4871:        for (agec=fage; agec>=(ageminpar-1); agec--){ 
                   4872:          nhstepm=(int) rint((agelim-agec)*YEARM/stepm); 
                   4873:          nhstepm = nhstepm/hstepm; 
                   4874:          p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   4875:          oldm=oldms;savm=savms;
                   4876:          hpxij(p3mat,nhstepm,agec,hstepm,p,nlstate,stepm,oldm,savm, k);  
                   4877:        
                   4878:          for (h=0; h<=nhstepm; h++){
                   4879:            if (h*hstepm/YEARM*stepm ==yearp) {
                   4880:               fprintf(ficresf,"\n");
                   4881:               for(j=1;j<=cptcoveff;j++) 
                   4882:                 fprintf(ficresf,"%d %d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
                   4883:              fprintf(ficresf,"%.f %.f ",anproj1+yearp,agec+h*hstepm/YEARM*stepm);
                   4884:            } 
                   4885:            for(j=1; j<=nlstate+ndeath;j++) {
                   4886:              ppij=0.;
                   4887:              for(i=1; i<=nlstate;i++) {
                   4888:                if (mobilav==1) 
                   4889:                  ppij=ppij+p3mat[i][j][h]*mobaverage[(int)agec][i][cptcod];
                   4890:                else {
                   4891:                  ppij=ppij+p3mat[i][j][h]*probs[(int)(agec)][i][cptcod];
                   4892:                }
                   4893:                if (h*hstepm/YEARM*stepm== yearp) {
                   4894:                  fprintf(ficresf," %.3f", p3mat[i][j][h]);
                   4895:                }
                   4896:              } /* end i */
                   4897:              if (h*hstepm/YEARM*stepm==yearp) {
                   4898:                fprintf(ficresf," %.3f", ppij);
                   4899:              }
                   4900:            }/* end j */
                   4901:          } /* end h */
                   4902:          free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   4903:        } /* end agec */
                   4904:       } /* end yearp */
                   4905:     } /* end cptcod */
                   4906:   } /* end  cptcov */
                   4907:        
                   4908:   if (mobilav!=0) free_ma3x(mobaverage,1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
                   4909: 
                   4910:   fclose(ficresf);
                   4911: }
                   4912: 
                   4913: /************** Forecasting *****not tested NB*************/
1.169     brouard  4914: 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  4915:   
                   4916:   int cpt, stepsize, hstepm, nhstepm, j,k,c, cptcod, i,h;
                   4917:   int *popage;
                   4918:   double calagedatem, agelim, kk1, kk2;
                   4919:   double *popeffectif,*popcount;
                   4920:   double ***p3mat,***tabpop,***tabpopprev;
                   4921:   double ***mobaverage;
                   4922:   char filerespop[FILENAMELENGTH];
                   4923: 
                   4924:   tabpop= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
                   4925:   tabpopprev= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
                   4926:   agelim=AGESUP;
                   4927:   calagedatem=(anpyram+mpyram/12.+jpyram/365.-dateintmean)*YEARM;
                   4928:   
                   4929:   prevalence(probs, ageminpar, agemax, s, agev, nlstate, imx, Tvar, nbcode, ncodemax, mint, anint, dateprev1, dateprev2, firstpass, lastpass);
                   4930:   
                   4931:   
                   4932:   strcpy(filerespop,"pop"); 
                   4933:   strcat(filerespop,fileres);
                   4934:   if((ficrespop=fopen(filerespop,"w"))==NULL) {
                   4935:     printf("Problem with forecast resultfile: %s\n", filerespop);
                   4936:     fprintf(ficlog,"Problem with forecast resultfile: %s\n", filerespop);
                   4937:   }
                   4938:   printf("Computing forecasting: result on file '%s' \n", filerespop);
                   4939:   fprintf(ficlog,"Computing forecasting: result on file '%s' \n", filerespop);
                   4940: 
                   4941:   if (cptcoveff==0) ncodemax[cptcoveff]=1;
                   4942: 
                   4943:   if (mobilav!=0) {
                   4944:     mobaverage= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
                   4945:     if (movingaverage(probs, ageminpar, fage, mobaverage,mobilav)!=0){
                   4946:       fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav);
                   4947:       printf(" Error in movingaverage mobilav=%d\n",mobilav);
                   4948:     }
                   4949:   }
                   4950: 
                   4951:   stepsize=(int) (stepm+YEARM-1)/YEARM;
                   4952:   if (stepm<=12) stepsize=1;
                   4953:   
                   4954:   agelim=AGESUP;
                   4955:   
                   4956:   hstepm=1;
                   4957:   hstepm=hstepm/stepm; 
                   4958:   
                   4959:   if (popforecast==1) {
                   4960:     if((ficpop=fopen(popfile,"r"))==NULL) {
                   4961:       printf("Problem with population file : %s\n",popfile);exit(0);
                   4962:       fprintf(ficlog,"Problem with population file : %s\n",popfile);exit(0);
                   4963:     } 
                   4964:     popage=ivector(0,AGESUP);
                   4965:     popeffectif=vector(0,AGESUP);
                   4966:     popcount=vector(0,AGESUP);
                   4967:     
                   4968:     i=1;   
                   4969:     while ((c=fscanf(ficpop,"%d %lf\n",&popage[i],&popcount[i])) != EOF) i=i+1;
                   4970:    
                   4971:     imx=i;
                   4972:     for (i=1; i<imx;i++) popeffectif[popage[i]]=popcount[i];
                   4973:   }
                   4974: 
                   4975:   for(cptcov=1,k=0;cptcov<=i2;cptcov++){
                   4976:    for(cptcod=1;cptcod<=ncodemax[cptcoveff];cptcod++){
                   4977:       k=k+1;
                   4978:       fprintf(ficrespop,"\n#******");
                   4979:       for(j=1;j<=cptcoveff;j++) {
                   4980:        fprintf(ficrespop," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
                   4981:       }
                   4982:       fprintf(ficrespop,"******\n");
                   4983:       fprintf(ficrespop,"# Age");
                   4984:       for(j=1; j<=nlstate+ndeath;j++) fprintf(ficrespop," P.%d",j);
                   4985:       if (popforecast==1)  fprintf(ficrespop," [Population]");
                   4986:       
                   4987:       for (cpt=0; cpt<=0;cpt++) { 
                   4988:        fprintf(ficrespop,"\n\n# Forecasting at date %.lf/%.lf/%.lf ",jpyram,mpyram,anpyram+cpt);   
                   4989:        
                   4990:        for (agedeb=(fage-((int)calagedatem %12/12.)); agedeb>=(ageminpar-((int)calagedatem %12)/12.); agedeb--){ 
                   4991:          nhstepm=(int) rint((agelim-agedeb)*YEARM/stepm); 
                   4992:          nhstepm = nhstepm/hstepm; 
                   4993:          
                   4994:          p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   4995:          oldm=oldms;savm=savms;
                   4996:          hpxij(p3mat,nhstepm,agedeb,hstepm,p,nlstate,stepm,oldm,savm, k);  
                   4997:        
                   4998:          for (h=0; h<=nhstepm; h++){
                   4999:            if (h==(int) (calagedatem+YEARM*cpt)) {
                   5000:              fprintf(ficrespop,"\n %3.f ",agedeb+h*hstepm/YEARM*stepm);
                   5001:            } 
                   5002:            for(j=1; j<=nlstate+ndeath;j++) {
                   5003:              kk1=0.;kk2=0;
                   5004:              for(i=1; i<=nlstate;i++) {              
                   5005:                if (mobilav==1) 
                   5006:                  kk1=kk1+p3mat[i][j][h]*mobaverage[(int)agedeb+1][i][cptcod];
                   5007:                else {
                   5008:                  kk1=kk1+p3mat[i][j][h]*probs[(int)(agedeb+1)][i][cptcod];
                   5009:                }
                   5010:              }
                   5011:              if (h==(int)(calagedatem+12*cpt)){
                   5012:                tabpop[(int)(agedeb)][j][cptcod]=kk1;
                   5013:                  /*fprintf(ficrespop," %.3f", kk1);
                   5014:                    if (popforecast==1) fprintf(ficrespop," [%.f]", kk1*popeffectif[(int)agedeb+1]);*/
                   5015:              }
                   5016:            }
                   5017:            for(i=1; i<=nlstate;i++){
                   5018:              kk1=0.;
                   5019:                for(j=1; j<=nlstate;j++){
                   5020:                  kk1= kk1+tabpop[(int)(agedeb)][j][cptcod]; 
                   5021:                }
                   5022:                  tabpopprev[(int)(agedeb)][i][cptcod]=tabpop[(int)(agedeb)][i][cptcod]/kk1*popeffectif[(int)(agedeb+(calagedatem+12*cpt)*hstepm/YEARM*stepm-1)];
                   5023:            }
                   5024: 
                   5025:            if (h==(int)(calagedatem+12*cpt)) for(j=1; j<=nlstate;j++) 
                   5026:              fprintf(ficrespop," %15.2f",tabpopprev[(int)(agedeb+1)][j][cptcod]);
                   5027:          }
                   5028:          free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   5029:        }
                   5030:       }
                   5031:  
                   5032:   /******/
                   5033: 
                   5034:       for (cpt=1; cpt<=(anpyram1-anpyram);cpt++) { 
                   5035:        fprintf(ficrespop,"\n\n# Forecasting at date %.lf/%.lf/%.lf ",jpyram,mpyram,anpyram+cpt);   
                   5036:        for (agedeb=(fage-((int)calagedatem %12/12.)); agedeb>=(ageminpar-((int)calagedatem %12)/12.); agedeb--){ 
                   5037:          nhstepm=(int) rint((agelim-agedeb)*YEARM/stepm); 
                   5038:          nhstepm = nhstepm/hstepm; 
                   5039:          
                   5040:          p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   5041:          oldm=oldms;savm=savms;
                   5042:          hpxij(p3mat,nhstepm,agedeb,hstepm,p,nlstate,stepm,oldm,savm, k);  
                   5043:          for (h=0; h<=nhstepm; h++){
                   5044:            if (h==(int) (calagedatem+YEARM*cpt)) {
                   5045:              fprintf(ficresf,"\n %3.f ",agedeb+h*hstepm/YEARM*stepm);
                   5046:            } 
                   5047:            for(j=1; j<=nlstate+ndeath;j++) {
                   5048:              kk1=0.;kk2=0;
                   5049:              for(i=1; i<=nlstate;i++) {              
                   5050:                kk1=kk1+p3mat[i][j][h]*tabpopprev[(int)agedeb+1][i][cptcod];    
                   5051:              }
                   5052:              if (h==(int)(calagedatem+12*cpt)) fprintf(ficresf," %15.2f", kk1);        
                   5053:            }
                   5054:          }
                   5055:          free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   5056:        }
                   5057:       }
                   5058:    } 
                   5059:   }
                   5060:  
                   5061:   if (mobilav!=0) free_ma3x(mobaverage,1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
                   5062: 
                   5063:   if (popforecast==1) {
                   5064:     free_ivector(popage,0,AGESUP);
                   5065:     free_vector(popeffectif,0,AGESUP);
                   5066:     free_vector(popcount,0,AGESUP);
                   5067:   }
                   5068:   free_ma3x(tabpop,1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
                   5069:   free_ma3x(tabpopprev,1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
                   5070:   fclose(ficrespop);
                   5071: } /* End of popforecast */
                   5072: 
                   5073: int fileappend(FILE *fichier, char *optionfich)
                   5074: {
                   5075:   if((fichier=fopen(optionfich,"a"))==NULL) {
                   5076:     printf("Problem with file: %s\n", optionfich);
                   5077:     fprintf(ficlog,"Problem with file: %s\n", optionfich);
                   5078:     return (0);
                   5079:   }
                   5080:   fflush(fichier);
                   5081:   return (1);
                   5082: }
                   5083: 
                   5084: 
                   5085: /**************** function prwizard **********************/
                   5086: void prwizard(int ncovmodel, int nlstate, int ndeath,  char model[], FILE *ficparo)
                   5087: {
                   5088: 
                   5089:   /* Wizard to print covariance matrix template */
                   5090: 
1.164     brouard  5091:   char ca[32], cb[32];
                   5092:   int i,j, k, li, lj, lk, ll, jj, npar, itimes;
1.126     brouard  5093:   int numlinepar;
                   5094: 
                   5095:   printf("# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
                   5096:   fprintf(ficparo,"# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
                   5097:   for(i=1; i <=nlstate; i++){
                   5098:     jj=0;
                   5099:     for(j=1; j <=nlstate+ndeath; j++){
                   5100:       if(j==i) continue;
                   5101:       jj++;
                   5102:       /*ca[0]= k+'a'-1;ca[1]='\0';*/
                   5103:       printf("%1d%1d",i,j);
                   5104:       fprintf(ficparo,"%1d%1d",i,j);
                   5105:       for(k=1; k<=ncovmodel;k++){
                   5106:        /*        printf(" %lf",param[i][j][k]); */
                   5107:        /*        fprintf(ficparo," %lf",param[i][j][k]); */
                   5108:        printf(" 0.");
                   5109:        fprintf(ficparo," 0.");
                   5110:       }
                   5111:       printf("\n");
                   5112:       fprintf(ficparo,"\n");
                   5113:     }
                   5114:   }
                   5115:   printf("# Scales (for hessian or gradient estimation)\n");
                   5116:   fprintf(ficparo,"# Scales (for hessian or gradient estimation)\n");
                   5117:   npar= (nlstate+ndeath-1)*nlstate*ncovmodel; /* Number of parameters*/ 
                   5118:   for(i=1; i <=nlstate; i++){
                   5119:     jj=0;
                   5120:     for(j=1; j <=nlstate+ndeath; j++){
                   5121:       if(j==i) continue;
                   5122:       jj++;
                   5123:       fprintf(ficparo,"%1d%1d",i,j);
                   5124:       printf("%1d%1d",i,j);
                   5125:       fflush(stdout);
                   5126:       for(k=1; k<=ncovmodel;k++){
                   5127:        /*      printf(" %le",delti3[i][j][k]); */
                   5128:        /*      fprintf(ficparo," %le",delti3[i][j][k]); */
                   5129:        printf(" 0.");
                   5130:        fprintf(ficparo," 0.");
                   5131:       }
                   5132:       numlinepar++;
                   5133:       printf("\n");
                   5134:       fprintf(ficparo,"\n");
                   5135:     }
                   5136:   }
                   5137:   printf("# Covariance matrix\n");
                   5138: /* # 121 Var(a12)\n\ */
                   5139: /* # 122 Cov(b12,a12) Var(b12)\n\ */
                   5140: /* # 131 Cov(a13,a12) Cov(a13,b12, Var(a13)\n\ */
                   5141: /* # 132 Cov(b13,a12) Cov(b13,b12, Cov(b13,a13) Var(b13)\n\ */
                   5142: /* # 212 Cov(a21,a12) Cov(a21,b12, Cov(a21,a13) Cov(a21,b13) Var(a21)\n\ */
                   5143: /* # 212 Cov(b21,a12) Cov(b21,b12, Cov(b21,a13) Cov(b21,b13) Cov(b21,a21) Var(b21)\n\ */
                   5144: /* # 232 Cov(a23,a12) Cov(a23,b12, Cov(a23,a13) Cov(a23,b13) Cov(a23,a21) Cov(a23,b21) Var(a23)\n\ */
                   5145: /* # 232 Cov(b23,a12) Cov(b23,b12) ... Var (b23)\n" */
                   5146:   fflush(stdout);
                   5147:   fprintf(ficparo,"# Covariance matrix\n");
                   5148:   /* # 121 Var(a12)\n\ */
                   5149:   /* # 122 Cov(b12,a12) Var(b12)\n\ */
                   5150:   /* #   ...\n\ */
                   5151:   /* # 232 Cov(b23,a12)  Cov(b23,b12) ... Var (b23)\n" */
                   5152:   
                   5153:   for(itimes=1;itimes<=2;itimes++){
                   5154:     jj=0;
                   5155:     for(i=1; i <=nlstate; i++){
                   5156:       for(j=1; j <=nlstate+ndeath; j++){
                   5157:        if(j==i) continue;
                   5158:        for(k=1; k<=ncovmodel;k++){
                   5159:          jj++;
                   5160:          ca[0]= k+'a'-1;ca[1]='\0';
                   5161:          if(itimes==1){
                   5162:            printf("#%1d%1d%d",i,j,k);
                   5163:            fprintf(ficparo,"#%1d%1d%d",i,j,k);
                   5164:          }else{
                   5165:            printf("%1d%1d%d",i,j,k);
                   5166:            fprintf(ficparo,"%1d%1d%d",i,j,k);
                   5167:            /*  printf(" %.5le",matcov[i][j]); */
                   5168:          }
                   5169:          ll=0;
                   5170:          for(li=1;li <=nlstate; li++){
                   5171:            for(lj=1;lj <=nlstate+ndeath; lj++){
                   5172:              if(lj==li) continue;
                   5173:              for(lk=1;lk<=ncovmodel;lk++){
                   5174:                ll++;
                   5175:                if(ll<=jj){
                   5176:                  cb[0]= lk +'a'-1;cb[1]='\0';
                   5177:                  if(ll<jj){
                   5178:                    if(itimes==1){
                   5179:                      printf(" Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
                   5180:                      fprintf(ficparo," Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
                   5181:                    }else{
                   5182:                      printf(" 0.");
                   5183:                      fprintf(ficparo," 0.");
                   5184:                    }
                   5185:                  }else{
                   5186:                    if(itimes==1){
                   5187:                      printf(" Var(%s%1d%1d)",ca,i,j);
                   5188:                      fprintf(ficparo," Var(%s%1d%1d)",ca,i,j);
                   5189:                    }else{
                   5190:                      printf(" 0.");
                   5191:                      fprintf(ficparo," 0.");
                   5192:                    }
                   5193:                  }
                   5194:                }
                   5195:              } /* end lk */
                   5196:            } /* end lj */
                   5197:          } /* end li */
                   5198:          printf("\n");
                   5199:          fprintf(ficparo,"\n");
                   5200:          numlinepar++;
                   5201:        } /* end k*/
                   5202:       } /*end j */
                   5203:     } /* end i */
                   5204:   } /* end itimes */
                   5205: 
                   5206: } /* end of prwizard */
                   5207: /******************* Gompertz Likelihood ******************************/
                   5208: double gompertz(double x[])
                   5209: { 
                   5210:   double A,B,L=0.0,sump=0.,num=0.;
                   5211:   int i,n=0; /* n is the size of the sample */
                   5212: 
                   5213:   for (i=0;i<=imx-1 ; i++) {
                   5214:     sump=sump+weight[i];
                   5215:     /*    sump=sump+1;*/
                   5216:     num=num+1;
                   5217:   }
                   5218:  
                   5219:  
                   5220:   /* for (i=0; i<=imx; i++) 
                   5221:      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]);*/
                   5222: 
                   5223:   for (i=1;i<=imx ; i++)
                   5224:     {
                   5225:       if (cens[i] == 1 && wav[i]>1)
                   5226:        A=-x[1]/(x[2])*(exp(x[2]*(agecens[i]-agegomp))-exp(x[2]*(ageexmed[i]-agegomp)));
                   5227:       
                   5228:       if (cens[i] == 0 && wav[i]>1)
                   5229:        A=-x[1]/(x[2])*(exp(x[2]*(agedc[i]-agegomp))-exp(x[2]*(ageexmed[i]-agegomp)))
                   5230:             +log(x[1]/YEARM)+x[2]*(agedc[i]-agegomp)+log(YEARM);  
                   5231:       
                   5232:       /*if (wav[i] > 1 && agecens[i] > 15) {*/ /* ??? */
                   5233:       if (wav[i] > 1 ) { /* ??? */
                   5234:        L=L+A*weight[i];
                   5235:        /*      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]);*/
                   5236:       }
                   5237:     }
                   5238: 
                   5239:  /*printf("x1=%2.9f x2=%2.9f x3=%2.9f L=%f\n",x[1],x[2],x[3],L);*/
                   5240:  
                   5241:   return -2*L*num/sump;
                   5242: }
                   5243: 
1.136     brouard  5244: #ifdef GSL
                   5245: /******************* Gompertz_f Likelihood ******************************/
                   5246: double gompertz_f(const gsl_vector *v, void *params)
                   5247: { 
                   5248:   double A,B,LL=0.0,sump=0.,num=0.;
                   5249:   double *x= (double *) v->data;
                   5250:   int i,n=0; /* n is the size of the sample */
                   5251: 
                   5252:   for (i=0;i<=imx-1 ; i++) {
                   5253:     sump=sump+weight[i];
                   5254:     /*    sump=sump+1;*/
                   5255:     num=num+1;
                   5256:   }
                   5257:  
                   5258:  
                   5259:   /* for (i=0; i<=imx; i++) 
                   5260:      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]);*/
                   5261:   printf("x[0]=%lf x[1]=%lf\n",x[0],x[1]);
                   5262:   for (i=1;i<=imx ; i++)
                   5263:     {
                   5264:       if (cens[i] == 1 && wav[i]>1)
                   5265:        A=-x[0]/(x[1])*(exp(x[1]*(agecens[i]-agegomp))-exp(x[1]*(ageexmed[i]-agegomp)));
                   5266:       
                   5267:       if (cens[i] == 0 && wav[i]>1)
                   5268:        A=-x[0]/(x[1])*(exp(x[1]*(agedc[i]-agegomp))-exp(x[1]*(ageexmed[i]-agegomp)))
                   5269:             +log(x[0]/YEARM)+x[1]*(agedc[i]-agegomp)+log(YEARM);  
                   5270:       
                   5271:       /*if (wav[i] > 1 && agecens[i] > 15) {*/ /* ??? */
                   5272:       if (wav[i] > 1 ) { /* ??? */
                   5273:        LL=LL+A*weight[i];
                   5274:        /*      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]);*/
                   5275:       }
                   5276:     }
                   5277: 
                   5278:  /*printf("x1=%2.9f x2=%2.9f x3=%2.9f L=%f\n",x[1],x[2],x[3],L);*/
                   5279:   printf("x[0]=%lf x[1]=%lf -2*LL*num/sump=%lf\n",x[0],x[1],-2*LL*num/sump);
                   5280:  
                   5281:   return -2*LL*num/sump;
                   5282: }
                   5283: #endif
                   5284: 
1.126     brouard  5285: /******************* Printing html file ***********/
                   5286: void printinghtmlmort(char fileres[], char title[], char datafile[], int firstpass, \
                   5287:                  int lastpass, int stepm, int weightopt, char model[],\
                   5288:                  int imx,  double p[],double **matcov,double agemortsup){
                   5289:   int i,k;
                   5290: 
                   5291:   fprintf(fichtm,"<ul><li><h4>Result files </h4>\n Force of mortality. Parameters of the Gompertz fit (with confidence interval in brackets):<br>");
                   5292:   fprintf(fichtm,"  mu(age) =%lf*exp(%lf*(age-%d)) per year<br><br>",p[1],p[2],agegomp);
                   5293:   for (i=1;i<=2;i++) 
                   5294:     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]));
                   5295:   fprintf(fichtm,"<br><br><img src=\"graphmort.png\">");
                   5296:   fprintf(fichtm,"</ul>");
                   5297: 
                   5298: fprintf(fichtm,"<ul><li><h4>Life table</h4>\n <br>");
                   5299: 
                   5300:  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>");
                   5301: 
                   5302:  for (k=agegomp;k<(agemortsup-2);k++) 
                   5303:    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]);
                   5304: 
                   5305:  
                   5306:   fflush(fichtm);
                   5307: }
                   5308: 
                   5309: /******************* Gnuplot file **************/
                   5310: void printinggnuplotmort(char fileres[], char optionfilefiname[], double ageminpar, double agemaxpar, double fage , char pathc[], double p[]){
                   5311: 
                   5312:   char dirfileres[132],optfileres[132];
1.164     brouard  5313: 
1.126     brouard  5314:   int ng;
                   5315: 
                   5316: 
                   5317:   /*#ifdef windows */
                   5318:   fprintf(ficgp,"cd \"%s\" \n",pathc);
                   5319:     /*#endif */
                   5320: 
                   5321: 
                   5322:   strcpy(dirfileres,optionfilefiname);
                   5323:   strcpy(optfileres,"vpl");
                   5324:   fprintf(ficgp,"set out \"graphmort.png\"\n "); 
                   5325:   fprintf(ficgp,"set xlabel \"Age\"\n set ylabel \"Force of mortality (per year)\" \n "); 
1.145     brouard  5326:   fprintf(ficgp, "set ter png small size 320, 240\n set log y\n"); 
                   5327:   /* fprintf(ficgp, "set size 0.65,0.65\n"); */
1.126     brouard  5328:   fprintf(ficgp,"plot [%d:100] %lf*exp(%lf*(x-%d))",agegomp,p[1],p[2],agegomp);
                   5329: 
                   5330: } 
                   5331: 
1.136     brouard  5332: int readdata(char datafile[], int firstobs, int lastobs, int *imax)
                   5333: {
1.126     brouard  5334: 
1.136     brouard  5335:   /*-------- data file ----------*/
                   5336:   FILE *fic;
                   5337:   char dummy[]="                         ";
1.164     brouard  5338:   int i=0, j=0, n=0;
1.136     brouard  5339:   int linei, month, year,iout;
                   5340:   char line[MAXLINE], linetmp[MAXLINE];
1.164     brouard  5341:   char stra[MAXLINE], strb[MAXLINE];
1.136     brouard  5342:   char *stratrunc;
                   5343:   int lstra;
1.126     brouard  5344: 
                   5345: 
1.136     brouard  5346:   if((fic=fopen(datafile,"r"))==NULL)    {
                   5347:     printf("Problem while opening datafile: %s\n", datafile);return 1;
                   5348:     fprintf(ficlog,"Problem while opening datafile: %s\n", datafile);return 1;
                   5349:   }
1.126     brouard  5350: 
1.136     brouard  5351:   i=1;
                   5352:   linei=0;
                   5353:   while ((fgets(line, MAXLINE, fic) != NULL) &&((i >= firstobs) && (i <=lastobs))) {
                   5354:     linei=linei+1;
                   5355:     for(j=strlen(line); j>=0;j--){  /* Untabifies line */
                   5356:       if(line[j] == '\t')
                   5357:        line[j] = ' ';
                   5358:     }
                   5359:     for(j=strlen(line)-1; (line[j]==' ')||(line[j]==10)||(line[j]==13);j--){
                   5360:       ;
                   5361:     };
                   5362:     line[j+1]=0;  /* Trims blanks at end of line */
                   5363:     if(line[0]=='#'){
                   5364:       fprintf(ficlog,"Comment line\n%s\n",line);
                   5365:       printf("Comment line\n%s\n",line);
                   5366:       continue;
                   5367:     }
                   5368:     trimbb(linetmp,line); /* Trims multiple blanks in line */
1.164     brouard  5369:     strcpy(line, linetmp);
1.136     brouard  5370:   
1.126     brouard  5371: 
1.136     brouard  5372:     for (j=maxwav;j>=1;j--){
1.137     brouard  5373:       cutv(stra, strb, line, ' '); 
1.136     brouard  5374:       if(strb[0]=='.') { /* Missing status */
                   5375:        lval=-1;
                   5376:       }else{
                   5377:        errno=0;
                   5378:        lval=strtol(strb,&endptr,10); 
                   5379:       /*       if (errno == ERANGE && (lval == LONG_MAX || lval == LONG_MIN))*/
                   5380:        if( strb[0]=='\0' || (*endptr != '\0')){
1.141     brouard  5381:          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);
                   5382:          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  5383:          return 1;
                   5384:        }
                   5385:       }
                   5386:       s[j][i]=lval;
                   5387:       
                   5388:       strcpy(line,stra);
                   5389:       cutv(stra, strb,line,' ');
1.169     brouard  5390:       if( (iout=sscanf(strb,"%d/%d",&month, &year)) != 0){
1.136     brouard  5391:       }
1.169     brouard  5392:       else  if( (iout=sscanf(strb,"%s.",dummy)) != 0){
1.136     brouard  5393:        month=99;
                   5394:        year=9999;
                   5395:       }else{
1.141     brouard  5396:        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);
                   5397:        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  5398:        return 1;
                   5399:       }
                   5400:       anint[j][i]= (double) year; 
                   5401:       mint[j][i]= (double)month; 
                   5402:       strcpy(line,stra);
                   5403:     } /* ENd Waves */
                   5404:     
                   5405:     cutv(stra, strb,line,' '); 
1.169     brouard  5406:     if( (iout=sscanf(strb,"%d/%d",&month, &year)) != 0){
1.136     brouard  5407:     }
1.169     brouard  5408:     else  if( (iout=sscanf(strb,"%s.",dummy)) != 0){
1.136     brouard  5409:       month=99;
                   5410:       year=9999;
                   5411:     }else{
1.141     brouard  5412:       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);
                   5413:        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  5414:        return 1;
                   5415:     }
                   5416:     andc[i]=(double) year; 
                   5417:     moisdc[i]=(double) month; 
                   5418:     strcpy(line,stra);
                   5419:     
                   5420:     cutv(stra, strb,line,' '); 
1.169     brouard  5421:     if( (iout=sscanf(strb,"%d/%d",&month, &year)) != 0){
1.136     brouard  5422:     }
1.169     brouard  5423:     else  if( (iout=sscanf(strb,"%s.", dummy)) != 0){
1.136     brouard  5424:       month=99;
                   5425:       year=9999;
                   5426:     }else{
1.141     brouard  5427:       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);
                   5428:       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  5429:        return 1;
                   5430:     }
                   5431:     if (year==9999) {
1.141     brouard  5432:       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);
                   5433:       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  5434:        return 1;
1.126     brouard  5435: 
1.136     brouard  5436:     }
                   5437:     annais[i]=(double)(year);
                   5438:     moisnais[i]=(double)(month); 
                   5439:     strcpy(line,stra);
                   5440:     
                   5441:     cutv(stra, strb,line,' '); 
                   5442:     errno=0;
                   5443:     dval=strtod(strb,&endptr); 
                   5444:     if( strb[0]=='\0' || (*endptr != '\0')){
1.141     brouard  5445:       printf("Error reading data around '%f' at line number %d, \"%s\" for individual %d\nShould be a weight.  Exiting.\n",dval, i,line,linei);
                   5446:       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  5447:       fflush(ficlog);
                   5448:       return 1;
                   5449:     }
                   5450:     weight[i]=dval; 
                   5451:     strcpy(line,stra);
                   5452:     
                   5453:     for (j=ncovcol;j>=1;j--){
                   5454:       cutv(stra, strb,line,' '); 
                   5455:       if(strb[0]=='.') { /* Missing status */
                   5456:        lval=-1;
                   5457:       }else{
                   5458:        errno=0;
                   5459:        lval=strtol(strb,&endptr,10); 
                   5460:        if( strb[0]=='\0' || (*endptr != '\0')){
1.141     brouard  5461:          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);
                   5462:          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  5463:          return 1;
                   5464:        }
                   5465:       }
                   5466:       if(lval <-1 || lval >1){
1.141     brouard  5467:        printf("Error reading data around '%ld' at line number %d for individual %d, '%s'\n \
1.136     brouard  5468:  Should be a value of %d(nth) covariate (0 should be the value for the reference and 1\n \
                   5469:  for the alternative. IMaCh does not build design variables automatically, do it yourself.\n \
                   5470:  For example, for multinomial values like 1, 2 and 3,\n \
                   5471:  build V1=0 V2=0 for the reference value (1),\n \
                   5472:         V1=1 V2=0 for (2) \n \
                   5473:  and V1=0 V2=1 for (3). V1=1 V2=1 should not exist and the corresponding\n \
                   5474:  output of IMaCh is often meaningless.\n \
                   5475:  Exiting.\n",lval,linei, i,line,j);
1.141     brouard  5476:        fprintf(ficlog,"Error reading data around '%ld' at line number %d for individual %d, '%s'\n \
1.136     brouard  5477:  Should be a value of %d(nth) covariate (0 should be the value for the reference and 1\n \
                   5478:  for the alternative. IMaCh does not build design variables automatically, do it yourself.\n \
                   5479:  For example, for multinomial values like 1, 2 and 3,\n \
                   5480:  build V1=0 V2=0 for the reference value (1),\n \
                   5481:         V1=1 V2=0 for (2) \n \
                   5482:  and V1=0 V2=1 for (3). V1=1 V2=1 should not exist and the corresponding\n \
                   5483:  output of IMaCh is often meaningless.\n \
                   5484:  Exiting.\n",lval,linei, i,line,j);fflush(ficlog);
                   5485:        return 1;
                   5486:       }
                   5487:       covar[j][i]=(double)(lval);
                   5488:       strcpy(line,stra);
                   5489:     }  
                   5490:     lstra=strlen(stra);
                   5491:      
                   5492:     if(lstra > 9){ /* More than 2**32 or max of what printf can write with %ld */
                   5493:       stratrunc = &(stra[lstra-9]);
                   5494:       num[i]=atol(stratrunc);
                   5495:     }
                   5496:     else
                   5497:       num[i]=atol(stra);
                   5498:     /*if((s[2][i]==2) && (s[3][i]==-1)&&(s[4][i]==9)){
                   5499:       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;}*/
                   5500:     
                   5501:     i=i+1;
                   5502:   } /* End loop reading  data */
1.126     brouard  5503: 
1.136     brouard  5504:   *imax=i-1; /* Number of individuals */
                   5505:   fclose(fic);
                   5506:  
                   5507:   return (0);
1.164     brouard  5508:   /* endread: */
1.136     brouard  5509:     printf("Exiting readdata: ");
                   5510:     fclose(fic);
                   5511:     return (1);
1.126     brouard  5512: 
                   5513: 
                   5514: 
1.136     brouard  5515: }
1.145     brouard  5516: void removespace(char *str) {
                   5517:   char *p1 = str, *p2 = str;
                   5518:   do
                   5519:     while (*p2 == ' ')
                   5520:       p2++;
1.169     brouard  5521:   while (*p1++ == *p2++);
1.145     brouard  5522: }
                   5523: 
                   5524: int decodemodel ( char model[], int lastobs) /**< This routine decode the model and returns:
1.187     brouard  5525:    * Model  V1+V2+V3+V8+V7*V8+V5*V6+V8*age+V3*age+age*age
                   5526:    * - nagesqr = 1 if age*age in the model, otherwise 0.
                   5527:    * - cptcovt total number of covariates of the model nbocc(+)+1 = 8 excepting constant and age and age*age
                   5528:    * - cptcovn or number of covariates k of the models excluding age*products =6 and age*age
1.145     brouard  5529:    * - cptcovage number of covariates with age*products =2
                   5530:    * - cptcovs number of simple covariates
                   5531:    * - 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
                   5532:    *     which is a new column after the 9 (ncovcol) variables. 
                   5533:    * - if k is a product Vn*Vm covar[k][i] is filled with correct values for each individual
                   5534:    * - Tprod[l] gives the kth covariates of the product Vn*Vm l=1 to cptcovprod-cptcovage
                   5535:    *    Tprod[1]@2 {5, 6}: position of first product V7*V8 is 5, and second V5*V6 is 6.
                   5536:    * - Tvard[k]  p Tvard[1][1]@4 {7, 8, 5, 6} for V7*V8 and V5*V6 .
                   5537:  */
1.136     brouard  5538: {
1.145     brouard  5539:   int i, j, k, ks;
1.164     brouard  5540:   int  j1, k1, k2;
1.136     brouard  5541:   char modelsav[80];
1.145     brouard  5542:   char stra[80], strb[80], strc[80], strd[80],stre[80];
1.187     brouard  5543:   char *strpt;
1.136     brouard  5544: 
1.145     brouard  5545:   /*removespace(model);*/
1.136     brouard  5546:   if (strlen(model) >1){ /* If there is at least 1 covariate */
1.145     brouard  5547:     j=0, j1=0, k1=0, k2=-1, ks=0, cptcovn=0;
1.137     brouard  5548:     if (strstr(model,"AGE") !=0){
1.187     brouard  5549:       printf("Error. AGE must be in lower case 'age' model=1+age+%s ",model);
                   5550:       fprintf(ficlog,"Error. AGE must be in lower case model=1+age+%s ",model);fflush(ficlog);
1.136     brouard  5551:       return 1;
                   5552:     }
1.141     brouard  5553:     if (strstr(model,"v") !=0){
                   5554:       printf("Error. 'v' must be in upper case 'V' model=%s ",model);
                   5555:       fprintf(ficlog,"Error. 'v' must be in upper case model=%s ",model);fflush(ficlog);
                   5556:       return 1;
                   5557:     }
1.187     brouard  5558:     strcpy(modelsav,model); 
                   5559:     if ((strpt=strstr(model,"age*age")) !=0){
                   5560:       printf(" strpt=%s, model=%s\n",strpt, model);
                   5561:       if(strpt != model){
                   5562:       printf("Error in model: 'model=%s'; 'age*age' should in first place before other covariates\n \
                   5563:  'model=1+age+age*age+V1' or 'model=1+age+age*age+V1+V1*age', please swap as well as \n \
                   5564:  corresponding column of parameters.\n",model);
                   5565:       fprintf(ficlog,"Error in model: 'model=%s'; 'age*age' should in first place before other covariates\n \
                   5566:  'model=1+age+age*age+V1' or 'model=1+age+age*age+V1+V1*age', please swap as well as \n \
                   5567:  corresponding column of parameters.\n",model); fflush(ficlog);
                   5568:       return 1;
                   5569:     }
                   5570: 
                   5571:       nagesqr=1;
                   5572:       if (strstr(model,"+age*age") !=0)
                   5573:        substrchaine(modelsav, model, "+age*age");
                   5574:       else if (strstr(model,"age*age+") !=0)
                   5575:        substrchaine(modelsav, model, "age*age+");
                   5576:       else 
                   5577:        substrchaine(modelsav, model, "age*age");
                   5578:     }else
                   5579:       nagesqr=0;
                   5580:     if (strlen(modelsav) >1){
                   5581:       j=nbocc(modelsav,'+'); /**< j=Number of '+' */
                   5582:       j1=nbocc(modelsav,'*'); /**< j1=Number of '*' */
                   5583:       cptcovs=j+1-j1; /**<  Number of simple covariates V1+V1*age+V3 +V3*V4+age*age=> V1 + V3 =2  */
                   5584:       cptcovt= j+1; /* Number of total covariates in the model, not including
                   5585:                   * cst, age and age*age 
                   5586:                   * V1+V1*age+ V3 + V3*V4+age*age=> 4*/
                   5587:                   /* including age products which are counted in cptcovage.
                   5588:                  * but the covariates which are products must be treated 
                   5589:                  * separately: ncovn=4- 2=2 (V1+V3). */
                   5590:       cptcovprod=j1; /**< Number of products  V1*V2 +v3*age = 2 */
                   5591:       cptcovprodnoage=0; /**< Number of covariate products without age: V3*V4 =1  */
                   5592: 
                   5593:     
                   5594:       /*   Design
                   5595:        *  V1   V2   V3   V4  V5  V6  V7  V8  V9 Weight
                   5596:        *  <          ncovcol=8                >
                   5597:        * Model V2 + V1 + V3*age + V3 + V5*V6 + V7*V8 + V8*age + V8
                   5598:        *   k=  1    2      3       4     5       6      7        8
                   5599:        *  cptcovn number of covariates (not including constant and age ) = # of + plus 1 = 7+1=8
                   5600:        *  covar[k,i], value of kth covariate if not including age for individual i:
                   5601:        *       covar[1][i]= (V2), covar[4][i]=(V3), covar[8][i]=(V8)
                   5602:        *  Tvar[k] # of the kth covariate:  Tvar[1]=2  Tvar[4]=3 Tvar[8]=8
                   5603:        *       if multiplied by age: V3*age Tvar[3=V3*age]=3 (V3) Tvar[7]=8 and 
                   5604:        *  Tage[++cptcovage]=k
                   5605:        *       if products, new covar are created after ncovcol with k1
                   5606:        *  Tvar[k]=ncovcol+k1; # of the kth covariate product:  Tvar[5]=ncovcol+1=10  Tvar[6]=ncovcol+1=11
                   5607:        *  Tprod[k1]=k; Tprod[1]=5 Tprod[2]= 6; gives the position of the k1th product
                   5608:        *  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
                   5609:        *  Tvar[cptcovn+k2]=Tvard[k1][1];Tvar[cptcovn+k2+1]=Tvard[k1][2];
                   5610:        *  Tvar[8+1]=5;Tvar[8+2]=6;Tvar[8+3]=7;Tvar[8+4]=8 inverted
                   5611:        *  V1   V2   V3   V4  V5  V6  V7  V8  V9  V10  V11
                   5612:        *  <          ncovcol=8                >
                   5613:        *       Model V2 + V1 + V3*age + V3 + V5*V6 + V7*V8 + V8*age + V8    d1   d1   d2  d2
                   5614:        *          k=  1    2      3       4     5       6      7        8    9   10   11  12
                   5615:        *     Tvar[k]= 2    1      3       3    10      11      8        8    5    6    7   8
                   5616:        * p Tvar[1]@12={2,   1,     3,      3,   11,     10,     8,       8,   7,   8,   5,  6}
                   5617:        * p Tprod[1]@2={                         6, 5}
                   5618:        *p Tvard[1][1]@4= {7, 8, 5, 6}
                   5619:        * covar[k][i]= V2   V1      ?      V3    V5*V6?   V7*V8?  ?       V8   
                   5620:        *  cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*cov[2];
                   5621:        *How to reorganize?
                   5622:        * Model V1 + V2 + V3 + V8 + V5*V6 + V7*V8 + V3*age + V8*age
                   5623:        * Tvars {2,   1,     3,      3,   11,     10,     8,       8,   7,   8,   5,  6}
                   5624:        *       {2,   1,     4,      8,    5,      6,     3,       7}
                   5625:        * Struct []
                   5626:        */
1.145     brouard  5627: 
1.187     brouard  5628:       /* This loop fills the array Tvar from the string 'model'.*/
                   5629:       /* j is the number of + signs in the model V1+V2+V3 j=2 i=3 to 1 */
                   5630:       /*   modelsav=V2+V1+V4+age*V3 strb=age*V3 stra=V2+V1+V4  */
                   5631:       /*       k=4 (age*V3) Tvar[k=4]= 3 (from V3) Tage[cptcovage=1]=4 */
                   5632:       /*       k=3 V4 Tvar[k=3]= 4 (from V4) */
                   5633:       /*       k=2 V1 Tvar[k=2]= 1 (from V1) */
                   5634:       /*       k=1 Tvar[1]=2 (from V2) */
                   5635:       /*       k=5 Tvar[5] */
                   5636:       /* for (k=1; k<=cptcovn;k++) { */
                   5637:       /*       cov[2+k]=nbcode[Tvar[k]][codtab[ij][Tvar[k]]]; */
                   5638:       /*       } */
                   5639:       /* for (k=1; k<=cptcovage;k++) cov[2+Tage[k]]=nbcode[Tvar[Tage[k]]][codtab[ij][Tvar[Tage[k]]]]*cov[2]; */
                   5640:       /*
                   5641:        * Treating invertedly V2+V1+V3*age+V2*V4 is as if written V2*V4 +V3*age + V1 + V2 */
                   5642:       for(k=cptcovt; k>=1;k--) /**< Number of covariates */
1.145     brouard  5643:         Tvar[k]=0;
1.187     brouard  5644:       cptcovage=0;
                   5645:       for(k=1; k<=cptcovt;k++){ /* Loop on total covariates of the model */
                   5646:        cutl(stra,strb,modelsav,'+'); /* keeps in strb after the first '+' 
                   5647:                                         modelsav==V2+V1+V4+V3*age strb=V3*age stra=V2+V1+V4 */ 
                   5648:        if (nbocc(modelsav,'+')==0) strcpy(strb,modelsav); /* and analyzes it */
                   5649:        /*      printf("i=%d a=%s b=%s sav=%s\n",i, stra,strb,modelsav);*/
                   5650:        /*scanf("%d",i);*/
                   5651:        if (strchr(strb,'*')) {  /**< Model includes a product V2+V1+V4+V3*age strb=V3*age */
                   5652:          cutl(strc,strd,strb,'*'); /**< strd*strc  Vm*Vn: strb=V3*age(input) strc=age strd=V3 ; V3*V2 strc=V2, strd=V3 */
                   5653:          if (strcmp(strc,"age")==0) { /**< Model includes age: Vn*age */
                   5654:            /* covar is not filled and then is empty */
                   5655:            cptcovprod--;
                   5656:            cutl(stre,strb,strd,'V'); /* strd=V3(input): stre="3" */
                   5657:            Tvar[k]=atoi(stre);  /* V2+V1+V4+V3*age Tvar[4]=3 ; V1+V2*age Tvar[2]=2; V1+V1*age Tvar[2]=1 */
                   5658:            cptcovage++; /* Sums the number of covariates which include age as a product */
                   5659:            Tage[cptcovage]=k;  /* Tvar[4]=3, Tage[1] = 4 or V1+V1*age Tvar[2]=1, Tage[1]=2 */
                   5660:            /*printf("stre=%s ", stre);*/
                   5661:          } else if (strcmp(strd,"age")==0) { /* or age*Vn */
                   5662:            cptcovprod--;
                   5663:            cutl(stre,strb,strc,'V');
                   5664:            Tvar[k]=atoi(stre);
                   5665:            cptcovage++;
                   5666:            Tage[cptcovage]=k;
                   5667:          } else {  /* Age is not in the model product V2+V1+V1*V4+V3*age+V3*V2  strb=V3*V2*/
                   5668:            /* loops on k1=1 (V3*V2) and k1=2 V4*V3 */
                   5669:            cptcovn++;
                   5670:            cptcovprodnoage++;k1++;
                   5671:            cutl(stre,strb,strc,'V'); /* strc= Vn, stre is n; strb=V3*V2 stre=3 strc=*/
                   5672:            Tvar[k]=ncovcol+k1; /* For model-covariate k tells which data-covariate to use but
                   5673:                                   because this model-covariate is a construction we invent a new column
                   5674:                                   ncovcol + k1
                   5675:                                   If already ncovcol=4 and model=V2+V1+V1*V4+age*V3+V3*V2
                   5676:                                   Tvar[3=V1*V4]=4+1 Tvar[5=V3*V2]=4 + 2= 6, etc */
                   5677:            cutl(strc,strb,strd,'V'); /* strd was Vm, strc is m */
                   5678:            Tprod[k1]=k;  /* Tprod[1]=3(=V1*V4) for V2+V1+V1*V4+age*V3+V3*V2  */
                   5679:            Tvard[k1][1] =atoi(strc); /* m 1 for V1*/
                   5680:            Tvard[k1][2] =atoi(stre); /* n 4 for V4*/
                   5681:            k2=k2+2;
                   5682:            Tvar[cptcovt+k2]=Tvard[k1][1]; /* Tvar[(cptcovt=4+k2=1)=5]= 1 (V1) */
                   5683:            Tvar[cptcovt+k2+1]=Tvard[k1][2];  /* Tvar[(cptcovt=4+(k2=1)+1)=6]= 4 (V4) */
                   5684:            for (i=1; i<=lastobs;i++){
                   5685:              /* Computes the new covariate which is a product of
                   5686:                 covar[n][i]* covar[m][i] and stores it at ncovol+k1 May not be defined */
                   5687:              covar[ncovcol+k1][i]=covar[atoi(stre)][i]*covar[atoi(strc)][i];
                   5688:            }
                   5689:          } /* End age is not in the model */
                   5690:        } /* End if model includes a product */
                   5691:        else { /* no more sum */
                   5692:          /*printf("d=%s c=%s b=%s\n", strd,strc,strb);*/
                   5693:          /*  scanf("%d",i);*/
                   5694:          cutl(strd,strc,strb,'V');
                   5695:          ks++; /**< Number of simple covariates */
1.145     brouard  5696:          cptcovn++;
1.187     brouard  5697:          Tvar[k]=atoi(strd);
                   5698:        }
                   5699:        strcpy(modelsav,stra);  /* modelsav=V2+V1+V4 stra=V2+V1+V4 */ 
                   5700:        /*printf("a=%s b=%s sav=%s\n", stra,strb,modelsav);
                   5701:          scanf("%d",i);*/
                   5702:       } /* end of loop + on total covariates */
                   5703:     } /* end if strlen(modelsave == 0) age*age might exist */
                   5704:   } /* end if strlen(model == 0) */
1.136     brouard  5705:   
                   5706:   /*The number n of Vn is stored in Tvar. cptcovage =number of age covariate. Tage gives the position of age. cptcovprod= number of products.
                   5707:     If model=V1+V1*age then Tvar[1]=1 Tvar[2]=1 cptcovage=1 Tage[1]=2 cptcovprod=0*/
                   5708: 
                   5709:   /* printf("tvar1=%d tvar2=%d tvar3=%d cptcovage=%d Tage=%d",Tvar[1],Tvar[2],Tvar[3],cptcovage,Tage[1]);
                   5710:   printf("cptcovprod=%d ", cptcovprod);
                   5711:   fprintf(ficlog,"cptcovprod=%d ", cptcovprod);
                   5712: 
                   5713:   scanf("%d ",i);*/
                   5714: 
                   5715: 
1.137     brouard  5716:   return (0); /* with covar[new additional covariate if product] and Tage if age */ 
1.164     brouard  5717:   /*endread:*/
1.136     brouard  5718:     printf("Exiting decodemodel: ");
                   5719:     return (1);
                   5720: }
                   5721: 
1.169     brouard  5722: int calandcheckages(int imx, int maxwav, double *agemin, double *agemax, int *nberr, int *nbwarn )
1.136     brouard  5723: {
                   5724:   int i, m;
                   5725: 
                   5726:   for (i=1; i<=imx; i++) {
                   5727:     for(m=2; (m<= maxwav); m++) {
                   5728:       if (((int)mint[m][i]== 99) && (s[m][i] <= nlstate)){
                   5729:        anint[m][i]=9999;
                   5730:        s[m][i]=-1;
                   5731:       }
                   5732:       if((int)moisdc[i]==99 && (int)andc[i]==9999 && s[m][i]>nlstate){
1.169     brouard  5733:        *nberr = *nberr + 1;
                   5734:        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);
                   5735:        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  5736:        s[m][i]=-1;
                   5737:       }
                   5738:       if((int)moisdc[i]==99 && (int)andc[i]!=9999 && s[m][i]>nlstate){
1.169     brouard  5739:        (*nberr)++;
1.136     brouard  5740:        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]); 
                   5741:        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]); 
                   5742:        s[m][i]=-1; /* We prefer to skip it (and to skip it in version 0.8a1 too */
                   5743:       }
                   5744:     }
                   5745:   }
                   5746: 
                   5747:   for (i=1; i<=imx; i++)  {
                   5748:     agedc[i]=(moisdc[i]/12.+andc[i])-(moisnais[i]/12.+annais[i]);
                   5749:     for(m=firstpass; (m<= lastpass); m++){
                   5750:       if(s[m][i] >0 || s[m][i]==-2 || s[m][i]==-4 || s[m][i]==-5){
                   5751:        if (s[m][i] >= nlstate+1) {
1.169     brouard  5752:          if(agedc[i]>0){
                   5753:            if((int)moisdc[i]!=99 && (int)andc[i]!=9999){
1.136     brouard  5754:              agev[m][i]=agedc[i];
                   5755:          /*if(moisdc[i]==99 && andc[i]==9999) s[m][i]=-1;*/
1.169     brouard  5756:            }else {
1.136     brouard  5757:              if ((int)andc[i]!=9999){
                   5758:                nbwarn++;
                   5759:                printf("Warning negative age at death: %ld line:%d\n",num[i],i);
                   5760:                fprintf(ficlog,"Warning negative age at death: %ld line:%d\n",num[i],i);
                   5761:                agev[m][i]=-1;
                   5762:              }
                   5763:            }
1.169     brouard  5764:          } /* agedc > 0 */
1.136     brouard  5765:        }
                   5766:        else if(s[m][i] !=9){ /* Standard case, age in fractional
                   5767:                                 years but with the precision of a month */
                   5768:          agev[m][i]=(mint[m][i]/12.+1./24.+anint[m][i])-(moisnais[i]/12.+1./24.+annais[i]);
                   5769:          if((int)mint[m][i]==99 || (int)anint[m][i]==9999)
                   5770:            agev[m][i]=1;
                   5771:          else if(agev[m][i] < *agemin){ 
                   5772:            *agemin=agev[m][i];
                   5773:            printf(" Min anint[%d][%d]=%.2f annais[%d]=%.2f, agemin=%.2f\n",m,i,anint[m][i], i,annais[i], *agemin);
                   5774:          }
                   5775:          else if(agev[m][i] >*agemax){
                   5776:            *agemax=agev[m][i];
1.156     brouard  5777:            /* printf(" Max anint[%d][%d]=%.0f annais[%d]=%.0f, agemax=%.2f\n",m,i,anint[m][i], i,annais[i], *agemax);*/
1.136     brouard  5778:          }
                   5779:          /*agev[m][i]=anint[m][i]-annais[i];*/
                   5780:          /*     agev[m][i] = age[i]+2*m;*/
                   5781:        }
                   5782:        else { /* =9 */
                   5783:          agev[m][i]=1;
                   5784:          s[m][i]=-1;
                   5785:        }
                   5786:       }
                   5787:       else /*= 0 Unknown */
                   5788:        agev[m][i]=1;
                   5789:     }
                   5790:     
                   5791:   }
                   5792:   for (i=1; i<=imx; i++)  {
                   5793:     for(m=firstpass; (m<=lastpass); m++){
                   5794:       if (s[m][i] > (nlstate+ndeath)) {
1.169     brouard  5795:        (*nberr)++;
1.136     brouard  5796:        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);     
                   5797:        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);     
                   5798:        return 1;
                   5799:       }
                   5800:     }
                   5801:   }
                   5802: 
                   5803:   /*for (i=1; i<=imx; i++){
                   5804:   for (m=firstpass; (m<lastpass); m++){
                   5805:      printf("%ld %d %.lf %d %d\n", num[i],(covar[1][i]),agev[m][i],s[m][i],s[m+1][i]);
                   5806: }
                   5807: 
                   5808: }*/
                   5809: 
                   5810: 
1.139     brouard  5811:   printf("Total number of individuals= %d, Agemin = %.2f, Agemax= %.2f\n\n", imx, *agemin, *agemax);
                   5812:   fprintf(ficlog,"Total number of individuals= %d, Agemin = %.2f, Agemax= %.2f\n\n", imx, *agemin, *agemax); 
1.136     brouard  5813: 
                   5814:   return (0);
1.164     brouard  5815:  /* endread:*/
1.136     brouard  5816:     printf("Exiting calandcheckages: ");
                   5817:     return (1);
                   5818: }
                   5819: 
1.172     brouard  5820: #if defined(_MSC_VER)
                   5821: /*printf("Visual C++ compiler: %s \n;", _MSC_FULL_VER);*/
                   5822: /*fprintf(ficlog, "Visual C++ compiler: %s \n;", _MSC_FULL_VER);*/
                   5823: //#include "stdafx.h"
                   5824: //#include <stdio.h>
                   5825: //#include <tchar.h>
                   5826: //#include <windows.h>
                   5827: //#include <iostream>
                   5828: typedef BOOL(WINAPI *LPFN_ISWOW64PROCESS) (HANDLE, PBOOL);
                   5829: 
                   5830: LPFN_ISWOW64PROCESS fnIsWow64Process;
                   5831: 
                   5832: BOOL IsWow64()
                   5833: {
                   5834:        BOOL bIsWow64 = FALSE;
                   5835: 
                   5836:        //typedef BOOL (APIENTRY *LPFN_ISWOW64PROCESS)
                   5837:        //  (HANDLE, PBOOL);
                   5838: 
                   5839:        //LPFN_ISWOW64PROCESS fnIsWow64Process;
                   5840: 
                   5841:        HMODULE module = GetModuleHandle(_T("kernel32"));
                   5842:        const char funcName[] = "IsWow64Process";
                   5843:        fnIsWow64Process = (LPFN_ISWOW64PROCESS)
                   5844:                GetProcAddress(module, funcName);
                   5845: 
                   5846:        if (NULL != fnIsWow64Process)
                   5847:        {
                   5848:                if (!fnIsWow64Process(GetCurrentProcess(),
                   5849:                        &bIsWow64))
                   5850:                        //throw std::exception("Unknown error");
                   5851:                        printf("Unknown error\n");
                   5852:        }
                   5853:        return bIsWow64 != FALSE;
                   5854: }
                   5855: #endif
1.177     brouard  5856: 
1.169     brouard  5857: void syscompilerinfo()
1.167     brouard  5858:  {
                   5859:    /* #include "syscompilerinfo.h"*/
1.185     brouard  5860:    /* command line Intel compiler 32bit windows, XP compatible:*/
                   5861:    /* /GS /W3 /Gy
                   5862:       /Zc:wchar_t /Zi /O2 /Fd"Release\vc120.pdb" /D "WIN32" /D "NDEBUG" /D
                   5863:       "_CONSOLE" /D "_LIB" /D "_USING_V110_SDK71_" /D "_UNICODE" /D
                   5864:       "UNICODE" /Qipo /Zc:forScope /Gd /Oi /MT /Fa"Release\" /EHsc /nologo
1.186     brouard  5865:       /Fo"Release\" /Qprof-dir "Release\" /Fp"Release\IMaCh.pch"
                   5866:    */ 
                   5867:    /* 64 bits */
1.185     brouard  5868:    /*
                   5869:      /GS /W3 /Gy
                   5870:      /Zc:wchar_t /Zi /O2 /Fd"x64\Release\vc120.pdb" /D "WIN32" /D "NDEBUG"
                   5871:      /D "_CONSOLE" /D "_LIB" /D "_UNICODE" /D "UNICODE" /Qipo /Zc:forScope
                   5872:      /Oi /MD /Fa"x64\Release\" /EHsc /nologo /Fo"x64\Release\" /Qprof-dir
                   5873:      "x64\Release\" /Fp"x64\Release\IMaCh.pch" */
                   5874:    /* Optimization are useless and O3 is slower than O2 */
                   5875:    /*
                   5876:      /GS /W3 /Gy /Zc:wchar_t /Zi /O3 /Fd"x64\Release\vc120.pdb" /D "WIN32" 
                   5877:      /D "NDEBUG" /D "_CONSOLE" /D "_LIB" /D "_UNICODE" /D "UNICODE" /Qipo 
                   5878:      /Zc:forScope /Oi /MD /Fa"x64\Release\" /EHsc /nologo /Qparallel 
                   5879:      /Fo"x64\Release\" /Qprof-dir "x64\Release\" /Fp"x64\Release\IMaCh.pch" 
                   5880:    */
1.186     brouard  5881:    /* Link is */ /* /OUT:"visual studio
1.185     brouard  5882:       2013\Projects\IMaCh\Release\IMaCh.exe" /MANIFEST /NXCOMPAT
                   5883:       /PDB:"visual studio
                   5884:       2013\Projects\IMaCh\Release\IMaCh.pdb" /DYNAMICBASE
                   5885:       "kernel32.lib" "user32.lib" "gdi32.lib" "winspool.lib"
                   5886:       "comdlg32.lib" "advapi32.lib" "shell32.lib" "ole32.lib"
                   5887:       "oleaut32.lib" "uuid.lib" "odbc32.lib" "odbccp32.lib"
                   5888:       /MACHINE:X86 /OPT:REF /SAFESEH /INCREMENTAL:NO
                   5889:       /SUBSYSTEM:CONSOLE",5.01" /MANIFESTUAC:"level='asInvoker'
                   5890:       uiAccess='false'"
                   5891:       /ManifestFile:"Release\IMaCh.exe.intermediate.manifest" /OPT:ICF
                   5892:       /NOLOGO /TLBID:1
                   5893:    */
1.177     brouard  5894: #if defined __INTEL_COMPILER
1.178     brouard  5895: #if defined(__GNUC__)
                   5896:        struct utsname sysInfo;  /* For Intel on Linux and OS/X */
                   5897: #endif
1.177     brouard  5898: #elif defined(__GNUC__) 
1.179     brouard  5899: #ifndef  __APPLE__
1.174     brouard  5900: #include <gnu/libc-version.h>  /* Only on gnu */
1.179     brouard  5901: #endif
1.177     brouard  5902:    struct utsname sysInfo;
1.178     brouard  5903:    int cross = CROSS;
                   5904:    if (cross){
                   5905:           printf("Cross-");
                   5906:           fprintf(ficlog, "Cross-");
                   5907:    }
1.174     brouard  5908: #endif
                   5909: 
1.171     brouard  5910: #include <stdint.h>
1.178     brouard  5911: 
1.169     brouard  5912:    printf("Compiled with:");fprintf(ficlog,"Compiled with:");
                   5913: #if defined(__clang__)
                   5914:    printf(" Clang/LLVM");fprintf(ficlog," Clang/LLVM");        /* Clang/LLVM. ---------------------------------------------- */
                   5915: #endif
                   5916: #if defined(__ICC) || defined(__INTEL_COMPILER)
                   5917:    printf(" Intel ICC/ICPC");fprintf(ficlog," Intel ICC/ICPC");/* Intel ICC/ICPC. ------------------------------------------ */
                   5918: #endif
                   5919: #if defined(__GNUC__) || defined(__GNUG__)
                   5920:    printf(" GNU GCC/G++");fprintf(ficlog," GNU GCC/G++");/* GNU GCC/G++. --------------------------------------------- */
                   5921: #endif
                   5922: #if defined(__HP_cc) || defined(__HP_aCC)
                   5923:    printf(" Hewlett-Packard C/aC++");fprintf(fcilog," Hewlett-Packard C/aC++"); /* Hewlett-Packard C/aC++. ---------------------------------- */
                   5924: #endif
                   5925: #if defined(__IBMC__) || defined(__IBMCPP__)
                   5926:    printf(" IBM XL C/C++"); fprintf(ficlog," IBM XL C/C++");/* IBM XL C/C++. -------------------------------------------- */
                   5927: #endif
                   5928: #if defined(_MSC_VER)
                   5929:    printf(" Microsoft Visual Studio");fprintf(ficlog," Microsoft Visual Studio");/* Microsoft Visual Studio. --------------------------------- */
                   5930: #endif
                   5931: #if defined(__PGI)
                   5932:    printf(" Portland Group PGCC/PGCPP");fprintf(ficlog," Portland Group PGCC/PGCPP");/* Portland Group PGCC/PGCPP. ------------------------------- */
                   5933: #endif
                   5934: #if defined(__SUNPRO_C) || defined(__SUNPRO_CC)
                   5935:    printf(" Oracle Solaris Studio");fprintf(ficlog," Oracle Solaris Studio\n");/* Oracle Solaris Studio. ----------------------------------- */
1.167     brouard  5936: #endif
1.174     brouard  5937:    printf(" for ");fprintf(ficlog," for ");
1.169     brouard  5938:    
1.167     brouard  5939: // http://stackoverflow.com/questions/4605842/how-to-identify-platform-compiler-from-preprocessor-macros
                   5940: #ifdef _WIN32 // note the underscore: without it, it's not msdn official!
                   5941:     // Windows (x64 and x86)
1.174     brouard  5942:    printf("Windows (x64 and x86) ");fprintf(ficlog,"Windows (x64 and x86) ");
1.167     brouard  5943: #elif __unix__ // all unices, not all compilers
                   5944:     // Unix
1.174     brouard  5945:    printf("Unix ");fprintf(ficlog,"Unix ");
1.167     brouard  5946: #elif __linux__
                   5947:     // linux
1.174     brouard  5948:    printf("linux ");fprintf(ficlog,"linux ");
1.167     brouard  5949: #elif __APPLE__
1.174     brouard  5950:     // Mac OS, not sure if this is covered by __posix__ and/or __unix__ though..
                   5951:    printf("Mac OS ");fprintf(ficlog,"Mac OS ");
1.167     brouard  5952: #endif
                   5953: 
                   5954: /*  __MINGW32__          */
                   5955: /*  __CYGWIN__  */
                   5956: /* __MINGW64__  */
                   5957: // http://msdn.microsoft.com/en-us/library/b0084kay.aspx
                   5958: /* _MSC_VER  //the Visual C++ compiler is 17.00.51106.1, the _MSC_VER macro evaluates to 1700. Type cl /?  */
                   5959: /* _MSC_FULL_VER //the Visual C++ compiler is 15.00.20706.01, the _MSC_FULL_VER macro evaluates to 150020706 */
                   5960: /* _WIN64  // Defined for applications for Win64. */
                   5961: /* _M_X64 // Defined for compilations that target x64 processors. */
                   5962: /* _DEBUG // Defined when you compile with /LDd, /MDd, and /MTd. */
1.171     brouard  5963: 
1.167     brouard  5964: #if UINTPTR_MAX == 0xffffffff
1.174     brouard  5965:    printf(" 32-bit"); fprintf(ficlog," 32-bit");/* 32-bit */
1.167     brouard  5966: #elif UINTPTR_MAX == 0xffffffffffffffff
1.174     brouard  5967:    printf(" 64-bit"); fprintf(ficlog," 64-bit");/* 64-bit */
1.167     brouard  5968: #else
1.174     brouard  5969:    printf(" wtf-bit"); fprintf(ficlog," wtf-bit");/* wtf */
1.167     brouard  5970: #endif
                   5971: 
1.169     brouard  5972: #if defined(__GNUC__)
                   5973: # if defined(__GNUC_PATCHLEVEL__)
                   5974: #  define __GNUC_VERSION__ (__GNUC__ * 10000 \
                   5975:                             + __GNUC_MINOR__ * 100 \
                   5976:                             + __GNUC_PATCHLEVEL__)
                   5977: # else
                   5978: #  define __GNUC_VERSION__ (__GNUC__ * 10000 \
                   5979:                             + __GNUC_MINOR__ * 100)
                   5980: # endif
1.174     brouard  5981:    printf(" using GNU C version %d.\n", __GNUC_VERSION__);
                   5982:    fprintf(ficlog, " using GNU C version %d.\n", __GNUC_VERSION__);
1.176     brouard  5983: 
                   5984:    if (uname(&sysInfo) != -1) {
                   5985:      printf("Running on: %s %s %s %s %s\n",sysInfo.sysname, sysInfo.nodename, sysInfo.release, sysInfo.version, sysInfo.machine);
                   5986:      fprintf(ficlog,"Running on: %s %s %s %s %s\n ",sysInfo.sysname, sysInfo.nodename, sysInfo.release, sysInfo.version, sysInfo.machine);
                   5987:    }
                   5988:    else
                   5989:       perror("uname() error");
1.179     brouard  5990:    //#ifndef __INTEL_COMPILER 
                   5991: #if !defined (__INTEL_COMPILER) && !defined(__APPLE__)
1.174     brouard  5992:    printf("GNU libc version: %s\n", gnu_get_libc_version()); 
1.179     brouard  5993:    fprintf(ficlog,"GNU libc version: %s\n", gnu_get_libc_version());
1.177     brouard  5994: #endif
1.169     brouard  5995: #endif
1.172     brouard  5996: 
                   5997:    //   void main()
                   5998:    //   {
1.169     brouard  5999: #if defined(_MSC_VER)
1.174     brouard  6000:    if (IsWow64()){
1.176     brouard  6001:           printf("The program (probably compiled for 32bit) is running under WOW64 (64bit) emulation.\n");
                   6002:           fprintf(ficlog, "The program (probably compiled for 32bit) is running under WOW64 (64bit) emulation.\n");
1.174     brouard  6003:    }
                   6004:    else{
1.176     brouard  6005:           printf("The process is not running under WOW64 (i.e probably on a 64bit Windows).\n");
1.178     brouard  6006:           fprintf(ficlog,"The programm is not running under WOW64 (i.e probably on a 64bit Windows).\n");
1.174     brouard  6007:    }
1.172     brouard  6008:    //     printf("\nPress Enter to continue...");
                   6009:    //     getchar();
                   6010:    //   }
                   6011: 
1.169     brouard  6012: #endif
                   6013:    
1.167     brouard  6014: 
                   6015:  }
1.136     brouard  6016: 
1.180     brouard  6017: int prevalence_limit(double *p, double **prlim, double ageminpar, double agemaxpar){
                   6018:   /*--------------- Prevalence limit  (period or stable prevalence) --------------*/
                   6019:   int i, j, k, i1 ;
                   6020:   double ftolpl = 1.e-10;
                   6021:   double age, agebase, agelim;
                   6022: 
                   6023:     strcpy(filerespl,"pl");
                   6024:     strcat(filerespl,fileres);
                   6025:     if((ficrespl=fopen(filerespl,"w"))==NULL) {
                   6026:       printf("Problem with period (stable) prevalence resultfile: %s\n", filerespl);return 1;
                   6027:       fprintf(ficlog,"Problem with period (stable) prevalence resultfile: %s\n", filerespl);return 1;
                   6028:     }
                   6029:     printf("Computing period (stable) prevalence: result on file '%s' \n", filerespl);
                   6030:     fprintf(ficlog,"Computing period (stable) prevalence: result on file '%s' \n", filerespl);
                   6031:     pstamp(ficrespl);
                   6032:     fprintf(ficrespl,"# Period (stable) prevalence \n");
                   6033:     fprintf(ficrespl,"#Age ");
                   6034:     for(i=1; i<=nlstate;i++) fprintf(ficrespl,"%d-%d ",i,i);
                   6035:     fprintf(ficrespl,"\n");
                   6036:   
                   6037:     /* prlim=matrix(1,nlstate,1,nlstate);*/ /* back in main */
                   6038: 
                   6039:     agebase=ageminpar;
                   6040:     agelim=agemaxpar;
                   6041: 
                   6042:     i1=pow(2,cptcoveff);
                   6043:     if (cptcovn < 1){i1=1;}
                   6044: 
                   6045:     for(cptcov=1,k=0;cptcov<=i1;cptcov++){
                   6046:     /* for(cptcov=1,k=0;cptcov<=1;cptcov++){ */
                   6047:       //for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){
                   6048:        k=k+1;
                   6049:        /* to clean */
                   6050:        //printf("cptcov=%d cptcod=%d codtab=%d\n",cptcov, cptcod,codtab[cptcod][cptcov]);
                   6051:        fprintf(ficrespl,"\n#******");
                   6052:        printf("\n#******");
                   6053:        fprintf(ficlog,"\n#******");
                   6054:        for(j=1;j<=cptcoveff;j++) {
                   6055:          fprintf(ficrespl," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
                   6056:          printf(" V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
                   6057:          fprintf(ficlog," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
                   6058:        }
                   6059:        fprintf(ficrespl,"******\n");
                   6060:        printf("******\n");
                   6061:        fprintf(ficlog,"******\n");
                   6062: 
                   6063:        fprintf(ficrespl,"#Age ");
                   6064:        for(j=1;j<=cptcoveff;j++) {
                   6065:          fprintf(ficrespl,"V%d %d",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
                   6066:        }
                   6067:        for(i=1; i<=nlstate;i++) fprintf(ficrespl,"%d-%d ",i,i);
                   6068:        fprintf(ficrespl,"\n");
                   6069:        
                   6070:        for (age=agebase; age<=agelim; age++){
                   6071:        /* for (age=agebase; age<=agebase; age++){ */
                   6072:          prevalim(prlim, nlstate, p, age, oldm, savm,ftolpl,k);
                   6073:          fprintf(ficrespl,"%.0f ",age );
                   6074:          for(j=1;j<=cptcoveff;j++)
                   6075:            fprintf(ficrespl,"%d %d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
                   6076:          for(i=1; i<=nlstate;i++)
                   6077:            fprintf(ficrespl," %.5f", prlim[i][i]);
                   6078:          fprintf(ficrespl,"\n");
                   6079:        } /* Age */
                   6080:        /* was end of cptcod */
                   6081:     } /* cptcov */
1.184     brouard  6082:        return 0;
1.180     brouard  6083: }
                   6084: 
                   6085: int hPijx(double *p, int bage, int fage){
                   6086:     /*------------- h Pij x at various ages ------------*/
                   6087: 
                   6088:   int stepsize;
                   6089:   int agelim;
                   6090:   int hstepm;
                   6091:   int nhstepm;
                   6092:   int h, i, i1, j, k;
                   6093: 
                   6094:   double agedeb;
                   6095:   double ***p3mat;
                   6096: 
                   6097:     strcpy(filerespij,"pij");  strcat(filerespij,fileres);
                   6098:     if((ficrespij=fopen(filerespij,"w"))==NULL) {
                   6099:       printf("Problem with Pij resultfile: %s\n", filerespij); return 1;
                   6100:       fprintf(ficlog,"Problem with Pij resultfile: %s\n", filerespij); return 1;
                   6101:     }
                   6102:     printf("Computing pij: result on file '%s' \n", filerespij);
                   6103:     fprintf(ficlog,"Computing pij: result on file '%s' \n", filerespij);
                   6104:   
                   6105:     stepsize=(int) (stepm+YEARM-1)/YEARM;
                   6106:     /*if (stepm<=24) stepsize=2;*/
                   6107: 
                   6108:     agelim=AGESUP;
                   6109:     hstepm=stepsize*YEARM; /* Every year of age */
                   6110:     hstepm=hstepm/stepm; /* Typically 2 years, = 2/6 months = 4 */ 
                   6111: 
                   6112:     /* hstepm=1;   aff par mois*/
                   6113:     pstamp(ficrespij);
                   6114:     fprintf(ficrespij,"#****** h Pij x Probability to be in state j at age x+h being in i at x ");
                   6115:     i1= pow(2,cptcoveff);
1.183     brouard  6116:    /* for(cptcov=1,k=0;cptcov<=i1;cptcov++){ */
                   6117:    /*    /\*for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){*\/ */
                   6118:    /*          k=k+1;  */
                   6119:     for (k=1; k <= (int) pow(2,cptcoveff); k++){
                   6120:       fprintf(ficrespij,"\n#****** ");
                   6121:       for(j=1;j<=cptcoveff;j++) 
                   6122:        fprintf(ficrespij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
                   6123:       fprintf(ficrespij,"******\n");
                   6124:       
                   6125:       for (agedeb=fage; agedeb>=bage; agedeb--){ /* If stepm=6 months */
                   6126:        nhstepm=(int) rint((agelim-agedeb)*YEARM/stepm); /* Typically 20 years = 20*12/6=40 */ 
                   6127:        nhstepm = nhstepm/hstepm; /* Typically 40/4=10 */
                   6128:        
                   6129:        /*        nhstepm=nhstepm*YEARM; aff par mois*/
1.180     brouard  6130:        
1.183     brouard  6131:        p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   6132:        oldm=oldms;savm=savms;
                   6133:        hpxij(p3mat,nhstepm,agedeb,hstepm,p,nlstate,stepm,oldm,savm, k);  
                   6134:        fprintf(ficrespij,"# Cov Agex agex+h hpijx with i,j=");
                   6135:        for(i=1; i<=nlstate;i++)
                   6136:          for(j=1; j<=nlstate+ndeath;j++)
                   6137:            fprintf(ficrespij," %1d-%1d",i,j);
                   6138:        fprintf(ficrespij,"\n");
                   6139:        for (h=0; h<=nhstepm; h++){
                   6140:          /*agedebphstep = agedeb + h*hstepm/YEARM*stepm;*/
                   6141:          fprintf(ficrespij,"%d %3.f %3.f",k, agedeb, agedeb + h*hstepm/YEARM*stepm );
1.180     brouard  6142:          for(i=1; i<=nlstate;i++)
                   6143:            for(j=1; j<=nlstate+ndeath;j++)
1.183     brouard  6144:              fprintf(ficrespij," %.5f", p3mat[i][j][h]);
1.180     brouard  6145:          fprintf(ficrespij,"\n");
                   6146:        }
1.183     brouard  6147:        free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   6148:        fprintf(ficrespij,"\n");
                   6149:       }
1.180     brouard  6150:       /*}*/
                   6151:     }
1.184     brouard  6152:        return 0;
1.180     brouard  6153: }
                   6154: 
                   6155: 
1.136     brouard  6156: /***********************************************/
                   6157: /**************** Main Program *****************/
                   6158: /***********************************************/
                   6159: 
                   6160: int main(int argc, char *argv[])
                   6161: {
                   6162: #ifdef GSL
                   6163:   const gsl_multimin_fminimizer_type *T;
                   6164:   size_t iteri = 0, it;
                   6165:   int rval = GSL_CONTINUE;
                   6166:   int status = GSL_SUCCESS;
                   6167:   double ssval;
                   6168: #endif
                   6169:   int movingaverage(double ***probs, double bage,double fage, double ***mobaverage, int mobilav);
1.164     brouard  6170:   int i,j, k, n=MAXN,iter=0,m,size=100, cptcod;
                   6171: 
                   6172:   int jj, ll, li, lj, lk;
1.136     brouard  6173:   int numlinepar=0; /* Current linenumber of parameter file */
                   6174:   int itimes;
                   6175:   int NDIM=2;
                   6176:   int vpopbased=0;
                   6177: 
1.164     brouard  6178:   char ca[32], cb[32];
1.136     brouard  6179:   /*  FILE *fichtm; *//* Html File */
                   6180:   /* FILE *ficgp;*/ /*Gnuplot File */
                   6181:   struct stat info;
1.164     brouard  6182:   double agedeb;
1.136     brouard  6183:   double ageminpar=1.e20,agemin=1.e20, agemaxpar=-1.e20, agemax=-1.e20;
                   6184: 
1.165     brouard  6185:   double fret;
1.136     brouard  6186:   double dum; /* Dummy variable */
                   6187:   double ***p3mat;
                   6188:   double ***mobaverage;
1.164     brouard  6189: 
                   6190:   char line[MAXLINE];
1.136     brouard  6191:   char path[MAXLINE],pathc[MAXLINE],pathcd[MAXLINE],pathtot[MAXLINE],model[MAXLINE];
                   6192:   char pathr[MAXLINE], pathimach[MAXLINE]; 
1.164     brouard  6193:   char *tok, *val; /* pathtot */
1.136     brouard  6194:   int firstobs=1, lastobs=10;
1.164     brouard  6195:   int c,  h , cpt;
                   6196:   int jl;
                   6197:   int i1, j1, jk, stepsize;
                   6198:   int *tab; 
1.136     brouard  6199:   int mobilavproj=0 , prevfcast=0 ; /* moving average of prev, If prevfcast=1 prevalence projection */
                   6200:   int mobilav=0,popforecast=0;
                   6201:   int hstepm, nhstepm;
                   6202:   int agemortsup;
                   6203:   float  sumlpop=0.;
                   6204:   double jprev1=1, mprev1=1,anprev1=2000,jprev2=1, mprev2=1,anprev2=2000;
                   6205:   double jpyram=1, mpyram=1,anpyram=2000,jpyram1=1, mpyram1=1,anpyram1=2000;
                   6206: 
1.164     brouard  6207:   double bage=0, fage=110, age, agelim, agebase;
1.136     brouard  6208:   double ftolpl=FTOL;
                   6209:   double **prlim;
                   6210:   double ***param; /* Matrix of parameters */
                   6211:   double  *p;
                   6212:   double **matcov; /* Matrix of covariance */
                   6213:   double ***delti3; /* Scale */
                   6214:   double *delti; /* Scale */
                   6215:   double ***eij, ***vareij;
                   6216:   double **varpl; /* Variances of prevalence limits by age */
                   6217:   double *epj, vepp;
1.164     brouard  6218: 
1.136     brouard  6219:   double dateprev1, dateprev2,jproj1=1,mproj1=1,anproj1=2000,jproj2=1,mproj2=1,anproj2=2000;
                   6220:   double **ximort;
1.145     brouard  6221:   char *alph[]={"a","a","b","c","d","e"}, str[4]="1234";
1.136     brouard  6222:   int *dcwave;
                   6223: 
1.164     brouard  6224:   char z[1]="c";
1.136     brouard  6225: 
                   6226:   /*char  *strt;*/
                   6227:   char strtend[80];
1.126     brouard  6228: 
1.164     brouard  6229: 
1.126     brouard  6230: /*   setlocale (LC_ALL, ""); */
                   6231: /*   bindtextdomain (PACKAGE, LOCALEDIR); */
                   6232: /*   textdomain (PACKAGE); */
                   6233: /*   setlocale (LC_CTYPE, ""); */
                   6234: /*   setlocale (LC_MESSAGES, ""); */
                   6235: 
                   6236:   /*   gettimeofday(&start_time, (struct timezone*)0); */ /* at first time */
1.157     brouard  6237:   rstart_time = time(NULL);  
                   6238:   /*  (void) gettimeofday(&start_time,&tzp);*/
                   6239:   start_time = *localtime(&rstart_time);
1.126     brouard  6240:   curr_time=start_time;
1.157     brouard  6241:   /*tml = *localtime(&start_time.tm_sec);*/
                   6242:   /* strcpy(strstart,asctime(&tml)); */
                   6243:   strcpy(strstart,asctime(&start_time));
1.126     brouard  6244: 
                   6245: /*  printf("Localtime (at start)=%s",strstart); */
1.157     brouard  6246: /*  tp.tm_sec = tp.tm_sec +86400; */
                   6247: /*  tm = *localtime(&start_time.tm_sec); */
1.126     brouard  6248: /*   tmg.tm_year=tmg.tm_year +dsign*dyear; */
                   6249: /*   tmg.tm_mon=tmg.tm_mon +dsign*dmonth; */
                   6250: /*   tmg.tm_hour=tmg.tm_hour + 1; */
1.157     brouard  6251: /*   tp.tm_sec = mktime(&tmg); */
1.126     brouard  6252: /*   strt=asctime(&tmg); */
                   6253: /*   printf("Time(after) =%s",strstart);  */
                   6254: /*  (void) time (&time_value);
                   6255: *  printf("time=%d,t-=%d\n",time_value,time_value-86400);
                   6256: *  tm = *localtime(&time_value);
                   6257: *  strstart=asctime(&tm);
                   6258: *  printf("tim_value=%d,asctime=%s\n",time_value,strstart); 
                   6259: */
                   6260: 
                   6261:   nberr=0; /* Number of errors and warnings */
                   6262:   nbwarn=0;
1.184     brouard  6263: #ifdef WIN32
                   6264:   _getcwd(pathcd, size);
                   6265: #else
1.126     brouard  6266:   getcwd(pathcd, size);
1.184     brouard  6267: #endif
1.126     brouard  6268: 
                   6269:   printf("\n%s\n%s",version,fullversion);
                   6270:   if(argc <=1){
                   6271:     printf("\nEnter the parameter file name: ");
                   6272:     fgets(pathr,FILENAMELENGTH,stdin);
                   6273:     i=strlen(pathr);
                   6274:     if(pathr[i-1]=='\n')
                   6275:       pathr[i-1]='\0';
1.156     brouard  6276:     i=strlen(pathr);
                   6277:     if(pathr[i-1]==' ') /* This may happen when dragging on oS/X! */
                   6278:       pathr[i-1]='\0';
1.126     brouard  6279:    for (tok = pathr; tok != NULL; ){
                   6280:       printf("Pathr |%s|\n",pathr);
                   6281:       while ((val = strsep(&tok, "\"" )) != NULL && *val == '\0');
                   6282:       printf("val= |%s| pathr=%s\n",val,pathr);
                   6283:       strcpy (pathtot, val);
                   6284:       if(pathr[0] == '\0') break; /* Dirty */
                   6285:     }
                   6286:   }
                   6287:   else{
                   6288:     strcpy(pathtot,argv[1]);
                   6289:   }
                   6290:   /*if(getcwd(pathcd, MAXLINE)!= NULL)printf ("Error pathcd\n");*/
                   6291:   /*cygwin_split_path(pathtot,path,optionfile);
                   6292:     printf("pathtot=%s, path=%s, optionfile=%s\n",pathtot,path,optionfile);*/
                   6293:   /* cutv(path,optionfile,pathtot,'\\');*/
                   6294: 
                   6295:   /* Split argv[0], imach program to get pathimach */
                   6296:   printf("\nargv[0]=%s argv[1]=%s, \n",argv[0],argv[1]);
                   6297:   split(argv[0],pathimach,optionfile,optionfilext,optionfilefiname);
                   6298:   printf("\nargv[0]=%s pathimach=%s, \noptionfile=%s \noptionfilext=%s \noptionfilefiname=%s\n",argv[0],pathimach,optionfile,optionfilext,optionfilefiname);
                   6299:  /*   strcpy(pathimach,argv[0]); */
                   6300:   /* Split argv[1]=pathtot, parameter file name to get path, optionfile, extension and name */
                   6301:   split(pathtot,path,optionfile,optionfilext,optionfilefiname);
                   6302:   printf("\npathtot=%s,\npath=%s,\noptionfile=%s \noptionfilext=%s \noptionfilefiname=%s\n",pathtot,path,optionfile,optionfilext,optionfilefiname);
1.184     brouard  6303: #ifdef WIN32
                   6304:   _chdir(path); /* Can be a relative path */
                   6305:   if(_getcwd(pathcd,MAXLINE) > 0) /* So pathcd is the full path */
                   6306: #else
1.126     brouard  6307:   chdir(path); /* Can be a relative path */
1.184     brouard  6308:   if (getcwd(pathcd, MAXLINE) > 0) /* So pathcd is the full path */
                   6309: #endif
                   6310:   printf("Current directory %s!\n",pathcd);
1.126     brouard  6311:   strcpy(command,"mkdir ");
                   6312:   strcat(command,optionfilefiname);
                   6313:   if((outcmd=system(command)) != 0){
1.169     brouard  6314:     printf("Directory already exists (or can't create it) %s%s, err=%d\n",path,optionfilefiname,outcmd);
1.126     brouard  6315:     /* fprintf(ficlog,"Problem creating directory %s%s\n",path,optionfilefiname); */
                   6316:     /* fclose(ficlog); */
                   6317: /*     exit(1); */
                   6318:   }
                   6319: /*   if((imk=mkdir(optionfilefiname))<0){ */
                   6320: /*     perror("mkdir"); */
                   6321: /*   } */
                   6322: 
                   6323:   /*-------- arguments in the command line --------*/
                   6324: 
1.186     brouard  6325:   /* Main Log file */
1.126     brouard  6326:   strcat(filelog, optionfilefiname);
                   6327:   strcat(filelog,".log");    /* */
                   6328:   if((ficlog=fopen(filelog,"w"))==NULL)    {
                   6329:     printf("Problem with logfile %s\n",filelog);
                   6330:     goto end;
                   6331:   }
                   6332:   fprintf(ficlog,"Log filename:%s\n",filelog);
                   6333:   fprintf(ficlog,"\n%s\n%s",version,fullversion);
                   6334:   fprintf(ficlog,"\nEnter the parameter file name: \n");
                   6335:   fprintf(ficlog,"pathimach=%s\npathtot=%s\n\
                   6336:  path=%s \n\
                   6337:  optionfile=%s\n\
                   6338:  optionfilext=%s\n\
1.156     brouard  6339:  optionfilefiname='%s'\n",pathimach,pathtot,path,optionfile,optionfilext,optionfilefiname);
1.126     brouard  6340: 
1.167     brouard  6341:   syscompilerinfo();
                   6342: 
1.126     brouard  6343:   printf("Local time (at start):%s",strstart);
                   6344:   fprintf(ficlog,"Local time (at start): %s",strstart);
                   6345:   fflush(ficlog);
                   6346: /*   (void) gettimeofday(&curr_time,&tzp); */
1.157     brouard  6347: /*   printf("Elapsed time %d\n", asc_diff_time(curr_time.tm_sec-start_time.tm_sec,tmpout)); */
1.126     brouard  6348: 
                   6349:   /* */
                   6350:   strcpy(fileres,"r");
                   6351:   strcat(fileres, optionfilefiname);
                   6352:   strcat(fileres,".txt");    /* Other files have txt extension */
                   6353: 
1.186     brouard  6354:   /* Main ---------arguments file --------*/
1.126     brouard  6355: 
                   6356:   if((ficpar=fopen(optionfile,"r"))==NULL)    {
1.155     brouard  6357:     printf("Problem with optionfile '%s' with errno='%s'\n",optionfile,strerror(errno));
                   6358:     fprintf(ficlog,"Problem with optionfile '%s' with errno='%s'\n",optionfile,strerror(errno));
1.126     brouard  6359:     fflush(ficlog);
1.149     brouard  6360:     /* goto end; */
                   6361:     exit(70); 
1.126     brouard  6362:   }
                   6363: 
                   6364: 
                   6365: 
                   6366:   strcpy(filereso,"o");
                   6367:   strcat(filereso,fileres);
                   6368:   if((ficparo=fopen(filereso,"w"))==NULL) { /* opened on subdirectory */
                   6369:     printf("Problem with Output resultfile: %s\n", filereso);
                   6370:     fprintf(ficlog,"Problem with Output resultfile: %s\n", filereso);
                   6371:     fflush(ficlog);
                   6372:     goto end;
                   6373:   }
                   6374: 
                   6375:   /* Reads comments: lines beginning with '#' */
                   6376:   numlinepar=0;
                   6377:   while((c=getc(ficpar))=='#' && c!= EOF){
                   6378:     ungetc(c,ficpar);
                   6379:     fgets(line, MAXLINE, ficpar);
                   6380:     numlinepar++;
1.141     brouard  6381:     fputs(line,stdout);
1.126     brouard  6382:     fputs(line,ficparo);
                   6383:     fputs(line,ficlog);
                   6384:   }
                   6385:   ungetc(c,ficpar);
                   6386: 
1.187     brouard  6387:   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.126     brouard  6388:   numlinepar++;
1.187     brouard  6389:   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);
                   6390:   if(model[strlen(model)-1]=='.') /* Suppressing leading dot in the model */
                   6391:     model[strlen(model)-1]='\0';
                   6392:   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);
                   6393:   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  6394:   fflush(ficlog);
1.187     brouard  6395:   if(model[0]=='#'|| model[0]== '\0'){
                   6396:     printf("Error in 'model' line: model should start with 'model=1+age+' and end with '.' \n \
                   6397:  'model=1+age+.' or 'model=1+age+V1.' or 'model=1+age+age*age+V1+V1*age.' or \n \
                   6398:  'model=1+age+V1+V2.' or 'model=1+age+V1+V2+V1*V2.' etc. \n");         \
                   6399:     if(mle != -1){
                   6400:       printf("Fix the model line and run imach with mle=-1 to get a correct template of the parameter file.\n");
                   6401:       exit(1);
                   6402:     }
                   6403:   }
1.126     brouard  6404:   while((c=getc(ficpar))=='#' && c!= EOF){
                   6405:     ungetc(c,ficpar);
                   6406:     fgets(line, MAXLINE, ficpar);
                   6407:     numlinepar++;
1.141     brouard  6408:     fputs(line, stdout);
                   6409:     //puts(line);
1.126     brouard  6410:     fputs(line,ficparo);
                   6411:     fputs(line,ficlog);
                   6412:   }
                   6413:   ungetc(c,ficpar);
                   6414: 
                   6415:    
1.145     brouard  6416:   covar=matrix(0,NCOVMAX,1,n);  /**< used in readdata */
1.136     brouard  6417:   cptcovn=0; /*Number of covariates, i.e. number of '+' in model statement plus one, indepently of n in Vn*/
                   6418:   /* v1+v2+v3+v2*v4+v5*age makes cptcovn = 5
                   6419:      v1+v2*age+v2*v3 makes cptcovn = 3
                   6420:   */
                   6421:   if (strlen(model)>1) 
1.187     brouard  6422:     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  6423:   else
1.187     brouard  6424:     ncovmodel=2; /* Constant and age */
1.133     brouard  6425:   nforce= (nlstate+ndeath-1)*nlstate; /* Number of forces ij from state i to j */
                   6426:   npar= nforce*ncovmodel; /* Number of parameters like aij*/
1.131     brouard  6427:   if(npar >MAXPARM || nlstate >NLSTATEMAX || ndeath >NDEATHMAX || ncovmodel>NCOVMAX){
                   6428:     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);
                   6429:     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);
                   6430:     fflush(stdout);
                   6431:     fclose (ficlog);
                   6432:     goto end;
                   6433:   }
1.126     brouard  6434:   delti3= ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel);
                   6435:   delti=delti3[1][1];
                   6436:   /*delti=vector(1,npar); *//* Scale of each paramater (output from hesscov)*/
                   6437:   if(mle==-1){ /* Print a wizard for help writing covariance matrix */
                   6438:     prwizard(ncovmodel, nlstate, ndeath, model, ficparo);
                   6439:     printf(" You choose mle=-1, look at file %s for a template of covariance matrix \n",filereso);
                   6440:     fprintf(ficlog," You choose mle=-1, look at file %s for a template of covariance matrix \n",filereso);
                   6441:     free_ma3x(delti3,1,nlstate,1, nlstate+ndeath-1,1,ncovmodel); 
                   6442:     fclose (ficparo);
                   6443:     fclose (ficlog);
                   6444:     goto end;
                   6445:     exit(0);
                   6446:   }
1.186     brouard  6447:   else if(mle==-3) { /* Main Wizard */
1.126     brouard  6448:     prwizard(ncovmodel, nlstate, ndeath, model, ficparo);
                   6449:     printf(" You choose mle=-3, look at file %s for a template of covariance matrix \n",filereso);
                   6450:     fprintf(ficlog," You choose mle=-3, look at file %s for a template of covariance matrix \n",filereso);
                   6451:     param= ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel);
                   6452:     matcov=matrix(1,npar,1,npar);
                   6453:   }
                   6454:   else{
1.145     brouard  6455:     /* Read guessed parameters */
1.126     brouard  6456:     /* Reads comments: lines beginning with '#' */
                   6457:     while((c=getc(ficpar))=='#' && c!= EOF){
                   6458:       ungetc(c,ficpar);
                   6459:       fgets(line, MAXLINE, ficpar);
                   6460:       numlinepar++;
1.141     brouard  6461:       fputs(line,stdout);
1.126     brouard  6462:       fputs(line,ficparo);
                   6463:       fputs(line,ficlog);
                   6464:     }
                   6465:     ungetc(c,ficpar);
                   6466:     
                   6467:     param= ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel);
                   6468:     for(i=1; i <=nlstate; i++){
                   6469:       j=0;
                   6470:       for(jj=1; jj <=nlstate+ndeath; jj++){
                   6471:        if(jj==i) continue;
                   6472:        j++;
                   6473:        fscanf(ficpar,"%1d%1d",&i1,&j1);
                   6474:        if ((i1 != i) && (j1 != j)){
                   6475:          printf("Error in line parameters number %d, %1d%1d instead of %1d%1d \n \
                   6476: It might be a problem of design; if ncovcol and the model are correct\n \
                   6477: run imach with mle=-1 to get a correct template of the parameter file.\n",numlinepar, i,j, i1, j1);
                   6478:          exit(1);
                   6479:        }
                   6480:        fprintf(ficparo,"%1d%1d",i1,j1);
                   6481:        if(mle==1)
                   6482:          printf("%1d%1d",i,j);
                   6483:        fprintf(ficlog,"%1d%1d",i,j);
                   6484:        for(k=1; k<=ncovmodel;k++){
                   6485:          fscanf(ficpar," %lf",&param[i][j][k]);
                   6486:          if(mle==1){
                   6487:            printf(" %lf",param[i][j][k]);
                   6488:            fprintf(ficlog," %lf",param[i][j][k]);
                   6489:          }
                   6490:          else
                   6491:            fprintf(ficlog," %lf",param[i][j][k]);
                   6492:          fprintf(ficparo," %lf",param[i][j][k]);
                   6493:        }
                   6494:        fscanf(ficpar,"\n");
                   6495:        numlinepar++;
                   6496:        if(mle==1)
                   6497:          printf("\n");
                   6498:        fprintf(ficlog,"\n");
                   6499:        fprintf(ficparo,"\n");
                   6500:       }
                   6501:     }  
                   6502:     fflush(ficlog);
                   6503: 
1.145     brouard  6504:     /* Reads scales values */
1.126     brouard  6505:     p=param[1][1];
                   6506:     
                   6507:     /* Reads comments: lines beginning with '#' */
                   6508:     while((c=getc(ficpar))=='#' && c!= EOF){
                   6509:       ungetc(c,ficpar);
                   6510:       fgets(line, MAXLINE, ficpar);
                   6511:       numlinepar++;
1.141     brouard  6512:       fputs(line,stdout);
1.126     brouard  6513:       fputs(line,ficparo);
                   6514:       fputs(line,ficlog);
                   6515:     }
                   6516:     ungetc(c,ficpar);
                   6517: 
                   6518:     for(i=1; i <=nlstate; i++){
                   6519:       for(j=1; j <=nlstate+ndeath-1; j++){
                   6520:        fscanf(ficpar,"%1d%1d",&i1,&j1);
1.164     brouard  6521:        if ( (i1-i) * (j1-j) != 0){
1.126     brouard  6522:          printf("Error in line parameters number %d, %1d%1d instead of %1d%1d \n",numlinepar, i,j, i1, j1);
                   6523:          exit(1);
                   6524:        }
                   6525:        printf("%1d%1d",i,j);
                   6526:        fprintf(ficparo,"%1d%1d",i1,j1);
                   6527:        fprintf(ficlog,"%1d%1d",i1,j1);
                   6528:        for(k=1; k<=ncovmodel;k++){
                   6529:          fscanf(ficpar,"%le",&delti3[i][j][k]);
                   6530:          printf(" %le",delti3[i][j][k]);
                   6531:          fprintf(ficparo," %le",delti3[i][j][k]);
                   6532:          fprintf(ficlog," %le",delti3[i][j][k]);
                   6533:        }
                   6534:        fscanf(ficpar,"\n");
                   6535:        numlinepar++;
                   6536:        printf("\n");
                   6537:        fprintf(ficparo,"\n");
                   6538:        fprintf(ficlog,"\n");
                   6539:       }
                   6540:     }
                   6541:     fflush(ficlog);
                   6542: 
1.145     brouard  6543:     /* Reads covariance matrix */
1.126     brouard  6544:     delti=delti3[1][1];
                   6545: 
                   6546: 
                   6547:     /* free_ma3x(delti3,1,nlstate,1,nlstate+ndeath-1,1,ncovmodel); */ /* Hasn't to to freed here otherwise delti is no more allocated */
                   6548:   
                   6549:     /* Reads comments: lines beginning with '#' */
                   6550:     while((c=getc(ficpar))=='#' && c!= EOF){
                   6551:       ungetc(c,ficpar);
                   6552:       fgets(line, MAXLINE, ficpar);
                   6553:       numlinepar++;
1.141     brouard  6554:       fputs(line,stdout);
1.126     brouard  6555:       fputs(line,ficparo);
                   6556:       fputs(line,ficlog);
                   6557:     }
                   6558:     ungetc(c,ficpar);
                   6559:   
                   6560:     matcov=matrix(1,npar,1,npar);
1.131     brouard  6561:     for(i=1; i <=npar; i++)
                   6562:       for(j=1; j <=npar; j++) matcov[i][j]=0.;
                   6563:       
1.126     brouard  6564:     for(i=1; i <=npar; i++){
1.145     brouard  6565:       fscanf(ficpar,"%s",str);
1.126     brouard  6566:       if(mle==1)
                   6567:        printf("%s",str);
                   6568:       fprintf(ficlog,"%s",str);
                   6569:       fprintf(ficparo,"%s",str);
                   6570:       for(j=1; j <=i; j++){
                   6571:        fscanf(ficpar," %le",&matcov[i][j]);
                   6572:        if(mle==1){
                   6573:          printf(" %.5le",matcov[i][j]);
                   6574:        }
                   6575:        fprintf(ficlog," %.5le",matcov[i][j]);
                   6576:        fprintf(ficparo," %.5le",matcov[i][j]);
                   6577:       }
                   6578:       fscanf(ficpar,"\n");
                   6579:       numlinepar++;
                   6580:       if(mle==1)
                   6581:        printf("\n");
                   6582:       fprintf(ficlog,"\n");
                   6583:       fprintf(ficparo,"\n");
                   6584:     }
                   6585:     for(i=1; i <=npar; i++)
                   6586:       for(j=i+1;j<=npar;j++)
                   6587:        matcov[i][j]=matcov[j][i];
                   6588:     
                   6589:     if(mle==1)
                   6590:       printf("\n");
                   6591:     fprintf(ficlog,"\n");
                   6592:     
                   6593:     fflush(ficlog);
                   6594:     
                   6595:     /*-------- Rewriting parameter file ----------*/
                   6596:     strcpy(rfileres,"r");    /* "Rparameterfile */
                   6597:     strcat(rfileres,optionfilefiname);    /* Parameter file first name*/
                   6598:     strcat(rfileres,".");    /* */
                   6599:     strcat(rfileres,optionfilext);    /* Other files have txt extension */
                   6600:     if((ficres =fopen(rfileres,"w"))==NULL) {
                   6601:       printf("Problem writing new parameter file: %s\n", fileres);goto end;
                   6602:       fprintf(ficlog,"Problem writing new parameter file: %s\n", fileres);goto end;
                   6603:     }
                   6604:     fprintf(ficres,"#%s\n",version);
                   6605:   }    /* End of mle != -3 */
                   6606: 
1.186     brouard  6607:   /*  Main data
                   6608:    */
1.126     brouard  6609:   n= lastobs;
                   6610:   num=lvector(1,n);
                   6611:   moisnais=vector(1,n);
                   6612:   annais=vector(1,n);
                   6613:   moisdc=vector(1,n);
                   6614:   andc=vector(1,n);
                   6615:   agedc=vector(1,n);
                   6616:   cod=ivector(1,n);
                   6617:   weight=vector(1,n);
                   6618:   for(i=1;i<=n;i++) weight[i]=1.0; /* Equal weights, 1 by default */
                   6619:   mint=matrix(1,maxwav,1,n);
                   6620:   anint=matrix(1,maxwav,1,n);
1.131     brouard  6621:   s=imatrix(1,maxwav+1,1,n); /* s[i][j] health state for wave i and individual j */ 
1.126     brouard  6622:   tab=ivector(1,NCOVMAX);
1.144     brouard  6623:   ncodemax=ivector(1,NCOVMAX); /* Number of code per covariate; if O and 1 only, 2**ncov; V1+V2+V3+V4=>16 */
1.126     brouard  6624: 
1.136     brouard  6625:   /* Reads data from file datafile */
                   6626:   if (readdata(datafile, firstobs, lastobs, &imx)==1)
                   6627:     goto end;
                   6628: 
                   6629:   /* Calculation of the number of parameters from char model */
1.137     brouard  6630:     /*    modelsav=V2+V1+V4+age*V3 strb=age*V3 stra=V2+V1+V4 
                   6631:        k=4 (age*V3) Tvar[k=4]= 3 (from V3) Tag[cptcovage=1]=4
                   6632:        k=3 V4 Tvar[k=3]= 4 (from V4)
                   6633:        k=2 V1 Tvar[k=2]= 1 (from V1)
                   6634:        k=1 Tvar[1]=2 (from V2)
                   6635:     */
                   6636:   Tvar=ivector(1,NCOVMAX); /* Was 15 changed to NCOVMAX. */
                   6637:   /*  V2+V1+V4+age*V3 is a model with 4 covariates (3 plus signs). 
                   6638:       For each model-covariate stores the data-covariate id. Tvar[1]=2, Tvar[2]=1, Tvar[3]=4, 
                   6639:       Tvar[4=age*V3] is 3 and 'age' is recorded in Tage.
                   6640:   */
                   6641:   /* For model-covariate k tells which data-covariate to use but
                   6642:     because this model-covariate is a construction we invent a new column
                   6643:     ncovcol + k1
                   6644:     If already ncovcol=4 and model=V2+V1+V1*V4+age*V3
                   6645:     Tvar[3=V1*V4]=4+1 etc */
1.145     brouard  6646:   Tprod=ivector(1,NCOVMAX); /* Gives the position of a product */
1.137     brouard  6647:   /* Tprod[k1=1]=3(=V1*V4) for V2+V1+V1*V4+age*V3
                   6648:      if  V2+V1+V1*V4+age*V3+V3*V2   TProd[k1=2]=5 (V3*V2)
                   6649:   */
1.145     brouard  6650:   Tvaraff=ivector(1,NCOVMAX); /* Unclear */
                   6651:   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  6652:                            * For V3*V2 (in V2+V1+V1*V4+age*V3+V3*V2), V3*V2 position is 2nd. 
                   6653:                            * Tvard[k1=2][1]=3 (V3) Tvard[k1=2][2]=2(V2) */
1.145     brouard  6654:   Tage=ivector(1,NCOVMAX); /* Gives the covariate id of covariates associated with age: V2 + V1 + age*V4 + V3*age
1.137     brouard  6655:                         4 covariates (3 plus signs)
                   6656:                         Tage[1=V3*age]= 4; Tage[2=age*V4] = 3
                   6657:                      */  
1.136     brouard  6658: 
1.186     brouard  6659: /* Main decodemodel */
                   6660: 
1.187     brouard  6661: 
1.136     brouard  6662:   if(decodemodel(model, lastobs) == 1)
                   6663:     goto end;
                   6664: 
1.137     brouard  6665:   if((double)(lastobs-imx)/(double)imx > 1.10){
                   6666:     nbwarn++;
                   6667:     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); 
                   6668:     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); 
                   6669:   }
1.136     brouard  6670:     /*  if(mle==1){*/
1.137     brouard  6671:   if (weightopt != 1) { /* Maximisation without weights. We can have weights different from 1 but want no weight*/
                   6672:     for(i=1;i<=imx;i++) weight[i]=1.0; /* changed to imx */
1.136     brouard  6673:   }
                   6674: 
                   6675:     /*-calculation of age at interview from date of interview and age at death -*/
                   6676:   agev=matrix(1,maxwav,1,imx);
                   6677: 
                   6678:   if(calandcheckages(imx, maxwav, &agemin, &agemax, &nberr, &nbwarn) == 1)
                   6679:     goto end;
                   6680: 
1.126     brouard  6681: 
1.136     brouard  6682:   agegomp=(int)agemin;
                   6683:   free_vector(moisnais,1,n);
                   6684:   free_vector(annais,1,n);
1.126     brouard  6685:   /* free_matrix(mint,1,maxwav,1,n);
                   6686:      free_matrix(anint,1,maxwav,1,n);*/
                   6687:   free_vector(moisdc,1,n);
                   6688:   free_vector(andc,1,n);
1.145     brouard  6689:   /* */
                   6690:   
1.126     brouard  6691:   wav=ivector(1,imx);
                   6692:   dh=imatrix(1,lastpass-firstpass+1,1,imx);
                   6693:   bh=imatrix(1,lastpass-firstpass+1,1,imx);
                   6694:   mw=imatrix(1,lastpass-firstpass+1,1,imx);
                   6695:    
                   6696:   /* Concatenates waves */
                   6697:   concatwav(wav, dh, bh, mw, s, agedc, agev,  firstpass, lastpass, imx, nlstate, stepm);
1.145     brouard  6698:   /* */
                   6699:  
1.126     brouard  6700:   /* Routine tricode is to calculate cptcoveff (real number of unique covariates) and to associate covariable number and modality */
                   6701: 
                   6702:   nbcode=imatrix(0,NCOVMAX,0,NCOVMAX); 
                   6703:   ncodemax[1]=1;
1.145     brouard  6704:   Ndum =ivector(-1,NCOVMAX);  
1.187     brouard  6705:   if (ncovmodel-nagesqr > 2 ) /* That is if covariate other than cst, age and age*age */
1.145     brouard  6706:     tricode(Tvar,nbcode,imx, Ndum); /**< Fills nbcode[Tvar[j]][l]; */
1.186     brouard  6707:   /* Nbcode gives the value of the lth modality of jth covariate, in
                   6708:      V2+V1*age, there are 3 covariates Tvar[2]=1 (V1).*/
                   6709:   /* 1 to ncodemax[j] is the maximum value of this jth covariate */
1.145     brouard  6710: 
                   6711:   codtab=imatrix(1,100,1,10); /* codtab[h,k]=( (h-1) - mod(k-1,2**(k-1) )/2**(k-1) */
                   6712:   /*printf(" codtab[1,1],codtab[100,10]=%d,%d\n", codtab[1][1],codtab[100][10]);*/
1.186     brouard  6713:   /* codtab gives the value 1 or 2 of the hth combination of k covariates (1 or 2).*/
1.145     brouard  6714:   h=0;
                   6715: 
                   6716: 
                   6717:   /*if (cptcovn > 0) */
1.126     brouard  6718:       
1.145     brouard  6719:  
1.126     brouard  6720:   m=pow(2,cptcoveff);
                   6721:  
1.131     brouard  6722:   for(k=1;k<=cptcoveff; k++){ /* scans any effective covariate */
1.143     brouard  6723:     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 */ 
                   6724:       for(j=1; j <= ncodemax[k]; j++){ /* For each modality of this covariate ncodemax=2*/
                   6725:        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  6726:          h++;
1.141     brouard  6727:          if (h>m) 
1.136     brouard  6728:            h=1;
1.144     brouard  6729:          /**< codtab(h,k)  k   = codtab[h,k]=( (h-1) - mod(k-1,2**(k-1) )/2**(k-1) + 1
1.186     brouard  6730:           * For k=4 covariates, h goes from 1 to 2**k
                   6731:           * codtabm(h,k)=  1 & (h-1) >> (k-1) ;
                   6732:           *     h\k   1     2     3     4
1.143     brouard  6733:           *______________________________  
                   6734:           *     1 i=1 1 i=1 1 i=1 1 i=1 1
                   6735:           *     2     2     1     1     1
                   6736:           *     3 i=2 1     2     1     1
                   6737:           *     4     2     2     1     1
                   6738:           *     5 i=3 1 i=2 1     2     1
                   6739:           *     6     2     1     2     1
                   6740:           *     7 i=4 1     2     2     1
                   6741:           *     8     2     2     2     1
                   6742:           *     9 i=5 1 i=3 1 i=2 1     1
                   6743:           *    10     2     1     1     1
                   6744:           *    11 i=6 1     2     1     1
                   6745:           *    12     2     2     1     1
                   6746:           *    13 i=7 1 i=4 1     2     1    
                   6747:           *    14     2     1     2     1
                   6748:           *    15 i=8 1     2     2     1
                   6749:           *    16     2     2     2     1
                   6750:           */
1.141     brouard  6751:          codtab[h][k]=j;
1.186     brouard  6752:          /* codtab[12][3]=1; */
1.145     brouard  6753:          /*codtab[h][Tvar[k]]=j;*/
1.130     brouard  6754:          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  6755:        } 
                   6756:       }
                   6757:     }
                   6758:   } 
                   6759:   /* printf("codtab[1][2]=%d codtab[2][2]=%d",codtab[1][2],codtab[2][2]); 
                   6760:      codtab[1][2]=1;codtab[2][2]=2; */
                   6761:   /* for(i=1; i <=m ;i++){ 
                   6762:      for(k=1; k <=cptcovn; k++){
1.131     brouard  6763:        printf("i=%d k=%d %d %d ",i,k,codtab[i][k], cptcoveff);
1.126     brouard  6764:      }
                   6765:      printf("\n");
                   6766:      }
                   6767:      scanf("%d",i);*/
1.145     brouard  6768: 
                   6769:  free_ivector(Ndum,-1,NCOVMAX);
                   6770: 
                   6771: 
1.126     brouard  6772:     
1.186     brouard  6773:   /* Initialisation of ----------- gnuplot -------------*/
1.126     brouard  6774:   strcpy(optionfilegnuplot,optionfilefiname);
                   6775:   if(mle==-3)
                   6776:     strcat(optionfilegnuplot,"-mort");
                   6777:   strcat(optionfilegnuplot,".gp");
                   6778: 
                   6779:   if((ficgp=fopen(optionfilegnuplot,"w"))==NULL) {
                   6780:     printf("Problem with file %s",optionfilegnuplot);
                   6781:   }
                   6782:   else{
                   6783:     fprintf(ficgp,"\n# %s\n", version); 
                   6784:     fprintf(ficgp,"# %s\n", optionfilegnuplot); 
1.141     brouard  6785:     //fprintf(ficgp,"set missing 'NaNq'\n");
                   6786:     fprintf(ficgp,"set datafile missing 'NaNq'\n");
1.126     brouard  6787:   }
                   6788:   /*  fclose(ficgp);*/
1.186     brouard  6789: 
                   6790: 
                   6791:   /* Initialisation of --------- index.htm --------*/
1.126     brouard  6792: 
                   6793:   strcpy(optionfilehtm,optionfilefiname); /* Main html file */
                   6794:   if(mle==-3)
                   6795:     strcat(optionfilehtm,"-mort");
                   6796:   strcat(optionfilehtm,".htm");
                   6797:   if((fichtm=fopen(optionfilehtm,"w"))==NULL)    {
1.131     brouard  6798:     printf("Problem with %s \n",optionfilehtm);
                   6799:     exit(0);
1.126     brouard  6800:   }
                   6801: 
                   6802:   strcpy(optionfilehtmcov,optionfilefiname); /* Only for matrix of covariance */
                   6803:   strcat(optionfilehtmcov,"-cov.htm");
                   6804:   if((fichtmcov=fopen(optionfilehtmcov,"w"))==NULL)    {
                   6805:     printf("Problem with %s \n",optionfilehtmcov), exit(0);
                   6806:   }
                   6807:   else{
                   6808:   fprintf(fichtmcov,"<html><head>\n<title>IMaCh Cov %s</title></head>\n <body><font size=\"2\">%s <br> %s</font> \
                   6809: <hr size=\"2\" color=\"#EC5E5E\"> \n\
                   6810: Title=%s <br>Datafile=%s Firstpass=%d Lastpass=%d Stepm=%d Weight=%d Model=%s<br>\n",\
                   6811:          optionfilehtmcov,version,fullversion,title,datafile,firstpass,lastpass,stepm, weightopt, model);
                   6812:   }
                   6813: 
                   6814:   fprintf(fichtm,"<html><head>\n<title>IMaCh %s</title></head>\n <body><font size=\"2\">%s <br> %s</font> \
                   6815: <hr size=\"2\" color=\"#EC5E5E\"> \n\
                   6816: Title=%s <br>Datafile=%s Firstpass=%d Lastpass=%d Stepm=%d Weight=%d Model=%s<br>\n\
                   6817: \n\
                   6818: <hr  size=\"2\" color=\"#EC5E5E\">\
                   6819:  <ul><li><h4>Parameter files</h4>\n\
                   6820:  - Parameter file: <a href=\"%s.%s\">%s.%s</a><br>\n\
                   6821:  - Copy of the parameter file: <a href=\"o%s\">o%s</a><br>\n\
                   6822:  - Log file of the run: <a href=\"%s\">%s</a><br>\n\
                   6823:  - Gnuplot file name: <a href=\"%s\">%s</a><br>\n\
                   6824:  - Date and time at start: %s</ul>\n",\
                   6825:          optionfilehtm,version,fullversion,title,datafile,firstpass,lastpass,stepm, weightopt, model,\
                   6826:          optionfilefiname,optionfilext,optionfilefiname,optionfilext,\
                   6827:          fileres,fileres,\
                   6828:          filelog,filelog,optionfilegnuplot,optionfilegnuplot,strstart);
                   6829:   fflush(fichtm);
                   6830: 
                   6831:   strcpy(pathr,path);
                   6832:   strcat(pathr,optionfilefiname);
1.184     brouard  6833: #ifdef WIN32
                   6834:   _chdir(optionfilefiname); /* Move to directory named optionfile */
                   6835: #else
1.126     brouard  6836:   chdir(optionfilefiname); /* Move to directory named optionfile */
1.184     brouard  6837: #endif
                   6838:          
1.126     brouard  6839:   
                   6840:   /* Calculates basic frequencies. Computes observed prevalence at single age
                   6841:      and prints on file fileres'p'. */
                   6842:   freqsummary(fileres, agemin, agemax, s, agev, nlstate, imx,Tvaraff,nbcode, ncodemax,mint,anint,strstart);
                   6843: 
                   6844:   fprintf(fichtm,"\n");
                   6845:   fprintf(fichtm,"<br>Total number of observations=%d <br>\n\
                   6846: Youngest age at first (selected) pass %.2f, oldest age %.2f<br>\n\
                   6847: Interval (in months) between two waves: Min=%d Max=%d Mean=%.2lf<br>\n",\
                   6848:          imx,agemin,agemax,jmin,jmax,jmean);
                   6849:   pmmij= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
                   6850:     oldms= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
                   6851:     newms= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
                   6852:     savms= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
                   6853:     oldm=oldms; newm=newms; savm=savms; /* Keeps fixed addresses to free */
                   6854:     
                   6855:    
                   6856:   /* For Powell, parameters are in a vector p[] starting at p[1]
                   6857:      so we point p on param[1][1] so that p[1] maps on param[1][1][1] */
                   6858:   p=param[1][1]; /* *(*(*(param +1)+1)+0) */
                   6859: 
                   6860:   globpr=0; /* To get the number ipmx of contributions and the sum of weights*/
1.186     brouard  6861:   /* For mortality only */
1.126     brouard  6862:   if (mle==-3){
1.136     brouard  6863:     ximort=matrix(1,NDIM,1,NDIM); 
1.186     brouard  6864:     /*     ximort=gsl_matrix_alloc(1,NDIM,1,NDIM); */
1.126     brouard  6865:     cens=ivector(1,n);
                   6866:     ageexmed=vector(1,n);
                   6867:     agecens=vector(1,n);
                   6868:     dcwave=ivector(1,n);
                   6869:  
                   6870:     for (i=1; i<=imx; i++){
                   6871:       dcwave[i]=-1;
                   6872:       for (m=firstpass; m<=lastpass; m++)
                   6873:        if (s[m][i]>nlstate) {
                   6874:          dcwave[i]=m;
                   6875:          /*    printf("i=%d j=%d s=%d dcwave=%d\n",i,j, s[j][i],dcwave[i]);*/
                   6876:          break;
                   6877:        }
                   6878:     }
                   6879: 
                   6880:     for (i=1; i<=imx; i++) {
                   6881:       if (wav[i]>0){
                   6882:        ageexmed[i]=agev[mw[1][i]][i];
                   6883:        j=wav[i];
                   6884:        agecens[i]=1.; 
                   6885: 
                   6886:        if (ageexmed[i]> 1 && wav[i] > 0){
                   6887:          agecens[i]=agev[mw[j][i]][i];
                   6888:          cens[i]= 1;
                   6889:        }else if (ageexmed[i]< 1) 
                   6890:          cens[i]= -1;
                   6891:        if (agedc[i]< AGESUP && agedc[i]>1 && dcwave[i]>firstpass && dcwave[i]<=lastpass)
                   6892:          cens[i]=0 ;
                   6893:       }
                   6894:       else cens[i]=-1;
                   6895:     }
                   6896:     
                   6897:     for (i=1;i<=NDIM;i++) {
                   6898:       for (j=1;j<=NDIM;j++)
                   6899:        ximort[i][j]=(i == j ? 1.0 : 0.0);
                   6900:     }
                   6901:     
1.145     brouard  6902:     /*p[1]=0.0268; p[NDIM]=0.083;*/
1.126     brouard  6903:     /*printf("%lf %lf", p[1], p[2]);*/
                   6904:     
                   6905:     
1.136     brouard  6906: #ifdef GSL
                   6907:     printf("GSL optimization\n");  fprintf(ficlog,"Powell\n");
1.162     brouard  6908: #else
1.126     brouard  6909:     printf("Powell\n");  fprintf(ficlog,"Powell\n");
1.136     brouard  6910: #endif
1.126     brouard  6911:     strcpy(filerespow,"pow-mort"); 
                   6912:     strcat(filerespow,fileres);
                   6913:     if((ficrespow=fopen(filerespow,"w"))==NULL) {
                   6914:       printf("Problem with resultfile: %s\n", filerespow);
                   6915:       fprintf(ficlog,"Problem with resultfile: %s\n", filerespow);
                   6916:     }
1.136     brouard  6917: #ifdef GSL
                   6918:     fprintf(ficrespow,"# GSL optimization\n# iter -2*LL");
1.162     brouard  6919: #else
1.126     brouard  6920:     fprintf(ficrespow,"# Powell\n# iter -2*LL");
1.136     brouard  6921: #endif
1.126     brouard  6922:     /*  for (i=1;i<=nlstate;i++)
                   6923:        for(j=1;j<=nlstate+ndeath;j++)
                   6924:        if(j!=i)fprintf(ficrespow," p%1d%1d",i,j);
                   6925:     */
                   6926:     fprintf(ficrespow,"\n");
1.136     brouard  6927: #ifdef GSL
                   6928:     /* gsl starts here */ 
                   6929:     T = gsl_multimin_fminimizer_nmsimplex;
                   6930:     gsl_multimin_fminimizer *sfm = NULL;
                   6931:     gsl_vector *ss, *x;
                   6932:     gsl_multimin_function minex_func;
                   6933: 
                   6934:     /* Initial vertex size vector */
                   6935:     ss = gsl_vector_alloc (NDIM);
                   6936:     
                   6937:     if (ss == NULL){
                   6938:       GSL_ERROR_VAL ("failed to allocate space for ss", GSL_ENOMEM, 0);
                   6939:     }
                   6940:     /* Set all step sizes to 1 */
                   6941:     gsl_vector_set_all (ss, 0.001);
                   6942: 
                   6943:     /* Starting point */
1.126     brouard  6944:     
1.136     brouard  6945:     x = gsl_vector_alloc (NDIM);
                   6946:     
                   6947:     if (x == NULL){
                   6948:       gsl_vector_free(ss);
                   6949:       GSL_ERROR_VAL ("failed to allocate space for x", GSL_ENOMEM, 0);
                   6950:     }
                   6951:   
                   6952:     /* Initialize method and iterate */
                   6953:     /*     p[1]=0.0268; p[NDIM]=0.083; */
1.186     brouard  6954:     /*     gsl_vector_set(x, 0, 0.0268); */
                   6955:     /*     gsl_vector_set(x, 1, 0.083); */
1.136     brouard  6956:     gsl_vector_set(x, 0, p[1]);
                   6957:     gsl_vector_set(x, 1, p[2]);
                   6958: 
                   6959:     minex_func.f = &gompertz_f;
                   6960:     minex_func.n = NDIM;
                   6961:     minex_func.params = (void *)&p; /* ??? */
                   6962:     
                   6963:     sfm = gsl_multimin_fminimizer_alloc (T, NDIM);
                   6964:     gsl_multimin_fminimizer_set (sfm, &minex_func, x, ss);
                   6965:     
                   6966:     printf("Iterations beginning .....\n\n");
                   6967:     printf("Iter. #    Intercept       Slope     -Log Likelihood     Simplex size\n");
                   6968: 
                   6969:     iteri=0;
                   6970:     while (rval == GSL_CONTINUE){
                   6971:       iteri++;
                   6972:       status = gsl_multimin_fminimizer_iterate(sfm);
                   6973:       
                   6974:       if (status) printf("error: %s\n", gsl_strerror (status));
                   6975:       fflush(0);
                   6976:       
                   6977:       if (status) 
                   6978:         break;
                   6979:       
                   6980:       rval = gsl_multimin_test_size (gsl_multimin_fminimizer_size (sfm), 1e-6);
                   6981:       ssval = gsl_multimin_fminimizer_size (sfm);
                   6982:       
                   6983:       if (rval == GSL_SUCCESS)
                   6984:         printf ("converged to a local maximum at\n");
                   6985:       
                   6986:       printf("%5d ", iteri);
                   6987:       for (it = 0; it < NDIM; it++){
                   6988:        printf ("%10.5f ", gsl_vector_get (sfm->x, it));
                   6989:       }
                   6990:       printf("f() = %-10.5f ssize = %.7f\n", sfm->fval, ssval);
                   6991:     }
                   6992:     
                   6993:     printf("\n\n Please note: Program should be run many times with varying starting points to detemine global maximum\n\n");
                   6994:     
                   6995:     gsl_vector_free(x); /* initial values */
                   6996:     gsl_vector_free(ss); /* inital step size */
                   6997:     for (it=0; it<NDIM; it++){
                   6998:       p[it+1]=gsl_vector_get(sfm->x,it);
                   6999:       fprintf(ficrespow," %.12lf", p[it]);
                   7000:     }
                   7001:     gsl_multimin_fminimizer_free (sfm); /* p *(sfm.x.data) et p *(sfm.x.data+1)  */
                   7002: #endif
                   7003: #ifdef POWELL
                   7004:      powell(p,ximort,NDIM,ftol,&iter,&fret,gompertz);
                   7005: #endif  
1.126     brouard  7006:     fclose(ficrespow);
                   7007:     
                   7008:     hesscov(matcov, p, NDIM, delti, 1e-4, gompertz); 
                   7009: 
                   7010:     for(i=1; i <=NDIM; i++)
                   7011:       for(j=i+1;j<=NDIM;j++)
                   7012:        matcov[i][j]=matcov[j][i];
                   7013:     
                   7014:     printf("\nCovariance matrix\n ");
                   7015:     for(i=1; i <=NDIM; i++) {
                   7016:       for(j=1;j<=NDIM;j++){ 
                   7017:        printf("%f ",matcov[i][j]);
                   7018:       }
                   7019:       printf("\n ");
                   7020:     }
                   7021:     
                   7022:     printf("iter=%d MLE=%f Eq=%lf*exp(%lf*(age-%d))\n",iter,-gompertz(p),p[1],p[2],agegomp);
                   7023:     for (i=1;i<=NDIM;i++) 
                   7024:       printf("%f [%f ; %f]\n",p[i],p[i]-2*sqrt(matcov[i][i]),p[i]+2*sqrt(matcov[i][i]));
                   7025: 
                   7026:     lsurv=vector(1,AGESUP);
                   7027:     lpop=vector(1,AGESUP);
                   7028:     tpop=vector(1,AGESUP);
                   7029:     lsurv[agegomp]=100000;
                   7030:     
                   7031:     for (k=agegomp;k<=AGESUP;k++) {
                   7032:       agemortsup=k;
                   7033:       if (p[1]*exp(p[2]*(k-agegomp))>1) break;
                   7034:     }
                   7035:     
                   7036:     for (k=agegomp;k<agemortsup;k++)
                   7037:       lsurv[k+1]=lsurv[k]-lsurv[k]*(p[1]*exp(p[2]*(k-agegomp)));
                   7038:     
                   7039:     for (k=agegomp;k<agemortsup;k++){
                   7040:       lpop[k]=(lsurv[k]+lsurv[k+1])/2.;
                   7041:       sumlpop=sumlpop+lpop[k];
                   7042:     }
                   7043:     
                   7044:     tpop[agegomp]=sumlpop;
                   7045:     for (k=agegomp;k<(agemortsup-3);k++){
                   7046:       /*  tpop[k+1]=2;*/
                   7047:       tpop[k+1]=tpop[k]-lpop[k];
                   7048:     }
                   7049:     
                   7050:     
                   7051:     printf("\nAge   lx     qx    dx    Lx     Tx     e(x)\n");
                   7052:     for (k=agegomp;k<(agemortsup-2);k++) 
                   7053:       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]);
                   7054:     
                   7055:     
                   7056:     replace_back_to_slash(pathc,pathcd); /* Even gnuplot wants a / */
                   7057:     printinggnuplotmort(fileres, optionfilefiname,ageminpar,agemaxpar,fage, pathc,p);
                   7058:     
                   7059:     printinghtmlmort(fileres,title,datafile, firstpass, lastpass, \
                   7060:                     stepm, weightopt,\
                   7061:                     model,imx,p,matcov,agemortsup);
                   7062:     
                   7063:     free_vector(lsurv,1,AGESUP);
                   7064:     free_vector(lpop,1,AGESUP);
                   7065:     free_vector(tpop,1,AGESUP);
1.136     brouard  7066: #ifdef GSL
                   7067:     free_ivector(cens,1,n);
                   7068:     free_vector(agecens,1,n);
                   7069:     free_ivector(dcwave,1,n);
                   7070:     free_matrix(ximort,1,NDIM,1,NDIM);
                   7071: #endif
1.186     brouard  7072:   } /* Endof if mle==-3 mortality only */
                   7073:   /* Standard maximisation */
1.126     brouard  7074:   else{ /* For mle >=1 */
1.132     brouard  7075:     globpr=0;/* debug */
1.186     brouard  7076:     /* Computes likelihood for initial parameters */
1.132     brouard  7077:     likelione(ficres, p, npar, nlstate, &globpr, &ipmx, &sw, &fretone, funcone); /* Prints the contributions to the likelihood */
1.126     brouard  7078:     printf("First Likeli=%12.6f ipmx=%ld sw=%12.6f",fretone,ipmx,sw);
                   7079:     for (k=1; k<=npar;k++)
                   7080:       printf(" %d %8.5f",k,p[k]);
                   7081:     printf("\n");
1.186     brouard  7082:     globpr=1; /* again, to print the contributions */
1.126     brouard  7083:     likelione(ficres, p, npar, nlstate, &globpr, &ipmx, &sw, &fretone, funcone); /* Prints the contributions to the likelihood */
                   7084:     printf("Second Likeli=%12.6f ipmx=%ld sw=%12.6f",fretone,ipmx,sw);
                   7085:     for (k=1; k<=npar;k++)
                   7086:       printf(" %d %8.5f",k,p[k]);
                   7087:     printf("\n");
1.186     brouard  7088:     if(mle>=1){ /* Could be 1 or 2, Real Maximisation */
1.126     brouard  7089:       mlikeli(ficres,p, npar, ncovmodel, nlstate, ftol, func);
                   7090:     }
                   7091:     
                   7092:     /*--------- results files --------------*/
1.187     brouard  7093:     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  7094:     
                   7095:     
                   7096:     fprintf(ficres,"# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
                   7097:     printf("# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
                   7098:     fprintf(ficlog,"# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
                   7099:     for(i=1,jk=1; i <=nlstate; i++){
                   7100:       for(k=1; k <=(nlstate+ndeath); k++){
                   7101:        if (k != i) {
                   7102:          printf("%d%d ",i,k);
                   7103:          fprintf(ficlog,"%d%d ",i,k);
                   7104:          fprintf(ficres,"%1d%1d ",i,k);
                   7105:          for(j=1; j <=ncovmodel; j++){
                   7106:            printf("%lf ",p[jk]);
                   7107:            fprintf(ficlog,"%lf ",p[jk]);
                   7108:            fprintf(ficres,"%lf ",p[jk]);
                   7109:            jk++; 
                   7110:          }
                   7111:          printf("\n");
                   7112:          fprintf(ficlog,"\n");
                   7113:          fprintf(ficres,"\n");
                   7114:        }
                   7115:       }
                   7116:     }
                   7117:     if(mle!=0){
                   7118:       /* Computing hessian and covariance matrix */
                   7119:       ftolhess=ftol; /* Usually correct */
                   7120:       hesscov(matcov, p, npar, delti, ftolhess, func);
                   7121:     }
                   7122:     fprintf(ficres,"# Scales (for hessian or gradient estimation)\n");
                   7123:     printf("# Scales (for hessian or gradient estimation)\n");
                   7124:     fprintf(ficlog,"# Scales (for hessian or gradient estimation)\n");
                   7125:     for(i=1,jk=1; i <=nlstate; i++){
                   7126:       for(j=1; j <=nlstate+ndeath; j++){
                   7127:        if (j!=i) {
                   7128:          fprintf(ficres,"%1d%1d",i,j);
                   7129:          printf("%1d%1d",i,j);
                   7130:          fprintf(ficlog,"%1d%1d",i,j);
                   7131:          for(k=1; k<=ncovmodel;k++){
                   7132:            printf(" %.5e",delti[jk]);
                   7133:            fprintf(ficlog," %.5e",delti[jk]);
                   7134:            fprintf(ficres," %.5e",delti[jk]);
                   7135:            jk++;
                   7136:          }
                   7137:          printf("\n");
                   7138:          fprintf(ficlog,"\n");
                   7139:          fprintf(ficres,"\n");
                   7140:        }
                   7141:       }
                   7142:     }
                   7143:     
                   7144:     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");
                   7145:     if(mle>=1)
                   7146:       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");
                   7147:     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");
                   7148:     /* # 121 Var(a12)\n\ */
                   7149:     /* # 122 Cov(b12,a12) Var(b12)\n\ */
                   7150:     /* # 131 Cov(a13,a12) Cov(a13,b12, Var(a13)\n\ */
                   7151:     /* # 132 Cov(b13,a12) Cov(b13,b12, Cov(b13,a13) Var(b13)\n\ */
                   7152:     /* # 212 Cov(a21,a12) Cov(a21,b12, Cov(a21,a13) Cov(a21,b13) Var(a21)\n\ */
                   7153:     /* # 212 Cov(b21,a12) Cov(b21,b12, Cov(b21,a13) Cov(b21,b13) Cov(b21,a21) Var(b21)\n\ */
                   7154:     /* # 232 Cov(a23,a12) Cov(a23,b12, Cov(a23,a13) Cov(a23,b13) Cov(a23,a21) Cov(a23,b21) Var(a23)\n\ */
                   7155:     /* # 232 Cov(b23,a12) Cov(b23,b12) ... Var (b23)\n" */
                   7156:     
                   7157:     
                   7158:     /* Just to have a covariance matrix which will be more understandable
                   7159:        even is we still don't want to manage dictionary of variables
                   7160:     */
                   7161:     for(itimes=1;itimes<=2;itimes++){
                   7162:       jj=0;
                   7163:       for(i=1; i <=nlstate; i++){
                   7164:        for(j=1; j <=nlstate+ndeath; j++){
                   7165:          if(j==i) continue;
                   7166:          for(k=1; k<=ncovmodel;k++){
                   7167:            jj++;
                   7168:            ca[0]= k+'a'-1;ca[1]='\0';
                   7169:            if(itimes==1){
                   7170:              if(mle>=1)
                   7171:                printf("#%1d%1d%d",i,j,k);
                   7172:              fprintf(ficlog,"#%1d%1d%d",i,j,k);
                   7173:              fprintf(ficres,"#%1d%1d%d",i,j,k);
                   7174:            }else{
                   7175:              if(mle>=1)
                   7176:                printf("%1d%1d%d",i,j,k);
                   7177:              fprintf(ficlog,"%1d%1d%d",i,j,k);
                   7178:              fprintf(ficres,"%1d%1d%d",i,j,k);
                   7179:            }
                   7180:            ll=0;
                   7181:            for(li=1;li <=nlstate; li++){
                   7182:              for(lj=1;lj <=nlstate+ndeath; lj++){
                   7183:                if(lj==li) continue;
                   7184:                for(lk=1;lk<=ncovmodel;lk++){
                   7185:                  ll++;
                   7186:                  if(ll<=jj){
                   7187:                    cb[0]= lk +'a'-1;cb[1]='\0';
                   7188:                    if(ll<jj){
                   7189:                      if(itimes==1){
                   7190:                        if(mle>=1)
                   7191:                          printf(" Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
                   7192:                        fprintf(ficlog," Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
                   7193:                        fprintf(ficres," Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
                   7194:                      }else{
                   7195:                        if(mle>=1)
                   7196:                          printf(" %.5e",matcov[jj][ll]); 
                   7197:                        fprintf(ficlog," %.5e",matcov[jj][ll]); 
                   7198:                        fprintf(ficres," %.5e",matcov[jj][ll]); 
                   7199:                      }
                   7200:                    }else{
                   7201:                      if(itimes==1){
                   7202:                        if(mle>=1)
                   7203:                          printf(" Var(%s%1d%1d)",ca,i,j);
                   7204:                        fprintf(ficlog," Var(%s%1d%1d)",ca,i,j);
                   7205:                        fprintf(ficres," Var(%s%1d%1d)",ca,i,j);
                   7206:                      }else{
                   7207:                        if(mle>=1)
                   7208:                          printf(" %.5e",matcov[jj][ll]); 
                   7209:                        fprintf(ficlog," %.5e",matcov[jj][ll]); 
                   7210:                        fprintf(ficres," %.5e",matcov[jj][ll]); 
                   7211:                      }
                   7212:                    }
                   7213:                  }
                   7214:                } /* end lk */
                   7215:              } /* end lj */
                   7216:            } /* end li */
                   7217:            if(mle>=1)
                   7218:              printf("\n");
                   7219:            fprintf(ficlog,"\n");
                   7220:            fprintf(ficres,"\n");
                   7221:            numlinepar++;
                   7222:          } /* end k*/
                   7223:        } /*end j */
                   7224:       } /* end i */
                   7225:     } /* end itimes */
                   7226:     
                   7227:     fflush(ficlog);
                   7228:     fflush(ficres);
                   7229:     
                   7230:     while((c=getc(ficpar))=='#' && c!= EOF){
                   7231:       ungetc(c,ficpar);
                   7232:       fgets(line, MAXLINE, ficpar);
1.141     brouard  7233:       fputs(line,stdout);
1.126     brouard  7234:       fputs(line,ficparo);
                   7235:     }
                   7236:     ungetc(c,ficpar);
                   7237:     
                   7238:     estepm=0;
                   7239:     fscanf(ficpar,"agemin=%lf agemax=%lf bage=%lf fage=%lf estepm=%d\n",&ageminpar,&agemaxpar, &bage, &fage, &estepm);
                   7240:     if (estepm==0 || estepm < stepm) estepm=stepm;
                   7241:     if (fage <= 2) {
                   7242:       bage = ageminpar;
                   7243:       fage = agemaxpar;
                   7244:     }
                   7245:     
                   7246:     fprintf(ficres,"# agemin agemax for life expectancy, bage fage (if mle==0 ie no data nor Max likelihood).\n");
                   7247:     fprintf(ficres,"agemin=%.0f agemax=%.0f bage=%.0f fage=%.0f estepm=%d\n",ageminpar,agemaxpar,bage,fage, estepm);
                   7248:     fprintf(ficparo,"agemin=%.0f agemax=%.0f bage=%.0f fage=%.0f estepm=%d\n",ageminpar,agemaxpar,bage,fage, estepm);
1.186     brouard  7249: 
                   7250:     /* Other stuffs, more or less useful */    
1.126     brouard  7251:     while((c=getc(ficpar))=='#' && c!= EOF){
                   7252:       ungetc(c,ficpar);
                   7253:       fgets(line, MAXLINE, ficpar);
1.141     brouard  7254:       fputs(line,stdout);
1.126     brouard  7255:       fputs(line,ficparo);
                   7256:     }
                   7257:     ungetc(c,ficpar);
                   7258:     
                   7259:     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);
                   7260:     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);
                   7261:     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);
                   7262:     printf("begin-prev-date=%.lf/%.lf/%.lf end-prev-date=%.lf/%.lf/%.lf mov_average=%d\n",jprev1, mprev1,anprev1,jprev2, mprev2,anprev2,mobilav);
                   7263:     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);
                   7264:     
                   7265:     while((c=getc(ficpar))=='#' && c!= EOF){
                   7266:       ungetc(c,ficpar);
                   7267:       fgets(line, MAXLINE, ficpar);
1.141     brouard  7268:       fputs(line,stdout);
1.126     brouard  7269:       fputs(line,ficparo);
                   7270:     }
                   7271:     ungetc(c,ficpar);
                   7272:     
                   7273:     
                   7274:     dateprev1=anprev1+(mprev1-1)/12.+(jprev1-1)/365.;
                   7275:     dateprev2=anprev2+(mprev2-1)/12.+(jprev2-1)/365.;
                   7276:     
                   7277:     fscanf(ficpar,"pop_based=%d\n",&popbased);
                   7278:     fprintf(ficparo,"pop_based=%d\n",popbased);   
                   7279:     fprintf(ficres,"pop_based=%d\n",popbased);   
                   7280:     
                   7281:     while((c=getc(ficpar))=='#' && c!= EOF){
                   7282:       ungetc(c,ficpar);
                   7283:       fgets(line, MAXLINE, ficpar);
1.141     brouard  7284:       fputs(line,stdout);
1.126     brouard  7285:       fputs(line,ficparo);
                   7286:     }
                   7287:     ungetc(c,ficpar);
                   7288:     
                   7289:     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);
                   7290:     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);
                   7291:     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);
                   7292:     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);
                   7293:     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);
                   7294:     /* day and month of proj2 are not used but only year anproj2.*/
                   7295:     
                   7296:     
                   7297:     
1.145     brouard  7298:      /* freqsummary(fileres, agemin, agemax, s, agev, nlstate, imx,Tvaraff,nbcode, ncodemax,mint,anint); */
                   7299:     /* ,dateprev1,dateprev2,jprev1, mprev1,anprev1,jprev2, mprev2,anprev2); */
1.126     brouard  7300:     
                   7301:     replace_back_to_slash(pathc,pathcd); /* Even gnuplot wants a / */
                   7302:     printinggnuplot(fileres, optionfilefiname,ageminpar,agemaxpar,fage, pathc,p);
                   7303:     
                   7304:     printinghtml(fileres,title,datafile, firstpass, lastpass, stepm, weightopt,\
                   7305:                 model,imx,jmin,jmax,jmean,rfileres,popforecast,estepm,\
                   7306:                 jprev1,mprev1,anprev1,jprev2,mprev2,anprev2);
                   7307:       
                   7308:    /*------------ free_vector  -------------*/
                   7309:    /*  chdir(path); */
                   7310:  
                   7311:     free_ivector(wav,1,imx);
                   7312:     free_imatrix(dh,1,lastpass-firstpass+1,1,imx);
                   7313:     free_imatrix(bh,1,lastpass-firstpass+1,1,imx);
                   7314:     free_imatrix(mw,1,lastpass-firstpass+1,1,imx);   
                   7315:     free_lvector(num,1,n);
                   7316:     free_vector(agedc,1,n);
                   7317:     /*free_matrix(covar,0,NCOVMAX,1,n);*/
                   7318:     /*free_matrix(covar,1,NCOVMAX,1,n);*/
                   7319:     fclose(ficparo);
                   7320:     fclose(ficres);
                   7321: 
                   7322: 
1.186     brouard  7323:     /* Other results (useful)*/
                   7324: 
                   7325: 
1.126     brouard  7326:     /*--------------- Prevalence limit  (period or stable prevalence) --------------*/
1.180     brouard  7327:     /*#include "prevlim.h"*/  /* Use ficrespl, ficlog */
                   7328:     prlim=matrix(1,nlstate,1,nlstate);
                   7329:     prevalence_limit(p, prlim,  ageminpar, agemaxpar);
1.126     brouard  7330:     fclose(ficrespl);
                   7331: 
1.145     brouard  7332: #ifdef FREEEXIT2
                   7333: #include "freeexit2.h"
                   7334: #endif
                   7335: 
1.126     brouard  7336:     /*------------- h Pij x at various ages ------------*/
1.180     brouard  7337:     /*#include "hpijx.h"*/
                   7338:     hPijx(p, bage, fage);
1.145     brouard  7339:     fclose(ficrespij);
1.126     brouard  7340: 
1.145     brouard  7341:   /*-------------- Variance of one-step probabilities---*/
                   7342:     k=1;
1.126     brouard  7343:     varprob(optionfilefiname, matcov, p, delti, nlstate, bage, fage,k,Tvar,nbcode, ncodemax,strstart);
                   7344: 
                   7345: 
                   7346:     probs= ma3x(1,AGESUP,1,NCOVMAX, 1,NCOVMAX);
                   7347:     for(i=1;i<=AGESUP;i++)
                   7348:       for(j=1;j<=NCOVMAX;j++)
                   7349:        for(k=1;k<=NCOVMAX;k++)
                   7350:          probs[i][j][k]=0.;
                   7351: 
                   7352:     /*---------- Forecasting ------------------*/
                   7353:     /*if((stepm == 1) && (strcmp(model,".")==0)){*/
                   7354:     if(prevfcast==1){
                   7355:       /*    if(stepm ==1){*/
                   7356:       prevforecast(fileres, anproj1, mproj1, jproj1, agemin, agemax, dateprev1, dateprev2, mobilavproj, bage, fage, firstpass, lastpass, anproj2, p, cptcoveff);
                   7357:       /* (popforecast==1) populforecast(fileres, anpyram,mpyram,jpyram, agemin,agemax, dateprev1, dateprev2,mobilav, agedeb, fage, popforecast, popfile, anpyram1,p, i1);*/
                   7358:       /*      }  */
                   7359:       /*      else{ */
                   7360:       /*        erreur=108; */
                   7361:       /*        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); */
                   7362:       /*        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); */
                   7363:       /*      } */
                   7364:     }
1.186     brouard  7365:  
                   7366:     /* ------ Other prevalence ratios------------ */
1.126     brouard  7367: 
1.127     brouard  7368:     /* Computes prevalence between agemin (i.e minimal age computed) and no more ageminpar */
                   7369: 
                   7370:     prevalence(probs, agemin, agemax, s, agev, nlstate, imx, Tvar, nbcode, ncodemax, mint, anint, dateprev1, dateprev2, firstpass, lastpass);
                   7371:     /*  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",\
                   7372:        ageminpar, agemax, s[lastpass][imx], agev[lastpass][imx], nlstate, imx, mint[lastpass][imx],anint[lastpass][imx], dateprev1, dateprev2, firstpass, lastpass);
                   7373:     */
1.126     brouard  7374: 
1.127     brouard  7375:     if (mobilav!=0) {
                   7376:       mobaverage= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
                   7377:       if (movingaverage(probs, bage, fage, mobaverage,mobilav)!=0){
                   7378:        fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav);
                   7379:        printf(" Error in movingaverage mobilav=%d\n",mobilav);
                   7380:       }
1.126     brouard  7381:     }
                   7382: 
                   7383: 
1.127     brouard  7384:     /*---------- Health expectancies, no variances ------------*/
                   7385: 
1.126     brouard  7386:     strcpy(filerese,"e");
                   7387:     strcat(filerese,fileres);
                   7388:     if((ficreseij=fopen(filerese,"w"))==NULL) {
                   7389:       printf("Problem with Health Exp. resultfile: %s\n", filerese); exit(0);
                   7390:       fprintf(ficlog,"Problem with Health Exp. resultfile: %s\n", filerese); exit(0);
                   7391:     }
                   7392:     printf("Computing Health Expectancies: result on file '%s' \n", filerese);
                   7393:     fprintf(ficlog,"Computing Health Expectancies: result on file '%s' \n", filerese);
1.145     brouard  7394:     /*for(cptcov=1,k=0;cptcov<=i1;cptcov++){
                   7395:       for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){*/
                   7396:           
                   7397:     for (k=1; k <= (int) pow(2,cptcoveff); k++){
1.127     brouard  7398:        fprintf(ficreseij,"\n#****** ");
                   7399:        for(j=1;j<=cptcoveff;j++) {
                   7400:          fprintf(ficreseij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
                   7401:        }
                   7402:        fprintf(ficreseij,"******\n");
                   7403: 
                   7404:        eij=ma3x(1,nlstate,1,nlstate,(int) bage, (int) fage);
                   7405:        oldm=oldms;savm=savms;
                   7406:        evsij(eij, p, nlstate, stepm, (int) bage, (int)fage, oldm, savm, k, estepm, strstart);  
                   7407:       
                   7408:        free_ma3x(eij,1,nlstate,1,nlstate,(int) bage, (int)fage);
1.145     brouard  7409:       /*}*/
1.127     brouard  7410:     }
                   7411:     fclose(ficreseij);
                   7412: 
                   7413: 
                   7414:     /*---------- Health expectancies and variances ------------*/
                   7415: 
                   7416: 
                   7417:     strcpy(filerest,"t");
                   7418:     strcat(filerest,fileres);
                   7419:     if((ficrest=fopen(filerest,"w"))==NULL) {
                   7420:       printf("Problem with total LE resultfile: %s\n", filerest);goto end;
                   7421:       fprintf(ficlog,"Problem with total LE resultfile: %s\n", filerest);goto end;
                   7422:     }
                   7423:     printf("Computing Total Life expectancies with their standard errors: file '%s' \n", filerest); 
                   7424:     fprintf(ficlog,"Computing Total Life expectancies with their standard errors: file '%s' \n", filerest); 
                   7425: 
1.126     brouard  7426: 
                   7427:     strcpy(fileresstde,"stde");
                   7428:     strcat(fileresstde,fileres);
                   7429:     if((ficresstdeij=fopen(fileresstde,"w"))==NULL) {
                   7430:       printf("Problem with Health Exp. and std errors resultfile: %s\n", fileresstde); exit(0);
                   7431:       fprintf(ficlog,"Problem with Health Exp. and std errors resultfile: %s\n", fileresstde); exit(0);
                   7432:     }
                   7433:     printf("Computing Health Expectancies and standard errors: result on file '%s' \n", fileresstde);
                   7434:     fprintf(ficlog,"Computing Health Expectancies and standard errors: result on file '%s' \n", fileresstde);
                   7435: 
                   7436:     strcpy(filerescve,"cve");
                   7437:     strcat(filerescve,fileres);
                   7438:     if((ficrescveij=fopen(filerescve,"w"))==NULL) {
                   7439:       printf("Problem with Covar. Health Exp. resultfile: %s\n", filerescve); exit(0);
                   7440:       fprintf(ficlog,"Problem with Covar. Health Exp. resultfile: %s\n", filerescve); exit(0);
                   7441:     }
                   7442:     printf("Computing Covar. of Health Expectancies: result on file '%s' \n", filerescve);
                   7443:     fprintf(ficlog,"Computing Covar. of Health Expectancies: result on file '%s' \n", filerescve);
                   7444: 
                   7445:     strcpy(fileresv,"v");
                   7446:     strcat(fileresv,fileres);
                   7447:     if((ficresvij=fopen(fileresv,"w"))==NULL) {
                   7448:       printf("Problem with variance resultfile: %s\n", fileresv);exit(0);
                   7449:       fprintf(ficlog,"Problem with variance resultfile: %s\n", fileresv);exit(0);
                   7450:     }
                   7451:     printf("Computing Variance-covariance of DFLEs: file '%s' \n", fileresv);
                   7452:     fprintf(ficlog,"Computing Variance-covariance of DFLEs: file '%s' \n", fileresv);
                   7453: 
1.145     brouard  7454:     /*for(cptcov=1,k=0;cptcov<=i1;cptcov++){
                   7455:       for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){*/
                   7456:           
                   7457:     for (k=1; k <= (int) pow(2,cptcoveff); k++){
                   7458:        fprintf(ficrest,"\n#****** ");
1.126     brouard  7459:        for(j=1;j<=cptcoveff;j++) 
                   7460:          fprintf(ficrest,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
                   7461:        fprintf(ficrest,"******\n");
                   7462: 
                   7463:        fprintf(ficresstdeij,"\n#****** ");
                   7464:        fprintf(ficrescveij,"\n#****** ");
                   7465:        for(j=1;j<=cptcoveff;j++) {
                   7466:          fprintf(ficresstdeij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
                   7467:          fprintf(ficrescveij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
                   7468:        }
                   7469:        fprintf(ficresstdeij,"******\n");
                   7470:        fprintf(ficrescveij,"******\n");
                   7471: 
                   7472:        fprintf(ficresvij,"\n#****** ");
                   7473:        for(j=1;j<=cptcoveff;j++) 
                   7474:          fprintf(ficresvij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
                   7475:        fprintf(ficresvij,"******\n");
                   7476: 
                   7477:        eij=ma3x(1,nlstate,1,nlstate,(int) bage, (int) fage);
                   7478:        oldm=oldms;savm=savms;
1.127     brouard  7479:        cvevsij(eij, p, nlstate, stepm, (int) bage, (int)fage, oldm, savm, k, estepm, delti, matcov, strstart);  
1.145     brouard  7480:        /*
                   7481:         */
                   7482:        /* goto endfree; */
1.126     brouard  7483:  
                   7484:        vareij=ma3x(1,nlstate,1,nlstate,(int) bage, (int) fage);
                   7485:        pstamp(ficrest);
1.145     brouard  7486: 
                   7487: 
1.128     brouard  7488:        for(vpopbased=0; vpopbased <= popbased; vpopbased++){ /* Done for vpopbased=0 and vpopbased=1 if popbased==1*/
1.145     brouard  7489:          oldm=oldms;savm=savms; /* Segmentation fault */
1.161     brouard  7490:          cptcod= 0; /* To be deleted */
                   7491:          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  7492:          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  7493:          if(vpopbased==1)
                   7494:            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);
                   7495:          else
                   7496:            fprintf(ficrest,"the age specific period (stable) prevalences in each health state \n");
                   7497:          fprintf(ficrest,"# Age e.. (std) ");
                   7498:          for (i=1;i<=nlstate;i++) fprintf(ficrest,"e.%d (std) ",i);
                   7499:          fprintf(ficrest,"\n");
1.126     brouard  7500: 
1.128     brouard  7501:          epj=vector(1,nlstate+1);
                   7502:          for(age=bage; age <=fage ;age++){
                   7503:            prevalim(prlim, nlstate, p, age, oldm, savm,ftolpl,k);
                   7504:            if (vpopbased==1) {
                   7505:              if(mobilav ==0){
                   7506:                for(i=1; i<=nlstate;i++)
                   7507:                  prlim[i][i]=probs[(int)age][i][k];
                   7508:              }else{ /* mobilav */ 
                   7509:                for(i=1; i<=nlstate;i++)
                   7510:                  prlim[i][i]=mobaverage[(int)age][i][k];
                   7511:              }
1.126     brouard  7512:            }
                   7513:        
1.128     brouard  7514:            fprintf(ficrest," %4.0f",age);
                   7515:            for(j=1, epj[nlstate+1]=0.;j <=nlstate;j++){
                   7516:              for(i=1, epj[j]=0.;i <=nlstate;i++) {
                   7517:                epj[j] += prlim[i][i]*eij[i][j][(int)age];
                   7518:                /*  printf("%lf %lf ", prlim[i][i] ,eij[i][j][(int)age]);*/
                   7519:              }
                   7520:              epj[nlstate+1] +=epj[j];
1.126     brouard  7521:            }
                   7522: 
1.128     brouard  7523:            for(i=1, vepp=0.;i <=nlstate;i++)
                   7524:              for(j=1;j <=nlstate;j++)
                   7525:                vepp += vareij[i][j][(int)age];
                   7526:            fprintf(ficrest," %7.3f (%7.3f)", epj[nlstate+1],sqrt(vepp));
                   7527:            for(j=1;j <=nlstate;j++){
                   7528:              fprintf(ficrest," %7.3f (%7.3f)", epj[j],sqrt(vareij[j][j][(int)age]));
                   7529:            }
                   7530:            fprintf(ficrest,"\n");
1.126     brouard  7531:          }
                   7532:        }
                   7533:        free_ma3x(eij,1,nlstate,1,nlstate,(int) bage, (int)fage);
                   7534:        free_ma3x(vareij,1,nlstate,1,nlstate,(int) bage, (int)fage);
                   7535:        free_vector(epj,1,nlstate+1);
1.145     brouard  7536:       /*}*/
1.126     brouard  7537:     }
                   7538:     free_vector(weight,1,n);
1.145     brouard  7539:     free_imatrix(Tvard,1,NCOVMAX,1,2);
1.126     brouard  7540:     free_imatrix(s,1,maxwav+1,1,n);
                   7541:     free_matrix(anint,1,maxwav,1,n); 
                   7542:     free_matrix(mint,1,maxwav,1,n);
                   7543:     free_ivector(cod,1,n);
                   7544:     free_ivector(tab,1,NCOVMAX);
                   7545:     fclose(ficresstdeij);
                   7546:     fclose(ficrescveij);
                   7547:     fclose(ficresvij);
                   7548:     fclose(ficrest);
                   7549:     fclose(ficpar);
                   7550:   
                   7551:     /*------- Variance of period (stable) prevalence------*/   
                   7552: 
                   7553:     strcpy(fileresvpl,"vpl");
                   7554:     strcat(fileresvpl,fileres);
                   7555:     if((ficresvpl=fopen(fileresvpl,"w"))==NULL) {
                   7556:       printf("Problem with variance of period (stable) prevalence  resultfile: %s\n", fileresvpl);
                   7557:       exit(0);
                   7558:     }
                   7559:     printf("Computing Variance-covariance of period (stable) prevalence: file '%s' \n", fileresvpl);
                   7560: 
1.145     brouard  7561:     /*for(cptcov=1,k=0;cptcov<=i1;cptcov++){
                   7562:       for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){*/
                   7563:           
                   7564:     for (k=1; k <= (int) pow(2,cptcoveff); k++){
                   7565:        fprintf(ficresvpl,"\n#****** ");
1.126     brouard  7566:        for(j=1;j<=cptcoveff;j++) 
                   7567:          fprintf(ficresvpl,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
                   7568:        fprintf(ficresvpl,"******\n");
                   7569:       
                   7570:        varpl=matrix(1,nlstate,(int) bage, (int) fage);
                   7571:        oldm=oldms;savm=savms;
                   7572:        varprevlim(fileres, varpl, matcov, p, delti, nlstate, stepm, (int) bage, (int) fage, oldm, savm, prlim, ftolpl,k,strstart);
                   7573:        free_matrix(varpl,1,nlstate,(int) bage, (int)fage);
1.145     brouard  7574:       /*}*/
1.126     brouard  7575:     }
                   7576: 
                   7577:     fclose(ficresvpl);
                   7578: 
                   7579:     /*---------- End : free ----------------*/
                   7580:     if (mobilav!=0) free_ma3x(mobaverage,1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
                   7581:     free_ma3x(probs,1,AGESUP,1,NCOVMAX, 1,NCOVMAX);
                   7582:   }  /* mle==-3 arrives here for freeing */
1.164     brouard  7583:  /* endfree:*/
1.141     brouard  7584:     free_matrix(prlim,1,nlstate,1,nlstate); /*here or after loop ? */
1.126     brouard  7585:     free_matrix(pmmij,1,nlstate+ndeath,1,nlstate+ndeath);
                   7586:     free_matrix(oldms, 1,nlstate+ndeath,1,nlstate+ndeath);
                   7587:     free_matrix(newms, 1,nlstate+ndeath,1,nlstate+ndeath);
                   7588:     free_matrix(savms, 1,nlstate+ndeath,1,nlstate+ndeath);
                   7589:     free_matrix(covar,0,NCOVMAX,1,n);
                   7590:     free_matrix(matcov,1,npar,1,npar);
                   7591:     /*free_vector(delti,1,npar);*/
                   7592:     free_ma3x(delti3,1,nlstate,1, nlstate+ndeath-1,1,ncovmodel); 
                   7593:     free_matrix(agev,1,maxwav,1,imx);
                   7594:     free_ma3x(param,1,nlstate,1, nlstate+ndeath-1,1,ncovmodel);
                   7595: 
1.145     brouard  7596:     free_ivector(ncodemax,1,NCOVMAX);
                   7597:     free_ivector(Tvar,1,NCOVMAX);
                   7598:     free_ivector(Tprod,1,NCOVMAX);
                   7599:     free_ivector(Tvaraff,1,NCOVMAX);
                   7600:     free_ivector(Tage,1,NCOVMAX);
1.126     brouard  7601: 
                   7602:     free_imatrix(nbcode,0,NCOVMAX,0,NCOVMAX);
                   7603:     free_imatrix(codtab,1,100,1,10);
                   7604:   fflush(fichtm);
                   7605:   fflush(ficgp);
                   7606:   
                   7607: 
                   7608:   if((nberr >0) || (nbwarn>0)){
                   7609:     printf("End of Imach with %d errors and/or %d warnings\n",nberr,nbwarn);
                   7610:     fprintf(ficlog,"End of Imach with %d errors and/or warnings %d\n",nberr,nbwarn);
                   7611:   }else{
                   7612:     printf("End of Imach\n");
                   7613:     fprintf(ficlog,"End of Imach\n");
                   7614:   }
                   7615:   printf("See log file on %s\n",filelog);
                   7616:   /*  gettimeofday(&end_time, (struct timezone*)0);*/  /* after time */
1.157     brouard  7617:   /*(void) gettimeofday(&end_time,&tzp);*/
                   7618:   rend_time = time(NULL);  
                   7619:   end_time = *localtime(&rend_time);
                   7620:   /* tml = *localtime(&end_time.tm_sec); */
                   7621:   strcpy(strtend,asctime(&end_time));
1.126     brouard  7622:   printf("Local time at start %s\nLocal time at end   %s",strstart, strtend); 
                   7623:   fprintf(ficlog,"Local time at start %s\nLocal time at end   %s\n",strstart, strtend); 
1.157     brouard  7624:   printf("Total time used %s\n", asc_diff_time(rend_time -rstart_time,tmpout));
1.126     brouard  7625: 
1.157     brouard  7626:   printf("Total time was %.0lf Sec.\n", difftime(rend_time,rstart_time));
                   7627:   fprintf(ficlog,"Total time used %s\n", asc_diff_time(rend_time -rstart_time,tmpout));
                   7628:   fprintf(ficlog,"Total time was %.0lf Sec.\n", difftime(rend_time,rstart_time));
1.126     brouard  7629:   /*  printf("Total time was %d uSec.\n", total_usecs);*/
                   7630: /*   if(fileappend(fichtm,optionfilehtm)){ */
                   7631:   fprintf(fichtm,"<br>Local time at start %s<br>Local time at end   %s<br>\n</body></html>",strstart, strtend);
                   7632:   fclose(fichtm);
                   7633:   fprintf(fichtmcov,"<br>Local time at start %s<br>Local time at end   %s<br>\n</body></html>",strstart, strtend);
                   7634:   fclose(fichtmcov);
                   7635:   fclose(ficgp);
                   7636:   fclose(ficlog);
                   7637:   /*------ End -----------*/
                   7638: 
                   7639: 
                   7640:    printf("Before Current directory %s!\n",pathcd);
1.184     brouard  7641: #ifdef WIN32
                   7642:    if (_chdir(pathcd) != 0)
                   7643:           printf("Can't move to directory %s!\n",path);
                   7644:    if(_getcwd(pathcd,MAXLINE) > 0)
                   7645: #else
1.126     brouard  7646:    if(chdir(pathcd) != 0)
1.184     brouard  7647:           printf("Can't move to directory %s!\n", path);
                   7648:    if (getcwd(pathcd, MAXLINE) > 0)
                   7649: #endif 
1.126     brouard  7650:     printf("Current directory %s!\n",pathcd);
                   7651:   /*strcat(plotcmd,CHARSEPARATOR);*/
                   7652:   sprintf(plotcmd,"gnuplot");
1.157     brouard  7653: #ifdef _WIN32
1.126     brouard  7654:   sprintf(plotcmd,"\"%sgnuplot.exe\"",pathimach);
                   7655: #endif
                   7656:   if(!stat(plotcmd,&info)){
1.158     brouard  7657:     printf("Error or gnuplot program not found: '%s'\n",plotcmd);fflush(stdout);
1.126     brouard  7658:     if(!stat(getenv("GNUPLOTBIN"),&info)){
1.158     brouard  7659:       printf("Error or gnuplot program not found: '%s' Environment GNUPLOTBIN not set.\n",plotcmd);fflush(stdout);
1.126     brouard  7660:     }else
                   7661:       strcpy(pplotcmd,plotcmd);
1.157     brouard  7662: #ifdef __unix
1.126     brouard  7663:     strcpy(plotcmd,GNUPLOTPROGRAM);
                   7664:     if(!stat(plotcmd,&info)){
1.158     brouard  7665:       printf("Error gnuplot program not found: '%s'\n",plotcmd);fflush(stdout);
1.126     brouard  7666:     }else
                   7667:       strcpy(pplotcmd,plotcmd);
                   7668: #endif
                   7669:   }else
                   7670:     strcpy(pplotcmd,plotcmd);
                   7671:   
                   7672:   sprintf(plotcmd,"%s %s",pplotcmd, optionfilegnuplot);
1.158     brouard  7673:   printf("Starting graphs with: '%s'\n",plotcmd);fflush(stdout);
1.126     brouard  7674: 
                   7675:   if((outcmd=system(plotcmd)) != 0){
1.158     brouard  7676:     printf("gnuplot command might not be in your path: '%s', err=%d\n", plotcmd, outcmd);
1.154     brouard  7677:     printf("\n Trying if gnuplot resides on the same directory that IMaCh\n");
1.152     brouard  7678:     sprintf(plotcmd,"%sgnuplot %s", pathimach, optionfilegnuplot);
1.150     brouard  7679:     if((outcmd=system(plotcmd)) != 0)
1.153     brouard  7680:       printf("\n Still a problem with gnuplot command %s, err=%d\n", plotcmd, outcmd);
1.126     brouard  7681:   }
1.158     brouard  7682:   printf(" Successful, please wait...");
1.126     brouard  7683:   while (z[0] != 'q') {
                   7684:     /* chdir(path); */
1.154     brouard  7685:     printf("\nType e to edit results with your browser, g to graph again and q for exit: ");
1.126     brouard  7686:     scanf("%s",z);
                   7687: /*     if (z[0] == 'c') system("./imach"); */
                   7688:     if (z[0] == 'e') {
1.158     brouard  7689: #ifdef __APPLE__
1.152     brouard  7690:       sprintf(pplotcmd, "open %s", optionfilehtm);
1.157     brouard  7691: #elif __linux
                   7692:       sprintf(pplotcmd, "xdg-open %s", optionfilehtm);
1.153     brouard  7693: #else
1.152     brouard  7694:       sprintf(pplotcmd, "%s", optionfilehtm);
1.153     brouard  7695: #endif
                   7696:       printf("Starting browser with: %s",pplotcmd);fflush(stdout);
                   7697:       system(pplotcmd);
1.126     brouard  7698:     }
                   7699:     else if (z[0] == 'g') system(plotcmd);
                   7700:     else if (z[0] == 'q') exit(0);
                   7701:   }
                   7702:   end:
                   7703:   while (z[0] != 'q') {
                   7704:     printf("\nType  q for exiting: ");
                   7705:     scanf("%s",z);
                   7706:   }
                   7707: }

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