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

1.185   ! brouard     1: /* $Id: imach.c,v 1.184 2015/03/11 11:52:39 brouard Exp $
1.126     brouard     2:   $State: Exp $
1.163     brouard     3:   $Log: imach.c,v $
1.185   ! brouard     4:   Revision 1.184  2015/03/11 11:52:39  brouard
        !             5:   Summary: Back from Windows 8. Intel Compiler
        !             6: 
1.184     brouard     7:   Revision 1.183  2015/03/10 20:34:32  brouard
                      8:   Summary: 0.98q0, trying with directest, mnbrak fixed
                      9: 
                     10:   We use directest instead of original Powell test; probably no
                     11:   incidence on the results, but better justifications;
                     12:   We fixed Numerical Recipes mnbrak routine which was wrong and gave
                     13:   wrong results.
                     14: 
1.183     brouard    15:   Revision 1.182  2015/02/12 08:19:57  brouard
                     16:   Summary: Trying to keep directest which seems simpler and more general
                     17:   Author: Nicolas Brouard
                     18: 
1.182     brouard    19:   Revision 1.181  2015/02/11 23:22:24  brouard
                     20:   Summary: Comments on Powell added
                     21: 
                     22:   Author:
                     23: 
1.181     brouard    24:   Revision 1.180  2015/02/11 17:33:45  brouard
                     25:   Summary: Finishing move from main to function (hpijx and prevalence_limit)
                     26: 
1.180     brouard    27:   Revision 1.179  2015/01/04 09:57:06  brouard
                     28:   Summary: back to OS/X
                     29: 
1.179     brouard    30:   Revision 1.178  2015/01/04 09:35:48  brouard
                     31:   *** empty log message ***
                     32: 
1.178     brouard    33:   Revision 1.177  2015/01/03 18:40:56  brouard
                     34:   Summary: Still testing ilc32 on OSX
                     35: 
1.177     brouard    36:   Revision 1.176  2015/01/03 16:45:04  brouard
                     37:   *** empty log message ***
                     38: 
1.176     brouard    39:   Revision 1.175  2015/01/03 16:33:42  brouard
                     40:   *** empty log message ***
                     41: 
1.175     brouard    42:   Revision 1.174  2015/01/03 16:15:49  brouard
                     43:   Summary: Still in cross-compilation
                     44: 
1.174     brouard    45:   Revision 1.173  2015/01/03 12:06:26  brouard
                     46:   Summary: trying to detect cross-compilation
                     47: 
1.173     brouard    48:   Revision 1.172  2014/12/27 12:07:47  brouard
                     49:   Summary: Back from Visual Studio and Intel, options for compiling for Windows XP
                     50: 
1.172     brouard    51:   Revision 1.171  2014/12/23 13:26:59  brouard
                     52:   Summary: Back from Visual C
                     53: 
                     54:   Still problem with utsname.h on Windows
                     55: 
1.171     brouard    56:   Revision 1.170  2014/12/23 11:17:12  brouard
                     57:   Summary: Cleaning some \%% back to %%
                     58: 
                     59:   The escape was mandatory for a specific compiler (which one?), but too many warnings.
                     60: 
1.170     brouard    61:   Revision 1.169  2014/12/22 23:08:31  brouard
                     62:   Summary: 0.98p
                     63: 
                     64:   Outputs some informations on compiler used, OS etc. Testing on different platforms.
                     65: 
1.169     brouard    66:   Revision 1.168  2014/12/22 15:17:42  brouard
1.170     brouard    67:   Summary: update
1.169     brouard    68: 
1.168     brouard    69:   Revision 1.167  2014/12/22 13:50:56  brouard
                     70:   Summary: Testing uname and compiler version and if compiled 32 or 64
                     71: 
                     72:   Testing on Linux 64
                     73: 
1.167     brouard    74:   Revision 1.166  2014/12/22 11:40:47  brouard
                     75:   *** empty log message ***
                     76: 
1.166     brouard    77:   Revision 1.165  2014/12/16 11:20:36  brouard
                     78:   Summary: After compiling on Visual C
                     79: 
                     80:   * imach.c (Module): Merging 1.61 to 1.162
                     81: 
1.165     brouard    82:   Revision 1.164  2014/12/16 10:52:11  brouard
                     83:   Summary: Merging with Visual C after suppressing some warnings for unused variables. Also fixing Saito's bug 0.98Xn
                     84: 
                     85:   * imach.c (Module): Merging 1.61 to 1.162
                     86: 
1.164     brouard    87:   Revision 1.163  2014/12/16 10:30:11  brouard
                     88:   * imach.c (Module): Merging 1.61 to 1.162
                     89: 
1.163     brouard    90:   Revision 1.162  2014/09/25 11:43:39  brouard
                     91:   Summary: temporary backup 0.99!
                     92: 
1.162     brouard    93:   Revision 1.1  2014/09/16 11:06:58  brouard
                     94:   Summary: With some code (wrong) for nlopt
                     95: 
                     96:   Author:
                     97: 
                     98:   Revision 1.161  2014/09/15 20:41:41  brouard
                     99:   Summary: Problem with macro SQR on Intel compiler
                    100: 
1.161     brouard   101:   Revision 1.160  2014/09/02 09:24:05  brouard
                    102:   *** empty log message ***
                    103: 
1.160     brouard   104:   Revision 1.159  2014/09/01 10:34:10  brouard
                    105:   Summary: WIN32
                    106:   Author: Brouard
                    107: 
1.159     brouard   108:   Revision 1.158  2014/08/27 17:11:51  brouard
                    109:   *** empty log message ***
                    110: 
1.158     brouard   111:   Revision 1.157  2014/08/27 16:26:55  brouard
                    112:   Summary: Preparing windows Visual studio version
                    113:   Author: Brouard
                    114: 
                    115:   In order to compile on Visual studio, time.h is now correct and time_t
                    116:   and tm struct should be used. difftime should be used but sometimes I
                    117:   just make the differences in raw time format (time(&now).
                    118:   Trying to suppress #ifdef LINUX
                    119:   Add xdg-open for __linux in order to open default browser.
                    120: 
1.157     brouard   121:   Revision 1.156  2014/08/25 20:10:10  brouard
                    122:   *** empty log message ***
                    123: 
1.156     brouard   124:   Revision 1.155  2014/08/25 18:32:34  brouard
                    125:   Summary: New compile, minor changes
                    126:   Author: Brouard
                    127: 
1.155     brouard   128:   Revision 1.154  2014/06/20 17:32:08  brouard
                    129:   Summary: Outputs now all graphs of convergence to period prevalence
                    130: 
1.154     brouard   131:   Revision 1.153  2014/06/20 16:45:46  brouard
                    132:   Summary: If 3 live state, convergence to period prevalence on same graph
                    133:   Author: Brouard
                    134: 
1.153     brouard   135:   Revision 1.152  2014/06/18 17:54:09  brouard
                    136:   Summary: open browser, use gnuplot on same dir than imach if not found in the path
                    137: 
1.152     brouard   138:   Revision 1.151  2014/06/18 16:43:30  brouard
                    139:   *** empty log message ***
                    140: 
1.151     brouard   141:   Revision 1.150  2014/06/18 16:42:35  brouard
                    142:   Summary: If gnuplot is not in the path try on same directory than imach binary (OSX)
                    143:   Author: brouard
                    144: 
1.150     brouard   145:   Revision 1.149  2014/06/18 15:51:14  brouard
                    146:   Summary: Some fixes in parameter files errors
                    147:   Author: Nicolas Brouard
                    148: 
1.149     brouard   149:   Revision 1.148  2014/06/17 17:38:48  brouard
                    150:   Summary: Nothing new
                    151:   Author: Brouard
                    152: 
                    153:   Just a new packaging for OS/X version 0.98nS
                    154: 
1.148     brouard   155:   Revision 1.147  2014/06/16 10:33:11  brouard
                    156:   *** empty log message ***
                    157: 
1.147     brouard   158:   Revision 1.146  2014/06/16 10:20:28  brouard
                    159:   Summary: Merge
                    160:   Author: Brouard
                    161: 
                    162:   Merge, before building revised version.
                    163: 
1.146     brouard   164:   Revision 1.145  2014/06/10 21:23:15  brouard
                    165:   Summary: Debugging with valgrind
                    166:   Author: Nicolas Brouard
                    167: 
                    168:   Lot of changes in order to output the results with some covariates
                    169:   After the Edimburgh REVES conference 2014, it seems mandatory to
                    170:   improve the code.
                    171:   No more memory valgrind error but a lot has to be done in order to
                    172:   continue the work of splitting the code into subroutines.
                    173:   Also, decodemodel has been improved. Tricode is still not
                    174:   optimal. nbcode should be improved. Documentation has been added in
                    175:   the source code.
                    176: 
1.144     brouard   177:   Revision 1.143  2014/01/26 09:45:38  brouard
                    178:   Summary: Version 0.98nR (to be improved, but gives same optimization results as 0.98k. Nice, promising
                    179: 
                    180:   * imach.c (Module): Trying to merge old staffs together while being at Tokyo. Not tested...
                    181:   (Module): Version 0.98nR Running ok, but output format still only works for three covariates.
                    182: 
1.143     brouard   183:   Revision 1.142  2014/01/26 03:57:36  brouard
                    184:   Summary: gnuplot changed plot w l 1 has to be changed to plot w l lt 2
                    185: 
                    186:   * imach.c (Module): Trying to merge old staffs together while being at Tokyo. Not tested...
                    187: 
1.142     brouard   188:   Revision 1.141  2014/01/26 02:42:01  brouard
                    189:   * imach.c (Module): Trying to merge old staffs together while being at Tokyo. Not tested...
                    190: 
1.141     brouard   191:   Revision 1.140  2011/09/02 10:37:54  brouard
                    192:   Summary: times.h is ok with mingw32 now.
                    193: 
1.140     brouard   194:   Revision 1.139  2010/06/14 07:50:17  brouard
                    195:   After the theft of my laptop, I probably lost some lines of codes which were not uploaded to the CVS tree.
                    196:   I remember having already fixed agemin agemax which are pointers now but not cvs saved.
                    197: 
1.139     brouard   198:   Revision 1.138  2010/04/30 18:19:40  brouard
                    199:   *** empty log message ***
                    200: 
1.138     brouard   201:   Revision 1.137  2010/04/29 18:11:38  brouard
                    202:   (Module): Checking covariates for more complex models
                    203:   than V1+V2. A lot of change to be done. Unstable.
                    204: 
1.137     brouard   205:   Revision 1.136  2010/04/26 20:30:53  brouard
                    206:   (Module): merging some libgsl code. Fixing computation
                    207:   of likelione (using inter/intrapolation if mle = 0) in order to
                    208:   get same likelihood as if mle=1.
                    209:   Some cleaning of code and comments added.
                    210: 
1.136     brouard   211:   Revision 1.135  2009/10/29 15:33:14  brouard
                    212:   (Module): Now imach stops if date of birth, at least year of birth, is not given. Some cleaning of the code.
                    213: 
1.135     brouard   214:   Revision 1.134  2009/10/29 13:18:53  brouard
                    215:   (Module): Now imach stops if date of birth, at least year of birth, is not given. Some cleaning of the code.
                    216: 
1.134     brouard   217:   Revision 1.133  2009/07/06 10:21:25  brouard
                    218:   just nforces
                    219: 
1.133     brouard   220:   Revision 1.132  2009/07/06 08:22:05  brouard
                    221:   Many tings
                    222: 
1.132     brouard   223:   Revision 1.131  2009/06/20 16:22:47  brouard
                    224:   Some dimensions resccaled
                    225: 
1.131     brouard   226:   Revision 1.130  2009/05/26 06:44:34  brouard
                    227:   (Module): Max Covariate is now set to 20 instead of 8. A
                    228:   lot of cleaning with variables initialized to 0. Trying to make
                    229:   V2+V3*age+V1+V4 strb=V3*age+V1+V4 working better.
                    230: 
1.130     brouard   231:   Revision 1.129  2007/08/31 13:49:27  lievre
                    232:   Modification of the way of exiting when the covariate is not binary in order to see on the window the error message before exiting
                    233: 
1.129     lievre    234:   Revision 1.128  2006/06/30 13:02:05  brouard
                    235:   (Module): Clarifications on computing e.j
                    236: 
1.128     brouard   237:   Revision 1.127  2006/04/28 18:11:50  brouard
                    238:   (Module): Yes the sum of survivors was wrong since
                    239:   imach-114 because nhstepm was no more computed in the age
                    240:   loop. Now we define nhstepma in the age loop.
                    241:   (Module): In order to speed up (in case of numerous covariates) we
                    242:   compute health expectancies (without variances) in a first step
                    243:   and then all the health expectancies with variances or standard
                    244:   deviation (needs data from the Hessian matrices) which slows the
                    245:   computation.
                    246:   In the future we should be able to stop the program is only health
                    247:   expectancies and graph are needed without standard deviations.
                    248: 
1.127     brouard   249:   Revision 1.126  2006/04/28 17:23:28  brouard
                    250:   (Module): Yes the sum of survivors was wrong since
                    251:   imach-114 because nhstepm was no more computed in the age
                    252:   loop. Now we define nhstepma in the age loop.
                    253:   Version 0.98h
                    254: 
1.126     brouard   255:   Revision 1.125  2006/04/04 15:20:31  lievre
                    256:   Errors in calculation of health expectancies. Age was not initialized.
                    257:   Forecasting file added.
                    258: 
                    259:   Revision 1.124  2006/03/22 17:13:53  lievre
                    260:   Parameters are printed with %lf instead of %f (more numbers after the comma).
                    261:   The log-likelihood is printed in the log file
                    262: 
                    263:   Revision 1.123  2006/03/20 10:52:43  brouard
                    264:   * imach.c (Module): <title> changed, corresponds to .htm file
                    265:   name. <head> headers where missing.
                    266: 
                    267:   * imach.c (Module): Weights can have a decimal point as for
                    268:   English (a comma might work with a correct LC_NUMERIC environment,
                    269:   otherwise the weight is truncated).
                    270:   Modification of warning when the covariates values are not 0 or
                    271:   1.
                    272:   Version 0.98g
                    273: 
                    274:   Revision 1.122  2006/03/20 09:45:41  brouard
                    275:   (Module): Weights can have a decimal point as for
                    276:   English (a comma might work with a correct LC_NUMERIC environment,
                    277:   otherwise the weight is truncated).
                    278:   Modification of warning when the covariates values are not 0 or
                    279:   1.
                    280:   Version 0.98g
                    281: 
                    282:   Revision 1.121  2006/03/16 17:45:01  lievre
                    283:   * imach.c (Module): Comments concerning covariates added
                    284: 
                    285:   * imach.c (Module): refinements in the computation of lli if
                    286:   status=-2 in order to have more reliable computation if stepm is
                    287:   not 1 month. Version 0.98f
                    288: 
                    289:   Revision 1.120  2006/03/16 15:10:38  lievre
                    290:   (Module): refinements in the computation of lli if
                    291:   status=-2 in order to have more reliable computation if stepm is
                    292:   not 1 month. Version 0.98f
                    293: 
                    294:   Revision 1.119  2006/03/15 17:42:26  brouard
                    295:   (Module): Bug if status = -2, the loglikelihood was
                    296:   computed as likelihood omitting the logarithm. Version O.98e
                    297: 
                    298:   Revision 1.118  2006/03/14 18:20:07  brouard
                    299:   (Module): varevsij Comments added explaining the second
                    300:   table of variances if popbased=1 .
                    301:   (Module): Covariances of eij, ekl added, graphs fixed, new html link.
                    302:   (Module): Function pstamp added
                    303:   (Module): Version 0.98d
                    304: 
                    305:   Revision 1.117  2006/03/14 17:16:22  brouard
                    306:   (Module): varevsij Comments added explaining the second
                    307:   table of variances if popbased=1 .
                    308:   (Module): Covariances of eij, ekl added, graphs fixed, new html link.
                    309:   (Module): Function pstamp added
                    310:   (Module): Version 0.98d
                    311: 
                    312:   Revision 1.116  2006/03/06 10:29:27  brouard
                    313:   (Module): Variance-covariance wrong links and
                    314:   varian-covariance of ej. is needed (Saito).
                    315: 
                    316:   Revision 1.115  2006/02/27 12:17:45  brouard
                    317:   (Module): One freematrix added in mlikeli! 0.98c
                    318: 
                    319:   Revision 1.114  2006/02/26 12:57:58  brouard
                    320:   (Module): Some improvements in processing parameter
                    321:   filename with strsep.
                    322: 
                    323:   Revision 1.113  2006/02/24 14:20:24  brouard
                    324:   (Module): Memory leaks checks with valgrind and:
                    325:   datafile was not closed, some imatrix were not freed and on matrix
                    326:   allocation too.
                    327: 
                    328:   Revision 1.112  2006/01/30 09:55:26  brouard
                    329:   (Module): Back to gnuplot.exe instead of wgnuplot.exe
                    330: 
                    331:   Revision 1.111  2006/01/25 20:38:18  brouard
                    332:   (Module): Lots of cleaning and bugs added (Gompertz)
                    333:   (Module): Comments can be added in data file. Missing date values
                    334:   can be a simple dot '.'.
                    335: 
                    336:   Revision 1.110  2006/01/25 00:51:50  brouard
                    337:   (Module): Lots of cleaning and bugs added (Gompertz)
                    338: 
                    339:   Revision 1.109  2006/01/24 19:37:15  brouard
                    340:   (Module): Comments (lines starting with a #) are allowed in data.
                    341: 
                    342:   Revision 1.108  2006/01/19 18:05:42  lievre
                    343:   Gnuplot problem appeared...
                    344:   To be fixed
                    345: 
                    346:   Revision 1.107  2006/01/19 16:20:37  brouard
                    347:   Test existence of gnuplot in imach path
                    348: 
                    349:   Revision 1.106  2006/01/19 13:24:36  brouard
                    350:   Some cleaning and links added in html output
                    351: 
                    352:   Revision 1.105  2006/01/05 20:23:19  lievre
                    353:   *** empty log message ***
                    354: 
                    355:   Revision 1.104  2005/09/30 16:11:43  lievre
                    356:   (Module): sump fixed, loop imx fixed, and simplifications.
                    357:   (Module): If the status is missing at the last wave but we know
                    358:   that the person is alive, then we can code his/her status as -2
                    359:   (instead of missing=-1 in earlier versions) and his/her
                    360:   contributions to the likelihood is 1 - Prob of dying from last
                    361:   health status (= 1-p13= p11+p12 in the easiest case of somebody in
                    362:   the healthy state at last known wave). Version is 0.98
                    363: 
                    364:   Revision 1.103  2005/09/30 15:54:49  lievre
                    365:   (Module): sump fixed, loop imx fixed, and simplifications.
                    366: 
                    367:   Revision 1.102  2004/09/15 17:31:30  brouard
                    368:   Add the possibility to read data file including tab characters.
                    369: 
                    370:   Revision 1.101  2004/09/15 10:38:38  brouard
                    371:   Fix on curr_time
                    372: 
                    373:   Revision 1.100  2004/07/12 18:29:06  brouard
                    374:   Add version for Mac OS X. Just define UNIX in Makefile
                    375: 
                    376:   Revision 1.99  2004/06/05 08:57:40  brouard
                    377:   *** empty log message ***
                    378: 
                    379:   Revision 1.98  2004/05/16 15:05:56  brouard
                    380:   New version 0.97 . First attempt to estimate force of mortality
                    381:   directly from the data i.e. without the need of knowing the health
                    382:   state at each age, but using a Gompertz model: log u =a + b*age .
                    383:   This is the basic analysis of mortality and should be done before any
                    384:   other analysis, in order to test if the mortality estimated from the
                    385:   cross-longitudinal survey is different from the mortality estimated
                    386:   from other sources like vital statistic data.
                    387: 
                    388:   The same imach parameter file can be used but the option for mle should be -3.
                    389: 
1.133     brouard   390:   Agnès, who wrote this part of the code, tried to keep most of the
1.126     brouard   391:   former routines in order to include the new code within the former code.
                    392: 
                    393:   The output is very simple: only an estimate of the intercept and of
                    394:   the slope with 95% confident intervals.
                    395: 
                    396:   Current limitations:
                    397:   A) Even if you enter covariates, i.e. with the
                    398:   model= V1+V2 equation for example, the programm does only estimate a unique global model without covariates.
                    399:   B) There is no computation of Life Expectancy nor Life Table.
                    400: 
                    401:   Revision 1.97  2004/02/20 13:25:42  lievre
                    402:   Version 0.96d. Population forecasting command line is (temporarily)
                    403:   suppressed.
                    404: 
                    405:   Revision 1.96  2003/07/15 15:38:55  brouard
                    406:   * imach.c (Repository): Errors in subdirf, 2, 3 while printing tmpout is
                    407:   rewritten within the same printf. Workaround: many printfs.
                    408: 
                    409:   Revision 1.95  2003/07/08 07:54:34  brouard
                    410:   * imach.c (Repository):
                    411:   (Repository): Using imachwizard code to output a more meaningful covariance
                    412:   matrix (cov(a12,c31) instead of numbers.
                    413: 
                    414:   Revision 1.94  2003/06/27 13:00:02  brouard
                    415:   Just cleaning
                    416: 
                    417:   Revision 1.93  2003/06/25 16:33:55  brouard
                    418:   (Module): On windows (cygwin) function asctime_r doesn't
                    419:   exist so I changed back to asctime which exists.
                    420:   (Module): Version 0.96b
                    421: 
                    422:   Revision 1.92  2003/06/25 16:30:45  brouard
                    423:   (Module): On windows (cygwin) function asctime_r doesn't
                    424:   exist so I changed back to asctime which exists.
                    425: 
                    426:   Revision 1.91  2003/06/25 15:30:29  brouard
                    427:   * imach.c (Repository): Duplicated warning errors corrected.
                    428:   (Repository): Elapsed time after each iteration is now output. It
                    429:   helps to forecast when convergence will be reached. Elapsed time
                    430:   is stamped in powell.  We created a new html file for the graphs
                    431:   concerning matrix of covariance. It has extension -cov.htm.
                    432: 
                    433:   Revision 1.90  2003/06/24 12:34:15  brouard
                    434:   (Module): Some bugs corrected for windows. Also, when
                    435:   mle=-1 a template is output in file "or"mypar.txt with the design
                    436:   of the covariance matrix to be input.
                    437: 
                    438:   Revision 1.89  2003/06/24 12:30:52  brouard
                    439:   (Module): Some bugs corrected for windows. Also, when
                    440:   mle=-1 a template is output in file "or"mypar.txt with the design
                    441:   of the covariance matrix to be input.
                    442: 
                    443:   Revision 1.88  2003/06/23 17:54:56  brouard
                    444:   * 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.
                    445: 
                    446:   Revision 1.87  2003/06/18 12:26:01  brouard
                    447:   Version 0.96
                    448: 
                    449:   Revision 1.86  2003/06/17 20:04:08  brouard
                    450:   (Module): Change position of html and gnuplot routines and added
                    451:   routine fileappend.
                    452: 
                    453:   Revision 1.85  2003/06/17 13:12:43  brouard
                    454:   * imach.c (Repository): Check when date of death was earlier that
                    455:   current date of interview. It may happen when the death was just
                    456:   prior to the death. In this case, dh was negative and likelihood
                    457:   was wrong (infinity). We still send an "Error" but patch by
                    458:   assuming that the date of death was just one stepm after the
                    459:   interview.
                    460:   (Repository): Because some people have very long ID (first column)
                    461:   we changed int to long in num[] and we added a new lvector for
                    462:   memory allocation. But we also truncated to 8 characters (left
                    463:   truncation)
                    464:   (Repository): No more line truncation errors.
                    465: 
                    466:   Revision 1.84  2003/06/13 21:44:43  brouard
                    467:   * imach.c (Repository): Replace "freqsummary" at a correct
                    468:   place. It differs from routine "prevalence" which may be called
                    469:   many times. Probs is memory consuming and must be used with
                    470:   parcimony.
                    471:   Version 0.95a3 (should output exactly the same maximization than 0.8a2)
                    472: 
                    473:   Revision 1.83  2003/06/10 13:39:11  lievre
                    474:   *** empty log message ***
                    475: 
                    476:   Revision 1.82  2003/06/05 15:57:20  brouard
                    477:   Add log in  imach.c and  fullversion number is now printed.
                    478: 
                    479: */
                    480: /*
                    481:    Interpolated Markov Chain
                    482: 
                    483:   Short summary of the programme:
                    484:   
                    485:   This program computes Healthy Life Expectancies from
                    486:   cross-longitudinal data. Cross-longitudinal data consist in: -1- a
                    487:   first survey ("cross") where individuals from different ages are
                    488:   interviewed on their health status or degree of disability (in the
                    489:   case of a health survey which is our main interest) -2- at least a
                    490:   second wave of interviews ("longitudinal") which measure each change
                    491:   (if any) in individual health status.  Health expectancies are
                    492:   computed from the time spent in each health state according to a
                    493:   model. More health states you consider, more time is necessary to reach the
                    494:   Maximum Likelihood of the parameters involved in the model.  The
                    495:   simplest model is the multinomial logistic model where pij is the
                    496:   probability to be observed in state j at the second wave
                    497:   conditional to be observed in state i at the first wave. Therefore
                    498:   the model is: log(pij/pii)= aij + bij*age+ cij*sex + etc , where
                    499:   'age' is age and 'sex' is a covariate. If you want to have a more
                    500:   complex model than "constant and age", you should modify the program
                    501:   where the markup *Covariates have to be included here again* invites
                    502:   you to do it.  More covariates you add, slower the
                    503:   convergence.
                    504: 
                    505:   The advantage of this computer programme, compared to a simple
                    506:   multinomial logistic model, is clear when the delay between waves is not
                    507:   identical for each individual. Also, if a individual missed an
                    508:   intermediate interview, the information is lost, but taken into
                    509:   account using an interpolation or extrapolation.  
                    510: 
                    511:   hPijx is the probability to be observed in state i at age x+h
                    512:   conditional to the observed state i at age x. The delay 'h' can be
                    513:   split into an exact number (nh*stepm) of unobserved intermediate
                    514:   states. This elementary transition (by month, quarter,
                    515:   semester or year) is modelled as a multinomial logistic.  The hPx
                    516:   matrix is simply the matrix product of nh*stepm elementary matrices
                    517:   and the contribution of each individual to the likelihood is simply
                    518:   hPijx.
                    519: 
                    520:   Also this programme outputs the covariance matrix of the parameters but also
                    521:   of the life expectancies. It also computes the period (stable) prevalence. 
                    522:   
1.133     brouard   523:   Authors: Nicolas Brouard (brouard@ined.fr) and Agnès Lièvre (lievre@ined.fr).
                    524:            Institut national d'études démographiques, Paris.
1.126     brouard   525:   This software have been partly granted by Euro-REVES, a concerted action
                    526:   from the European Union.
                    527:   It is copyrighted identically to a GNU software product, ie programme and
                    528:   software can be distributed freely for non commercial use. Latest version
                    529:   can be accessed at http://euroreves.ined.fr/imach .
                    530: 
                    531:   Help to debug: LD_PRELOAD=/usr/local/lib/libnjamd.so ./imach foo.imach
                    532:   or better on gdb : set env LD_PRELOAD=/usr/local/lib/libnjamd.so
                    533:   
                    534:   **********************************************************************/
                    535: /*
                    536:   main
                    537:   read parameterfile
                    538:   read datafile
                    539:   concatwav
                    540:   freqsummary
                    541:   if (mle >= 1)
                    542:     mlikeli
                    543:   print results files
                    544:   if mle==1 
                    545:      computes hessian
                    546:   read end of parameter file: agemin, agemax, bage, fage, estepm
                    547:       begin-prev-date,...
                    548:   open gnuplot file
                    549:   open html file
1.145     brouard   550:   period (stable) prevalence      | pl_nom    1-1 2-2 etc by covariate
                    551:    for age prevalim()             | #****** V1=0  V2=1  V3=1  V4=0 ******
                    552:                                   | 65 1 0 2 1 3 1 4 0  0.96326 0.03674
                    553:     freexexit2 possible for memory heap.
                    554: 
                    555:   h Pij x                         | pij_nom  ficrestpij
                    556:    # Cov Agex agex+h hpijx with i,j= 1-1 1-2     1-3     2-1     2-2     2-3
                    557:        1  85   85    1.00000             0.00000 0.00000 0.00000 1.00000 0.00000
                    558:        1  85   86    0.68299             0.22291 0.09410 0.71093 0.00000 0.28907
                    559: 
                    560:        1  65   99    0.00364             0.00322 0.99314 0.00350 0.00310 0.99340
                    561:        1  65  100    0.00214             0.00204 0.99581 0.00206 0.00196 0.99597
                    562:   variance of p one-step probabilities varprob  | prob_nom   ficresprob #One-step probabilities and stand. devi in ()
                    563:    Standard deviation of one-step probabilities | probcor_nom   ficresprobcor #One-step probabilities and correlation matrix
                    564:    Matrix of variance covariance of one-step probabilities |  probcov_nom ficresprobcov #One-step probabilities and covariance matrix
                    565: 
1.126     brouard   566:   forecasting if prevfcast==1 prevforecast call prevalence()
                    567:   health expectancies
                    568:   Variance-covariance of DFLE
                    569:   prevalence()
                    570:    movingaverage()
                    571:   varevsij() 
                    572:   if popbased==1 varevsij(,popbased)
                    573:   total life expectancies
                    574:   Variance of period (stable) prevalence
                    575:  end
                    576: */
                    577: 
1.165     brouard   578: #define POWELL /* Instead of NLOPT */
1.183     brouard   579: /* #define POWELLORIGINAL */ /* Don't use Directest to decide new direction but original Powell test */
1.184     brouard   580: /* #define MNBRAKORIGINAL */ /* Don't use mnbrak fix */
1.126     brouard   581: 
                    582: #include <math.h>
                    583: #include <stdio.h>
                    584: #include <stdlib.h>
                    585: #include <string.h>
1.159     brouard   586: 
                    587: #ifdef _WIN32
                    588: #include <io.h>
1.172     brouard   589: #include <windows.h>
                    590: #include <tchar.h>
1.159     brouard   591: #else
1.126     brouard   592: #include <unistd.h>
1.159     brouard   593: #endif
1.126     brouard   594: 
                    595: #include <limits.h>
                    596: #include <sys/types.h>
1.171     brouard   597: 
                    598: #if defined(__GNUC__)
                    599: #include <sys/utsname.h> /* Doesn't work on Windows */
                    600: #endif
                    601: 
1.126     brouard   602: #include <sys/stat.h>
                    603: #include <errno.h>
1.159     brouard   604: /* extern int errno; */
1.126     brouard   605: 
1.157     brouard   606: /* #ifdef LINUX */
                    607: /* #include <time.h> */
                    608: /* #include "timeval.h" */
                    609: /* #else */
                    610: /* #include <sys/time.h> */
                    611: /* #endif */
                    612: 
1.126     brouard   613: #include <time.h>
                    614: 
1.136     brouard   615: #ifdef GSL
                    616: #include <gsl/gsl_errno.h>
                    617: #include <gsl/gsl_multimin.h>
                    618: #endif
                    619: 
1.167     brouard   620: 
1.162     brouard   621: #ifdef NLOPT
                    622: #include <nlopt.h>
                    623: typedef struct {
                    624:   double (* function)(double [] );
                    625: } myfunc_data ;
                    626: #endif
                    627: 
1.126     brouard   628: /* #include <libintl.h> */
                    629: /* #define _(String) gettext (String) */
                    630: 
1.141     brouard   631: #define MAXLINE 1024 /* Was 256. Overflow with 312 with 2 states and 4 covariates. Should be ok */
1.126     brouard   632: 
                    633: #define GNUPLOTPROGRAM "gnuplot"
                    634: /*#define GNUPLOTPROGRAM "..\\gp37mgw\\wgnuplot"*/
                    635: #define FILENAMELENGTH 132
                    636: 
                    637: #define        GLOCK_ERROR_NOPATH              -1      /* empty path */
                    638: #define        GLOCK_ERROR_GETCWD              -2      /* cannot get cwd */
                    639: 
1.144     brouard   640: #define MAXPARM 128 /**< Maximum number of parameters for the optimization */
                    641: #define NPARMAX 64 /**< (nlstate+ndeath-1)*nlstate*ncovmodel */
1.126     brouard   642: 
                    643: #define NINTERVMAX 8
1.144     brouard   644: #define NLSTATEMAX 8 /**< Maximum number of live states (for func) */
                    645: #define NDEATHMAX 8 /**< Maximum number of dead states (for func) */
                    646: #define NCOVMAX 20 /**< Maximum number of covariates, including generated covariates V1*V2 */
1.145     brouard   647: #define codtabm(h,k)  1 & (h-1) >> (k-1) ;
1.126     brouard   648: #define MAXN 20000
1.144     brouard   649: #define YEARM 12. /**< Number of months per year */
1.126     brouard   650: #define AGESUP 130
                    651: #define AGEBASE 40
1.164     brouard   652: #define AGEGOMP 10 /**< Minimal age for Gompertz adjustment */
1.157     brouard   653: #ifdef _WIN32
                    654: #define DIRSEPARATOR '\\'
                    655: #define CHARSEPARATOR "\\"
                    656: #define ODIRSEPARATOR '/'
                    657: #else
1.126     brouard   658: #define DIRSEPARATOR '/'
                    659: #define CHARSEPARATOR "/"
                    660: #define ODIRSEPARATOR '\\'
                    661: #endif
                    662: 
1.185   ! brouard   663: /* $Id: imach.c,v 1.184 2015/03/11 11:52:39 brouard Exp $ */
1.126     brouard   664: /* $State: Exp $ */
                    665: 
1.183     brouard   666: char version[]="Imach version 0.98q0, March 2015,INED-EUROREVES-Institut de longevite-Japan Society for the Promotion of Science (Grant-in-Aid for Scientific Research 25293121), Intel Software 2015";
1.185   ! brouard   667: char fullversion[]="$Revision: 1.184 $ $Date: 2015/03/11 11:52:39 $"; 
1.126     brouard   668: char strstart[80];
                    669: char optionfilext[10], optionfilefiname[FILENAMELENGTH];
1.130     brouard   670: int erreur=0, nberr=0, nbwarn=0; /* Error number, number of errors number of warnings  */
1.133     brouard   671: int nvar=0, nforce=0; /* Number of variables, number of forces */
1.145     brouard   672: /* Number of covariates model=V2+V1+ V3*age+V2*V4 */
                    673: int cptcovn=0; /**< cptcovn number of covariates added in the model (excepting constant and age and age*product) */
                    674: int cptcovt=0; /**< cptcovt number of covariates added in the model (excepting constant and age) */
                    675: int cptcovs=0; /**< cptcovs number of simple covariates V2+V1 =2 */
                    676: int cptcovage=0; /**< Number of covariates with age: V3*age only =1 */
                    677: int cptcovprodnoage=0; /**< Number of covariate products without age */   
                    678: int cptcoveff=0; /* Total number of covariates to vary for printing results */
                    679: int cptcov=0; /* Working variable */
1.126     brouard   680: int npar=NPARMAX;
                    681: int nlstate=2; /* Number of live states */
                    682: int ndeath=1; /* Number of dead states */
1.130     brouard   683: int ncovmodel=0, ncovcol=0;     /* Total number of covariables including constant a12*1 +b12*x ncovmodel=2 */
1.126     brouard   684: int popbased=0;
                    685: 
                    686: int *wav; /* Number of waves for this individuual 0 is possible */
1.130     brouard   687: int maxwav=0; /* Maxim number of waves */
                    688: int jmin=0, jmax=0; /* min, max spacing between 2 waves */
                    689: int ijmin=0, ijmax=0; /* Individuals having jmin and jmax */ 
                    690: int gipmx=0, gsw=0; /* Global variables on the number of contributions 
1.126     brouard   691:                   to the likelihood and the sum of weights (done by funcone)*/
1.130     brouard   692: int mle=1, weightopt=0;
1.126     brouard   693: int **mw; /* mw[mi][i] is number of the mi wave for this individual */
                    694: int **dh; /* dh[mi][i] is number of steps between mi,mi+1 for this individual */
                    695: int **bh; /* bh[mi][i] is the bias (+ or -) for this individual if the delay between
                    696:           * wave mi and wave mi+1 is not an exact multiple of stepm. */
1.162     brouard   697: int countcallfunc=0;  /* Count the number of calls to func */
1.130     brouard   698: double jmean=1; /* Mean space between 2 waves */
1.145     brouard   699: double **matprod2(); /* test */
1.126     brouard   700: double **oldm, **newm, **savm; /* Working pointers to matrices */
                    701: double **oldms, **newms, **savms; /* Fixed working pointers to matrices */
1.136     brouard   702: /*FILE *fic ; */ /* Used in readdata only */
                    703: FILE *ficpar, *ficparo,*ficres, *ficresp, *ficrespl, *ficrespij, *ficrest,*ficresf,*ficrespop;
1.126     brouard   704: FILE *ficlog, *ficrespow;
1.130     brouard   705: int globpr=0; /* Global variable for printing or not */
1.126     brouard   706: double fretone; /* Only one call to likelihood */
1.130     brouard   707: long ipmx=0; /* Number of contributions */
1.126     brouard   708: double sw; /* Sum of weights */
                    709: char filerespow[FILENAMELENGTH];
                    710: char fileresilk[FILENAMELENGTH]; /* File of individual contributions to the likelihood */
                    711: FILE *ficresilk;
                    712: FILE *ficgp,*ficresprob,*ficpop, *ficresprobcov, *ficresprobcor;
                    713: FILE *ficresprobmorprev;
                    714: FILE *fichtm, *fichtmcov; /* Html File */
                    715: FILE *ficreseij;
                    716: char filerese[FILENAMELENGTH];
                    717: FILE *ficresstdeij;
                    718: char fileresstde[FILENAMELENGTH];
                    719: FILE *ficrescveij;
                    720: char filerescve[FILENAMELENGTH];
                    721: FILE  *ficresvij;
                    722: char fileresv[FILENAMELENGTH];
                    723: FILE  *ficresvpl;
                    724: char fileresvpl[FILENAMELENGTH];
                    725: char title[MAXLINE];
                    726: char optionfile[FILENAMELENGTH], datafile[FILENAMELENGTH],  filerespl[FILENAMELENGTH];
                    727: char plotcmd[FILENAMELENGTH], pplotcmd[FILENAMELENGTH];
                    728: char tmpout[FILENAMELENGTH],  tmpout2[FILENAMELENGTH]; 
                    729: char command[FILENAMELENGTH];
                    730: int  outcmd=0;
                    731: 
                    732: char fileres[FILENAMELENGTH], filerespij[FILENAMELENGTH], filereso[FILENAMELENGTH], rfileres[FILENAMELENGTH];
                    733: 
                    734: char filelog[FILENAMELENGTH]; /* Log file */
                    735: char filerest[FILENAMELENGTH];
                    736: char fileregp[FILENAMELENGTH];
                    737: char popfile[FILENAMELENGTH];
                    738: 
                    739: char optionfilegnuplot[FILENAMELENGTH], optionfilehtm[FILENAMELENGTH], optionfilehtmcov[FILENAMELENGTH] ;
                    740: 
1.157     brouard   741: /* struct timeval start_time, end_time, curr_time, last_time, forecast_time; */
                    742: /* struct timezone tzp; */
                    743: /* extern int gettimeofday(); */
                    744: struct tm tml, *gmtime(), *localtime();
                    745: 
                    746: extern time_t time();
                    747: 
                    748: struct tm start_time, end_time, curr_time, last_time, forecast_time;
                    749: time_t  rstart_time, rend_time, rcurr_time, rlast_time, rforecast_time; /* raw time */
                    750: struct tm tm;
                    751: 
1.126     brouard   752: char strcurr[80], strfor[80];
                    753: 
                    754: char *endptr;
                    755: long lval;
                    756: double dval;
                    757: 
                    758: #define NR_END 1
                    759: #define FREE_ARG char*
                    760: #define FTOL 1.0e-10
                    761: 
                    762: #define NRANSI 
                    763: #define ITMAX 200 
                    764: 
                    765: #define TOL 2.0e-4 
                    766: 
                    767: #define CGOLD 0.3819660 
                    768: #define ZEPS 1.0e-10 
                    769: #define SHFT(a,b,c,d) (a)=(b);(b)=(c);(c)=(d); 
                    770: 
                    771: #define GOLD 1.618034 
                    772: #define GLIMIT 100.0 
                    773: #define TINY 1.0e-20 
                    774: 
                    775: static double maxarg1,maxarg2;
                    776: #define FMAX(a,b) (maxarg1=(a),maxarg2=(b),(maxarg1)>(maxarg2)? (maxarg1):(maxarg2))
                    777: #define FMIN(a,b) (maxarg1=(a),maxarg2=(b),(maxarg1)<(maxarg2)? (maxarg1):(maxarg2))
                    778:   
                    779: #define SIGN(a,b) ((b)>0.0 ? fabs(a) : -fabs(a))
                    780: #define rint(a) floor(a+0.5)
1.166     brouard   781: /* http://www.thphys.uni-heidelberg.de/~robbers/cmbeasy/doc/html/myutils_8h-source.html */
1.183     brouard   782: #define mytinydouble 1.0e-16
1.166     brouard   783: /* #define DEQUAL(a,b) (fabs((a)-(b))<mytinydouble) */
                    784: /* http://www.thphys.uni-heidelberg.de/~robbers/cmbeasy/doc/html/mynrutils_8h-source.html */
                    785: /* static double dsqrarg; */
                    786: /* #define DSQR(a) (DEQUAL((dsqrarg=(a)),0.0) ? 0.0 : dsqrarg*dsqrarg) */
1.126     brouard   787: static double sqrarg;
                    788: #define SQR(a) ((sqrarg=(a)) == 0.0 ? 0.0 :sqrarg*sqrarg)
                    789: #define SWAP(a,b) {temp=(a);(a)=(b);(b)=temp;} 
                    790: int agegomp= AGEGOMP;
                    791: 
                    792: int imx; 
                    793: int stepm=1;
                    794: /* Stepm, step in month: minimum step interpolation*/
                    795: 
                    796: int estepm;
                    797: /* Estepm, step in month to interpolate survival function in order to approximate Life Expectancy*/
                    798: 
                    799: int m,nb;
                    800: long *num;
                    801: int firstpass=0, lastpass=4,*cod, *ncodemax, *Tage,*cens;
                    802: double **agev,*moisnais, *annais, *moisdc, *andc,**mint, **anint;
                    803: double **pmmij, ***probs;
                    804: double *ageexmed,*agecens;
                    805: double dateintmean=0;
                    806: 
                    807: double *weight;
                    808: int **s; /* Status */
1.141     brouard   809: double *agedc;
1.145     brouard   810: double  **covar; /**< covar[j,i], value of jth covariate for individual i,
1.141     brouard   811:                  * covar=matrix(0,NCOVMAX,1,n); 
                    812:                  * cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*cov[2]; */
                    813: double  idx; 
                    814: int **nbcode, *Tvar; /**< model=V2 => Tvar[1]= 2 */
1.145     brouard   815: int *Ndum; /** Freq of modality (tricode */
1.141     brouard   816: int **codtab; /**< codtab=imatrix(1,100,1,10); */
                    817: int **Tvard, *Tprod, cptcovprod, *Tvaraff;
1.126     brouard   818: double *lsurv, *lpop, *tpop;
                    819: 
1.143     brouard   820: double ftol=FTOL; /**< Tolerance for computing Max Likelihood */
                    821: double ftolhess; /**< Tolerance for computing hessian */
1.126     brouard   822: 
                    823: /**************** split *************************/
                    824: static int split( char *path, char *dirc, char *name, char *ext, char *finame )
                    825: {
                    826:   /* From a file name with (full) path (either Unix or Windows) we extract the directory (dirc)
                    827:      the name of the file (name), its extension only (ext) and its first part of the name (finame)
                    828:   */ 
                    829:   char *ss;                            /* pointer */
                    830:   int  l1, l2;                         /* length counters */
                    831: 
                    832:   l1 = strlen(path );                  /* length of path */
                    833:   if ( l1 == 0 ) return( GLOCK_ERROR_NOPATH );
                    834:   ss= strrchr( path, DIRSEPARATOR );           /* find last / */
                    835:   if ( ss == NULL ) {                  /* no directory, so determine current directory */
                    836:     strcpy( name, path );              /* we got the fullname name because no directory */
                    837:     /*if(strrchr(path, ODIRSEPARATOR )==NULL)
                    838:       printf("Warning you should use %s as a separator\n",DIRSEPARATOR);*/
                    839:     /* get current working directory */
                    840:     /*    extern  char* getcwd ( char *buf , int len);*/
1.184     brouard   841: #ifdef WIN32
                    842:     if (_getcwd( dirc, FILENAME_MAX ) == NULL ) {
                    843: #else
                    844:        if (getcwd(dirc, FILENAME_MAX) == NULL) {
                    845: #endif
1.126     brouard   846:       return( GLOCK_ERROR_GETCWD );
                    847:     }
                    848:     /* got dirc from getcwd*/
                    849:     printf(" DIRC = %s \n",dirc);
                    850:   } else {                             /* strip direcotry from path */
                    851:     ss++;                              /* after this, the filename */
                    852:     l2 = strlen( ss );                 /* length of filename */
                    853:     if ( l2 == 0 ) return( GLOCK_ERROR_NOPATH );
                    854:     strcpy( name, ss );                /* save file name */
                    855:     strncpy( dirc, path, l1 - l2 );    /* now the directory */
                    856:     dirc[l1-l2] = 0;                   /* add zero */
                    857:     printf(" DIRC2 = %s \n",dirc);
                    858:   }
                    859:   /* We add a separator at the end of dirc if not exists */
                    860:   l1 = strlen( dirc );                 /* length of directory */
                    861:   if( dirc[l1-1] != DIRSEPARATOR ){
                    862:     dirc[l1] =  DIRSEPARATOR;
                    863:     dirc[l1+1] = 0; 
                    864:     printf(" DIRC3 = %s \n",dirc);
                    865:   }
                    866:   ss = strrchr( name, '.' );           /* find last / */
                    867:   if (ss >0){
                    868:     ss++;
                    869:     strcpy(ext,ss);                    /* save extension */
                    870:     l1= strlen( name);
                    871:     l2= strlen(ss)+1;
                    872:     strncpy( finame, name, l1-l2);
                    873:     finame[l1-l2]= 0;
                    874:   }
                    875: 
                    876:   return( 0 );                         /* we're done */
                    877: }
                    878: 
                    879: 
                    880: /******************************************/
                    881: 
                    882: void replace_back_to_slash(char *s, char*t)
                    883: {
                    884:   int i;
                    885:   int lg=0;
                    886:   i=0;
                    887:   lg=strlen(t);
                    888:   for(i=0; i<= lg; i++) {
                    889:     (s[i] = t[i]);
                    890:     if (t[i]== '\\') s[i]='/';
                    891:   }
                    892: }
                    893: 
1.132     brouard   894: char *trimbb(char *out, char *in)
1.137     brouard   895: { /* Trim multiple blanks in line but keeps first blanks if line starts with blanks */
1.132     brouard   896:   char *s;
                    897:   s=out;
                    898:   while (*in != '\0'){
1.137     brouard   899:     while( *in == ' ' && *(in+1) == ' '){ /* && *(in+1) != '\0'){*/
1.132     brouard   900:       in++;
                    901:     }
                    902:     *out++ = *in++;
                    903:   }
                    904:   *out='\0';
                    905:   return s;
                    906: }
                    907: 
1.145     brouard   908: char *cutl(char *blocc, char *alocc, char *in, char occ)
                    909: {
                    910:   /* cuts string in into blocc and alocc where blocc ends before first occurence of char 'occ' 
                    911:      and alocc starts after first occurence of char 'occ' : ex cutv(blocc,alocc,"abcdef2ghi2j",'2')
                    912:      gives blocc="abcdef2ghi" and alocc="j".
                    913:      If occ is not found blocc is null and alocc is equal to in. Returns blocc
                    914:   */
1.160     brouard   915:   char *s, *t;
1.145     brouard   916:   t=in;s=in;
                    917:   while ((*in != occ) && (*in != '\0')){
                    918:     *alocc++ = *in++;
                    919:   }
                    920:   if( *in == occ){
                    921:     *(alocc)='\0';
                    922:     s=++in;
                    923:   }
                    924:  
                    925:   if (s == t) {/* occ not found */
                    926:     *(alocc-(in-s))='\0';
                    927:     in=s;
                    928:   }
                    929:   while ( *in != '\0'){
                    930:     *blocc++ = *in++;
                    931:   }
                    932: 
                    933:   *blocc='\0';
                    934:   return t;
                    935: }
1.137     brouard   936: char *cutv(char *blocc, char *alocc, char *in, char occ)
                    937: {
                    938:   /* cuts string in into blocc and alocc where blocc ends before last occurence of char 'occ' 
                    939:      and alocc starts after last occurence of char 'occ' : ex cutv(blocc,alocc,"abcdef2ghi2j",'2')
                    940:      gives blocc="abcdef2ghi" and alocc="j".
                    941:      If occ is not found blocc is null and alocc is equal to in. Returns alocc
                    942:   */
                    943:   char *s, *t;
                    944:   t=in;s=in;
                    945:   while (*in != '\0'){
                    946:     while( *in == occ){
                    947:       *blocc++ = *in++;
                    948:       s=in;
                    949:     }
                    950:     *blocc++ = *in++;
                    951:   }
                    952:   if (s == t) /* occ not found */
                    953:     *(blocc-(in-s))='\0';
                    954:   else
                    955:     *(blocc-(in-s)-1)='\0';
                    956:   in=s;
                    957:   while ( *in != '\0'){
                    958:     *alocc++ = *in++;
                    959:   }
                    960: 
                    961:   *alocc='\0';
                    962:   return s;
                    963: }
                    964: 
1.126     brouard   965: int nbocc(char *s, char occ)
                    966: {
                    967:   int i,j=0;
                    968:   int lg=20;
                    969:   i=0;
                    970:   lg=strlen(s);
                    971:   for(i=0; i<= lg; i++) {
                    972:   if  (s[i] == occ ) j++;
                    973:   }
                    974:   return j;
                    975: }
                    976: 
1.137     brouard   977: /* void cutv(char *u,char *v, char*t, char occ) */
                    978: /* { */
                    979: /*   /\* cuts string t into u and v where u ends before last occurence of char 'occ'  */
                    980: /*      and v starts after last occurence of char 'occ' : ex cutv(u,v,"abcdef2ghi2j",'2') */
                    981: /*      gives u="abcdef2ghi" and v="j" *\/ */
                    982: /*   int i,lg,j,p=0; */
                    983: /*   i=0; */
                    984: /*   lg=strlen(t); */
                    985: /*   for(j=0; j<=lg-1; j++) { */
                    986: /*     if((t[j]!= occ) && (t[j+1]== occ)) p=j+1; */
                    987: /*   } */
1.126     brouard   988: 
1.137     brouard   989: /*   for(j=0; j<p; j++) { */
                    990: /*     (u[j] = t[j]); */
                    991: /*   } */
                    992: /*      u[p]='\0'; */
1.126     brouard   993: 
1.137     brouard   994: /*    for(j=0; j<= lg; j++) { */
                    995: /*     if (j>=(p+1))(v[j-p-1] = t[j]); */
                    996: /*   } */
                    997: /* } */
1.126     brouard   998: 
1.160     brouard   999: #ifdef _WIN32
                   1000: char * strsep(char **pp, const char *delim)
                   1001: {
                   1002:   char *p, *q;
                   1003:          
                   1004:   if ((p = *pp) == NULL)
                   1005:     return 0;
                   1006:   if ((q = strpbrk (p, delim)) != NULL)
                   1007:   {
                   1008:     *pp = q + 1;
                   1009:     *q = '\0';
                   1010:   }
                   1011:   else
                   1012:     *pp = 0;
                   1013:   return p;
                   1014: }
                   1015: #endif
                   1016: 
1.126     brouard  1017: /********************** nrerror ********************/
                   1018: 
                   1019: void nrerror(char error_text[])
                   1020: {
                   1021:   fprintf(stderr,"ERREUR ...\n");
                   1022:   fprintf(stderr,"%s\n",error_text);
                   1023:   exit(EXIT_FAILURE);
                   1024: }
                   1025: /*********************** vector *******************/
                   1026: double *vector(int nl, int nh)
                   1027: {
                   1028:   double *v;
                   1029:   v=(double *) malloc((size_t)((nh-nl+1+NR_END)*sizeof(double)));
                   1030:   if (!v) nrerror("allocation failure in vector");
                   1031:   return v-nl+NR_END;
                   1032: }
                   1033: 
                   1034: /************************ free vector ******************/
                   1035: void free_vector(double*v, int nl, int nh)
                   1036: {
                   1037:   free((FREE_ARG)(v+nl-NR_END));
                   1038: }
                   1039: 
                   1040: /************************ivector *******************************/
                   1041: int *ivector(long nl,long nh)
                   1042: {
                   1043:   int *v;
                   1044:   v=(int *) malloc((size_t)((nh-nl+1+NR_END)*sizeof(int)));
                   1045:   if (!v) nrerror("allocation failure in ivector");
                   1046:   return v-nl+NR_END;
                   1047: }
                   1048: 
                   1049: /******************free ivector **************************/
                   1050: void free_ivector(int *v, long nl, long nh)
                   1051: {
                   1052:   free((FREE_ARG)(v+nl-NR_END));
                   1053: }
                   1054: 
                   1055: /************************lvector *******************************/
                   1056: long *lvector(long nl,long nh)
                   1057: {
                   1058:   long *v;
                   1059:   v=(long *) malloc((size_t)((nh-nl+1+NR_END)*sizeof(long)));
                   1060:   if (!v) nrerror("allocation failure in ivector");
                   1061:   return v-nl+NR_END;
                   1062: }
                   1063: 
                   1064: /******************free lvector **************************/
                   1065: void free_lvector(long *v, long nl, long nh)
                   1066: {
                   1067:   free((FREE_ARG)(v+nl-NR_END));
                   1068: }
                   1069: 
                   1070: /******************* imatrix *******************************/
                   1071: int **imatrix(long nrl, long nrh, long ncl, long nch) 
                   1072:      /* allocate a int matrix with subscript range m[nrl..nrh][ncl..nch] */ 
                   1073: { 
                   1074:   long i, nrow=nrh-nrl+1,ncol=nch-ncl+1; 
                   1075:   int **m; 
                   1076:   
                   1077:   /* allocate pointers to rows */ 
                   1078:   m=(int **) malloc((size_t)((nrow+NR_END)*sizeof(int*))); 
                   1079:   if (!m) nrerror("allocation failure 1 in matrix()"); 
                   1080:   m += NR_END; 
                   1081:   m -= nrl; 
                   1082:   
                   1083:   
                   1084:   /* allocate rows and set pointers to them */ 
                   1085:   m[nrl]=(int *) malloc((size_t)((nrow*ncol+NR_END)*sizeof(int))); 
                   1086:   if (!m[nrl]) nrerror("allocation failure 2 in matrix()"); 
                   1087:   m[nrl] += NR_END; 
                   1088:   m[nrl] -= ncl; 
                   1089:   
                   1090:   for(i=nrl+1;i<=nrh;i++) m[i]=m[i-1]+ncol; 
                   1091:   
                   1092:   /* return pointer to array of pointers to rows */ 
                   1093:   return m; 
                   1094: } 
                   1095: 
                   1096: /****************** free_imatrix *************************/
                   1097: void free_imatrix(m,nrl,nrh,ncl,nch)
                   1098:       int **m;
                   1099:       long nch,ncl,nrh,nrl; 
                   1100:      /* free an int matrix allocated by imatrix() */ 
                   1101: { 
                   1102:   free((FREE_ARG) (m[nrl]+ncl-NR_END)); 
                   1103:   free((FREE_ARG) (m+nrl-NR_END)); 
                   1104: } 
                   1105: 
                   1106: /******************* matrix *******************************/
                   1107: double **matrix(long nrl, long nrh, long ncl, long nch)
                   1108: {
                   1109:   long i, nrow=nrh-nrl+1, ncol=nch-ncl+1;
                   1110:   double **m;
                   1111: 
                   1112:   m=(double **) malloc((size_t)((nrow+NR_END)*sizeof(double*)));
                   1113:   if (!m) nrerror("allocation failure 1 in matrix()");
                   1114:   m += NR_END;
                   1115:   m -= nrl;
                   1116: 
                   1117:   m[nrl]=(double *) malloc((size_t)((nrow*ncol+NR_END)*sizeof(double)));
                   1118:   if (!m[nrl]) nrerror("allocation failure 2 in matrix()");
                   1119:   m[nrl] += NR_END;
                   1120:   m[nrl] -= ncl;
                   1121: 
                   1122:   for (i=nrl+1; i<=nrh; i++) m[i]=m[i-1]+ncol;
                   1123:   return m;
1.145     brouard  1124:   /* print *(*(m+1)+70) or print m[1][70]; print m+1 or print &(m[1]) or &(m[1][0])
                   1125: m[i] = address of ith row of the table. &(m[i]) is its value which is another adress
                   1126: that of m[i][0]. In order to get the value p m[i][0] but it is unitialized.
1.126     brouard  1127:    */
                   1128: }
                   1129: 
                   1130: /*************************free matrix ************************/
                   1131: void free_matrix(double **m, long nrl, long nrh, long ncl, long nch)
                   1132: {
                   1133:   free((FREE_ARG)(m[nrl]+ncl-NR_END));
                   1134:   free((FREE_ARG)(m+nrl-NR_END));
                   1135: }
                   1136: 
                   1137: /******************* ma3x *******************************/
                   1138: double ***ma3x(long nrl, long nrh, long ncl, long nch, long nll, long nlh)
                   1139: {
                   1140:   long i, j, nrow=nrh-nrl+1, ncol=nch-ncl+1, nlay=nlh-nll+1;
                   1141:   double ***m;
                   1142: 
                   1143:   m=(double ***) malloc((size_t)((nrow+NR_END)*sizeof(double*)));
                   1144:   if (!m) nrerror("allocation failure 1 in matrix()");
                   1145:   m += NR_END;
                   1146:   m -= nrl;
                   1147: 
                   1148:   m[nrl]=(double **) malloc((size_t)((nrow*ncol+NR_END)*sizeof(double)));
                   1149:   if (!m[nrl]) nrerror("allocation failure 2 in matrix()");
                   1150:   m[nrl] += NR_END;
                   1151:   m[nrl] -= ncl;
                   1152: 
                   1153:   for (i=nrl+1; i<=nrh; i++) m[i]=m[i-1]+ncol;
                   1154: 
                   1155:   m[nrl][ncl]=(double *) malloc((size_t)((nrow*ncol*nlay+NR_END)*sizeof(double)));
                   1156:   if (!m[nrl][ncl]) nrerror("allocation failure 3 in matrix()");
                   1157:   m[nrl][ncl] += NR_END;
                   1158:   m[nrl][ncl] -= nll;
                   1159:   for (j=ncl+1; j<=nch; j++) 
                   1160:     m[nrl][j]=m[nrl][j-1]+nlay;
                   1161:   
                   1162:   for (i=nrl+1; i<=nrh; i++) {
                   1163:     m[i][ncl]=m[i-1l][ncl]+ncol*nlay;
                   1164:     for (j=ncl+1; j<=nch; j++) 
                   1165:       m[i][j]=m[i][j-1]+nlay;
                   1166:   }
                   1167:   return m; 
                   1168:   /*  gdb: p *(m+1) <=> p m[1] and p (m+1) <=> p (m+1) <=> p &(m[1])
                   1169:            &(m[i][j][k]) <=> *((*(m+i) + j)+k)
                   1170:   */
                   1171: }
                   1172: 
                   1173: /*************************free ma3x ************************/
                   1174: void free_ma3x(double ***m, long nrl, long nrh, long ncl, long nch,long nll, long nlh)
                   1175: {
                   1176:   free((FREE_ARG)(m[nrl][ncl]+ nll-NR_END));
                   1177:   free((FREE_ARG)(m[nrl]+ncl-NR_END));
                   1178:   free((FREE_ARG)(m+nrl-NR_END));
                   1179: }
                   1180: 
                   1181: /*************** function subdirf ***********/
                   1182: char *subdirf(char fileres[])
                   1183: {
                   1184:   /* Caution optionfilefiname is hidden */
                   1185:   strcpy(tmpout,optionfilefiname);
                   1186:   strcat(tmpout,"/"); /* Add to the right */
                   1187:   strcat(tmpout,fileres);
                   1188:   return tmpout;
                   1189: }
                   1190: 
                   1191: /*************** function subdirf2 ***********/
                   1192: char *subdirf2(char fileres[], char *preop)
                   1193: {
                   1194:   
                   1195:   /* Caution optionfilefiname is hidden */
                   1196:   strcpy(tmpout,optionfilefiname);
                   1197:   strcat(tmpout,"/");
                   1198:   strcat(tmpout,preop);
                   1199:   strcat(tmpout,fileres);
                   1200:   return tmpout;
                   1201: }
                   1202: 
                   1203: /*************** function subdirf3 ***********/
                   1204: char *subdirf3(char fileres[], char *preop, char *preop2)
                   1205: {
                   1206:   
                   1207:   /* Caution optionfilefiname is hidden */
                   1208:   strcpy(tmpout,optionfilefiname);
                   1209:   strcat(tmpout,"/");
                   1210:   strcat(tmpout,preop);
                   1211:   strcat(tmpout,preop2);
                   1212:   strcat(tmpout,fileres);
                   1213:   return tmpout;
                   1214: }
                   1215: 
1.162     brouard  1216: char *asc_diff_time(long time_sec, char ascdiff[])
                   1217: {
                   1218:   long sec_left, days, hours, minutes;
                   1219:   days = (time_sec) / (60*60*24);
                   1220:   sec_left = (time_sec) % (60*60*24);
                   1221:   hours = (sec_left) / (60*60) ;
                   1222:   sec_left = (sec_left) %(60*60);
                   1223:   minutes = (sec_left) /60;
                   1224:   sec_left = (sec_left) % (60);
                   1225:   sprintf(ascdiff,"%ld day(s) %ld hour(s) %ld minute(s) %ld second(s)",days, hours, minutes, sec_left);  
                   1226:   return ascdiff;
                   1227: }
                   1228: 
1.126     brouard  1229: /***************** f1dim *************************/
                   1230: extern int ncom; 
                   1231: extern double *pcom,*xicom;
                   1232: extern double (*nrfunc)(double []); 
                   1233:  
                   1234: double f1dim(double x) 
                   1235: { 
                   1236:   int j; 
                   1237:   double f;
                   1238:   double *xt; 
                   1239:  
                   1240:   xt=vector(1,ncom); 
                   1241:   for (j=1;j<=ncom;j++) xt[j]=pcom[j]+x*xicom[j]; 
                   1242:   f=(*nrfunc)(xt); 
                   1243:   free_vector(xt,1,ncom); 
                   1244:   return f; 
                   1245: } 
                   1246: 
                   1247: /*****************brent *************************/
                   1248: double brent(double ax, double bx, double cx, double (*f)(double), double tol,         double *xmin) 
                   1249: { 
                   1250:   int iter; 
                   1251:   double a,b,d,etemp;
1.159     brouard  1252:   double fu=0,fv,fw,fx;
1.164     brouard  1253:   double ftemp=0.;
1.126     brouard  1254:   double p,q,r,tol1,tol2,u,v,w,x,xm; 
                   1255:   double e=0.0; 
                   1256:  
                   1257:   a=(ax < cx ? ax : cx); 
                   1258:   b=(ax > cx ? ax : cx); 
                   1259:   x=w=v=bx; 
                   1260:   fw=fv=fx=(*f)(x); 
                   1261:   for (iter=1;iter<=ITMAX;iter++) { 
                   1262:     xm=0.5*(a+b); 
                   1263:     tol2=2.0*(tol1=tol*fabs(x)+ZEPS); 
                   1264:     /*         if (2.0*fabs(fp-(*fret)) <= ftol*(fabs(fp)+fabs(*fret)))*/
                   1265:     printf(".");fflush(stdout);
                   1266:     fprintf(ficlog,".");fflush(ficlog);
1.162     brouard  1267: #ifdef DEBUGBRENT
1.126     brouard  1268:     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);
                   1269:     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);
                   1270:     /*         if ((fabs(x-xm) <= (tol2-0.5*(b-a)))||(2.0*fabs(fu-ftemp) <= ftol*1.e-2*(fabs(fu)+fabs(ftemp)))) { */
                   1271: #endif
                   1272:     if (fabs(x-xm) <= (tol2-0.5*(b-a))){ 
                   1273:       *xmin=x; 
                   1274:       return fx; 
                   1275:     } 
                   1276:     ftemp=fu;
                   1277:     if (fabs(e) > tol1) { 
                   1278:       r=(x-w)*(fx-fv); 
                   1279:       q=(x-v)*(fx-fw); 
                   1280:       p=(x-v)*q-(x-w)*r; 
                   1281:       q=2.0*(q-r); 
                   1282:       if (q > 0.0) p = -p; 
                   1283:       q=fabs(q); 
                   1284:       etemp=e; 
                   1285:       e=d; 
                   1286:       if (fabs(p) >= fabs(0.5*q*etemp) || p <= q*(a-x) || p >= q*(b-x)) 
                   1287:        d=CGOLD*(e=(x >= xm ? a-x : b-x)); 
                   1288:       else { 
                   1289:        d=p/q; 
                   1290:        u=x+d; 
                   1291:        if (u-a < tol2 || b-u < tol2) 
                   1292:          d=SIGN(tol1,xm-x); 
                   1293:       } 
                   1294:     } else { 
                   1295:       d=CGOLD*(e=(x >= xm ? a-x : b-x)); 
                   1296:     } 
                   1297:     u=(fabs(d) >= tol1 ? x+d : x+SIGN(tol1,d)); 
                   1298:     fu=(*f)(u); 
                   1299:     if (fu <= fx) { 
                   1300:       if (u >= x) a=x; else b=x; 
                   1301:       SHFT(v,w,x,u) 
1.183     brouard  1302:       SHFT(fv,fw,fx,fu) 
                   1303:     } else { 
                   1304:       if (u < x) a=u; else b=u; 
                   1305:       if (fu <= fw || w == x) { 
                   1306:        v=w; 
                   1307:        w=u; 
                   1308:        fv=fw; 
                   1309:        fw=fu; 
                   1310:       } else if (fu <= fv || v == x || v == w) { 
                   1311:        v=u; 
                   1312:        fv=fu; 
                   1313:       } 
                   1314:     } 
1.126     brouard  1315:   } 
                   1316:   nrerror("Too many iterations in brent"); 
                   1317:   *xmin=x; 
                   1318:   return fx; 
                   1319: } 
                   1320: 
                   1321: /****************** mnbrak ***********************/
                   1322: 
                   1323: void mnbrak(double *ax, double *bx, double *cx, double *fa, double *fb, double *fc, 
                   1324:            double (*func)(double)) 
1.183     brouard  1325: { /* Given a function func , and given distinct initial points ax and bx , this routine searches in
                   1326: the downhill direction (defined by the function as evaluated at the initial points) and returns
                   1327: new points ax , bx , cx that bracket a minimum of the function. Also returned are the function
                   1328: values at the three points, fa, fb , and fc such that fa > fb and fb < fc.
                   1329:    */
1.126     brouard  1330:   double ulim,u,r,q, dum;
                   1331:   double fu; 
                   1332:  
                   1333:   *fa=(*func)(*ax); 
                   1334:   *fb=(*func)(*bx); 
                   1335:   if (*fb > *fa) { 
                   1336:     SHFT(dum,*ax,*bx,dum) 
1.183     brouard  1337:     SHFT(dum,*fb,*fa,dum) 
                   1338:   } 
1.126     brouard  1339:   *cx=(*bx)+GOLD*(*bx-*ax); 
                   1340:   *fc=(*func)(*cx); 
1.183     brouard  1341: #ifdef DEBUG
                   1342:   printf("mnbrak0 *fb=%.12e *fc=%.12e\n",*fb,*fc);
                   1343:   fprintf(ficlog,"mnbrak0 *fb=%.12e *fc=%.12e\n",*fb,*fc);
                   1344: #endif
                   1345:   while (*fb > *fc) { /* Declining a,b,c with fa> fb > fc */
1.126     brouard  1346:     r=(*bx-*ax)*(*fb-*fc); 
                   1347:     q=(*bx-*cx)*(*fb-*fa); 
                   1348:     u=(*bx)-((*bx-*cx)*q-(*bx-*ax)*r)/ 
1.183     brouard  1349:       (2.0*SIGN(FMAX(fabs(q-r),TINY),q-r)); /* Minimum abscissa of a parabolic estimated from (a,fa), (b,fb) and (c,fc). */
                   1350:     ulim=(*bx)+GLIMIT*(*cx-*bx); /* Maximum abscissa where function should be evaluated */
                   1351:     if ((*bx-u)*(u-*cx) > 0.0) { /* if u_p is between b and c */
1.126     brouard  1352:       fu=(*func)(u); 
1.163     brouard  1353: #ifdef DEBUG
                   1354:       /* f(x)=A(x-u)**2+f(u) */
                   1355:       double A, fparabu; 
                   1356:       A= (*fb - *fa)/(*bx-*ax)/(*bx+*ax-2*u);
                   1357:       fparabu= *fa - A*(*ax-u)*(*ax-u);
                   1358:       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);
                   1359:       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  1360:       /* And thus,it can be that fu > *fc even if fparabu < *fc */
                   1361:       /* mnbrak (*ax=7.666299858533, *fa=299039.693133272231), (*bx=8.595447774979, *fb=298976.598289369489),
                   1362:         (*cx=10.098840694817, *fc=298946.631474258087),  (*u=9.852501168332, fu=298948.773013752128, fparabu=298945.434711494134) */
                   1363:       /* In that case, there is no bracket in the output! Routine is wrong with many consequences.*/
1.163     brouard  1364: #endif 
1.184     brouard  1365: #ifdef MNBRAKORIGINAL
1.183     brouard  1366: #else
                   1367:       if (fu > *fc) {
                   1368: #ifdef DEBUG
                   1369:       printf("mnbrak4  fu > fc \n");
                   1370:       fprintf(ficlog, "mnbrak4 fu > fc\n");
                   1371: #endif
                   1372:        /* 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 *\/  */
                   1373:        /* SHFT(*fa,*fc,fu,*fc) /\* (b, u, c) is a bracket while test fb > fc will be fu > fc  will exit *\/ */
                   1374:        dum=u; /* Shifting c and u */
                   1375:        u = *cx;
                   1376:        *cx = dum;
                   1377:        dum = fu;
                   1378:        fu = *fc;
                   1379:        *fc =dum;
                   1380:       } else { /* end */
                   1381: #ifdef DEBUG
                   1382:       printf("mnbrak3  fu < fc \n");
                   1383:       fprintf(ficlog, "mnbrak3 fu < fc\n");
                   1384: #endif
                   1385:        dum=u; /* Shifting c and u */
                   1386:        u = *cx;
                   1387:        *cx = dum;
                   1388:        dum = fu;
                   1389:        fu = *fc;
                   1390:        *fc =dum;
                   1391:       }
                   1392: #endif
1.162     brouard  1393:     } else if ((*cx-u)*(u-ulim) > 0.0) { /* u is after c but before ulim */
1.183     brouard  1394: #ifdef DEBUG
                   1395:       printf("mnbrak2  u after c but before ulim\n");
                   1396:       fprintf(ficlog, "mnbrak2 u after c but before ulim\n");
                   1397: #endif
1.126     brouard  1398:       fu=(*func)(u); 
                   1399:       if (fu < *fc) { 
1.183     brouard  1400: #ifdef DEBUG
                   1401:       printf("mnbrak2  u after c but before ulim AND fu < fc\n");
                   1402:       fprintf(ficlog, "mnbrak2 u after c but before ulim AND fu <fc \n");
                   1403: #endif
1.126     brouard  1404:        SHFT(*bx,*cx,u,*cx+GOLD*(*cx-*bx)) 
1.183     brouard  1405:        SHFT(*fb,*fc,fu,(*func)(u)) 
                   1406:       } 
1.162     brouard  1407:     } else if ((u-ulim)*(ulim-*cx) >= 0.0) { /* u outside ulim (verifying that ulim is beyond c) */
1.183     brouard  1408: #ifdef DEBUG
                   1409:       printf("mnbrak2  u outside ulim (verifying that ulim is beyond c)\n");
                   1410:       fprintf(ficlog, "mnbrak2 u outside ulim (verifying that ulim is beyond c)\n");
                   1411: #endif
1.126     brouard  1412:       u=ulim; 
                   1413:       fu=(*func)(u); 
1.183     brouard  1414:     } else { /* u could be left to b (if r > q parabola has a maximum) */
                   1415: #ifdef DEBUG
                   1416:       printf("mnbrak2  u could be left to b (if r > q parabola has a maximum)\n");
                   1417:       fprintf(ficlog, "mnbrak2  u could be left to b (if r > q parabola has a maximum)\n");
                   1418: #endif
1.126     brouard  1419:       u=(*cx)+GOLD*(*cx-*bx); 
                   1420:       fu=(*func)(u); 
1.183     brouard  1421:     } /* end tests */
1.126     brouard  1422:     SHFT(*ax,*bx,*cx,u) 
1.183     brouard  1423:     SHFT(*fa,*fb,*fc,fu) 
                   1424: #ifdef DEBUG
                   1425:       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);
                   1426:       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);
                   1427: #endif
                   1428:   } /* 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  1429: } 
                   1430: 
                   1431: /*************** linmin ************************/
1.162     brouard  1432: /* Given an n -dimensional point p[1..n] and an n -dimensional direction xi[1..n] , moves and
                   1433: resets p to where the function func(p) takes on a minimum along the direction xi from p ,
                   1434: and replaces xi by the actual vector displacement that p was moved. Also returns as fret
                   1435: the value of func at the returned location p . This is actually all accomplished by calling the
                   1436: routines mnbrak and brent .*/
1.126     brouard  1437: int ncom; 
                   1438: double *pcom,*xicom;
                   1439: double (*nrfunc)(double []); 
                   1440:  
                   1441: void linmin(double p[], double xi[], int n, double *fret,double (*func)(double [])) 
                   1442: { 
                   1443:   double brent(double ax, double bx, double cx, 
                   1444:               double (*f)(double), double tol, double *xmin); 
                   1445:   double f1dim(double x); 
                   1446:   void mnbrak(double *ax, double *bx, double *cx, double *fa, double *fb, 
                   1447:              double *fc, double (*func)(double)); 
                   1448:   int j; 
                   1449:   double xx,xmin,bx,ax; 
                   1450:   double fx,fb,fa;
                   1451:  
                   1452:   ncom=n; 
                   1453:   pcom=vector(1,n); 
                   1454:   xicom=vector(1,n); 
                   1455:   nrfunc=func; 
                   1456:   for (j=1;j<=n;j++) { 
                   1457:     pcom[j]=p[j]; 
                   1458:     xicom[j]=xi[j]; 
                   1459:   } 
                   1460:   ax=0.0; 
                   1461:   xx=1.0; 
1.162     brouard  1462:   mnbrak(&ax,&xx,&bx,&fa,&fx,&fb,f1dim); /* Find a bracket a,x,b in direction n=xi ie xicom */
                   1463:   *fret=brent(ax,xx,bx,f1dim,TOL,&xmin); /* Find a minimum P+lambda n in that direction (lambdamin), with TOL between abscisses */
1.126     brouard  1464: #ifdef DEBUG
                   1465:   printf("retour brent fret=%.12e xmin=%.12e\n",*fret,xmin);
                   1466:   fprintf(ficlog,"retour brent fret=%.12e xmin=%.12e\n",*fret,xmin);
                   1467: #endif
                   1468:   for (j=1;j<=n;j++) { 
                   1469:     xi[j] *= xmin; 
                   1470:     p[j] += xi[j]; 
                   1471:   } 
                   1472:   free_vector(xicom,1,n); 
                   1473:   free_vector(pcom,1,n); 
                   1474: } 
                   1475: 
                   1476: 
                   1477: /*************** powell ************************/
1.162     brouard  1478: /*
                   1479: Minimization of a function func of n variables. Input consists of an initial starting point
                   1480: p[1..n] ; an initial matrix xi[1..n][1..n] , whose columns contain the initial set of di-
                   1481: rections (usually the n unit vectors); and ftol , the fractional tolerance in the function value
                   1482: such that failure to decrease by more than this amount on one iteration signals doneness. On
                   1483: output, p is set to the best point found, xi is the then-current direction set, fret is the returned
                   1484: function value at p , and iter is the number of iterations taken. The routine linmin is used.
                   1485:  */
1.126     brouard  1486: void powell(double p[], double **xi, int n, double ftol, int *iter, double *fret, 
                   1487:            double (*func)(double [])) 
                   1488: { 
                   1489:   void linmin(double p[], double xi[], int n, double *fret, 
                   1490:              double (*func)(double [])); 
                   1491:   int i,ibig,j; 
                   1492:   double del,t,*pt,*ptt,*xit;
1.181     brouard  1493:   double directest;
1.126     brouard  1494:   double fp,fptt;
                   1495:   double *xits;
                   1496:   int niterf, itmp;
                   1497: 
                   1498:   pt=vector(1,n); 
                   1499:   ptt=vector(1,n); 
                   1500:   xit=vector(1,n); 
                   1501:   xits=vector(1,n); 
                   1502:   *fret=(*func)(p); 
                   1503:   for (j=1;j<=n;j++) pt[j]=p[j]; 
1.157     brouard  1504:     rcurr_time = time(NULL);  
1.126     brouard  1505:   for (*iter=1;;++(*iter)) { 
                   1506:     fp=(*fret); 
                   1507:     ibig=0; 
                   1508:     del=0.0; 
1.157     brouard  1509:     rlast_time=rcurr_time;
                   1510:     /* (void) gettimeofday(&curr_time,&tzp); */
                   1511:     rcurr_time = time(NULL);  
                   1512:     curr_time = *localtime(&rcurr_time);
                   1513:     printf("\nPowell iter=%d -2*LL=%.12f %ld sec. %ld sec.",*iter,*fret, rcurr_time-rlast_time, rcurr_time-rstart_time);fflush(stdout);
                   1514:     fprintf(ficlog,"\nPowell iter=%d -2*LL=%.12f %ld sec. %ld sec.",*iter,*fret,rcurr_time-rlast_time, rcurr_time-rstart_time); fflush(ficlog);
                   1515: /*     fprintf(ficrespow,"%d %.12f %ld",*iter,*fret,curr_time.tm_sec-start_time.tm_sec); */
1.126     brouard  1516:    for (i=1;i<=n;i++) {
                   1517:       printf(" %d %.12f",i, p[i]);
                   1518:       fprintf(ficlog," %d %.12lf",i, p[i]);
                   1519:       fprintf(ficrespow," %.12lf", p[i]);
                   1520:     }
                   1521:     printf("\n");
                   1522:     fprintf(ficlog,"\n");
                   1523:     fprintf(ficrespow,"\n");fflush(ficrespow);
                   1524:     if(*iter <=3){
1.157     brouard  1525:       tml = *localtime(&rcurr_time);
                   1526:       strcpy(strcurr,asctime(&tml));
                   1527:       rforecast_time=rcurr_time; 
1.126     brouard  1528:       itmp = strlen(strcurr);
                   1529:       if(strcurr[itmp-1]=='\n')  /* Windows outputs with a new line */
                   1530:        strcurr[itmp-1]='\0';
1.162     brouard  1531:       printf("\nConsidering the time needed for the last iteration #%d: %ld seconds,\n",*iter,rcurr_time-rlast_time);
1.157     brouard  1532:       fprintf(ficlog,"\nConsidering the time needed for this last iteration #%d: %ld seconds,\n",*iter,rcurr_time-rlast_time);
1.126     brouard  1533:       for(niterf=10;niterf<=30;niterf+=10){
1.157     brouard  1534:        rforecast_time=rcurr_time+(niterf-*iter)*(rcurr_time-rlast_time);
                   1535:        forecast_time = *localtime(&rforecast_time);
                   1536:        strcpy(strfor,asctime(&forecast_time));
1.126     brouard  1537:        itmp = strlen(strfor);
                   1538:        if(strfor[itmp-1]=='\n')
                   1539:        strfor[itmp-1]='\0';
1.157     brouard  1540:        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);
                   1541:        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  1542:       }
                   1543:     }
                   1544:     for (i=1;i<=n;i++) { 
                   1545:       for (j=1;j<=n;j++) xit[j]=xi[j][i]; 
                   1546:       fptt=(*fret); 
                   1547: #ifdef DEBUG
1.164     brouard  1548:          printf("fret=%lf, %lf, %lf \n", *fret, *fret, *fret);
                   1549:          fprintf(ficlog, "fret=%lf, %lf, %lf \n", *fret, *fret, *fret);
1.126     brouard  1550: #endif
                   1551:       printf("%d",i);fflush(stdout);
                   1552:       fprintf(ficlog,"%d",i);fflush(ficlog);
1.183     brouard  1553:       linmin(p,xit,n,fret,func); /* xit[n] has been loaded for direction i */
1.181     brouard  1554:       if (fabs(fptt-(*fret)) > del) { /* We are keeping the max gain on each of the n directions 
                   1555:                                       because that direction will be replaced unless the gain del is small
                   1556:                                      in comparison with the 'probable' gain, mu^2, with the last average direction.
                   1557:                                      Unless the n directions are conjugate some gain in the determinant may be obtained
                   1558:                                      with the new direction.
                   1559:                                      */
1.126     brouard  1560:        del=fabs(fptt-(*fret)); 
                   1561:        ibig=i; 
                   1562:       } 
                   1563: #ifdef DEBUG
                   1564:       printf("%d %.12e",i,(*fret));
                   1565:       fprintf(ficlog,"%d %.12e",i,(*fret));
                   1566:       for (j=1;j<=n;j++) {
                   1567:        xits[j]=FMAX(fabs(p[j]-pt[j]),1.e-5);
                   1568:        printf(" x(%d)=%.12e",j,xit[j]);
                   1569:        fprintf(ficlog," x(%d)=%.12e",j,xit[j]);
                   1570:       }
                   1571:       for(j=1;j<=n;j++) {
1.162     brouard  1572:        printf(" p(%d)=%.12e",j,p[j]);
                   1573:        fprintf(ficlog," p(%d)=%.12e",j,p[j]);
1.126     brouard  1574:       }
                   1575:       printf("\n");
                   1576:       fprintf(ficlog,"\n");
                   1577: #endif
1.162     brouard  1578:     } /* end i */
1.182     brouard  1579:     if (2.0*fabs(fp-(*fret)) <= ftol*(fabs(fp)+fabs(*fret))) { /* Did we reach enough precision? */
1.126     brouard  1580: #ifdef DEBUG
                   1581:       int k[2],l;
                   1582:       k[0]=1;
                   1583:       k[1]=-1;
                   1584:       printf("Max: %.12e",(*func)(p));
                   1585:       fprintf(ficlog,"Max: %.12e",(*func)(p));
                   1586:       for (j=1;j<=n;j++) {
                   1587:        printf(" %.12e",p[j]);
                   1588:        fprintf(ficlog," %.12e",p[j]);
                   1589:       }
                   1590:       printf("\n");
                   1591:       fprintf(ficlog,"\n");
                   1592:       for(l=0;l<=1;l++) {
                   1593:        for (j=1;j<=n;j++) {
                   1594:          ptt[j]=p[j]+(p[j]-pt[j])*k[l];
                   1595:          printf("l=%d j=%d ptt=%.12e, xits=%.12e, p=%.12e, xit=%.12e", l,j,ptt[j],xits[j],p[j],xit[j]);
                   1596:          fprintf(ficlog,"l=%d j=%d ptt=%.12e, xits=%.12e, p=%.12e, xit=%.12e", l,j,ptt[j],xits[j],p[j],xit[j]);
                   1597:        }
                   1598:        printf("func(ptt)=%.12e, deriv=%.12e\n",(*func)(ptt),(ptt[j]-p[j])/((*func)(ptt)-(*func)(p)));
                   1599:        fprintf(ficlog,"func(ptt)=%.12e, deriv=%.12e\n",(*func)(ptt),(ptt[j]-p[j])/((*func)(ptt)-(*func)(p)));
                   1600:       }
                   1601: #endif
                   1602: 
                   1603: 
                   1604:       free_vector(xit,1,n); 
                   1605:       free_vector(xits,1,n); 
                   1606:       free_vector(ptt,1,n); 
                   1607:       free_vector(pt,1,n); 
                   1608:       return; 
                   1609:     } 
                   1610:     if (*iter == ITMAX) nrerror("powell exceeding maximum iterations."); 
1.181     brouard  1611:     for (j=1;j<=n;j++) { /* Computes the extrapolated point P_0 + 2 (P_n-P_0) */
1.126     brouard  1612:       ptt[j]=2.0*p[j]-pt[j]; 
                   1613:       xit[j]=p[j]-pt[j]; 
                   1614:       pt[j]=p[j]; 
                   1615:     } 
1.181     brouard  1616:     fptt=(*func)(ptt); /* f_3 */
1.161     brouard  1617:     if (fptt < fp) { /* If extrapolated point is better, decide if we keep that new direction or not */
1.162     brouard  1618:       /* (x1 f1=fp), (x2 f2=*fret), (x3 f3=fptt), (xm fm) */
1.161     brouard  1619:       /* From x1 (P0) distance of x2 is at h and x3 is 2h */
1.162     brouard  1620:       /* Let f"(x2) be the 2nd derivative equal everywhere.  */
                   1621:       /* Then the parabolic through (x1,f1), (x2,f2) and (x3,f3) */
                   1622:       /* will reach at f3 = fm + h^2/2 f"m  ; f" = (f1 -2f2 +f3 ) / h**2 */
1.181     brouard  1623:       /* Conditional for using this new direction is that mu^2 = (f1-2f2+f3)^2 /2 < del */
1.161     brouard  1624:       /* t=2.0*(fp-2.0*(*fret)+fptt)*SQR(fp-(*fret)-del)-del*SQR(fp-fptt); */
1.183     brouard  1625: #ifdef NRCORIGINAL
                   1626:       t=2.0*(fp-2.0*(*fret)+fptt)*SQR(fp-(*fret)-del)- del*SQR(fp-fptt); /* Original Numerical Recipes in C*/
                   1627: #else
                   1628:       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  1629:       t= t- del*SQR(fp-fptt);
1.183     brouard  1630: #endif
1.182     brouard  1631:       directest = fp-2.0*(*fret)+fptt - 2.0 * del; /* If del was big enough we change it for a new direction */
1.161     brouard  1632: #ifdef DEBUG
1.181     brouard  1633:       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);
                   1634:       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  1635:       printf("t3= %.12lf, t4= %.12lf, t3*= %.12lf, t4*= %.12lf\n",SQR(fp-(*fret)-del),SQR(fp-fptt),
                   1636:             (fp-(*fret)-del)*(fp-(*fret)-del),(fp-fptt)*(fp-fptt));
                   1637:       fprintf(ficlog,"t3= %.12lf, t4= %.12lf, t3*= %.12lf, t4*= %.12lf\n",SQR(fp-(*fret)-del),SQR(fp-fptt),
                   1638:             (fp-(*fret)-del)*(fp-(*fret)-del),(fp-fptt)*(fp-fptt));
                   1639:       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);
                   1640:       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);
                   1641: #endif
1.183     brouard  1642: #ifdef POWELLORIGINAL
                   1643:       if (t < 0.0) { /* Then we use it for new direction */
                   1644: #else
1.182     brouard  1645:       if (directest*t < 0.0) { /* Contradiction between both tests */
1.184     brouard  1646:       printf("directest= %.12lf, t= %.12lf, f1= %.12lf,f2= %.12lf,f3= %.12lf, del= %.12lf\n",directest, t, fp,(*fret),fptt,del);
1.182     brouard  1647:       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  1648:       fprintf(ficlog,"directest= %.12lf, t= %.12lf, f1= %.12lf,f2= %.12lf,f3= %.12lf, del= %.12lf\n",directest, t, fp,(*fret),fptt, del);
1.182     brouard  1649:       fprintf(ficlog,"f1-2f2+f3= %.12lf, f1-f2-del= %.12lf, f1-f3= %.12lf\n",fp-2.0*(*fret)+fptt, fp -(*fret) -del, fp-fptt);
                   1650:     } 
1.181     brouard  1651:       if (directest < 0.0) { /* Then we use it for new direction */
                   1652: #endif
                   1653:        linmin(p,xit,n,fret,func); /* computes minimum on the extrapolated direction.*/
1.126     brouard  1654:        for (j=1;j<=n;j++) { 
1.181     brouard  1655:          xi[j][ibig]=xi[j][n]; /* Replace direction with biggest decrease by last direction n */
                   1656:          xi[j][n]=xit[j];      /* and this nth direction by the by the average p_0 p_n */
1.126     brouard  1657:        }
1.181     brouard  1658:        printf("Gaining to use new average direction of P0 P%d instead of biggest increase direction %d :\n",n,ibig);
                   1659:        fprintf(ficlog,"Gaining to use new average direction of P0 P%d instead of biggest increase direction %d :\n",n,ibig);
1.161     brouard  1660: 
1.126     brouard  1661: #ifdef DEBUG
1.164     brouard  1662:        printf("Direction changed  last moved %d in place of ibig=%d, new last is the average:\n",n,ibig);
                   1663:        fprintf(ficlog,"Direction changed  last moved %d in place of ibig=%d, new last is the average:\n",n,ibig);
1.126     brouard  1664:        for(j=1;j<=n;j++){
                   1665:          printf(" %.12e",xit[j]);
                   1666:          fprintf(ficlog," %.12e",xit[j]);
                   1667:        }
                   1668:        printf("\n");
                   1669:        fprintf(ficlog,"\n");
                   1670: #endif
1.162     brouard  1671:       } /* end of t negative */
                   1672:     } /* end if (fptt < fp)  */
1.126     brouard  1673:   } 
                   1674: } 
                   1675: 
                   1676: /**** Prevalence limit (stable or period prevalence)  ****************/
                   1677: 
                   1678: double **prevalim(double **prlim, int nlstate, double x[], double age, double **oldm, double **savm, double ftolpl, int ij)
                   1679: {
                   1680:   /* Computes the prevalence limit in each live state at age x by left multiplying the unit
                   1681:      matrix by transitions matrix until convergence is reached */
1.169     brouard  1682:   
1.126     brouard  1683:   int i, ii,j,k;
                   1684:   double min, max, maxmin, maxmax,sumnew=0.;
1.145     brouard  1685:   /* double **matprod2(); */ /* test */
1.131     brouard  1686:   double **out, cov[NCOVMAX+1], **pmij();
1.126     brouard  1687:   double **newm;
                   1688:   double agefin, delaymax=50 ; /* Max number of years to converge */
1.169     brouard  1689:   
1.126     brouard  1690:   for (ii=1;ii<=nlstate+ndeath;ii++)
                   1691:     for (j=1;j<=nlstate+ndeath;j++){
                   1692:       oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   1693:     }
1.169     brouard  1694:   
                   1695:   cov[1]=1.;
                   1696:   
                   1697:   /* Even if hstepm = 1, at least one multiplication by the unit matrix */
1.126     brouard  1698:   for(agefin=age-stepm/YEARM; agefin>=age-delaymax; agefin=agefin-stepm/YEARM){
                   1699:     newm=savm;
                   1700:     /* Covariates have to be included here again */
1.138     brouard  1701:     cov[2]=agefin;
                   1702:     
                   1703:     for (k=1; k<=cptcovn;k++) {
                   1704:       cov[2+k]=nbcode[Tvar[k]][codtab[ij][Tvar[k]]];
1.145     brouard  1705:       /*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  1706:     }
1.145     brouard  1707:     /* for (k=1; k<=cptcovage;k++) cov[2+Tage[k]]=cov[2+Tage[k]]*cov[2]; */
                   1708:     /* for (k=1; k<=cptcovprod;k++) /\* Useless *\/ */
                   1709:     /*   cov[2+Tprod[k]]=nbcode[Tvard[k][1]][codtab[ij][Tvard[k][1]]] * nbcode[Tvard[k][2]][codtab[ij][Tvard[k][2]]]; */
1.138     brouard  1710:     
                   1711:     /*printf("ij=%d cptcovprod=%d tvar=%d ", ij, cptcovprod, Tvar[1]);*/
                   1712:     /*printf("ij=%d cov[3]=%lf cov[4]=%lf \n",ij, cov[3],cov[4]);*/
                   1713:     /*printf("ij=%d cov[3]=%lf \n",ij, cov[3]);*/
1.145     brouard  1714:     /* savm=pmij(pmmij,cov,ncovmodel,x,nlstate); */
                   1715:     /* out=matprod2(newm, pmij(pmmij,cov,ncovmodel,x,nlstate),1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, oldm); /\* Bug Valgrind *\/ */
1.142     brouard  1716:     out=matprod2(newm, pmij(pmmij,cov,ncovmodel,x,nlstate),1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, oldm); /* Bug Valgrind */
1.138     brouard  1717:     
1.126     brouard  1718:     savm=oldm;
                   1719:     oldm=newm;
                   1720:     maxmax=0.;
                   1721:     for(j=1;j<=nlstate;j++){
                   1722:       min=1.;
                   1723:       max=0.;
                   1724:       for(i=1; i<=nlstate; i++) {
                   1725:        sumnew=0;
                   1726:        for(k=1; k<=ndeath; k++) sumnew+=newm[i][nlstate+k];
                   1727:        prlim[i][j]= newm[i][j]/(1-sumnew);
1.145     brouard  1728:         /*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  1729:        max=FMAX(max,prlim[i][j]);
                   1730:        min=FMIN(min,prlim[i][j]);
                   1731:       }
                   1732:       maxmin=max-min;
                   1733:       maxmax=FMAX(maxmax,maxmin);
1.169     brouard  1734:     } /* j loop */
1.126     brouard  1735:     if(maxmax < ftolpl){
                   1736:       return prlim;
                   1737:     }
1.169     brouard  1738:   } /* age loop */
                   1739:   return prlim; /* should not reach here */
1.126     brouard  1740: }
                   1741: 
                   1742: /*************** transition probabilities ***************/ 
                   1743: 
                   1744: double **pmij(double **ps, double *cov, int ncovmodel, double *x, int nlstate )
                   1745: {
1.138     brouard  1746:   /* According to parameters values stored in x and the covariate's values stored in cov,
                   1747:      computes the probability to be observed in state j being in state i by appying the
                   1748:      model to the ncovmodel covariates (including constant and age).
                   1749:      lnpijopii=ln(pij/pii)= aij+bij*age+cij*v1+dij*v2+... = sum_nc=1^ncovmodel xij(nc)*cov[nc]
                   1750:      and, according on how parameters are entered, the position of the coefficient xij(nc) of the
                   1751:      ncth covariate in the global vector x is given by the formula:
                   1752:      j<i nc+((i-1)*(nlstate+ndeath-1)+j-1)*ncovmodel
                   1753:      j>=i nc + ((i-1)*(nlstate+ndeath-1)+(j-2))*ncovmodel
                   1754:      Computes ln(pij/pii) (lnpijopii), deduces pij/pii by exponentiation,
                   1755:      sums on j different of i to get 1-pii/pii, deduces pii, and then all pij.
                   1756:      Outputs ps[i][j] the probability to be observed in j being in j according to
                   1757:      the values of the covariates cov[nc] and corresponding parameter values x[nc+shiftij]
                   1758:   */
                   1759:   double s1, lnpijopii;
1.126     brouard  1760:   /*double t34;*/
1.164     brouard  1761:   int i,j, nc, ii, jj;
1.126     brouard  1762: 
                   1763:     for(i=1; i<= nlstate; i++){
                   1764:       for(j=1; j<i;j++){
1.138     brouard  1765:        for (nc=1, lnpijopii=0.;nc <=ncovmodel; nc++){
                   1766:          /*lnpijopii += param[i][j][nc]*cov[nc];*/
                   1767:          lnpijopii += x[nc+((i-1)*(nlstate+ndeath-1)+j-1)*ncovmodel]*cov[nc];
                   1768: /*      printf("Int j<i s1=%.17e, lnpijopii=%.17e\n",s1,lnpijopii); */
1.126     brouard  1769:        }
1.138     brouard  1770:        ps[i][j]=lnpijopii; /* In fact ln(pij/pii) */
                   1771: /*     printf("s1=%.17e, lnpijopii=%.17e\n",s1,lnpijopii); */
1.126     brouard  1772:       }
                   1773:       for(j=i+1; j<=nlstate+ndeath;j++){
1.138     brouard  1774:        for (nc=1, lnpijopii=0.;nc <=ncovmodel; nc++){
                   1775:          /*lnpijopii += x[(i-1)*nlstate*ncovmodel+(j-2)*ncovmodel+nc+(i-1)*(ndeath-1)*ncovmodel]*cov[nc];*/
                   1776:          lnpijopii += x[nc + ((i-1)*(nlstate+ndeath-1)+(j-2))*ncovmodel]*cov[nc];
                   1777: /*       printf("Int j>i s1=%.17e, lnpijopii=%.17e %lx %lx\n",s1,lnpijopii,s1,lnpijopii); */
1.126     brouard  1778:        }
1.138     brouard  1779:        ps[i][j]=lnpijopii; /* In fact ln(pij/pii) */
1.126     brouard  1780:       }
                   1781:     }
                   1782:     
                   1783:     for(i=1; i<= nlstate; i++){
                   1784:       s1=0;
1.131     brouard  1785:       for(j=1; j<i; j++){
1.138     brouard  1786:        s1+=exp(ps[i][j]); /* In fact sums pij/pii */
1.131     brouard  1787:        /*printf("debug1 %d %d ps=%lf exp(ps)=%lf s1+=%lf\n",i,j,ps[i][j],exp(ps[i][j]),s1); */
                   1788:       }
                   1789:       for(j=i+1; j<=nlstate+ndeath; j++){
1.138     brouard  1790:        s1+=exp(ps[i][j]); /* In fact sums pij/pii */
1.131     brouard  1791:        /*printf("debug2 %d %d ps=%lf exp(ps)=%lf s1+=%lf\n",i,j,ps[i][j],exp(ps[i][j]),s1); */
                   1792:       }
1.138     brouard  1793:       /* s1= sum_{j<>i} pij/pii=(1-pii)/pii and thus pii is known from s1 */
1.126     brouard  1794:       ps[i][i]=1./(s1+1.);
1.138     brouard  1795:       /* Computing other pijs */
1.126     brouard  1796:       for(j=1; j<i; j++)
                   1797:        ps[i][j]= exp(ps[i][j])*ps[i][i];
                   1798:       for(j=i+1; j<=nlstate+ndeath; j++)
                   1799:        ps[i][j]= exp(ps[i][j])*ps[i][i];
                   1800:       /* ps[i][nlstate+1]=1.-s1- ps[i][i];*/ /* Sum should be 1 */
                   1801:     } /* end i */
                   1802:     
                   1803:     for(ii=nlstate+1; ii<= nlstate+ndeath; ii++){
                   1804:       for(jj=1; jj<= nlstate+ndeath; jj++){
                   1805:        ps[ii][jj]=0;
                   1806:        ps[ii][ii]=1;
                   1807:       }
                   1808:     }
                   1809:     
1.145     brouard  1810:     
                   1811:     /* for(ii=1; ii<= nlstate+ndeath; ii++){ */
                   1812:     /*   for(jj=1; jj<= nlstate+ndeath; jj++){ */
                   1813:     /*         printf(" pmij  ps[%d][%d]=%lf ",ii,jj,ps[ii][jj]); */
                   1814:     /*   } */
                   1815:     /*   printf("\n "); */
                   1816:     /* } */
                   1817:     /* printf("\n ");printf("%lf ",cov[2]);*/
                   1818:     /*
1.126     brouard  1819:       for(i=1; i<= npar; i++) printf("%f ",x[i]);
                   1820:       goto end;*/
                   1821:     return ps;
                   1822: }
                   1823: 
                   1824: /**************** Product of 2 matrices ******************/
                   1825: 
1.145     brouard  1826: double **matprod2(double **out, double **in,int nrl, int nrh, int ncl, int nch, int ncolol, int ncoloh, double **b)
1.126     brouard  1827: {
                   1828:   /* Computes the matrix product of in(1,nrh-nrl+1)(1,nch-ncl+1) times
                   1829:      b(1,nch-ncl+1)(1,ncoloh-ncolol+1) into out(...) */
                   1830:   /* in, b, out are matrice of pointers which should have been initialized 
                   1831:      before: only the contents of out is modified. The function returns
                   1832:      a pointer to pointers identical to out */
1.145     brouard  1833:   int i, j, k;
1.126     brouard  1834:   for(i=nrl; i<= nrh; i++)
1.145     brouard  1835:     for(k=ncolol; k<=ncoloh; k++){
                   1836:       out[i][k]=0.;
                   1837:       for(j=ncl; j<=nch; j++)
                   1838:        out[i][k] +=in[i][j]*b[j][k];
                   1839:     }
1.126     brouard  1840:   return out;
                   1841: }
                   1842: 
                   1843: 
                   1844: /************* Higher Matrix Product ***************/
                   1845: 
                   1846: double ***hpxij(double ***po, int nhstepm, double age, int hstepm, double *x, int nlstate, int stepm, double **oldm, double **savm, int ij )
                   1847: {
                   1848:   /* Computes the transition matrix starting at age 'age' over 
                   1849:      'nhstepm*hstepm*stepm' months (i.e. until
                   1850:      age (in years)  age+nhstepm*hstepm*stepm/12) by multiplying 
                   1851:      nhstepm*hstepm matrices. 
                   1852:      Output is stored in matrix po[i][j][h] for h every 'hstepm' step 
                   1853:      (typically every 2 years instead of every month which is too big 
                   1854:      for the memory).
                   1855:      Model is determined by parameters x and covariates have to be 
                   1856:      included manually here. 
                   1857: 
                   1858:      */
                   1859: 
                   1860:   int i, j, d, h, k;
1.131     brouard  1861:   double **out, cov[NCOVMAX+1];
1.126     brouard  1862:   double **newm;
                   1863: 
                   1864:   /* Hstepm could be zero and should return the unit matrix */
                   1865:   for (i=1;i<=nlstate+ndeath;i++)
                   1866:     for (j=1;j<=nlstate+ndeath;j++){
                   1867:       oldm[i][j]=(i==j ? 1.0 : 0.0);
                   1868:       po[i][j][0]=(i==j ? 1.0 : 0.0);
                   1869:     }
                   1870:   /* Even if hstepm = 1, at least one multiplication by the unit matrix */
                   1871:   for(h=1; h <=nhstepm; h++){
                   1872:     for(d=1; d <=hstepm; d++){
                   1873:       newm=savm;
                   1874:       /* Covariates have to be included here again */
                   1875:       cov[1]=1.;
                   1876:       cov[2]=age+((h-1)*hstepm + (d-1))*stepm/YEARM;
1.131     brouard  1877:       for (k=1; k<=cptcovn;k++) 
                   1878:        cov[2+k]=nbcode[Tvar[k]][codtab[ij][Tvar[k]]];
1.126     brouard  1879:       for (k=1; k<=cptcovage;k++)
                   1880:        cov[2+Tage[k]]=cov[2+Tage[k]]*cov[2];
1.145     brouard  1881:       for (k=1; k<=cptcovprod;k++) /* Useless because included in cptcovn */
1.126     brouard  1882:        cov[2+Tprod[k]]=nbcode[Tvard[k][1]][codtab[ij][Tvard[k][1]]]*nbcode[Tvard[k][2]][codtab[ij][Tvard[k][2]]];
                   1883: 
                   1884: 
                   1885:       /*printf("hxi cptcov=%d cptcode=%d\n",cptcov,cptcode);*/
                   1886:       /*printf("h=%d d=%d age=%f cov=%f\n",h,d,age,cov[2]);*/
                   1887:       out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, 
                   1888:                   pmij(pmmij,cov,ncovmodel,x,nlstate));
                   1889:       savm=oldm;
                   1890:       oldm=newm;
                   1891:     }
                   1892:     for(i=1; i<=nlstate+ndeath; i++)
                   1893:       for(j=1;j<=nlstate+ndeath;j++) {
                   1894:        po[i][j][h]=newm[i][j];
1.128     brouard  1895:        /*if(h==nhstepm) printf("po[%d][%d][%d]=%f ",i,j,h,po[i][j][h]);*/
1.126     brouard  1896:       }
1.128     brouard  1897:     /*printf("h=%d ",h);*/
1.126     brouard  1898:   } /* end h */
1.128     brouard  1899: /*     printf("\n H=%d \n",h); */
1.126     brouard  1900:   return po;
                   1901: }
                   1902: 
1.162     brouard  1903: #ifdef NLOPT
                   1904:   double  myfunc(unsigned n, const double *p1, double *grad, void *pd){
                   1905:   double fret;
                   1906:   double *xt;
                   1907:   int j;
                   1908:   myfunc_data *d2 = (myfunc_data *) pd;
                   1909: /* xt = (p1-1); */
                   1910:   xt=vector(1,n); 
                   1911:   for (j=1;j<=n;j++)   xt[j]=p1[j-1]; /* xt[1]=p1[0] */
                   1912: 
                   1913:   fret=(d2->function)(xt); /*  p xt[1]@8 is fine */
                   1914:   /* fret=(*func)(xt); /\*  p xt[1]@8 is fine *\/ */
                   1915:   printf("Function = %.12lf ",fret);
                   1916:   for (j=1;j<=n;j++) printf(" %d %.8lf", j, xt[j]); 
                   1917:   printf("\n");
                   1918:  free_vector(xt,1,n);
                   1919:   return fret;
                   1920: }
                   1921: #endif
1.126     brouard  1922: 
                   1923: /*************** log-likelihood *************/
                   1924: double func( double *x)
                   1925: {
                   1926:   int i, ii, j, k, mi, d, kk;
1.131     brouard  1927:   double l, ll[NLSTATEMAX+1], cov[NCOVMAX+1];
1.126     brouard  1928:   double **out;
                   1929:   double sw; /* Sum of weights */
                   1930:   double lli; /* Individual log likelihood */
                   1931:   int s1, s2;
                   1932:   double bbh, survp;
                   1933:   long ipmx;
                   1934:   /*extern weight */
                   1935:   /* We are differentiating ll according to initial status */
                   1936:   /*  for (i=1;i<=npar;i++) printf("%f ", x[i]);*/
                   1937:   /*for(i=1;i<imx;i++) 
                   1938:     printf(" %d\n",s[4][i]);
                   1939:   */
1.162     brouard  1940: 
                   1941:   ++countcallfunc;
                   1942: 
1.126     brouard  1943:   cov[1]=1.;
                   1944: 
                   1945:   for(k=1; k<=nlstate; k++) ll[k]=0.;
                   1946: 
                   1947:   if(mle==1){
                   1948:     for (i=1,ipmx=0, sw=0.; i<=imx; i++){
1.138     brouard  1949:       /* Computes the values of the ncovmodel covariates of the model
                   1950:         depending if the covariates are fixed or variying (age dependent) and stores them in cov[]
                   1951:         Then computes with function pmij which return a matrix p[i][j] giving the elementary probability
                   1952:         to be observed in j being in i according to the model.
                   1953:        */
1.145     brouard  1954:       for (k=1; k<=cptcovn;k++){ /* Simple and product covariates without age* products */
                   1955:        cov[2+k]=covar[Tvar[k]][i];
                   1956:       }
1.137     brouard  1957:       /* In model V2+V1*V4+age*V3+V3*V2 Tvar[1] is V2, Tvar[2=V1*V4] 
1.138     brouard  1958:         is 6, Tvar[3=age*V3] should not be computed because of age Tvar[4=V3*V2] 
1.137     brouard  1959:         has been calculated etc */
1.126     brouard  1960:       for(mi=1; mi<= wav[i]-1; mi++){
                   1961:        for (ii=1;ii<=nlstate+ndeath;ii++)
                   1962:          for (j=1;j<=nlstate+ndeath;j++){
                   1963:            oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   1964:            savm[ii][j]=(ii==j ? 1.0 : 0.0);
                   1965:          }
                   1966:        for(d=0; d<dh[mi][i]; d++){
                   1967:          newm=savm;
                   1968:          cov[2]=agev[mw[mi][i]][i]+d*stepm/YEARM;
                   1969:          for (kk=1; kk<=cptcovage;kk++) {
1.137     brouard  1970:            cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*cov[2]; /* Tage[kk] gives the data-covariate associated with age */
1.126     brouard  1971:          }
                   1972:          out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
                   1973:                       1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
                   1974:          savm=oldm;
                   1975:          oldm=newm;
                   1976:        } /* end mult */
                   1977:       
                   1978:        /*lli=log(out[s[mw[mi][i]][i]][s[mw[mi+1][i]][i]]);*/ /* Original formula */
                   1979:        /* But now since version 0.9 we anticipate for bias at large stepm.
                   1980:         * If stepm is larger than one month (smallest stepm) and if the exact delay 
                   1981:         * (in months) between two waves is not a multiple of stepm, we rounded to 
                   1982:         * the nearest (and in case of equal distance, to the lowest) interval but now
                   1983:         * we keep into memory the bias bh[mi][i] and also the previous matrix product
                   1984:         * (i.e to dh[mi][i]-1) saved in 'savm'. Then we inter(extra)polate the
                   1985:         * probability in order to take into account the bias as a fraction of the way
                   1986:         * from savm to out if bh is negative or even beyond if bh is positive. bh varies
                   1987:         * -stepm/2 to stepm/2 .
                   1988:         * For stepm=1 the results are the same as for previous versions of Imach.
                   1989:         * For stepm > 1 the results are less biased than in previous versions. 
                   1990:         */
                   1991:        s1=s[mw[mi][i]][i];
                   1992:        s2=s[mw[mi+1][i]][i];
                   1993:        bbh=(double)bh[mi][i]/(double)stepm; 
                   1994:        /* bias bh is positive if real duration
                   1995:         * is higher than the multiple of stepm and negative otherwise.
                   1996:         */
                   1997:        /* lli= (savm[s1][s2]>1.e-8 ?(1.+bbh)*log(out[s1][s2])- bbh*log(savm[s1][s2]):log((1.+bbh)*out[s1][s2]));*/
                   1998:        if( s2 > nlstate){ 
                   1999:          /* i.e. if s2 is a death state and if the date of death is known 
                   2000:             then the contribution to the likelihood is the probability to 
                   2001:             die between last step unit time and current  step unit time, 
                   2002:             which is also equal to probability to die before dh 
                   2003:             minus probability to die before dh-stepm . 
                   2004:             In version up to 0.92 likelihood was computed
                   2005:        as if date of death was unknown. Death was treated as any other
                   2006:        health state: the date of the interview describes the actual state
                   2007:        and not the date of a change in health state. The former idea was
                   2008:        to consider that at each interview the state was recorded
                   2009:        (healthy, disable or death) and IMaCh was corrected; but when we
                   2010:        introduced the exact date of death then we should have modified
                   2011:        the contribution of an exact death to the likelihood. This new
                   2012:        contribution is smaller and very dependent of the step unit
                   2013:        stepm. It is no more the probability to die between last interview
                   2014:        and month of death but the probability to survive from last
                   2015:        interview up to one month before death multiplied by the
                   2016:        probability to die within a month. Thanks to Chris
                   2017:        Jackson for correcting this bug.  Former versions increased
                   2018:        mortality artificially. The bad side is that we add another loop
                   2019:        which slows down the processing. The difference can be up to 10%
                   2020:        lower mortality.
                   2021:          */
1.183     brouard  2022:        /* If, at the beginning of the maximization mostly, the
                   2023:           cumulative probability or probability to be dead is
                   2024:           constant (ie = 1) over time d, the difference is equal to
                   2025:           0.  out[s1][3] = savm[s1][3]: probability, being at state
                   2026:           s1 at precedent wave, to be dead a month before current
                   2027:           wave is equal to probability, being at state s1 at
                   2028:           precedent wave, to be dead at mont of the current
                   2029:           wave. Then the observed probability (that this person died)
                   2030:           is null according to current estimated parameter. In fact,
                   2031:           it should be very low but not zero otherwise the log go to
                   2032:           infinity.
                   2033:        */
                   2034: /* #ifdef INFINITYORIGINAL */
                   2035: /*         lli=log(out[s1][s2] - savm[s1][s2]); */
                   2036: /* #else */
                   2037: /*       if ((out[s1][s2] - savm[s1][s2]) < mytinydouble)  */
                   2038: /*         lli=log(mytinydouble); */
                   2039: /*       else */
                   2040: /*         lli=log(out[s1][s2] - savm[s1][s2]); */
                   2041: /* #endif */
                   2042:            lli=log(out[s1][s2] - savm[s1][s2]);
1.126     brouard  2043: 
                   2044:        } else if  (s2==-2) {
                   2045:          for (j=1,survp=0. ; j<=nlstate; j++) 
                   2046:            survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j];
                   2047:          /*survp += out[s1][j]; */
                   2048:          lli= log(survp);
                   2049:        }
                   2050:        
                   2051:        else if  (s2==-4) { 
                   2052:          for (j=3,survp=0. ; j<=nlstate; j++)  
                   2053:            survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j];
                   2054:          lli= log(survp); 
                   2055:        } 
                   2056: 
                   2057:        else if  (s2==-5) { 
                   2058:          for (j=1,survp=0. ; j<=2; j++)  
                   2059:            survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j];
                   2060:          lli= log(survp); 
                   2061:        } 
                   2062:        
                   2063:        else{
                   2064:          lli= log((1.+bbh)*out[s1][s2]- bbh*savm[s1][s2]); /* linear interpolation */
                   2065:          /*  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 */
                   2066:        } 
                   2067:        /*lli=(1.+bbh)*log(out[s1][s2])- bbh*log(savm[s1][s2]);*/
                   2068:        /*if(lli ==000.0)*/
                   2069:        /*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); */
                   2070:        ipmx +=1;
                   2071:        sw += weight[i];
                   2072:        ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
1.183     brouard  2073:        /* if (lli < log(mytinydouble)){ */
                   2074:        /*   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); */
                   2075:        /*   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]); */
                   2076:        /* } */
1.126     brouard  2077:       } /* end of wave */
                   2078:     } /* end of individual */
                   2079:   }  else if(mle==2){
                   2080:     for (i=1,ipmx=0, sw=0.; i<=imx; i++){
                   2081:       for (k=1; k<=cptcovn;k++) cov[2+k]=covar[Tvar[k]][i];
                   2082:       for(mi=1; mi<= wav[i]-1; mi++){
                   2083:        for (ii=1;ii<=nlstate+ndeath;ii++)
                   2084:          for (j=1;j<=nlstate+ndeath;j++){
                   2085:            oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   2086:            savm[ii][j]=(ii==j ? 1.0 : 0.0);
                   2087:          }
                   2088:        for(d=0; d<=dh[mi][i]; d++){
                   2089:          newm=savm;
                   2090:          cov[2]=agev[mw[mi][i]][i]+d*stepm/YEARM;
                   2091:          for (kk=1; kk<=cptcovage;kk++) {
                   2092:            cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*cov[2];
                   2093:          }
                   2094:          out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
                   2095:                       1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
                   2096:          savm=oldm;
                   2097:          oldm=newm;
                   2098:        } /* end mult */
                   2099:       
                   2100:        s1=s[mw[mi][i]][i];
                   2101:        s2=s[mw[mi+1][i]][i];
                   2102:        bbh=(double)bh[mi][i]/(double)stepm; 
                   2103:        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 */
                   2104:        ipmx +=1;
                   2105:        sw += weight[i];
                   2106:        ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
                   2107:       } /* end of wave */
                   2108:     } /* end of individual */
                   2109:   }  else if(mle==3){  /* exponential inter-extrapolation */
                   2110:     for (i=1,ipmx=0, sw=0.; i<=imx; i++){
                   2111:       for (k=1; k<=cptcovn;k++) cov[2+k]=covar[Tvar[k]][i];
                   2112:       for(mi=1; mi<= wav[i]-1; mi++){
                   2113:        for (ii=1;ii<=nlstate+ndeath;ii++)
                   2114:          for (j=1;j<=nlstate+ndeath;j++){
                   2115:            oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   2116:            savm[ii][j]=(ii==j ? 1.0 : 0.0);
                   2117:          }
                   2118:        for(d=0; d<dh[mi][i]; d++){
                   2119:          newm=savm;
                   2120:          cov[2]=agev[mw[mi][i]][i]+d*stepm/YEARM;
                   2121:          for (kk=1; kk<=cptcovage;kk++) {
                   2122:            cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*cov[2];
                   2123:          }
                   2124:          out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
                   2125:                       1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
                   2126:          savm=oldm;
                   2127:          oldm=newm;
                   2128:        } /* end mult */
                   2129:       
                   2130:        s1=s[mw[mi][i]][i];
                   2131:        s2=s[mw[mi+1][i]][i];
                   2132:        bbh=(double)bh[mi][i]/(double)stepm; 
                   2133:        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 */
                   2134:        ipmx +=1;
                   2135:        sw += weight[i];
                   2136:        ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
                   2137:       } /* end of wave */
                   2138:     } /* end of individual */
                   2139:   }else if (mle==4){  /* ml=4 no inter-extrapolation */
                   2140:     for (i=1,ipmx=0, sw=0.; i<=imx; i++){
                   2141:       for (k=1; k<=cptcovn;k++) cov[2+k]=covar[Tvar[k]][i];
                   2142:       for(mi=1; mi<= wav[i]-1; mi++){
                   2143:        for (ii=1;ii<=nlstate+ndeath;ii++)
                   2144:          for (j=1;j<=nlstate+ndeath;j++){
                   2145:            oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   2146:            savm[ii][j]=(ii==j ? 1.0 : 0.0);
                   2147:          }
                   2148:        for(d=0; d<dh[mi][i]; d++){
                   2149:          newm=savm;
                   2150:          cov[2]=agev[mw[mi][i]][i]+d*stepm/YEARM;
                   2151:          for (kk=1; kk<=cptcovage;kk++) {
                   2152:            cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*cov[2];
                   2153:          }
                   2154:        
                   2155:          out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
                   2156:                       1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
                   2157:          savm=oldm;
                   2158:          oldm=newm;
                   2159:        } /* end mult */
                   2160:       
                   2161:        s1=s[mw[mi][i]][i];
                   2162:        s2=s[mw[mi+1][i]][i];
                   2163:        if( s2 > nlstate){ 
                   2164:          lli=log(out[s1][s2] - savm[s1][s2]);
                   2165:        }else{
                   2166:          lli=log(out[s[mw[mi][i]][i]][s[mw[mi+1][i]][i]]); /* Original formula */
                   2167:        }
                   2168:        ipmx +=1;
                   2169:        sw += weight[i];
                   2170:        ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
                   2171: /*     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]); */
                   2172:       } /* end of wave */
                   2173:     } /* end of individual */
                   2174:   }else{  /* ml=5 no inter-extrapolation no jackson =0.8a */
                   2175:     for (i=1,ipmx=0, sw=0.; i<=imx; i++){
                   2176:       for (k=1; k<=cptcovn;k++) cov[2+k]=covar[Tvar[k]][i];
                   2177:       for(mi=1; mi<= wav[i]-1; mi++){
                   2178:        for (ii=1;ii<=nlstate+ndeath;ii++)
                   2179:          for (j=1;j<=nlstate+ndeath;j++){
                   2180:            oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   2181:            savm[ii][j]=(ii==j ? 1.0 : 0.0);
                   2182:          }
                   2183:        for(d=0; d<dh[mi][i]; d++){
                   2184:          newm=savm;
                   2185:          cov[2]=agev[mw[mi][i]][i]+d*stepm/YEARM;
                   2186:          for (kk=1; kk<=cptcovage;kk++) {
                   2187:            cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*cov[2];
                   2188:          }
                   2189:        
                   2190:          out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
                   2191:                       1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
                   2192:          savm=oldm;
                   2193:          oldm=newm;
                   2194:        } /* end mult */
                   2195:       
                   2196:        s1=s[mw[mi][i]][i];
                   2197:        s2=s[mw[mi+1][i]][i];
                   2198:        lli=log(out[s[mw[mi][i]][i]][s[mw[mi+1][i]][i]]); /* Original formula */
                   2199:        ipmx +=1;
                   2200:        sw += weight[i];
                   2201:        ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
                   2202:        /*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]);*/
                   2203:       } /* end of wave */
                   2204:     } /* end of individual */
                   2205:   } /* End of if */
                   2206:   for(k=1,l=0.; k<=nlstate; k++) l += ll[k];
                   2207:   /* printf("l1=%f l2=%f ",ll[1],ll[2]); */
                   2208:   l= l*ipmx/sw; /* To get the same order of magnitude as if weight=1 for every body */
                   2209:   return -l;
                   2210: }
                   2211: 
                   2212: /*************** log-likelihood *************/
                   2213: double funcone( double *x)
                   2214: {
                   2215:   /* Same as likeli but slower because of a lot of printf and if */
                   2216:   int i, ii, j, k, mi, d, kk;
1.131     brouard  2217:   double l, ll[NLSTATEMAX+1], cov[NCOVMAX+1];
1.126     brouard  2218:   double **out;
                   2219:   double lli; /* Individual log likelihood */
                   2220:   double llt;
                   2221:   int s1, s2;
                   2222:   double bbh, survp;
                   2223:   /*extern weight */
                   2224:   /* We are differentiating ll according to initial status */
                   2225:   /*  for (i=1;i<=npar;i++) printf("%f ", x[i]);*/
                   2226:   /*for(i=1;i<imx;i++) 
                   2227:     printf(" %d\n",s[4][i]);
                   2228:   */
                   2229:   cov[1]=1.;
                   2230: 
                   2231:   for(k=1; k<=nlstate; k++) ll[k]=0.;
                   2232: 
                   2233:   for (i=1,ipmx=0, sw=0.; i<=imx; i++){
                   2234:     for (k=1; k<=cptcovn;k++) cov[2+k]=covar[Tvar[k]][i];
                   2235:     for(mi=1; mi<= wav[i]-1; mi++){
                   2236:       for (ii=1;ii<=nlstate+ndeath;ii++)
                   2237:        for (j=1;j<=nlstate+ndeath;j++){
                   2238:          oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   2239:          savm[ii][j]=(ii==j ? 1.0 : 0.0);
                   2240:        }
                   2241:       for(d=0; d<dh[mi][i]; d++){
                   2242:        newm=savm;
                   2243:        cov[2]=agev[mw[mi][i]][i]+d*stepm/YEARM;
                   2244:        for (kk=1; kk<=cptcovage;kk++) {
                   2245:          cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*cov[2];
                   2246:        }
1.145     brouard  2247:        /* savm=pmij(pmmij,cov,ncovmodel,x,nlstate); */
1.126     brouard  2248:        out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
                   2249:                     1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
1.145     brouard  2250:        /* out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath, */
                   2251:        /*           1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate)); */
1.126     brouard  2252:        savm=oldm;
                   2253:        oldm=newm;
                   2254:       } /* end mult */
                   2255:       
                   2256:       s1=s[mw[mi][i]][i];
                   2257:       s2=s[mw[mi+1][i]][i];
                   2258:       bbh=(double)bh[mi][i]/(double)stepm; 
                   2259:       /* bias is positive if real duration
                   2260:        * is higher than the multiple of stepm and negative otherwise.
                   2261:        */
                   2262:       if( s2 > nlstate && (mle <5) ){  /* Jackson */
                   2263:        lli=log(out[s1][s2] - savm[s1][s2]);
                   2264:       } else if  (s2==-2) {
                   2265:        for (j=1,survp=0. ; j<=nlstate; j++) 
                   2266:          survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j];
                   2267:        lli= log(survp);
                   2268:       }else if (mle==1){
                   2269:        lli= log((1.+bbh)*out[s1][s2]- bbh*savm[s1][s2]); /* linear interpolation */
                   2270:       } else if(mle==2){
                   2271:        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 */
                   2272:       } else if(mle==3){  /* exponential inter-extrapolation */
                   2273:        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 */
                   2274:       } else if (mle==4){  /* mle=4 no inter-extrapolation */
                   2275:        lli=log(out[s1][s2]); /* Original formula */
1.136     brouard  2276:       } else{  /* mle=0 back to 1 */
                   2277:        lli= log((1.+bbh)*out[s1][s2]- bbh*savm[s1][s2]); /* linear interpolation */
                   2278:        /*lli=log(out[s1][s2]); */ /* Original formula */
1.126     brouard  2279:       } /* End of if */
                   2280:       ipmx +=1;
                   2281:       sw += weight[i];
                   2282:       ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
1.132     brouard  2283:       /*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  2284:       if(globpr){
1.141     brouard  2285:        fprintf(ficresilk,"%9ld %6d %2d %2d %1d %1d %3d %11.6f %8.4f\
1.126     brouard  2286:  %11.6f %11.6f %11.6f ", \
                   2287:                num[i],i,s1,s2,mi,mw[mi][i],dh[mi][i],exp(lli),weight[i],
                   2288:                2*weight[i]*lli,out[s1][s2],savm[s1][s2]);
                   2289:        for(k=1,llt=0.,l=0.; k<=nlstate; k++){
                   2290:          llt +=ll[k]*gipmx/gsw;
                   2291:          fprintf(ficresilk," %10.6f",-ll[k]*gipmx/gsw);
                   2292:        }
                   2293:        fprintf(ficresilk," %10.6f\n", -llt);
                   2294:       }
                   2295:     } /* end of wave */
                   2296:   } /* end of individual */
                   2297:   for(k=1,l=0.; k<=nlstate; k++) l += ll[k];
                   2298:   /* printf("l1=%f l2=%f ",ll[1],ll[2]); */
                   2299:   l= l*ipmx/sw; /* To get the same order of magnitude as if weight=1 for every body */
                   2300:   if(globpr==0){ /* First time we count the contributions and weights */
                   2301:     gipmx=ipmx;
                   2302:     gsw=sw;
                   2303:   }
                   2304:   return -l;
                   2305: }
                   2306: 
                   2307: 
                   2308: /*************** function likelione ***********/
                   2309: void likelione(FILE *ficres,double p[], int npar, int nlstate, int *globpri, long *ipmx, double *sw, double *fretone, double (*funcone)(double []))
                   2310: {
                   2311:   /* This routine should help understanding what is done with 
                   2312:      the selection of individuals/waves and
                   2313:      to check the exact contribution to the likelihood.
                   2314:      Plotting could be done.
                   2315:    */
                   2316:   int k;
                   2317: 
                   2318:   if(*globpri !=0){ /* Just counts and sums, no printings */
                   2319:     strcpy(fileresilk,"ilk"); 
                   2320:     strcat(fileresilk,fileres);
                   2321:     if((ficresilk=fopen(fileresilk,"w"))==NULL) {
                   2322:       printf("Problem with resultfile: %s\n", fileresilk);
                   2323:       fprintf(ficlog,"Problem with resultfile: %s\n", fileresilk);
                   2324:     }
                   2325:     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");
                   2326:     fprintf(ficresilk, "#num_i i s1 s2 mi mw dh likeli weight 2wlli out sav ");
                   2327:     /*         i,s1,s2,mi,mw[mi][i],dh[mi][i],exp(lli),weight[i],2*weight[i]*lli,out[s1][s2],savm[s1][s2]); */
                   2328:     for(k=1; k<=nlstate; k++) 
                   2329:       fprintf(ficresilk," -2*gipw/gsw*weight*ll[%d]++",k);
                   2330:     fprintf(ficresilk," -2*gipw/gsw*weight*ll(total)\n");
                   2331:   }
                   2332: 
                   2333:   *fretone=(*funcone)(p);
                   2334:   if(*globpri !=0){
                   2335:     fclose(ficresilk);
                   2336:     fprintf(fichtm,"\n<br>File of contributions to the likelihood: <a href=\"%s\">%s</a><br>\n",subdirf(fileresilk),subdirf(fileresilk));
                   2337:     fflush(fichtm); 
                   2338:   } 
                   2339:   return;
                   2340: }
                   2341: 
                   2342: 
                   2343: /*********** Maximum Likelihood Estimation ***************/
                   2344: 
                   2345: void mlikeli(FILE *ficres,double p[], int npar, int ncovmodel, int nlstate, double ftol, double (*func)(double []))
                   2346: {
1.165     brouard  2347:   int i,j, iter=0;
1.126     brouard  2348:   double **xi;
                   2349:   double fret;
                   2350:   double fretone; /* Only one call to likelihood */
                   2351:   /*  char filerespow[FILENAMELENGTH];*/
1.162     brouard  2352: 
                   2353: #ifdef NLOPT
                   2354:   int creturn;
                   2355:   nlopt_opt opt;
                   2356:   /* double lb[9] = { -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL }; /\* lower bounds *\/ */
                   2357:   double *lb;
                   2358:   double minf; /* the minimum objective value, upon return */
                   2359:   double * p1; /* Shifted parameters from 0 instead of 1 */
                   2360:   myfunc_data dinst, *d = &dinst;
                   2361: #endif
                   2362: 
                   2363: 
1.126     brouard  2364:   xi=matrix(1,npar,1,npar);
                   2365:   for (i=1;i<=npar;i++)
                   2366:     for (j=1;j<=npar;j++)
                   2367:       xi[i][j]=(i==j ? 1.0 : 0.0);
                   2368:   printf("Powell\n");  fprintf(ficlog,"Powell\n");
                   2369:   strcpy(filerespow,"pow"); 
                   2370:   strcat(filerespow,fileres);
                   2371:   if((ficrespow=fopen(filerespow,"w"))==NULL) {
                   2372:     printf("Problem with resultfile: %s\n", filerespow);
                   2373:     fprintf(ficlog,"Problem with resultfile: %s\n", filerespow);
                   2374:   }
                   2375:   fprintf(ficrespow,"# Powell\n# iter -2*LL");
                   2376:   for (i=1;i<=nlstate;i++)
                   2377:     for(j=1;j<=nlstate+ndeath;j++)
                   2378:       if(j!=i)fprintf(ficrespow," p%1d%1d",i,j);
                   2379:   fprintf(ficrespow,"\n");
1.162     brouard  2380: #ifdef POWELL
1.126     brouard  2381:   powell(p,xi,npar,ftol,&iter,&fret,func);
1.162     brouard  2382: #endif
1.126     brouard  2383: 
1.162     brouard  2384: #ifdef NLOPT
                   2385: #ifdef NEWUOA
                   2386:   opt = nlopt_create(NLOPT_LN_NEWUOA,npar);
                   2387: #else
                   2388:   opt = nlopt_create(NLOPT_LN_BOBYQA,npar);
                   2389: #endif
                   2390:   lb=vector(0,npar-1);
                   2391:   for (i=0;i<npar;i++) lb[i]= -HUGE_VAL;
                   2392:   nlopt_set_lower_bounds(opt, lb);
                   2393:   nlopt_set_initial_step1(opt, 0.1);
                   2394:   
                   2395:   p1= (p+1); /*  p *(p+1)@8 and p *(p1)@8 are equal p1[0]=p[1] */
                   2396:   d->function = func;
                   2397:   printf(" Func %.12lf \n",myfunc(npar,p1,NULL,d));
                   2398:   nlopt_set_min_objective(opt, myfunc, d);
                   2399:   nlopt_set_xtol_rel(opt, ftol);
                   2400:   if ((creturn=nlopt_optimize(opt, p1, &minf)) < 0) {
                   2401:     printf("nlopt failed! %d\n",creturn); 
                   2402:   }
                   2403:   else {
                   2404:     printf("found minimum after %d evaluations (NLOPT=%d)\n", countcallfunc ,NLOPT);
                   2405:     printf("found minimum at f(%g,%g) = %0.10g\n", p[0], p[1], minf);
                   2406:     iter=1; /* not equal */
                   2407:   }
                   2408:   nlopt_destroy(opt);
                   2409: #endif
1.126     brouard  2410:   free_matrix(xi,1,npar,1,npar);
                   2411:   fclose(ficrespow);
1.180     brouard  2412:   printf("#Number of iterations & function calls = %d & %d, -2 Log likelihood = %.12f\n",iter, countcallfunc,func(p));
                   2413:   fprintf(ficlog,"#Number of iterations & function calls = %d & %d, -2 Log likelihood = %.12f\n",iter, countcallfunc,func(p));
                   2414:   fprintf(ficres,"#Number of iterations & function calls = %d & %d, -2 Log likelihood = %.12f\n",iter, countcallfunc,func(p));
1.126     brouard  2415: 
                   2416: }
                   2417: 
                   2418: /**** Computes Hessian and covariance matrix ***/
                   2419: void hesscov(double **matcov, double p[], int npar, double delti[], double ftolhess, double (*func)(double []))
                   2420: {
                   2421:   double  **a,**y,*x,pd;
                   2422:   double **hess;
1.164     brouard  2423:   int i, j;
1.126     brouard  2424:   int *indx;
                   2425: 
                   2426:   double hessii(double p[], double delta, int theta, double delti[],double (*func)(double []),int npar);
                   2427:   double hessij(double p[], double delti[], int i, int j,double (*func)(double []),int npar);
                   2428:   void lubksb(double **a, int npar, int *indx, double b[]) ;
                   2429:   void ludcmp(double **a, int npar, int *indx, double *d) ;
                   2430:   double gompertz(double p[]);
                   2431:   hess=matrix(1,npar,1,npar);
                   2432: 
                   2433:   printf("\nCalculation of the hessian matrix. Wait...\n");
                   2434:   fprintf(ficlog,"\nCalculation of the hessian matrix. Wait...\n");
                   2435:   for (i=1;i<=npar;i++){
                   2436:     printf("%d",i);fflush(stdout);
                   2437:     fprintf(ficlog,"%d",i);fflush(ficlog);
                   2438:    
                   2439:      hess[i][i]=hessii(p,ftolhess,i,delti,func,npar);
                   2440:     
                   2441:     /*  printf(" %f ",p[i]);
                   2442:        printf(" %lf %lf %lf",hess[i][i],ftolhess,delti[i]);*/
                   2443:   }
                   2444:   
                   2445:   for (i=1;i<=npar;i++) {
                   2446:     for (j=1;j<=npar;j++)  {
                   2447:       if (j>i) { 
                   2448:        printf(".%d%d",i,j);fflush(stdout);
                   2449:        fprintf(ficlog,".%d%d",i,j);fflush(ficlog);
                   2450:        hess[i][j]=hessij(p,delti,i,j,func,npar);
                   2451:        
                   2452:        hess[j][i]=hess[i][j];    
                   2453:        /*printf(" %lf ",hess[i][j]);*/
                   2454:       }
                   2455:     }
                   2456:   }
                   2457:   printf("\n");
                   2458:   fprintf(ficlog,"\n");
                   2459: 
                   2460:   printf("\nInverting the hessian to get the covariance matrix. Wait...\n");
                   2461:   fprintf(ficlog,"\nInverting the hessian to get the covariance matrix. Wait...\n");
                   2462:   
                   2463:   a=matrix(1,npar,1,npar);
                   2464:   y=matrix(1,npar,1,npar);
                   2465:   x=vector(1,npar);
                   2466:   indx=ivector(1,npar);
                   2467:   for (i=1;i<=npar;i++)
                   2468:     for (j=1;j<=npar;j++) a[i][j]=hess[i][j];
                   2469:   ludcmp(a,npar,indx,&pd);
                   2470: 
                   2471:   for (j=1;j<=npar;j++) {
                   2472:     for (i=1;i<=npar;i++) x[i]=0;
                   2473:     x[j]=1;
                   2474:     lubksb(a,npar,indx,x);
                   2475:     for (i=1;i<=npar;i++){ 
                   2476:       matcov[i][j]=x[i];
                   2477:     }
                   2478:   }
                   2479: 
                   2480:   printf("\n#Hessian matrix#\n");
                   2481:   fprintf(ficlog,"\n#Hessian matrix#\n");
                   2482:   for (i=1;i<=npar;i++) { 
                   2483:     for (j=1;j<=npar;j++) { 
                   2484:       printf("%.3e ",hess[i][j]);
                   2485:       fprintf(ficlog,"%.3e ",hess[i][j]);
                   2486:     }
                   2487:     printf("\n");
                   2488:     fprintf(ficlog,"\n");
                   2489:   }
                   2490: 
                   2491:   /* Recompute Inverse */
                   2492:   for (i=1;i<=npar;i++)
                   2493:     for (j=1;j<=npar;j++) a[i][j]=matcov[i][j];
                   2494:   ludcmp(a,npar,indx,&pd);
                   2495: 
                   2496:   /*  printf("\n#Hessian matrix recomputed#\n");
                   2497: 
                   2498:   for (j=1;j<=npar;j++) {
                   2499:     for (i=1;i<=npar;i++) x[i]=0;
                   2500:     x[j]=1;
                   2501:     lubksb(a,npar,indx,x);
                   2502:     for (i=1;i<=npar;i++){ 
                   2503:       y[i][j]=x[i];
                   2504:       printf("%.3e ",y[i][j]);
                   2505:       fprintf(ficlog,"%.3e ",y[i][j]);
                   2506:     }
                   2507:     printf("\n");
                   2508:     fprintf(ficlog,"\n");
                   2509:   }
                   2510:   */
                   2511: 
                   2512:   free_matrix(a,1,npar,1,npar);
                   2513:   free_matrix(y,1,npar,1,npar);
                   2514:   free_vector(x,1,npar);
                   2515:   free_ivector(indx,1,npar);
                   2516:   free_matrix(hess,1,npar,1,npar);
                   2517: 
                   2518: 
                   2519: }
                   2520: 
                   2521: /*************** hessian matrix ****************/
                   2522: double hessii(double x[], double delta, int theta, double delti[], double (*func)(double []), int npar)
                   2523: {
                   2524:   int i;
                   2525:   int l=1, lmax=20;
                   2526:   double k1,k2;
1.132     brouard  2527:   double p2[MAXPARM+1]; /* identical to x */
1.126     brouard  2528:   double res;
                   2529:   double delt=0.0001, delts, nkhi=10.,nkhif=1., khi=1.e-4;
                   2530:   double fx;
                   2531:   int k=0,kmax=10;
                   2532:   double l1;
                   2533: 
                   2534:   fx=func(x);
                   2535:   for (i=1;i<=npar;i++) p2[i]=x[i];
1.145     brouard  2536:   for(l=0 ; l <=lmax; l++){  /* Enlarging the zone around the Maximum */
1.126     brouard  2537:     l1=pow(10,l);
                   2538:     delts=delt;
                   2539:     for(k=1 ; k <kmax; k=k+1){
                   2540:       delt = delta*(l1*k);
                   2541:       p2[theta]=x[theta] +delt;
1.145     brouard  2542:       k1=func(p2)-fx;   /* Might be negative if too close to the theoretical maximum */
1.126     brouard  2543:       p2[theta]=x[theta]-delt;
                   2544:       k2=func(p2)-fx;
                   2545:       /*res= (k1-2.0*fx+k2)/delt/delt; */
                   2546:       res= (k1+k2)/delt/delt/2.; /* Divided by because L and not 2*L */
                   2547:       
1.132     brouard  2548: #ifdef DEBUGHESS
1.126     brouard  2549:       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);
                   2550:       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);
                   2551: #endif
                   2552:       /*if(fabs(k1-2.0*fx+k2) <1.e-13){ */
                   2553:       if((k1 <khi/nkhi/2.) || (k2 <khi/nkhi/2.)){
                   2554:        k=kmax;
                   2555:       }
                   2556:       else if((k1 >khi/nkhif) || (k2 >khi/nkhif)){ /* Keeps lastvalue before 3.84/2 KHI2 5% 1d.f. */
1.164     brouard  2557:        k=kmax; l=lmax*10;
1.126     brouard  2558:       }
                   2559:       else if((k1 >khi/nkhi) || (k2 >khi/nkhi)){ 
                   2560:        delts=delt;
                   2561:       }
                   2562:     }
                   2563:   }
                   2564:   delti[theta]=delts;
                   2565:   return res; 
                   2566:   
                   2567: }
                   2568: 
                   2569: double hessij( double x[], double delti[], int thetai,int thetaj,double (*func)(double []),int npar)
                   2570: {
                   2571:   int i;
1.164     brouard  2572:   int l=1, lmax=20;
1.126     brouard  2573:   double k1,k2,k3,k4,res,fx;
1.132     brouard  2574:   double p2[MAXPARM+1];
1.126     brouard  2575:   int k;
                   2576: 
                   2577:   fx=func(x);
                   2578:   for (k=1; k<=2; k++) {
                   2579:     for (i=1;i<=npar;i++) p2[i]=x[i];
                   2580:     p2[thetai]=x[thetai]+delti[thetai]/k;
                   2581:     p2[thetaj]=x[thetaj]+delti[thetaj]/k;
                   2582:     k1=func(p2)-fx;
                   2583:   
                   2584:     p2[thetai]=x[thetai]+delti[thetai]/k;
                   2585:     p2[thetaj]=x[thetaj]-delti[thetaj]/k;
                   2586:     k2=func(p2)-fx;
                   2587:   
                   2588:     p2[thetai]=x[thetai]-delti[thetai]/k;
                   2589:     p2[thetaj]=x[thetaj]+delti[thetaj]/k;
                   2590:     k3=func(p2)-fx;
                   2591:   
                   2592:     p2[thetai]=x[thetai]-delti[thetai]/k;
                   2593:     p2[thetaj]=x[thetaj]-delti[thetaj]/k;
                   2594:     k4=func(p2)-fx;
                   2595:     res=(k1-k2-k3+k4)/4.0/delti[thetai]*k/delti[thetaj]*k/2.; /* Because of L not 2*L */
                   2596: #ifdef DEBUG
                   2597:     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);
                   2598:     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);
                   2599: #endif
                   2600:   }
                   2601:   return res;
                   2602: }
                   2603: 
                   2604: /************** Inverse of matrix **************/
                   2605: void ludcmp(double **a, int n, int *indx, double *d) 
                   2606: { 
                   2607:   int i,imax,j,k; 
                   2608:   double big,dum,sum,temp; 
                   2609:   double *vv; 
                   2610:  
                   2611:   vv=vector(1,n); 
                   2612:   *d=1.0; 
                   2613:   for (i=1;i<=n;i++) { 
                   2614:     big=0.0; 
                   2615:     for (j=1;j<=n;j++) 
                   2616:       if ((temp=fabs(a[i][j])) > big) big=temp; 
                   2617:     if (big == 0.0) nrerror("Singular matrix in routine ludcmp"); 
                   2618:     vv[i]=1.0/big; 
                   2619:   } 
                   2620:   for (j=1;j<=n;j++) { 
                   2621:     for (i=1;i<j;i++) { 
                   2622:       sum=a[i][j]; 
                   2623:       for (k=1;k<i;k++) sum -= a[i][k]*a[k][j]; 
                   2624:       a[i][j]=sum; 
                   2625:     } 
                   2626:     big=0.0; 
                   2627:     for (i=j;i<=n;i++) { 
                   2628:       sum=a[i][j]; 
                   2629:       for (k=1;k<j;k++) 
                   2630:        sum -= a[i][k]*a[k][j]; 
                   2631:       a[i][j]=sum; 
                   2632:       if ( (dum=vv[i]*fabs(sum)) >= big) { 
                   2633:        big=dum; 
                   2634:        imax=i; 
                   2635:       } 
                   2636:     } 
                   2637:     if (j != imax) { 
                   2638:       for (k=1;k<=n;k++) { 
                   2639:        dum=a[imax][k]; 
                   2640:        a[imax][k]=a[j][k]; 
                   2641:        a[j][k]=dum; 
                   2642:       } 
                   2643:       *d = -(*d); 
                   2644:       vv[imax]=vv[j]; 
                   2645:     } 
                   2646:     indx[j]=imax; 
                   2647:     if (a[j][j] == 0.0) a[j][j]=TINY; 
                   2648:     if (j != n) { 
                   2649:       dum=1.0/(a[j][j]); 
                   2650:       for (i=j+1;i<=n;i++) a[i][j] *= dum; 
                   2651:     } 
                   2652:   } 
                   2653:   free_vector(vv,1,n);  /* Doesn't work */
                   2654: ;
                   2655: } 
                   2656: 
                   2657: void lubksb(double **a, int n, int *indx, double b[]) 
                   2658: { 
                   2659:   int i,ii=0,ip,j; 
                   2660:   double sum; 
                   2661:  
                   2662:   for (i=1;i<=n;i++) { 
                   2663:     ip=indx[i]; 
                   2664:     sum=b[ip]; 
                   2665:     b[ip]=b[i]; 
                   2666:     if (ii) 
                   2667:       for (j=ii;j<=i-1;j++) sum -= a[i][j]*b[j]; 
                   2668:     else if (sum) ii=i; 
                   2669:     b[i]=sum; 
                   2670:   } 
                   2671:   for (i=n;i>=1;i--) { 
                   2672:     sum=b[i]; 
                   2673:     for (j=i+1;j<=n;j++) sum -= a[i][j]*b[j]; 
                   2674:     b[i]=sum/a[i][i]; 
                   2675:   } 
                   2676: } 
                   2677: 
                   2678: void pstamp(FILE *fichier)
                   2679: {
                   2680:   fprintf(fichier,"# %s.%s\n#%s\n#%s\n# %s", optionfilefiname,optionfilext,version,fullversion,strstart);
                   2681: }
                   2682: 
                   2683: /************ Frequencies ********************/
                   2684: 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[])
                   2685: {  /* Some frequencies */
                   2686:   
1.164     brouard  2687:   int i, m, jk, j1, bool, z1,j;
1.126     brouard  2688:   int first;
                   2689:   double ***freq; /* Frequencies */
                   2690:   double *pp, **prop;
                   2691:   double pos,posprop, k2, dateintsum=0,k2cpt=0;
                   2692:   char fileresp[FILENAMELENGTH];
                   2693:   
                   2694:   pp=vector(1,nlstate);
                   2695:   prop=matrix(1,nlstate,iagemin,iagemax+3);
                   2696:   strcpy(fileresp,"p");
                   2697:   strcat(fileresp,fileres);
                   2698:   if((ficresp=fopen(fileresp,"w"))==NULL) {
                   2699:     printf("Problem with prevalence resultfile: %s\n", fileresp);
                   2700:     fprintf(ficlog,"Problem with prevalence resultfile: %s\n", fileresp);
                   2701:     exit(0);
                   2702:   }
                   2703:   freq= ma3x(-5,nlstate+ndeath,-5,nlstate+ndeath,iagemin,iagemax+3);
                   2704:   j1=0;
                   2705:   
                   2706:   j=cptcoveff;
                   2707:   if (cptcovn<1) {j=1;ncodemax[1]=1;}
                   2708: 
                   2709:   first=1;
                   2710: 
1.169     brouard  2711:   /* for(k1=1; k1<=j ; k1++){ */  /* Loop on covariates */
                   2712:   /*  for(i1=1; i1<=ncodemax[k1];i1++){ */ /* Now it is 2 */
                   2713:   /*    j1++; */
1.145     brouard  2714:   for (j1 = 1; j1 <= (int) pow(2,cptcoveff); j1++){
1.126     brouard  2715:       /*printf("cptcoveff=%d Tvaraff=%d", cptcoveff,Tvaraff[1]);
                   2716:        scanf("%d", i);*/
                   2717:       for (i=-5; i<=nlstate+ndeath; i++)  
                   2718:        for (jk=-5; jk<=nlstate+ndeath; jk++)  
                   2719:          for(m=iagemin; m <= iagemax+3; m++)
                   2720:            freq[i][jk][m]=0;
1.143     brouard  2721:       
                   2722:       for (i=1; i<=nlstate; i++)  
                   2723:        for(m=iagemin; m <= iagemax+3; m++)
                   2724:          prop[i][m]=0;
1.126     brouard  2725:       
                   2726:       dateintsum=0;
                   2727:       k2cpt=0;
                   2728:       for (i=1; i<=imx; i++) {
                   2729:        bool=1;
1.144     brouard  2730:        if  (cptcovn>0) { /* Filter is here: Must be looked at for model=V1+V2+V3+V4 */
                   2731:          for (z1=1; z1<=cptcoveff; z1++)       
                   2732:             if (covar[Tvaraff[z1]][i]!= nbcode[Tvaraff[z1]][codtab[j1][z1]]){
1.145     brouard  2733:                 /* Tests if the value of each of the covariates of i is equal to filter j1 */
1.144     brouard  2734:               bool=0;
1.145     brouard  2735:               /* 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", 
                   2736:                 bool,i,z1, z1, Tvaraff[z1],i,covar[Tvaraff[z1]][i],j1,z1,codtab[j1][z1],
                   2737:                 j1,z1,nbcode[Tvaraff[z1]][codtab[j1][z1]],j1);*/
1.144     brouard  2738:               /* For j1=7 in V1+V2+V3+V4 = 0 1 1 0 and codtab[7][3]=1 and nbcde[3][?]=1*/
                   2739:             } 
1.126     brouard  2740:        }
1.144     brouard  2741:  
1.126     brouard  2742:        if (bool==1){
                   2743:          for(m=firstpass; m<=lastpass; m++){
                   2744:            k2=anint[m][i]+(mint[m][i]/12.);
                   2745:            /*if ((k2>=dateprev1) && (k2<=dateprev2)) {*/
                   2746:              if(agev[m][i]==0) agev[m][i]=iagemax+1;
                   2747:              if(agev[m][i]==1) agev[m][i]=iagemax+2;
                   2748:              if (s[m][i]>0 && s[m][i]<=nlstate) prop[s[m][i]][(int)agev[m][i]] += weight[i];
                   2749:              if (m<lastpass) {
                   2750:                freq[s[m][i]][s[m+1][i]][(int)agev[m][i]] += weight[i];
                   2751:                freq[s[m][i]][s[m+1][i]][iagemax+3] += weight[i];
                   2752:              }
                   2753:              
                   2754:              if ((agev[m][i]>1) && (agev[m][i]< (iagemax+3))) {
                   2755:                dateintsum=dateintsum+k2;
                   2756:                k2cpt++;
                   2757:              }
                   2758:              /*}*/
                   2759:          }
                   2760:        }
1.145     brouard  2761:       } /* end i */
1.126     brouard  2762:        
                   2763:       /*      fprintf(ficresp, "#Count between %.lf/%.lf/%.lf and %.lf/%.lf/%.lf\n",jprev1, mprev1,anprev1,jprev2, mprev2,anprev2);*/
                   2764:       pstamp(ficresp);
                   2765:       if  (cptcovn>0) {
                   2766:        fprintf(ficresp, "\n#********** Variable "); 
                   2767:        for (z1=1; z1<=cptcoveff; z1++) fprintf(ficresp, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtab[j1][z1]]);
                   2768:        fprintf(ficresp, "**********\n#");
1.143     brouard  2769:        fprintf(ficlog, "\n#********** Variable "); 
                   2770:        for (z1=1; z1<=cptcoveff; z1++) fprintf(ficlog, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtab[j1][z1]]);
                   2771:        fprintf(ficlog, "**********\n#");
1.126     brouard  2772:       }
                   2773:       for(i=1; i<=nlstate;i++) 
                   2774:        fprintf(ficresp, " Age Prev(%d) N(%d) N",i,i);
                   2775:       fprintf(ficresp, "\n");
                   2776:       
                   2777:       for(i=iagemin; i <= iagemax+3; i++){
                   2778:        if(i==iagemax+3){
                   2779:          fprintf(ficlog,"Total");
                   2780:        }else{
                   2781:          if(first==1){
                   2782:            first=0;
                   2783:            printf("See log file for details...\n");
                   2784:          }
                   2785:          fprintf(ficlog,"Age %d", i);
                   2786:        }
                   2787:        for(jk=1; jk <=nlstate ; jk++){
                   2788:          for(m=-1, pp[jk]=0; m <=nlstate+ndeath ; m++)
                   2789:            pp[jk] += freq[jk][m][i]; 
                   2790:        }
                   2791:        for(jk=1; jk <=nlstate ; jk++){
                   2792:          for(m=-1, pos=0; m <=0 ; m++)
                   2793:            pos += freq[jk][m][i];
                   2794:          if(pp[jk]>=1.e-10){
                   2795:            if(first==1){
1.132     brouard  2796:              printf(" %d.=%.0f loss[%d]=%.1f%%",jk,pp[jk],jk,100*pos/pp[jk]);
1.126     brouard  2797:            }
                   2798:            fprintf(ficlog," %d.=%.0f loss[%d]=%.1f%%",jk,pp[jk],jk,100*pos/pp[jk]);
                   2799:          }else{
                   2800:            if(first==1)
                   2801:              printf(" %d.=%.0f loss[%d]=NaNQ%%",jk,pp[jk],jk);
                   2802:            fprintf(ficlog," %d.=%.0f loss[%d]=NaNQ%%",jk,pp[jk],jk);
                   2803:          }
                   2804:        }
                   2805: 
                   2806:        for(jk=1; jk <=nlstate ; jk++){
                   2807:          for(m=0, pp[jk]=0; m <=nlstate+ndeath; m++)
                   2808:            pp[jk] += freq[jk][m][i];
                   2809:        }       
                   2810:        for(jk=1,pos=0,posprop=0; jk <=nlstate ; jk++){
                   2811:          pos += pp[jk];
                   2812:          posprop += prop[jk][i];
                   2813:        }
                   2814:        for(jk=1; jk <=nlstate ; jk++){
                   2815:          if(pos>=1.e-5){
                   2816:            if(first==1)
                   2817:              printf(" %d.=%.0f prev[%d]=%.1f%%",jk,pp[jk],jk,100*pp[jk]/pos);
                   2818:            fprintf(ficlog," %d.=%.0f prev[%d]=%.1f%%",jk,pp[jk],jk,100*pp[jk]/pos);
                   2819:          }else{
                   2820:            if(first==1)
                   2821:              printf(" %d.=%.0f prev[%d]=NaNQ%%",jk,pp[jk],jk);
                   2822:            fprintf(ficlog," %d.=%.0f prev[%d]=NaNQ%%",jk,pp[jk],jk);
                   2823:          }
                   2824:          if( i <= iagemax){
                   2825:            if(pos>=1.e-5){
                   2826:              fprintf(ficresp," %d %.5f %.0f %.0f",i,prop[jk][i]/posprop, prop[jk][i],posprop);
                   2827:              /*probs[i][jk][j1]= pp[jk]/pos;*/
                   2828:              /*printf("\ni=%d jk=%d j1=%d %.5f %.0f %.0f %f",i,jk,j1,pp[jk]/pos, pp[jk],pos,probs[i][jk][j1]);*/
                   2829:            }
                   2830:            else
                   2831:              fprintf(ficresp," %d NaNq %.0f %.0f",i,prop[jk][i],posprop);
                   2832:          }
                   2833:        }
                   2834:        
                   2835:        for(jk=-1; jk <=nlstate+ndeath; jk++)
                   2836:          for(m=-1; m <=nlstate+ndeath; m++)
                   2837:            if(freq[jk][m][i] !=0 ) {
                   2838:            if(first==1)
                   2839:              printf(" %d%d=%.0f",jk,m,freq[jk][m][i]);
                   2840:              fprintf(ficlog," %d%d=%.0f",jk,m,freq[jk][m][i]);
                   2841:            }
                   2842:        if(i <= iagemax)
                   2843:          fprintf(ficresp,"\n");
                   2844:        if(first==1)
                   2845:          printf("Others in log...\n");
                   2846:        fprintf(ficlog,"\n");
                   2847:       }
1.145     brouard  2848:       /*}*/
1.126     brouard  2849:   }
                   2850:   dateintmean=dateintsum/k2cpt; 
                   2851:  
                   2852:   fclose(ficresp);
                   2853:   free_ma3x(freq,-5,nlstate+ndeath,-5,nlstate+ndeath, iagemin, iagemax+3);
                   2854:   free_vector(pp,1,nlstate);
                   2855:   free_matrix(prop,1,nlstate,iagemin, iagemax+3);
                   2856:   /* End of Freq */
                   2857: }
                   2858: 
                   2859: /************ Prevalence ********************/
                   2860: 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)
                   2861: {  
                   2862:   /* Compute observed prevalence between dateprev1 and dateprev2 by counting the number of people
                   2863:      in each health status at the date of interview (if between dateprev1 and dateprev2).
                   2864:      We still use firstpass and lastpass as another selection.
                   2865:   */
                   2866:  
1.164     brouard  2867:   int i, m, jk, j1, bool, z1,j;
                   2868: 
                   2869:   double **prop;
                   2870:   double posprop; 
1.126     brouard  2871:   double  y2; /* in fractional years */
                   2872:   int iagemin, iagemax;
1.145     brouard  2873:   int first; /** to stop verbosity which is redirected to log file */
1.126     brouard  2874: 
                   2875:   iagemin= (int) agemin;
                   2876:   iagemax= (int) agemax;
                   2877:   /*pp=vector(1,nlstate);*/
                   2878:   prop=matrix(1,nlstate,iagemin,iagemax+3); 
                   2879:   /*  freq=ma3x(-1,nlstate+ndeath,-1,nlstate+ndeath,iagemin,iagemax+3);*/
                   2880:   j1=0;
                   2881:   
1.145     brouard  2882:   /*j=cptcoveff;*/
1.126     brouard  2883:   if (cptcovn<1) {j=1;ncodemax[1]=1;}
                   2884:   
1.145     brouard  2885:   first=1;
                   2886:   for(j1=1; j1<= (int) pow(2,cptcoveff);j1++){
                   2887:     /*for(i1=1; i1<=ncodemax[k1];i1++){
                   2888:       j1++;*/
1.126     brouard  2889:       
                   2890:       for (i=1; i<=nlstate; i++)  
                   2891:        for(m=iagemin; m <= iagemax+3; m++)
                   2892:          prop[i][m]=0.0;
                   2893:      
                   2894:       for (i=1; i<=imx; i++) { /* Each individual */
                   2895:        bool=1;
                   2896:        if  (cptcovn>0) {
                   2897:          for (z1=1; z1<=cptcoveff; z1++) 
                   2898:            if (covar[Tvaraff[z1]][i]!= nbcode[Tvaraff[z1]][codtab[j1][z1]]) 
                   2899:              bool=0;
                   2900:        } 
                   2901:        if (bool==1) { 
                   2902:          for(m=firstpass; m<=lastpass; m++){/* Other selection (we can limit to certain interviews*/
                   2903:            y2=anint[m][i]+(mint[m][i]/12.); /* Fractional date in year */
                   2904:            if ((y2>=dateprev1) && (y2<=dateprev2)) { /* Here is the main selection (fractional years) */
                   2905:              if(agev[m][i]==0) agev[m][i]=iagemax+1;
                   2906:              if(agev[m][i]==1) agev[m][i]=iagemax+2;
                   2907:              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); 
                   2908:              if (s[m][i]>0 && s[m][i]<=nlstate) { 
                   2909:                /*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]]);*/
                   2910:                prop[s[m][i]][(int)agev[m][i]] += weight[i];
                   2911:                prop[s[m][i]][iagemax+3] += weight[i]; 
                   2912:              } 
                   2913:            }
                   2914:          } /* end selection of waves */
                   2915:        }
                   2916:       }
                   2917:       for(i=iagemin; i <= iagemax+3; i++){  
                   2918:        for(jk=1,posprop=0; jk <=nlstate ; jk++) { 
                   2919:          posprop += prop[jk][i]; 
                   2920:        } 
1.145     brouard  2921:        
1.126     brouard  2922:        for(jk=1; jk <=nlstate ; jk++){     
                   2923:          if( i <=  iagemax){ 
                   2924:            if(posprop>=1.e-5){ 
                   2925:              probs[i][jk][j1]= prop[jk][i]/posprop;
1.145     brouard  2926:            } else{
                   2927:              if(first==1){
                   2928:                first=0;
                   2929:                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]);
                   2930:              }
                   2931:            }
1.126     brouard  2932:          } 
                   2933:        }/* end jk */ 
                   2934:       }/* end i */ 
1.145     brouard  2935:     /*} *//* end i1 */
                   2936:   } /* end j1 */
1.126     brouard  2937:   
                   2938:   /*  free_ma3x(freq,-1,nlstate+ndeath,-1,nlstate+ndeath, iagemin, iagemax+3);*/
                   2939:   /*free_vector(pp,1,nlstate);*/
                   2940:   free_matrix(prop,1,nlstate, iagemin,iagemax+3);
                   2941: }  /* End of prevalence */
                   2942: 
                   2943: /************* Waves Concatenation ***************/
                   2944: 
                   2945: 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)
                   2946: {
                   2947:   /* Concatenates waves: wav[i] is the number of effective (useful waves) of individual i.
                   2948:      Death is a valid wave (if date is known).
                   2949:      mw[mi][i] is the mi (mi=1 to wav[i])  effective wave of individual i
                   2950:      dh[m][i] or dh[mw[mi][i]][i] is the delay between two effective waves m=mw[mi][i]
                   2951:      and mw[mi+1][i]. dh depends on stepm.
                   2952:      */
                   2953: 
                   2954:   int i, mi, m;
                   2955:   /* int j, k=0,jk, ju, jl,jmin=1e+5, jmax=-1;
                   2956:      double sum=0., jmean=0.;*/
                   2957:   int first;
                   2958:   int j, k=0,jk, ju, jl;
                   2959:   double sum=0.;
                   2960:   first=0;
1.164     brouard  2961:   jmin=100000;
1.126     brouard  2962:   jmax=-1;
                   2963:   jmean=0.;
                   2964:   for(i=1; i<=imx; i++){
                   2965:     mi=0;
                   2966:     m=firstpass;
                   2967:     while(s[m][i] <= nlstate){
                   2968:       if(s[m][i]>=1 || s[m][i]==-2 || s[m][i]==-4 || s[m][i]==-5)
                   2969:        mw[++mi][i]=m;
                   2970:       if(m >=lastpass)
                   2971:        break;
                   2972:       else
                   2973:        m++;
                   2974:     }/* end while */
                   2975:     if (s[m][i] > nlstate){
                   2976:       mi++;    /* Death is another wave */
                   2977:       /* if(mi==0)  never been interviewed correctly before death */
                   2978:         /* Only death is a correct wave */
                   2979:       mw[mi][i]=m;
                   2980:     }
                   2981: 
                   2982:     wav[i]=mi;
                   2983:     if(mi==0){
                   2984:       nbwarn++;
                   2985:       if(first==0){
                   2986:        printf("Warning! No valid information for individual %ld line=%d (skipped) and may be others, see log file\n",num[i],i);
                   2987:        first=1;
                   2988:       }
                   2989:       if(first==1){
                   2990:        fprintf(ficlog,"Warning! No valid information for individual %ld line=%d (skipped)\n",num[i],i);
                   2991:       }
                   2992:     } /* end mi==0 */
                   2993:   } /* End individuals */
                   2994: 
                   2995:   for(i=1; i<=imx; i++){
                   2996:     for(mi=1; mi<wav[i];mi++){
                   2997:       if (stepm <=0)
                   2998:        dh[mi][i]=1;
                   2999:       else{
                   3000:        if (s[mw[mi+1][i]][i] > nlstate) { /* A death */
                   3001:          if (agedc[i] < 2*AGESUP) {
                   3002:            j= rint(agedc[i]*12-agev[mw[mi][i]][i]*12); 
                   3003:            if(j==0) j=1;  /* Survives at least one month after exam */
                   3004:            else if(j<0){
                   3005:              nberr++;
                   3006:              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]);
                   3007:              j=1; /* Temporary Dangerous patch */
                   3008:              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);
                   3009:              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]);
                   3010:              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);
                   3011:            }
                   3012:            k=k+1;
                   3013:            if (j >= jmax){
                   3014:              jmax=j;
                   3015:              ijmax=i;
                   3016:            }
                   3017:            if (j <= jmin){
                   3018:              jmin=j;
                   3019:              ijmin=i;
                   3020:            }
                   3021:            sum=sum+j;
                   3022:            /*if (j<0) printf("j=%d num=%d \n",j,i);*/
                   3023:            /*    printf("%d %d %d %d\n", s[mw[mi][i]][i] ,s[mw[mi+1][i]][i],j,i);*/
                   3024:          }
                   3025:        }
                   3026:        else{
                   3027:          j= rint( (agev[mw[mi+1][i]][i]*12 - agev[mw[mi][i]][i]*12));
                   3028: /*       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]); */
                   3029: 
                   3030:          k=k+1;
                   3031:          if (j >= jmax) {
                   3032:            jmax=j;
                   3033:            ijmax=i;
                   3034:          }
                   3035:          else if (j <= jmin){
                   3036:            jmin=j;
                   3037:            ijmin=i;
                   3038:          }
                   3039:          /*        if (j<10) printf("j=%d jmin=%d num=%d ",j,jmin,i); */
                   3040:          /*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]);*/
                   3041:          if(j<0){
                   3042:            nberr++;
                   3043:            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]);
                   3044:            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]);
                   3045:          }
                   3046:          sum=sum+j;
                   3047:        }
                   3048:        jk= j/stepm;
                   3049:        jl= j -jk*stepm;
                   3050:        ju= j -(jk+1)*stepm;
                   3051:        if(mle <=1){ /* only if we use a the linear-interpoloation pseudo-likelihood */
                   3052:          if(jl==0){
                   3053:            dh[mi][i]=jk;
                   3054:            bh[mi][i]=0;
                   3055:          }else{ /* We want a negative bias in order to only have interpolation ie
1.136     brouard  3056:                  * to avoid the price of an extra matrix product in likelihood */
1.126     brouard  3057:            dh[mi][i]=jk+1;
                   3058:            bh[mi][i]=ju;
                   3059:          }
                   3060:        }else{
                   3061:          if(jl <= -ju){
                   3062:            dh[mi][i]=jk;
                   3063:            bh[mi][i]=jl;       /* bias is positive if real duration
                   3064:                                 * is higher than the multiple of stepm and negative otherwise.
                   3065:                                 */
                   3066:          }
                   3067:          else{
                   3068:            dh[mi][i]=jk+1;
                   3069:            bh[mi][i]=ju;
                   3070:          }
                   3071:          if(dh[mi][i]==0){
                   3072:            dh[mi][i]=1; /* At least one step */
                   3073:            bh[mi][i]=ju; /* At least one step */
                   3074:            /*  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);*/
                   3075:          }
                   3076:        } /* end if mle */
                   3077:       }
                   3078:     } /* end wave */
                   3079:   }
                   3080:   jmean=sum/k;
                   3081:   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  3082:   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  3083:  }
                   3084: 
                   3085: /*********** Tricode ****************************/
1.145     brouard  3086: void tricode(int *Tvar, int **nbcode, int imx, int *Ndum)
1.126     brouard  3087: {
1.144     brouard  3088:   /**< Uses cptcovn+2*cptcovprod as the number of covariates */
                   3089:   /*     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  3090:    * Boring subroutine which should only output nbcode[Tvar[j]][k]
1.145     brouard  3091:    * Tvar[5] in V2+V1+V3*age+V2*V4 is 2 (V2)
1.169     brouard  3092:    * nbcode[Tvar[j]][1]= 
1.144     brouard  3093:   */
1.130     brouard  3094: 
1.145     brouard  3095:   int ij=1, k=0, j=0, i=0, maxncov=NCOVMAX;
1.136     brouard  3096:   int modmaxcovj=0; /* Modality max of covariates j */
1.145     brouard  3097:   int cptcode=0; /* Modality max of covariates j */
                   3098:   int modmincovj=0; /* Modality min of covariates j */
                   3099: 
                   3100: 
1.126     brouard  3101:   cptcoveff=0; 
                   3102:  
1.145     brouard  3103:   for (k=-1; k < maxncov; k++) Ndum[k]=0;
1.144     brouard  3104:   for (k=1; k <= maxncov; k++) ncodemax[k]=0; /* Horrible constant again replaced by NCOVMAX */
1.126     brouard  3105: 
1.145     brouard  3106:   /* Loop on covariates without age and products */
                   3107:   for (j=1; j<=(cptcovs); j++) { /* model V1 + V2*age+ V3 + V3*V4 : V1 + V3 = 2 only */
                   3108:     for (i=1; i<=imx; i++) { /* Lopp on individuals: reads the data file to get the maximum value of the 
1.136     brouard  3109:                               modality of this covariate Vj*/ 
1.145     brouard  3110:       ij=(int)(covar[Tvar[j]][i]); /* ij=0 or 1 or -1. Value of the covariate Tvar[j] for individual i
                   3111:                                    * If product of Vn*Vm, still boolean *:
                   3112:                                    * If it was coded 1, 2, 3, 4 should be splitted into 3 boolean variables
                   3113:                                    * 1 => 0 0 0, 2 => 0 0 1, 3 => 0 1 1, 4=1 0 0   */
                   3114:       /* Finds for covariate j, n=Tvar[j] of Vn . ij is the
1.136     brouard  3115:                                      modality of the nth covariate of individual i. */
1.145     brouard  3116:       if (ij > modmaxcovj)
                   3117:         modmaxcovj=ij; 
                   3118:       else if (ij < modmincovj) 
                   3119:        modmincovj=ij; 
                   3120:       if ((ij < -1) && (ij > NCOVMAX)){
                   3121:        printf( "Error: minimal is less than -1 or maximal is bigger than %d. Exiting. \n", NCOVMAX );
                   3122:        exit(1);
                   3123:       }else
1.136     brouard  3124:       Ndum[ij]++; /*counts and stores the occurence of this modality 0, 1, -1*/
1.145     brouard  3125:       /*  If coded 1, 2, 3 , counts the number of 1 Ndum[1], number of 2, Ndum[2], etc */
1.126     brouard  3126:       /*printf("i=%d ij=%d Ndum[ij]=%d imx=%d",i,ij,Ndum[ij],imx);*/
1.136     brouard  3127:       /* getting the maximum value of the modality of the covariate
                   3128:         (should be 0 or 1 now) Tvar[j]. If V=sex and male is coded 0 and
                   3129:         female is 1, then modmaxcovj=1.*/
1.126     brouard  3130:     }
1.145     brouard  3131:     printf(" Minimal and maximal values of %d th covariate V%d: min=%d max=%d \n", j, Tvar[j], modmincovj, modmaxcovj);
                   3132:     cptcode=modmaxcovj;
1.137     brouard  3133:     /* Ndum[0] = frequency of 0 for model-covariate j, Ndum[1] frequency of 1 etc. */
1.145     brouard  3134:    /*for (i=0; i<=cptcode; i++) {*/
                   3135:     for (i=modmincovj;  i<=modmaxcovj; i++) { /* i=-1 ? 0 and 1*//* For each value of the modality of model-cov j */
                   3136:       printf("Frequencies of covariates %d V%d %d\n", j, Tvar[j], Ndum[i]);
                   3137:       if( Ndum[i] != 0 ){ /* Counts if nobody answered, empty modality */
                   3138:        ncodemax[j]++;  /* ncodemax[j]= Number of non-null modalities of the j th covariate. */
                   3139:       }
                   3140:       /* In fact  ncodemax[j]=2 (dichotom. variables only) but it could be more for
                   3141:         historical reasons: 3 if coded 1, 2, 3 and 4 and Ndum[2]=0 */
1.131     brouard  3142:     } /* Ndum[-1] number of undefined modalities */
1.126     brouard  3143: 
1.136     brouard  3144:     /* j is a covariate, n=Tvar[j] of Vn; Fills nbcode */
1.145     brouard  3145:     /* For covariate j, modalities could be 1, 2, 3, 4. If Ndum[2]=0 ncodemax[j] is not 4 but 3 */
                   3146:     /* If Ndum[3}= 635; Ndum[4]=0; Ndum[5]=0; Ndum[6]=27; Ndum[7]=125;
                   3147:        modmincovj=3; modmaxcovj = 7;
                   3148:        There are only 3 modalities non empty (or 2 if 27 is too few) : ncodemax[j]=3;
                   3149:        which will be coded 0, 1, 2 which in binary on 3-1 digits are 0=00 1=01, 2=10; defining two dummy 
                   3150:        variables V1_1 and V1_2.
                   3151:        nbcode[Tvar[j]][ij]=k;
                   3152:        nbcode[Tvar[j]][1]=0;
                   3153:        nbcode[Tvar[j]][2]=1;
                   3154:        nbcode[Tvar[j]][3]=2;
                   3155:     */
                   3156:     ij=1; /* ij is similar to i but can jumps over null modalities */
                   3157:     for (i=modmincovj; i<=modmaxcovj; i++) { /* i= 1 to 2 for dichotomous, or from 1 to 3 */
                   3158:       for (k=0; k<= cptcode; k++) { /* k=-1 ? k=0 to 1 *//* Could be 1 to 4 */
                   3159:        /*recode from 0 */
1.131     brouard  3160:        if (Ndum[k] != 0) { /* If at least one individual responded to this modality k */
                   3161:          nbcode[Tvar[j]][ij]=k;  /* stores the modality in an array nbcode. 
                   3162:                                     k is a modality. If we have model=V1+V1*sex 
                   3163:                                     then: nbcode[1][1]=0 ; nbcode[1][2]=1; nbcode[2][1]=0 ; nbcode[2][2]=1; */
1.126     brouard  3164:          ij++;
                   3165:        }
                   3166:        if (ij > ncodemax[j]) break; 
1.137     brouard  3167:       }  /* end of loop on */
                   3168:     } /* end of loop on modality */ 
                   3169:   } /* end of loop on model-covariate j. nbcode[Tvarj][1]=0 and nbcode[Tvarj][2]=1 sets the value of covariate j*/  
                   3170:   
1.145     brouard  3171:  for (k=-1; k< maxncov; k++) Ndum[k]=0; 
1.137     brouard  3172:   
1.145     brouard  3173:   for (i=1; i<=ncovmodel-2; i++) { /* -2, cste and age */ 
                   3174:    /* Listing of all covariables in statement model to see if some covariates appear twice. For example, V1 appears twice in V1+V1*V2.*/ 
                   3175:    ij=Tvar[i]; /* Tvar might be -1 if status was unknown */ 
                   3176:    Ndum[ij]++; 
                   3177:  } 
1.126     brouard  3178: 
                   3179:  ij=1;
1.145     brouard  3180:  for (i=0; i<=  maxncov-1; i++) { /* modmaxcovj is unknown here. Only Ndum[2(V2),3(age*V3), 5(V3*V2) 6(V1*V4) */
                   3181:    /*printf("Ndum[%d]=%d\n",i, Ndum[i]);*/
1.126     brouard  3182:    if((Ndum[i]!=0) && (i<=ncovcol)){
1.145     brouard  3183:      /*printf("diff Ndum[%d]=%d\n",i, Ndum[i]);*/
                   3184:      Tvaraff[ij]=i; /*For printing (unclear) */
1.126     brouard  3185:      ij++;
1.145     brouard  3186:    }else
                   3187:        Tvaraff[ij]=0;
1.126     brouard  3188:  }
1.131     brouard  3189:  ij--;
1.144     brouard  3190:  cptcoveff=ij; /*Number of total covariates*/
1.145     brouard  3191: 
1.126     brouard  3192: }
                   3193: 
1.145     brouard  3194: 
1.126     brouard  3195: /*********** Health Expectancies ****************/
                   3196: 
1.127     brouard  3197: 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  3198: 
                   3199: {
                   3200:   /* Health expectancies, no variances */
1.164     brouard  3201:   int i, j, nhstepm, hstepm, h, nstepm;
1.126     brouard  3202:   int nhstepma, nstepma; /* Decreasing with age */
                   3203:   double age, agelim, hf;
                   3204:   double ***p3mat;
                   3205:   double eip;
                   3206: 
                   3207:   pstamp(ficreseij);
                   3208:   fprintf(ficreseij,"# (a) Life expectancies by health status at initial age and (b) health expectancies by health status at initial age\n");
                   3209:   fprintf(ficreseij,"# Age");
                   3210:   for(i=1; i<=nlstate;i++){
                   3211:     for(j=1; j<=nlstate;j++){
                   3212:       fprintf(ficreseij," e%1d%1d ",i,j);
                   3213:     }
                   3214:     fprintf(ficreseij," e%1d. ",i);
                   3215:   }
                   3216:   fprintf(ficreseij,"\n");
                   3217: 
                   3218:   
                   3219:   if(estepm < stepm){
                   3220:     printf ("Problem %d lower than %d\n",estepm, stepm);
                   3221:   }
                   3222:   else  hstepm=estepm;   
                   3223:   /* We compute the life expectancy from trapezoids spaced every estepm months
                   3224:    * This is mainly to measure the difference between two models: for example
                   3225:    * if stepm=24 months pijx are given only every 2 years and by summing them
                   3226:    * we are calculating an estimate of the Life Expectancy assuming a linear 
                   3227:    * progression in between and thus overestimating or underestimating according
                   3228:    * to the curvature of the survival function. If, for the same date, we 
                   3229:    * estimate the model with stepm=1 month, we can keep estepm to 24 months
                   3230:    * to compare the new estimate of Life expectancy with the same linear 
                   3231:    * hypothesis. A more precise result, taking into account a more precise
                   3232:    * curvature will be obtained if estepm is as small as stepm. */
                   3233: 
                   3234:   /* For example we decided to compute the life expectancy with the smallest unit */
                   3235:   /* hstepm beeing the number of stepms, if hstepm=1 the length of hstepm is stepm. 
                   3236:      nhstepm is the number of hstepm from age to agelim 
                   3237:      nstepm is the number of stepm from age to agelin. 
                   3238:      Look at hpijx to understand the reason of that which relies in memory size
                   3239:      and note for a fixed period like estepm months */
                   3240:   /* We decided (b) to get a life expectancy respecting the most precise curvature of the
                   3241:      survival function given by stepm (the optimization length). Unfortunately it
                   3242:      means that if the survival funtion is printed only each two years of age and if
                   3243:      you sum them up and add 1 year (area under the trapezoids) you won't get the same 
                   3244:      results. So we changed our mind and took the option of the best precision.
                   3245:   */
                   3246:   hstepm=hstepm/stepm; /* Typically in stepm units, if stepm=6 & estepm=24 , = 24/6 months = 4 */ 
                   3247: 
                   3248:   agelim=AGESUP;
                   3249:   /* If stepm=6 months */
                   3250:     /* Computed by stepm unit matrices, product of hstepm matrices, stored
                   3251:        in an array of nhstepm length: nhstepm=10, hstepm=4, stepm=6 months */
                   3252:     
                   3253: /* nhstepm age range expressed in number of stepm */
                   3254:   nstepm=(int) rint((agelim-bage)*YEARM/stepm); /* Biggest nstepm */
                   3255:   /* Typically if 20 years nstepm = 20*12/6=40 stepm */ 
                   3256:   /* if (stepm >= YEARM) hstepm=1;*/
                   3257:   nhstepm = nstepm/hstepm;/* Expressed in hstepm, typically nhstepm=40/4=10 */
                   3258:   p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   3259: 
                   3260:   for (age=bage; age<=fage; age ++){ 
                   3261:     nstepma=(int) rint((agelim-bage)*YEARM/stepm); /* Biggest nstepm */
                   3262:     /* Typically if 20 years nstepm = 20*12/6=40 stepm */ 
                   3263:     /* if (stepm >= YEARM) hstepm=1;*/
                   3264:     nhstepma = nstepma/hstepm;/* Expressed in hstepm, typically nhstepma=40/4=10 */
                   3265: 
                   3266:     /* If stepm=6 months */
                   3267:     /* Computed by stepm unit matrices, product of hstepma matrices, stored
                   3268:        in an array of nhstepma length: nhstepma=10, hstepm=4, stepm=6 months */
                   3269:     
                   3270:     hpxij(p3mat,nhstepma,age,hstepm,x,nlstate,stepm,oldm, savm, cij);  
                   3271:     
                   3272:     hf=hstepm*stepm/YEARM;  /* Duration of hstepm expressed in year unit. */
                   3273:     
                   3274:     printf("%d|",(int)age);fflush(stdout);
                   3275:     fprintf(ficlog,"%d|",(int)age);fflush(ficlog);
                   3276:     
                   3277:     /* Computing expectancies */
                   3278:     for(i=1; i<=nlstate;i++)
                   3279:       for(j=1; j<=nlstate;j++)
                   3280:        for (h=0, eij[i][j][(int)age]=0; h<=nhstepm-1; h++){
                   3281:          eij[i][j][(int)age] += (p3mat[i][j][h]+p3mat[i][j][h+1])/2.0*hf;
                   3282:          
                   3283:          /* 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]);*/
                   3284: 
                   3285:        }
                   3286: 
                   3287:     fprintf(ficreseij,"%3.0f",age );
                   3288:     for(i=1; i<=nlstate;i++){
                   3289:       eip=0;
                   3290:       for(j=1; j<=nlstate;j++){
                   3291:        eip +=eij[i][j][(int)age];
                   3292:        fprintf(ficreseij,"%9.4f", eij[i][j][(int)age] );
                   3293:       }
                   3294:       fprintf(ficreseij,"%9.4f", eip );
                   3295:     }
                   3296:     fprintf(ficreseij,"\n");
                   3297:     
                   3298:   }
                   3299:   free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   3300:   printf("\n");
                   3301:   fprintf(ficlog,"\n");
                   3302:   
                   3303: }
                   3304: 
1.127     brouard  3305: 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  3306: 
                   3307: {
                   3308:   /* Covariances of health expectancies eij and of total life expectancies according
                   3309:    to initial status i, ei. .
                   3310:   */
                   3311:   int i, j, nhstepm, hstepm, h, nstepm, k, cptj, cptj2, i2, j2, ij, ji;
                   3312:   int nhstepma, nstepma; /* Decreasing with age */
                   3313:   double age, agelim, hf;
                   3314:   double ***p3matp, ***p3matm, ***varhe;
                   3315:   double **dnewm,**doldm;
                   3316:   double *xp, *xm;
                   3317:   double **gp, **gm;
                   3318:   double ***gradg, ***trgradg;
                   3319:   int theta;
                   3320: 
                   3321:   double eip, vip;
                   3322: 
                   3323:   varhe=ma3x(1,nlstate*nlstate,1,nlstate*nlstate,(int) bage, (int) fage);
                   3324:   xp=vector(1,npar);
                   3325:   xm=vector(1,npar);
                   3326:   dnewm=matrix(1,nlstate*nlstate,1,npar);
                   3327:   doldm=matrix(1,nlstate*nlstate,1,nlstate*nlstate);
                   3328:   
                   3329:   pstamp(ficresstdeij);
                   3330:   fprintf(ficresstdeij,"# Health expectancies with standard errors\n");
                   3331:   fprintf(ficresstdeij,"# Age");
                   3332:   for(i=1; i<=nlstate;i++){
                   3333:     for(j=1; j<=nlstate;j++)
                   3334:       fprintf(ficresstdeij," e%1d%1d (SE)",i,j);
                   3335:     fprintf(ficresstdeij," e%1d. ",i);
                   3336:   }
                   3337:   fprintf(ficresstdeij,"\n");
                   3338: 
                   3339:   pstamp(ficrescveij);
                   3340:   fprintf(ficrescveij,"# Subdiagonal matrix of covariances of health expectancies by age: cov(eij,ekl)\n");
                   3341:   fprintf(ficrescveij,"# Age");
                   3342:   for(i=1; i<=nlstate;i++)
                   3343:     for(j=1; j<=nlstate;j++){
                   3344:       cptj= (j-1)*nlstate+i;
                   3345:       for(i2=1; i2<=nlstate;i2++)
                   3346:        for(j2=1; j2<=nlstate;j2++){
                   3347:          cptj2= (j2-1)*nlstate+i2;
                   3348:          if(cptj2 <= cptj)
                   3349:            fprintf(ficrescveij,"  %1d%1d,%1d%1d",i,j,i2,j2);
                   3350:        }
                   3351:     }
                   3352:   fprintf(ficrescveij,"\n");
                   3353:   
                   3354:   if(estepm < stepm){
                   3355:     printf ("Problem %d lower than %d\n",estepm, stepm);
                   3356:   }
                   3357:   else  hstepm=estepm;   
                   3358:   /* We compute the life expectancy from trapezoids spaced every estepm months
                   3359:    * This is mainly to measure the difference between two models: for example
                   3360:    * if stepm=24 months pijx are given only every 2 years and by summing them
                   3361:    * we are calculating an estimate of the Life Expectancy assuming a linear 
                   3362:    * progression in between and thus overestimating or underestimating according
                   3363:    * to the curvature of the survival function. If, for the same date, we 
                   3364:    * estimate the model with stepm=1 month, we can keep estepm to 24 months
                   3365:    * to compare the new estimate of Life expectancy with the same linear 
                   3366:    * hypothesis. A more precise result, taking into account a more precise
                   3367:    * curvature will be obtained if estepm is as small as stepm. */
                   3368: 
                   3369:   /* For example we decided to compute the life expectancy with the smallest unit */
                   3370:   /* hstepm beeing the number of stepms, if hstepm=1 the length of hstepm is stepm. 
                   3371:      nhstepm is the number of hstepm from age to agelim 
                   3372:      nstepm is the number of stepm from age to agelin. 
                   3373:      Look at hpijx to understand the reason of that which relies in memory size
                   3374:      and note for a fixed period like estepm months */
                   3375:   /* We decided (b) to get a life expectancy respecting the most precise curvature of the
                   3376:      survival function given by stepm (the optimization length). Unfortunately it
                   3377:      means that if the survival funtion is printed only each two years of age and if
                   3378:      you sum them up and add 1 year (area under the trapezoids) you won't get the same 
                   3379:      results. So we changed our mind and took the option of the best precision.
                   3380:   */
                   3381:   hstepm=hstepm/stepm; /* Typically in stepm units, if stepm=6 & estepm=24 , = 24/6 months = 4 */ 
                   3382: 
                   3383:   /* If stepm=6 months */
                   3384:   /* nhstepm age range expressed in number of stepm */
                   3385:   agelim=AGESUP;
                   3386:   nstepm=(int) rint((agelim-bage)*YEARM/stepm); 
                   3387:   /* Typically if 20 years nstepm = 20*12/6=40 stepm */ 
                   3388:   /* if (stepm >= YEARM) hstepm=1;*/
                   3389:   nhstepm = nstepm/hstepm;/* Expressed in hstepm, typically nhstepm=40/4=10 */
                   3390:   
                   3391:   p3matp=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   3392:   p3matm=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   3393:   gradg=ma3x(0,nhstepm,1,npar,1,nlstate*nlstate);
                   3394:   trgradg =ma3x(0,nhstepm,1,nlstate*nlstate,1,npar);
                   3395:   gp=matrix(0,nhstepm,1,nlstate*nlstate);
                   3396:   gm=matrix(0,nhstepm,1,nlstate*nlstate);
                   3397: 
                   3398:   for (age=bage; age<=fage; age ++){ 
                   3399:     nstepma=(int) rint((agelim-bage)*YEARM/stepm); /* Biggest nstepm */
                   3400:     /* Typically if 20 years nstepm = 20*12/6=40 stepm */ 
                   3401:     /* if (stepm >= YEARM) hstepm=1;*/
                   3402:     nhstepma = nstepma/hstepm;/* Expressed in hstepm, typically nhstepma=40/4=10 */
                   3403: 
                   3404:     /* If stepm=6 months */
                   3405:     /* Computed by stepm unit matrices, product of hstepma matrices, stored
                   3406:        in an array of nhstepma length: nhstepma=10, hstepm=4, stepm=6 months */
                   3407:     
                   3408:     hf=hstepm*stepm/YEARM;  /* Duration of hstepm expressed in year unit. */
                   3409: 
                   3410:     /* Computing  Variances of health expectancies */
                   3411:     /* Gradient is computed with plus gp and minus gm. Code is duplicated in order to
                   3412:        decrease memory allocation */
                   3413:     for(theta=1; theta <=npar; theta++){
                   3414:       for(i=1; i<=npar; i++){ 
                   3415:        xp[i] = x[i] + (i==theta ?delti[theta]:0);
                   3416:        xm[i] = x[i] - (i==theta ?delti[theta]:0);
                   3417:       }
                   3418:       hpxij(p3matp,nhstepm,age,hstepm,xp,nlstate,stepm,oldm,savm, cij);  
                   3419:       hpxij(p3matm,nhstepm,age,hstepm,xm,nlstate,stepm,oldm,savm, cij);  
                   3420:   
                   3421:       for(j=1; j<= nlstate; j++){
                   3422:        for(i=1; i<=nlstate; i++){
                   3423:          for(h=0; h<=nhstepm-1; h++){
                   3424:            gp[h][(j-1)*nlstate + i] = (p3matp[i][j][h]+p3matp[i][j][h+1])/2.;
                   3425:            gm[h][(j-1)*nlstate + i] = (p3matm[i][j][h]+p3matm[i][j][h+1])/2.;
                   3426:          }
                   3427:        }
                   3428:       }
                   3429:      
                   3430:       for(ij=1; ij<= nlstate*nlstate; ij++)
                   3431:        for(h=0; h<=nhstepm-1; h++){
                   3432:          gradg[h][theta][ij]= (gp[h][ij]-gm[h][ij])/2./delti[theta];
                   3433:        }
                   3434:     }/* End theta */
                   3435:     
                   3436:     
                   3437:     for(h=0; h<=nhstepm-1; h++)
                   3438:       for(j=1; j<=nlstate*nlstate;j++)
                   3439:        for(theta=1; theta <=npar; theta++)
                   3440:          trgradg[h][j][theta]=gradg[h][theta][j];
                   3441:     
                   3442: 
                   3443:      for(ij=1;ij<=nlstate*nlstate;ij++)
                   3444:       for(ji=1;ji<=nlstate*nlstate;ji++)
                   3445:        varhe[ij][ji][(int)age] =0.;
                   3446: 
                   3447:      printf("%d|",(int)age);fflush(stdout);
                   3448:      fprintf(ficlog,"%d|",(int)age);fflush(ficlog);
                   3449:      for(h=0;h<=nhstepm-1;h++){
                   3450:       for(k=0;k<=nhstepm-1;k++){
                   3451:        matprod2(dnewm,trgradg[h],1,nlstate*nlstate,1,npar,1,npar,matcov);
                   3452:        matprod2(doldm,dnewm,1,nlstate*nlstate,1,npar,1,nlstate*nlstate,gradg[k]);
                   3453:        for(ij=1;ij<=nlstate*nlstate;ij++)
                   3454:          for(ji=1;ji<=nlstate*nlstate;ji++)
                   3455:            varhe[ij][ji][(int)age] += doldm[ij][ji]*hf*hf;
                   3456:       }
                   3457:     }
                   3458: 
                   3459:     /* Computing expectancies */
                   3460:     hpxij(p3matm,nhstepm,age,hstepm,x,nlstate,stepm,oldm, savm, cij);  
                   3461:     for(i=1; i<=nlstate;i++)
                   3462:       for(j=1; j<=nlstate;j++)
                   3463:        for (h=0, eij[i][j][(int)age]=0; h<=nhstepm-1; h++){
                   3464:          eij[i][j][(int)age] += (p3matm[i][j][h]+p3matm[i][j][h+1])/2.0*hf;
                   3465:          
                   3466:          /* 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]);*/
                   3467: 
                   3468:        }
                   3469: 
                   3470:     fprintf(ficresstdeij,"%3.0f",age );
                   3471:     for(i=1; i<=nlstate;i++){
                   3472:       eip=0.;
                   3473:       vip=0.;
                   3474:       for(j=1; j<=nlstate;j++){
                   3475:        eip += eij[i][j][(int)age];
                   3476:        for(k=1; k<=nlstate;k++) /* Sum on j and k of cov(eij,eik) */
                   3477:          vip += varhe[(j-1)*nlstate+i][(k-1)*nlstate+i][(int)age];
                   3478:        fprintf(ficresstdeij," %9.4f (%.4f)", eij[i][j][(int)age], sqrt(varhe[(j-1)*nlstate+i][(j-1)*nlstate+i][(int)age]) );
                   3479:       }
                   3480:       fprintf(ficresstdeij," %9.4f (%.4f)", eip, sqrt(vip));
                   3481:     }
                   3482:     fprintf(ficresstdeij,"\n");
                   3483: 
                   3484:     fprintf(ficrescveij,"%3.0f",age );
                   3485:     for(i=1; i<=nlstate;i++)
                   3486:       for(j=1; j<=nlstate;j++){
                   3487:        cptj= (j-1)*nlstate+i;
                   3488:        for(i2=1; i2<=nlstate;i2++)
                   3489:          for(j2=1; j2<=nlstate;j2++){
                   3490:            cptj2= (j2-1)*nlstate+i2;
                   3491:            if(cptj2 <= cptj)
                   3492:              fprintf(ficrescveij," %.4f", varhe[cptj][cptj2][(int)age]);
                   3493:          }
                   3494:       }
                   3495:     fprintf(ficrescveij,"\n");
                   3496:    
                   3497:   }
                   3498:   free_matrix(gm,0,nhstepm,1,nlstate*nlstate);
                   3499:   free_matrix(gp,0,nhstepm,1,nlstate*nlstate);
                   3500:   free_ma3x(gradg,0,nhstepm,1,npar,1,nlstate*nlstate);
                   3501:   free_ma3x(trgradg,0,nhstepm,1,nlstate*nlstate,1,npar);
                   3502:   free_ma3x(p3matm,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   3503:   free_ma3x(p3matp,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   3504:   printf("\n");
                   3505:   fprintf(ficlog,"\n");
                   3506: 
                   3507:   free_vector(xm,1,npar);
                   3508:   free_vector(xp,1,npar);
                   3509:   free_matrix(dnewm,1,nlstate*nlstate,1,npar);
                   3510:   free_matrix(doldm,1,nlstate*nlstate,1,nlstate*nlstate);
                   3511:   free_ma3x(varhe,1,nlstate*nlstate,1,nlstate*nlstate,(int) bage, (int)fage);
                   3512: }
                   3513: 
                   3514: /************ Variance ******************/
                   3515: 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[])
                   3516: {
                   3517:   /* Variance of health expectancies */
                   3518:   /*  double **prevalim(double **prlim, int nlstate, double *xp, double age, double **oldm, double ** savm,double ftolpl);*/
                   3519:   /* double **newm;*/
1.169     brouard  3520:   /* int movingaverage(double ***probs, double bage,double fage, double ***mobaverage, int mobilav)*/
                   3521:   
                   3522:   int movingaverage();
1.126     brouard  3523:   double **dnewm,**doldm;
                   3524:   double **dnewmp,**doldmp;
                   3525:   int i, j, nhstepm, hstepm, h, nstepm ;
1.164     brouard  3526:   int k;
1.126     brouard  3527:   double *xp;
                   3528:   double **gp, **gm;  /* for var eij */
                   3529:   double ***gradg, ***trgradg; /*for var eij */
                   3530:   double **gradgp, **trgradgp; /* for var p point j */
                   3531:   double *gpp, *gmp; /* for var p point j */
                   3532:   double **varppt; /* for var p point j nlstate to nlstate+ndeath */
                   3533:   double ***p3mat;
                   3534:   double age,agelim, hf;
                   3535:   double ***mobaverage;
                   3536:   int theta;
                   3537:   char digit[4];
                   3538:   char digitp[25];
                   3539: 
                   3540:   char fileresprobmorprev[FILENAMELENGTH];
                   3541: 
                   3542:   if(popbased==1){
                   3543:     if(mobilav!=0)
                   3544:       strcpy(digitp,"-populbased-mobilav-");
                   3545:     else strcpy(digitp,"-populbased-nomobil-");
                   3546:   }
                   3547:   else 
                   3548:     strcpy(digitp,"-stablbased-");
                   3549: 
                   3550:   if (mobilav!=0) {
                   3551:     mobaverage= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
                   3552:     if (movingaverage(probs, bage, fage, mobaverage,mobilav)!=0){
                   3553:       fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav);
                   3554:       printf(" Error in movingaverage mobilav=%d\n",mobilav);
                   3555:     }
                   3556:   }
                   3557: 
                   3558:   strcpy(fileresprobmorprev,"prmorprev"); 
                   3559:   sprintf(digit,"%-d",ij);
                   3560:   /*printf("DIGIT=%s, ij=%d ijr=%-d|\n",digit, ij,ij);*/
                   3561:   strcat(fileresprobmorprev,digit); /* Tvar to be done */
                   3562:   strcat(fileresprobmorprev,digitp); /* Popbased or not, mobilav or not */
                   3563:   strcat(fileresprobmorprev,fileres);
                   3564:   if((ficresprobmorprev=fopen(fileresprobmorprev,"w"))==NULL) {
                   3565:     printf("Problem with resultfile: %s\n", fileresprobmorprev);
                   3566:     fprintf(ficlog,"Problem with resultfile: %s\n", fileresprobmorprev);
                   3567:   }
                   3568:   printf("Computing total mortality p.j=w1*p1j+w2*p2j+..: result on file '%s' \n",fileresprobmorprev);
                   3569:  
                   3570:   fprintf(ficlog,"Computing total mortality p.j=w1*p1j+w2*p2j+..: result on file '%s' \n",fileresprobmorprev);
                   3571:   pstamp(ficresprobmorprev);
                   3572:   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);
                   3573:   fprintf(ficresprobmorprev,"# Age cov=%-d",ij);
                   3574:   for(j=nlstate+1; j<=(nlstate+ndeath);j++){
                   3575:     fprintf(ficresprobmorprev," p.%-d SE",j);
                   3576:     for(i=1; i<=nlstate;i++)
                   3577:       fprintf(ficresprobmorprev," w%1d p%-d%-d",i,i,j);
                   3578:   }  
                   3579:   fprintf(ficresprobmorprev,"\n");
                   3580:   fprintf(ficgp,"\n# Routine varevsij");
                   3581:   /* fprintf(fichtm, "#Local time at start: %s", strstart);*/
                   3582:   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");
                   3583:   fprintf(fichtm,"\n<br>%s  <br>\n",digitp);
                   3584: /*   } */
                   3585:   varppt = matrix(nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);
                   3586:   pstamp(ficresvij);
                   3587:   fprintf(ficresvij,"# Variance and covariance of health expectancies e.j \n#  (weighted average of eij where weights are ");
                   3588:   if(popbased==1)
1.128     brouard  3589:     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  3590:   else
                   3591:     fprintf(ficresvij,"the age specific period (stable) prevalences in each health state \n");
                   3592:   fprintf(ficresvij,"# Age");
                   3593:   for(i=1; i<=nlstate;i++)
                   3594:     for(j=1; j<=nlstate;j++)
                   3595:       fprintf(ficresvij," Cov(e.%1d, e.%1d)",i,j);
                   3596:   fprintf(ficresvij,"\n");
                   3597: 
                   3598:   xp=vector(1,npar);
                   3599:   dnewm=matrix(1,nlstate,1,npar);
                   3600:   doldm=matrix(1,nlstate,1,nlstate);
                   3601:   dnewmp= matrix(nlstate+1,nlstate+ndeath,1,npar);
                   3602:   doldmp= matrix(nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);
                   3603: 
                   3604:   gradgp=matrix(1,npar,nlstate+1,nlstate+ndeath);
                   3605:   gpp=vector(nlstate+1,nlstate+ndeath);
                   3606:   gmp=vector(nlstate+1,nlstate+ndeath);
                   3607:   trgradgp =matrix(nlstate+1,nlstate+ndeath,1,npar); /* mu or p point j*/
                   3608:   
                   3609:   if(estepm < stepm){
                   3610:     printf ("Problem %d lower than %d\n",estepm, stepm);
                   3611:   }
                   3612:   else  hstepm=estepm;   
                   3613:   /* For example we decided to compute the life expectancy with the smallest unit */
                   3614:   /* hstepm beeing the number of stepms, if hstepm=1 the length of hstepm is stepm. 
                   3615:      nhstepm is the number of hstepm from age to agelim 
                   3616:      nstepm is the number of stepm from age to agelin. 
1.128     brouard  3617:      Look at function hpijx to understand why (it is linked to memory size questions) */
1.126     brouard  3618:   /* We decided (b) to get a life expectancy respecting the most precise curvature of the
                   3619:      survival function given by stepm (the optimization length). Unfortunately it
                   3620:      means that if the survival funtion is printed every two years of age and if
                   3621:      you sum them up and add 1 year (area under the trapezoids) you won't get the same 
                   3622:      results. So we changed our mind and took the option of the best precision.
                   3623:   */
                   3624:   hstepm=hstepm/stepm; /* Typically in stepm units, if stepm=6 & estepm=24 , = 24/6 months = 4 */ 
                   3625:   agelim = AGESUP;
                   3626:   for (age=bage; age<=fage; age ++){ /* If stepm=6 months */
                   3627:     nstepm=(int) rint((agelim-age)*YEARM/stepm); /* Typically 20 years = 20*12/6=40 */ 
                   3628:     nhstepm = nstepm/hstepm;/* Expressed in hstepm, typically nhstepm=40/4=10 */
                   3629:     p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   3630:     gradg=ma3x(0,nhstepm,1,npar,1,nlstate);
                   3631:     gp=matrix(0,nhstepm,1,nlstate);
                   3632:     gm=matrix(0,nhstepm,1,nlstate);
                   3633: 
                   3634: 
                   3635:     for(theta=1; theta <=npar; theta++){
                   3636:       for(i=1; i<=npar; i++){ /* Computes gradient x + delta*/
                   3637:        xp[i] = x[i] + (i==theta ?delti[theta]:0);
                   3638:       }
                   3639:       hpxij(p3mat,nhstepm,age,hstepm,xp,nlstate,stepm,oldm,savm, ij);  
                   3640:       prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ij);
                   3641: 
                   3642:       if (popbased==1) {
                   3643:        if(mobilav ==0){
                   3644:          for(i=1; i<=nlstate;i++)
                   3645:            prlim[i][i]=probs[(int)age][i][ij];
                   3646:        }else{ /* mobilav */ 
                   3647:          for(i=1; i<=nlstate;i++)
                   3648:            prlim[i][i]=mobaverage[(int)age][i][ij];
                   3649:        }
                   3650:       }
                   3651:   
                   3652:       for(j=1; j<= nlstate; j++){
                   3653:        for(h=0; h<=nhstepm; h++){
                   3654:          for(i=1, gp[h][j]=0.;i<=nlstate;i++)
                   3655:            gp[h][j] += prlim[i][i]*p3mat[i][j][h];
                   3656:        }
                   3657:       }
                   3658:       /* This for computing probability of death (h=1 means
                   3659:          computed over hstepm matrices product = hstepm*stepm months) 
                   3660:          as a weighted average of prlim.
                   3661:       */
                   3662:       for(j=nlstate+1;j<=nlstate+ndeath;j++){
                   3663:        for(i=1,gpp[j]=0.; i<= nlstate; i++)
                   3664:          gpp[j] += prlim[i][i]*p3mat[i][j][1];
                   3665:       }    
                   3666:       /* end probability of death */
                   3667: 
                   3668:       for(i=1; i<=npar; i++) /* Computes gradient x - delta */
                   3669:        xp[i] = x[i] - (i==theta ?delti[theta]:0);
                   3670:       hpxij(p3mat,nhstepm,age,hstepm,xp,nlstate,stepm,oldm,savm, ij);  
                   3671:       prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ij);
                   3672:  
                   3673:       if (popbased==1) {
                   3674:        if(mobilav ==0){
                   3675:          for(i=1; i<=nlstate;i++)
                   3676:            prlim[i][i]=probs[(int)age][i][ij];
                   3677:        }else{ /* mobilav */ 
                   3678:          for(i=1; i<=nlstate;i++)
                   3679:            prlim[i][i]=mobaverage[(int)age][i][ij];
                   3680:        }
                   3681:       }
                   3682: 
1.128     brouard  3683:       for(j=1; j<= nlstate; j++){  /* Sum of wi * eij = e.j */
1.126     brouard  3684:        for(h=0; h<=nhstepm; h++){
                   3685:          for(i=1, gm[h][j]=0.;i<=nlstate;i++)
                   3686:            gm[h][j] += prlim[i][i]*p3mat[i][j][h];
                   3687:        }
                   3688:       }
                   3689:       /* This for computing probability of death (h=1 means
                   3690:          computed over hstepm matrices product = hstepm*stepm months) 
                   3691:          as a weighted average of prlim.
                   3692:       */
                   3693:       for(j=nlstate+1;j<=nlstate+ndeath;j++){
                   3694:        for(i=1,gmp[j]=0.; i<= nlstate; i++)
                   3695:          gmp[j] += prlim[i][i]*p3mat[i][j][1];
                   3696:       }    
                   3697:       /* end probability of death */
                   3698: 
                   3699:       for(j=1; j<= nlstate; j++) /* vareij */
                   3700:        for(h=0; h<=nhstepm; h++){
                   3701:          gradg[h][theta][j]= (gp[h][j]-gm[h][j])/2./delti[theta];
                   3702:        }
                   3703: 
                   3704:       for(j=nlstate+1; j<= nlstate+ndeath; j++){ /* var mu */
                   3705:        gradgp[theta][j]= (gpp[j]-gmp[j])/2./delti[theta];
                   3706:       }
                   3707: 
                   3708:     } /* End theta */
                   3709: 
                   3710:     trgradg =ma3x(0,nhstepm,1,nlstate,1,npar); /* veij */
                   3711: 
                   3712:     for(h=0; h<=nhstepm; h++) /* veij */
                   3713:       for(j=1; j<=nlstate;j++)
                   3714:        for(theta=1; theta <=npar; theta++)
                   3715:          trgradg[h][j][theta]=gradg[h][theta][j];
                   3716: 
                   3717:     for(j=nlstate+1; j<=nlstate+ndeath;j++) /* mu */
                   3718:       for(theta=1; theta <=npar; theta++)
                   3719:        trgradgp[j][theta]=gradgp[theta][j];
                   3720:   
                   3721: 
                   3722:     hf=hstepm*stepm/YEARM;  /* Duration of hstepm expressed in year unit. */
                   3723:     for(i=1;i<=nlstate;i++)
                   3724:       for(j=1;j<=nlstate;j++)
                   3725:        vareij[i][j][(int)age] =0.;
                   3726: 
                   3727:     for(h=0;h<=nhstepm;h++){
                   3728:       for(k=0;k<=nhstepm;k++){
                   3729:        matprod2(dnewm,trgradg[h],1,nlstate,1,npar,1,npar,matcov);
                   3730:        matprod2(doldm,dnewm,1,nlstate,1,npar,1,nlstate,gradg[k]);
                   3731:        for(i=1;i<=nlstate;i++)
                   3732:          for(j=1;j<=nlstate;j++)
                   3733:            vareij[i][j][(int)age] += doldm[i][j]*hf*hf;
                   3734:       }
                   3735:     }
                   3736:   
                   3737:     /* pptj */
                   3738:     matprod2(dnewmp,trgradgp,nlstate+1,nlstate+ndeath,1,npar,1,npar,matcov);
                   3739:     matprod2(doldmp,dnewmp,nlstate+1,nlstate+ndeath,1,npar,nlstate+1,nlstate+ndeath,gradgp);
                   3740:     for(j=nlstate+1;j<=nlstate+ndeath;j++)
                   3741:       for(i=nlstate+1;i<=nlstate+ndeath;i++)
                   3742:        varppt[j][i]=doldmp[j][i];
                   3743:     /* end ppptj */
                   3744:     /*  x centered again */
                   3745:     hpxij(p3mat,nhstepm,age,hstepm,x,nlstate,stepm,oldm,savm, ij);  
                   3746:     prevalim(prlim,nlstate,x,age,oldm,savm,ftolpl,ij);
                   3747:  
                   3748:     if (popbased==1) {
                   3749:       if(mobilav ==0){
                   3750:        for(i=1; i<=nlstate;i++)
                   3751:          prlim[i][i]=probs[(int)age][i][ij];
                   3752:       }else{ /* mobilav */ 
                   3753:        for(i=1; i<=nlstate;i++)
                   3754:          prlim[i][i]=mobaverage[(int)age][i][ij];
                   3755:       }
                   3756:     }
                   3757:              
                   3758:     /* This for computing probability of death (h=1 means
                   3759:        computed over hstepm (estepm) matrices product = hstepm*stepm months) 
                   3760:        as a weighted average of prlim.
                   3761:     */
                   3762:     for(j=nlstate+1;j<=nlstate+ndeath;j++){
                   3763:       for(i=1,gmp[j]=0.;i<= nlstate; i++) 
                   3764:        gmp[j] += prlim[i][i]*p3mat[i][j][1]; 
                   3765:     }    
                   3766:     /* end probability of death */
                   3767: 
                   3768:     fprintf(ficresprobmorprev,"%3d %d ",(int) age, ij);
                   3769:     for(j=nlstate+1; j<=(nlstate+ndeath);j++){
                   3770:       fprintf(ficresprobmorprev," %11.3e %11.3e",gmp[j], sqrt(varppt[j][j]));
                   3771:       for(i=1; i<=nlstate;i++){
                   3772:        fprintf(ficresprobmorprev," %11.3e %11.3e ",prlim[i][i],p3mat[i][j][1]);
                   3773:       }
                   3774:     } 
                   3775:     fprintf(ficresprobmorprev,"\n");
                   3776: 
                   3777:     fprintf(ficresvij,"%.0f ",age );
                   3778:     for(i=1; i<=nlstate;i++)
                   3779:       for(j=1; j<=nlstate;j++){
                   3780:        fprintf(ficresvij," %.4f", vareij[i][j][(int)age]);
                   3781:       }
                   3782:     fprintf(ficresvij,"\n");
                   3783:     free_matrix(gp,0,nhstepm,1,nlstate);
                   3784:     free_matrix(gm,0,nhstepm,1,nlstate);
                   3785:     free_ma3x(gradg,0,nhstepm,1,npar,1,nlstate);
                   3786:     free_ma3x(trgradg,0,nhstepm,1,nlstate,1,npar);
                   3787:     free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   3788:   } /* End age */
                   3789:   free_vector(gpp,nlstate+1,nlstate+ndeath);
                   3790:   free_vector(gmp,nlstate+1,nlstate+ndeath);
                   3791:   free_matrix(gradgp,1,npar,nlstate+1,nlstate+ndeath);
                   3792:   free_matrix(trgradgp,nlstate+1,nlstate+ndeath,1,npar); /* mu or p point j*/
1.145     brouard  3793:   fprintf(ficgp,"\nunset parametric;unset label; set ter png small size 320, 240");
1.126     brouard  3794:   /* for(j=nlstate+1; j<= nlstate+ndeath; j++){ *//* Only the first actually */
1.131     brouard  3795:   fprintf(ficgp,"\n set log y; unset log x;set xlabel \"Age\"; set ylabel \"Force of mortality (year-1)\";");
1.126     brouard  3796: /*   fprintf(ficgp,"\n plot \"%s\"  u 1:($3*%6.3f) not w l 1 ",fileresprobmorprev,YEARM/estepm); */
                   3797: /*   fprintf(ficgp,"\n replot \"%s\"  u 1:(($3+1.96*$4)*%6.3f) t \"95\%% interval\" w l 2 ",fileresprobmorprev,YEARM/estepm); */
                   3798: /*   fprintf(ficgp,"\n replot \"%s\"  u 1:(($3-1.96*$4)*%6.3f) not w l 2 ",fileresprobmorprev,YEARM/estepm); */
1.145     brouard  3799:   fprintf(ficgp,"\n plot \"%s\"  u 1:($3) not w l lt 1 ",subdirf(fileresprobmorprev));
1.170     brouard  3800:   fprintf(ficgp,"\n replot \"%s\"  u 1:(($3+1.96*$4)) t \"95%% interval\" w l lt 2 ",subdirf(fileresprobmorprev));
1.145     brouard  3801:   fprintf(ficgp,"\n replot \"%s\"  u 1:(($3-1.96*$4)) not w l lt 2 ",subdirf(fileresprobmorprev));
1.126     brouard  3802:   fprintf(fichtm,"\n<br> File (multiple files are possible if covariates are present): <A href=\"%s\">%s</a>\n",subdirf(fileresprobmorprev),subdirf(fileresprobmorprev));
                   3803:   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);
                   3804:   /*  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);
                   3805: */
                   3806: /*   fprintf(ficgp,"\nset out \"varmuptjgr%s%s%s.png\";replot;",digitp,optionfilefiname,digit); */
                   3807:   fprintf(ficgp,"\nset out \"%s%s.png\";replot;\n",subdirf3(optionfilefiname,"varmuptjgr",digitp),digit);
                   3808: 
                   3809:   free_vector(xp,1,npar);
                   3810:   free_matrix(doldm,1,nlstate,1,nlstate);
                   3811:   free_matrix(dnewm,1,nlstate,1,npar);
                   3812:   free_matrix(doldmp,nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);
                   3813:   free_matrix(dnewmp,nlstate+1,nlstate+ndeath,1,npar);
                   3814:   free_matrix(varppt,nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);
                   3815:   if (mobilav!=0) free_ma3x(mobaverage,1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
                   3816:   fclose(ficresprobmorprev);
                   3817:   fflush(ficgp);
                   3818:   fflush(fichtm); 
                   3819: }  /* end varevsij */
                   3820: 
                   3821: /************ Variance of prevlim ******************/
                   3822: 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[])
                   3823: {
                   3824:   /* Variance of prevalence limit */
                   3825:   /*  double **prevalim(double **prlim, int nlstate, double *xp, double age, double **oldm, double **savm,double ftolpl);*/
1.164     brouard  3826: 
1.126     brouard  3827:   double **dnewm,**doldm;
                   3828:   int i, j, nhstepm, hstepm;
                   3829:   double *xp;
                   3830:   double *gp, *gm;
                   3831:   double **gradg, **trgradg;
                   3832:   double age,agelim;
                   3833:   int theta;
                   3834:   
                   3835:   pstamp(ficresvpl);
                   3836:   fprintf(ficresvpl,"# Standard deviation of period (stable) prevalences \n");
                   3837:   fprintf(ficresvpl,"# Age");
                   3838:   for(i=1; i<=nlstate;i++)
                   3839:       fprintf(ficresvpl," %1d-%1d",i,i);
                   3840:   fprintf(ficresvpl,"\n");
                   3841: 
                   3842:   xp=vector(1,npar);
                   3843:   dnewm=matrix(1,nlstate,1,npar);
                   3844:   doldm=matrix(1,nlstate,1,nlstate);
                   3845:   
                   3846:   hstepm=1*YEARM; /* Every year of age */
                   3847:   hstepm=hstepm/stepm; /* Typically in stepm units, if j= 2 years, = 2/6 months = 4 */ 
                   3848:   agelim = AGESUP;
                   3849:   for (age=bage; age<=fage; age ++){ /* If stepm=6 months */
                   3850:     nhstepm=(int) rint((agelim-age)*YEARM/stepm); /* Typically 20 years = 20*12/6=40 */ 
                   3851:     if (stepm >= YEARM) hstepm=1;
                   3852:     nhstepm = nhstepm/hstepm; /* Typically 40/4=10 */
                   3853:     gradg=matrix(1,npar,1,nlstate);
                   3854:     gp=vector(1,nlstate);
                   3855:     gm=vector(1,nlstate);
                   3856: 
                   3857:     for(theta=1; theta <=npar; theta++){
                   3858:       for(i=1; i<=npar; i++){ /* Computes gradient */
                   3859:        xp[i] = x[i] + (i==theta ?delti[theta]:0);
                   3860:       }
                   3861:       prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ij);
                   3862:       for(i=1;i<=nlstate;i++)
                   3863:        gp[i] = prlim[i][i];
                   3864:     
                   3865:       for(i=1; i<=npar; i++) /* Computes gradient */
                   3866:        xp[i] = x[i] - (i==theta ?delti[theta]:0);
                   3867:       prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ij);
                   3868:       for(i=1;i<=nlstate;i++)
                   3869:        gm[i] = prlim[i][i];
                   3870: 
                   3871:       for(i=1;i<=nlstate;i++)
                   3872:        gradg[theta][i]= (gp[i]-gm[i])/2./delti[theta];
                   3873:     } /* End theta */
                   3874: 
                   3875:     trgradg =matrix(1,nlstate,1,npar);
                   3876: 
                   3877:     for(j=1; j<=nlstate;j++)
                   3878:       for(theta=1; theta <=npar; theta++)
                   3879:        trgradg[j][theta]=gradg[theta][j];
                   3880: 
                   3881:     for(i=1;i<=nlstate;i++)
                   3882:       varpl[i][(int)age] =0.;
                   3883:     matprod2(dnewm,trgradg,1,nlstate,1,npar,1,npar,matcov);
                   3884:     matprod2(doldm,dnewm,1,nlstate,1,npar,1,nlstate,gradg);
                   3885:     for(i=1;i<=nlstate;i++)
                   3886:       varpl[i][(int)age] = doldm[i][i]; /* Covariances are useless */
                   3887: 
                   3888:     fprintf(ficresvpl,"%.0f ",age );
                   3889:     for(i=1; i<=nlstate;i++)
                   3890:       fprintf(ficresvpl," %.5f (%.5f)",prlim[i][i],sqrt(varpl[i][(int)age]));
                   3891:     fprintf(ficresvpl,"\n");
                   3892:     free_vector(gp,1,nlstate);
                   3893:     free_vector(gm,1,nlstate);
                   3894:     free_matrix(gradg,1,npar,1,nlstate);
                   3895:     free_matrix(trgradg,1,nlstate,1,npar);
                   3896:   } /* End age */
                   3897: 
                   3898:   free_vector(xp,1,npar);
                   3899:   free_matrix(doldm,1,nlstate,1,npar);
                   3900:   free_matrix(dnewm,1,nlstate,1,nlstate);
                   3901: 
                   3902: }
                   3903: 
                   3904: /************ Variance of one-step probabilities  ******************/
                   3905: 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[])
                   3906: {
1.164     brouard  3907:   int i, j=0,  k1, l1, tj;
1.126     brouard  3908:   int k2, l2, j1,  z1;
1.164     brouard  3909:   int k=0, l;
1.145     brouard  3910:   int first=1, first1, first2;
1.126     brouard  3911:   double cv12, mu1, mu2, lc1, lc2, v12, v21, v11, v22,v1,v2, c12, tnalp;
                   3912:   double **dnewm,**doldm;
                   3913:   double *xp;
                   3914:   double *gp, *gm;
                   3915:   double **gradg, **trgradg;
                   3916:   double **mu;
1.164     brouard  3917:   double age, cov[NCOVMAX+1];
1.126     brouard  3918:   double std=2.0; /* Number of standard deviation wide of confidence ellipsoids */
                   3919:   int theta;
                   3920:   char fileresprob[FILENAMELENGTH];
                   3921:   char fileresprobcov[FILENAMELENGTH];
                   3922:   char fileresprobcor[FILENAMELENGTH];
                   3923:   double ***varpij;
                   3924: 
                   3925:   strcpy(fileresprob,"prob"); 
                   3926:   strcat(fileresprob,fileres);
                   3927:   if((ficresprob=fopen(fileresprob,"w"))==NULL) {
                   3928:     printf("Problem with resultfile: %s\n", fileresprob);
                   3929:     fprintf(ficlog,"Problem with resultfile: %s\n", fileresprob);
                   3930:   }
                   3931:   strcpy(fileresprobcov,"probcov"); 
                   3932:   strcat(fileresprobcov,fileres);
                   3933:   if((ficresprobcov=fopen(fileresprobcov,"w"))==NULL) {
                   3934:     printf("Problem with resultfile: %s\n", fileresprobcov);
                   3935:     fprintf(ficlog,"Problem with resultfile: %s\n", fileresprobcov);
                   3936:   }
                   3937:   strcpy(fileresprobcor,"probcor"); 
                   3938:   strcat(fileresprobcor,fileres);
                   3939:   if((ficresprobcor=fopen(fileresprobcor,"w"))==NULL) {
                   3940:     printf("Problem with resultfile: %s\n", fileresprobcor);
                   3941:     fprintf(ficlog,"Problem with resultfile: %s\n", fileresprobcor);
                   3942:   }
                   3943:   printf("Computing standard deviation of one-step probabilities: result on file '%s' \n",fileresprob);
                   3944:   fprintf(ficlog,"Computing standard deviation of one-step probabilities: result on file '%s' \n",fileresprob);
                   3945:   printf("Computing matrix of variance covariance of one-step probabilities: result on file '%s' \n",fileresprobcov);
                   3946:   fprintf(ficlog,"Computing matrix of variance covariance of one-step probabilities: result on file '%s' \n",fileresprobcov);
                   3947:   printf("and correlation matrix of one-step probabilities: result on file '%s' \n",fileresprobcor);
                   3948:   fprintf(ficlog,"and correlation matrix of one-step probabilities: result on file '%s' \n",fileresprobcor);
                   3949:   pstamp(ficresprob);
                   3950:   fprintf(ficresprob,"#One-step probabilities and stand. devi in ()\n");
                   3951:   fprintf(ficresprob,"# Age");
                   3952:   pstamp(ficresprobcov);
                   3953:   fprintf(ficresprobcov,"#One-step probabilities and covariance matrix\n");
                   3954:   fprintf(ficresprobcov,"# Age");
                   3955:   pstamp(ficresprobcor);
                   3956:   fprintf(ficresprobcor,"#One-step probabilities and correlation matrix\n");
                   3957:   fprintf(ficresprobcor,"# Age");
                   3958: 
                   3959: 
                   3960:   for(i=1; i<=nlstate;i++)
                   3961:     for(j=1; j<=(nlstate+ndeath);j++){
                   3962:       fprintf(ficresprob," p%1d-%1d (SE)",i,j);
                   3963:       fprintf(ficresprobcov," p%1d-%1d ",i,j);
                   3964:       fprintf(ficresprobcor," p%1d-%1d ",i,j);
                   3965:     }  
                   3966:  /* fprintf(ficresprob,"\n");
                   3967:   fprintf(ficresprobcov,"\n");
                   3968:   fprintf(ficresprobcor,"\n");
                   3969:  */
1.131     brouard  3970:   xp=vector(1,npar);
1.126     brouard  3971:   dnewm=matrix(1,(nlstate)*(nlstate+ndeath),1,npar);
                   3972:   doldm=matrix(1,(nlstate)*(nlstate+ndeath),1,(nlstate)*(nlstate+ndeath));
                   3973:   mu=matrix(1,(nlstate)*(nlstate+ndeath), (int) bage, (int)fage);
                   3974:   varpij=ma3x(1,nlstate*(nlstate+ndeath),1,nlstate*(nlstate+ndeath),(int) bage, (int) fage);
                   3975:   first=1;
                   3976:   fprintf(ficgp,"\n# Routine varprob");
                   3977:   fprintf(fichtm,"\n<li><h4> Computing and drawing one step probabilities with their confidence intervals</h4></li>\n");
                   3978:   fprintf(fichtm,"\n");
                   3979: 
                   3980:   fprintf(fichtm,"\n<li><h4> <a href=\"%s\">Matrix of variance-covariance of pairs of step probabilities (drawings)</a></h4></li>\n",optionfilehtmcov);
                   3981:   fprintf(fichtmcov,"\n<h4>Matrix of variance-covariance of pairs of step probabilities</h4>\n\
                   3982:   file %s<br>\n",optionfilehtmcov);
                   3983:   fprintf(fichtmcov,"\nEllipsoids of confidence centered on point (p<inf>ij</inf>, p<inf>kl</inf>) are estimated\
                   3984: and drawn. It helps understanding how is the covariance between two incidences.\
                   3985:  They are expressed in year<sup>-1</sup> in order to be less dependent of stepm.<br>\n");
                   3986:   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. \
                   3987: It can be understood this way: if pij and pkl where uncorrelated the (2x2) matrix of covariance \
                   3988: would have been (1/(var pij), 0 , 0, 1/(var pkl)), and the confidence interval would be 2 \
                   3989: standard deviations wide on each axis. <br>\
                   3990:  Now, if both incidences are correlated (usual case) we diagonalised the inverse of the covariance matrix\
                   3991:  and made the appropriate rotation to look at the uncorrelated principal directions.<br>\
                   3992: To be simple, these graphs help to understand the significativity of each parameter in relation to a second other one.<br> \n");
                   3993: 
                   3994:   cov[1]=1;
1.145     brouard  3995:   /* tj=cptcoveff; */
                   3996:   tj = (int) pow(2,cptcoveff);
1.126     brouard  3997:   if (cptcovn<1) {tj=1;ncodemax[1]=1;}
                   3998:   j1=0;
1.145     brouard  3999:   for(j1=1; j1<=tj;j1++){
                   4000:     /*for(i1=1; i1<=ncodemax[t];i1++){ */
                   4001:     /*j1++;*/
1.126     brouard  4002:       if  (cptcovn>0) {
                   4003:        fprintf(ficresprob, "\n#********** Variable "); 
                   4004:        for (z1=1; z1<=cptcoveff; z1++) fprintf(ficresprob, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtab[j1][z1]]);
                   4005:        fprintf(ficresprob, "**********\n#\n");
                   4006:        fprintf(ficresprobcov, "\n#********** Variable "); 
                   4007:        for (z1=1; z1<=cptcoveff; z1++) fprintf(ficresprobcov, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtab[j1][z1]]);
                   4008:        fprintf(ficresprobcov, "**********\n#\n");
                   4009:        
                   4010:        fprintf(ficgp, "\n#********** Variable "); 
                   4011:        for (z1=1; z1<=cptcoveff; z1++) fprintf(ficgp, " V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtab[j1][z1]]);
                   4012:        fprintf(ficgp, "**********\n#\n");
                   4013:        
                   4014:        
                   4015:        fprintf(fichtmcov, "\n<hr  size=\"2\" color=\"#EC5E5E\">********** Variable "); 
                   4016:        for (z1=1; z1<=cptcoveff; z1++) fprintf(fichtm, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtab[j1][z1]]);
                   4017:        fprintf(fichtmcov, "**********\n<hr size=\"2\" color=\"#EC5E5E\">");
                   4018:        
                   4019:        fprintf(ficresprobcor, "\n#********** Variable ");    
                   4020:        for (z1=1; z1<=cptcoveff; z1++) fprintf(ficresprobcor, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtab[j1][z1]]);
                   4021:        fprintf(ficresprobcor, "**********\n#");    
                   4022:       }
                   4023:       
1.145     brouard  4024:       gradg=matrix(1,npar,1,(nlstate)*(nlstate+ndeath));
                   4025:       trgradg=matrix(1,(nlstate)*(nlstate+ndeath),1,npar);
                   4026:       gp=vector(1,(nlstate)*(nlstate+ndeath));
                   4027:       gm=vector(1,(nlstate)*(nlstate+ndeath));
1.126     brouard  4028:       for (age=bage; age<=fage; age ++){ 
                   4029:        cov[2]=age;
                   4030:        for (k=1; k<=cptcovn;k++) {
1.145     brouard  4031:          cov[2+k]=nbcode[Tvar[k]][codtab[j1][Tvar[k]]];/* j1 1 2 3 4
                   4032:                                                         * 1  1 1 1 1
                   4033:                                                         * 2  2 1 1 1
                   4034:                                                         * 3  1 2 1 1
                   4035:                                                         */
                   4036:          /* nbcode[1][1]=0 nbcode[1][2]=1;*/
1.126     brouard  4037:        }
                   4038:        for (k=1; k<=cptcovage;k++) cov[2+Tage[k]]=cov[2+Tage[k]]*cov[2];
                   4039:        for (k=1; k<=cptcovprod;k++)
                   4040:          cov[2+Tprod[k]]=nbcode[Tvard[k][1]][codtab[ij][Tvard[k][1]]]*nbcode[Tvard[k][2]][codtab[ij][Tvard[k][2]]];
                   4041:        
                   4042:     
                   4043:        for(theta=1; theta <=npar; theta++){
                   4044:          for(i=1; i<=npar; i++)
                   4045:            xp[i] = x[i] + (i==theta ?delti[theta]:(double)0);
                   4046:          
                   4047:          pmij(pmmij,cov,ncovmodel,xp,nlstate);
                   4048:          
                   4049:          k=0;
                   4050:          for(i=1; i<= (nlstate); i++){
                   4051:            for(j=1; j<=(nlstate+ndeath);j++){
                   4052:              k=k+1;
                   4053:              gp[k]=pmmij[i][j];
                   4054:            }
                   4055:          }
                   4056:          
                   4057:          for(i=1; i<=npar; i++)
                   4058:            xp[i] = x[i] - (i==theta ?delti[theta]:(double)0);
                   4059:     
                   4060:          pmij(pmmij,cov,ncovmodel,xp,nlstate);
                   4061:          k=0;
                   4062:          for(i=1; i<=(nlstate); i++){
                   4063:            for(j=1; j<=(nlstate+ndeath);j++){
                   4064:              k=k+1;
                   4065:              gm[k]=pmmij[i][j];
                   4066:            }
                   4067:          }
                   4068:      
                   4069:          for(i=1; i<= (nlstate)*(nlstate+ndeath); i++) 
                   4070:            gradg[theta][i]=(gp[i]-gm[i])/(double)2./delti[theta];  
                   4071:        }
                   4072: 
                   4073:        for(j=1; j<=(nlstate)*(nlstate+ndeath);j++)
                   4074:          for(theta=1; theta <=npar; theta++)
                   4075:            trgradg[j][theta]=gradg[theta][j];
                   4076:        
                   4077:        matprod2(dnewm,trgradg,1,(nlstate)*(nlstate+ndeath),1,npar,1,npar,matcov); 
                   4078:        matprod2(doldm,dnewm,1,(nlstate)*(nlstate+ndeath),1,npar,1,(nlstate)*(nlstate+ndeath),gradg);
                   4079: 
                   4080:        pmij(pmmij,cov,ncovmodel,x,nlstate);
                   4081:        
                   4082:        k=0;
                   4083:        for(i=1; i<=(nlstate); i++){
                   4084:          for(j=1; j<=(nlstate+ndeath);j++){
                   4085:            k=k+1;
                   4086:            mu[k][(int) age]=pmmij[i][j];
                   4087:          }
                   4088:        }
                   4089:        for(i=1;i<=(nlstate)*(nlstate+ndeath);i++)
                   4090:          for(j=1;j<=(nlstate)*(nlstate+ndeath);j++)
                   4091:            varpij[i][j][(int)age] = doldm[i][j];
                   4092: 
                   4093:        /*printf("\n%d ",(int)age);
                   4094:          for (i=1; i<=(nlstate)*(nlstate+ndeath);i++){
                   4095:          printf("%e [%e ;%e] ",gm[i],gm[i]-2*sqrt(doldm[i][i]),gm[i]+2*sqrt(doldm[i][i]));
                   4096:          fprintf(ficlog,"%e [%e ;%e] ",gm[i],gm[i]-2*sqrt(doldm[i][i]),gm[i]+2*sqrt(doldm[i][i]));
                   4097:          }*/
                   4098: 
                   4099:        fprintf(ficresprob,"\n%d ",(int)age);
                   4100:        fprintf(ficresprobcov,"\n%d ",(int)age);
                   4101:        fprintf(ficresprobcor,"\n%d ",(int)age);
                   4102: 
                   4103:        for (i=1; i<=(nlstate)*(nlstate+ndeath);i++)
                   4104:          fprintf(ficresprob,"%11.3e (%11.3e) ",mu[i][(int) age],sqrt(varpij[i][i][(int)age]));
                   4105:        for (i=1; i<=(nlstate)*(nlstate+ndeath);i++){
                   4106:          fprintf(ficresprobcov,"%11.3e ",mu[i][(int) age]);
                   4107:          fprintf(ficresprobcor,"%11.3e ",mu[i][(int) age]);
                   4108:        }
                   4109:        i=0;
                   4110:        for (k=1; k<=(nlstate);k++){
                   4111:          for (l=1; l<=(nlstate+ndeath);l++){ 
1.145     brouard  4112:            i++;
1.126     brouard  4113:            fprintf(ficresprobcov,"\n%d %d-%d",(int)age,k,l);
                   4114:            fprintf(ficresprobcor,"\n%d %d-%d",(int)age,k,l);
                   4115:            for (j=1; j<=i;j++){
1.145     brouard  4116:              /* printf(" k=%d l=%d i=%d j=%d\n",k,l,i,j);fflush(stdout); */
1.126     brouard  4117:              fprintf(ficresprobcov," %11.3e",varpij[i][j][(int)age]);
                   4118:              fprintf(ficresprobcor," %11.3e",varpij[i][j][(int) age]/sqrt(varpij[i][i][(int) age])/sqrt(varpij[j][j][(int)age]));
                   4119:            }
                   4120:          }
                   4121:        }/* end of loop for state */
                   4122:       } /* end of loop for age */
1.145     brouard  4123:       free_vector(gp,1,(nlstate+ndeath)*(nlstate+ndeath));
                   4124:       free_vector(gm,1,(nlstate+ndeath)*(nlstate+ndeath));
                   4125:       free_matrix(trgradg,1,(nlstate+ndeath)*(nlstate+ndeath),1,npar);
                   4126:       free_matrix(gradg,1,(nlstate+ndeath)*(nlstate+ndeath),1,npar);
                   4127:       
1.126     brouard  4128:       /* Confidence intervalle of pij  */
                   4129:       /*
1.131     brouard  4130:        fprintf(ficgp,"\nunset parametric;unset label");
1.126     brouard  4131:        fprintf(ficgp,"\nset log y;unset log x; set xlabel \"Age\";set ylabel \"probability (year-1)\"");
                   4132:        fprintf(ficgp,"\nset ter png small\nset size 0.65,0.65");
                   4133:        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);
                   4134:        fprintf(fichtm,"\n<br><img src=\"pijgr%s.png\"> ",optionfilefiname);
                   4135:        fprintf(ficgp,"\nset out \"pijgr%s.png\"",optionfilefiname);
                   4136:        fprintf(ficgp,"\nplot \"%s\" every :::%d::%d u 1:2 \"\%%lf",k1,k2,xfilevarprob);
                   4137:       */
                   4138: 
                   4139:       /* Drawing ellipsoids of confidence of two variables p(k1-l1,k2-l2)*/
1.145     brouard  4140:       first1=1;first2=2;
1.126     brouard  4141:       for (k2=1; k2<=(nlstate);k2++){
                   4142:        for (l2=1; l2<=(nlstate+ndeath);l2++){ 
                   4143:          if(l2==k2) continue;
                   4144:          j=(k2-1)*(nlstate+ndeath)+l2;
                   4145:          for (k1=1; k1<=(nlstate);k1++){
                   4146:            for (l1=1; l1<=(nlstate+ndeath);l1++){ 
                   4147:              if(l1==k1) continue;
                   4148:              i=(k1-1)*(nlstate+ndeath)+l1;
                   4149:              if(i<=j) continue;
                   4150:              for (age=bage; age<=fage; age ++){ 
                   4151:                if ((int)age %5==0){
                   4152:                  v1=varpij[i][i][(int)age]/stepm*YEARM/stepm*YEARM;
                   4153:                  v2=varpij[j][j][(int)age]/stepm*YEARM/stepm*YEARM;
                   4154:                  cv12=varpij[i][j][(int)age]/stepm*YEARM/stepm*YEARM;
                   4155:                  mu1=mu[i][(int) age]/stepm*YEARM ;
                   4156:                  mu2=mu[j][(int) age]/stepm*YEARM;
                   4157:                  c12=cv12/sqrt(v1*v2);
                   4158:                  /* Computing eigen value of matrix of covariance */
                   4159:                  lc1=((v1+v2)+sqrt((v1+v2)*(v1+v2) - 4*(v1*v2-cv12*cv12)))/2.;
                   4160:                  lc2=((v1+v2)-sqrt((v1+v2)*(v1+v2) - 4*(v1*v2-cv12*cv12)))/2.;
1.135     brouard  4161:                  if ((lc2 <0) || (lc1 <0) ){
1.145     brouard  4162:                    if(first2==1){
                   4163:                      first1=0;
                   4164:                    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);
                   4165:                    }
                   4166:                    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);
                   4167:                    /* lc1=fabs(lc1); */ /* If we want to have them positive */
                   4168:                    /* lc2=fabs(lc2); */
1.135     brouard  4169:                  }
                   4170: 
1.126     brouard  4171:                  /* Eigen vectors */
                   4172:                  v11=(1./sqrt(1+(v1-lc1)*(v1-lc1)/cv12/cv12));
                   4173:                  /*v21=sqrt(1.-v11*v11); *//* error */
                   4174:                  v21=(lc1-v1)/cv12*v11;
                   4175:                  v12=-v21;
                   4176:                  v22=v11;
                   4177:                  tnalp=v21/v11;
                   4178:                  if(first1==1){
                   4179:                    first1=0;
                   4180:                    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);
                   4181:                  }
                   4182:                  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);
                   4183:                  /*printf(fignu*/
                   4184:                  /* mu1+ v11*lc1*cost + v12*lc2*sin(t) */
                   4185:                  /* mu2+ v21*lc1*cost + v22*lc2*sin(t) */
                   4186:                  if(first==1){
                   4187:                    first=0;
                   4188:                    fprintf(ficgp,"\nset parametric;unset label");
                   4189:                    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  4190:                    fprintf(ficgp,"\nset ter png small size 320, 240");
1.126     brouard  4191:                    fprintf(fichtmcov,"\n<br>Ellipsoids of confidence cov(p%1d%1d,p%1d%1d) expressed in year<sup>-1</sup>\
                   4192:  :<a href=\"%s%d%1d%1d-%1d%1d.png\">\
                   4193: %s%d%1d%1d-%1d%1d.png</A>, ",k1,l1,k2,l2,\
                   4194:                            subdirf2(optionfilefiname,"varpijgr"), j1,k1,l1,k2,l2,\
                   4195:                            subdirf2(optionfilefiname,"varpijgr"), j1,k1,l1,k2,l2);
                   4196:                    fprintf(fichtmcov,"\n<br><img src=\"%s%d%1d%1d-%1d%1d.png\"> ",subdirf2(optionfilefiname,"varpijgr"), j1,k1,l1,k2,l2);
                   4197:                    fprintf(fichtmcov,"\n<br> Correlation at age %d (%.3f),",(int) age, c12);
                   4198:                    fprintf(ficgp,"\nset out \"%s%d%1d%1d-%1d%1d.png\"",subdirf2(optionfilefiname,"varpijgr"), j1,k1,l1,k2,l2);
                   4199:                    fprintf(ficgp,"\nset label \"%d\" at %11.3e,%11.3e center",(int) age, mu1,mu2);
                   4200:                    fprintf(ficgp,"\n# Age %d, p%1d%1d - p%1d%1d",(int) age, k1,l1,k2,l2);
                   4201:                    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",\
                   4202:                            mu1,std,v11,sqrt(lc1),v12,sqrt(lc2),\
                   4203:                            mu2,std,v21,sqrt(lc1),v22,sqrt(lc2));
                   4204:                  }else{
                   4205:                    first=0;
                   4206:                    fprintf(fichtmcov," %d (%.3f),",(int) age, c12);
                   4207:                    fprintf(ficgp,"\n# Age %d, p%1d%1d - p%1d%1d",(int) age, k1,l1,k2,l2);
                   4208:                    fprintf(ficgp,"\nset label \"%d\" at %11.3e,%11.3e center",(int) age, mu1,mu2);
                   4209:                    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",\
                   4210:                            mu1,std,v11,sqrt(lc1),v12,sqrt(lc2),\
                   4211:                            mu2,std,v21,sqrt(lc1),v22,sqrt(lc2));
                   4212:                  }/* if first */
                   4213:                } /* age mod 5 */
                   4214:              } /* end loop age */
                   4215:              fprintf(ficgp,"\nset out \"%s%d%1d%1d-%1d%1d.png\";replot;",subdirf2(optionfilefiname,"varpijgr"), j1,k1,l1,k2,l2);
                   4216:              first=1;
                   4217:            } /*l12 */
                   4218:          } /* k12 */
                   4219:        } /*l1 */
                   4220:       }/* k1 */
1.169     brouard  4221:       /* } */ /* loop covariates */
1.126     brouard  4222:   }
                   4223:   free_ma3x(varpij,1,nlstate,1,nlstate+ndeath,(int) bage, (int)fage);
                   4224:   free_matrix(mu,1,(nlstate+ndeath)*(nlstate+ndeath),(int) bage, (int)fage);
                   4225:   free_matrix(doldm,1,(nlstate)*(nlstate+ndeath),1,(nlstate)*(nlstate+ndeath));
                   4226:   free_matrix(dnewm,1,(nlstate)*(nlstate+ndeath),1,npar);
                   4227:   free_vector(xp,1,npar);
                   4228:   fclose(ficresprob);
                   4229:   fclose(ficresprobcov);
                   4230:   fclose(ficresprobcor);
                   4231:   fflush(ficgp);
                   4232:   fflush(fichtmcov);
                   4233: }
                   4234: 
                   4235: 
                   4236: /******************* Printing html file ***********/
                   4237: void printinghtml(char fileres[], char title[], char datafile[], int firstpass, \
                   4238:                  int lastpass, int stepm, int weightopt, char model[],\
                   4239:                  int imx,int jmin, int jmax, double jmeanint,char rfileres[],\
                   4240:                  int popforecast, int estepm ,\
                   4241:                  double jprev1, double mprev1,double anprev1, \
                   4242:                  double jprev2, double mprev2,double anprev2){
                   4243:   int jj1, k1, i1, cpt;
                   4244: 
                   4245:    fprintf(fichtm,"<ul><li><a href='#firstorder'>Result files (first order: no variance)</a>\n \
                   4246:    <li><a href='#secondorder'>Result files (second order (variance)</a>\n \
                   4247: </ul>");
                   4248:    fprintf(fichtm,"<ul><li><h4><a name='firstorder'>Result files (first order: no variance)</a></h4>\n \
                   4249:  - Observed prevalence in each state (during the period defined between %.lf/%.lf/%.lf and %.lf/%.lf/%.lf): <a href=\"%s\">%s</a> <br>\n ",
                   4250:           jprev1, mprev1,anprev1,jprev2, mprev2,anprev2,subdirf2(fileres,"p"),subdirf2(fileres,"p"));
                   4251:    fprintf(fichtm,"\
                   4252:  - Estimated transition probabilities over %d (stepm) months: <a href=\"%s\">%s</a><br>\n ",
                   4253:           stepm,subdirf2(fileres,"pij"),subdirf2(fileres,"pij"));
                   4254:    fprintf(fichtm,"\
                   4255:  - Period (stable) prevalence in each health state: <a href=\"%s\">%s</a> <br>\n",
                   4256:           subdirf2(fileres,"pl"),subdirf2(fileres,"pl"));
                   4257:    fprintf(fichtm,"\
1.128     brouard  4258:  - (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  4259:    <a href=\"%s\">%s</a> <br>\n",
                   4260:           estepm,subdirf2(fileres,"e"),subdirf2(fileres,"e"));
                   4261:    fprintf(fichtm,"\
                   4262:  - Population projections by age and states: \
                   4263:    <a href=\"%s\">%s</a> <br>\n</li>", subdirf2(fileres,"f"),subdirf2(fileres,"f"));
                   4264: 
                   4265: fprintf(fichtm," \n<ul><li><b>Graphs</b></li><p>");
                   4266: 
1.145     brouard  4267:  m=pow(2,cptcoveff);
1.126     brouard  4268:  if (cptcovn < 1) {m=1;ncodemax[1]=1;}
                   4269: 
                   4270:  jj1=0;
                   4271:  for(k1=1; k1<=m;k1++){
                   4272:    for(i1=1; i1<=ncodemax[k1];i1++){
                   4273:      jj1++;
                   4274:      if (cptcovn > 0) {
                   4275:        fprintf(fichtm,"<hr  size=\"2\" color=\"#EC5E5E\">************ Results for covariates");
                   4276:        for (cpt=1; cpt<=cptcoveff;cpt++) 
                   4277:         fprintf(fichtm," V%d=%d ",Tvaraff[cpt],nbcode[Tvaraff[cpt]][codtab[jj1][cpt]]);
                   4278:        fprintf(fichtm," ************\n<hr size=\"2\" color=\"#EC5E5E\">");
                   4279:      }
                   4280:      /* Pij */
1.145     brouard  4281:      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> \
                   4282: <img src=\"%s%d_1.png\">",stepm,subdirf2(optionfilefiname,"pe"),jj1,subdirf2(optionfilefiname,"pe"),jj1,subdirf2(optionfilefiname,"pe"),jj1);     
1.126     brouard  4283:      /* Quasi-incidences */
                   4284:      fprintf(fichtm,"<br>- Pij or Conditional probabilities to be observed in state j being in state i %d (stepm) months\
1.145     brouard  4285:  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> \
                   4286: <img src=\"%s%d_2.png\">",stepm,subdirf2(optionfilefiname,"pe"),jj1,subdirf2(optionfilefiname,"pe"),jj1,subdirf2(optionfilefiname,"pe"),jj1); 
1.126     brouard  4287:        /* Period (stable) prevalence in each health state */
1.154     brouard  4288:        for(cpt=1; cpt<=nlstate;cpt++){
1.166     brouard  4289:         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> \
                   4290: <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  4291:        }
                   4292:      for(cpt=1; cpt<=nlstate;cpt++) {
1.154     brouard  4293:         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> \
                   4294: <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  4295:      }
                   4296:    } /* end i1 */
                   4297:  }/* End k1 */
                   4298:  fprintf(fichtm,"</ul>");
                   4299: 
                   4300: 
                   4301:  fprintf(fichtm,"\
                   4302: \n<br><li><h4> <a name='secondorder'>Result files (second order: variances)</a></h4>\n\
                   4303:  - Parameter file with estimated parameters and covariance matrix: <a href=\"%s\">%s</a> <br>\n", rfileres,rfileres);
                   4304: 
                   4305:  fprintf(fichtm," - Variance of one-step probabilities: <a href=\"%s\">%s</a> <br>\n",
                   4306:         subdirf2(fileres,"prob"),subdirf2(fileres,"prob"));
                   4307:  fprintf(fichtm,"\
                   4308:  - Variance-covariance of one-step probabilities: <a href=\"%s\">%s</a> <br>\n",
                   4309:         subdirf2(fileres,"probcov"),subdirf2(fileres,"probcov"));
                   4310: 
                   4311:  fprintf(fichtm,"\
                   4312:  - Correlation matrix of one-step probabilities: <a href=\"%s\">%s</a> <br>\n",
                   4313:         subdirf2(fileres,"probcor"),subdirf2(fileres,"probcor"));
                   4314:  fprintf(fichtm,"\
                   4315:  - 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): \
                   4316:    <a href=\"%s\">%s</a> <br>\n</li>",
                   4317:           estepm,subdirf2(fileres,"cve"),subdirf2(fileres,"cve"));
                   4318:  fprintf(fichtm,"\
                   4319:  - (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): \
                   4320:    <a href=\"%s\">%s</a> <br>\n</li>",
                   4321:           estepm,subdirf2(fileres,"stde"),subdirf2(fileres,"stde"));
                   4322:  fprintf(fichtm,"\
1.128     brouard  4323:  - 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  4324:         estepm, subdirf2(fileres,"v"),subdirf2(fileres,"v"));
                   4325:  fprintf(fichtm,"\
1.128     brouard  4326:  - 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",
                   4327:         estepm, subdirf2(fileres,"t"),subdirf2(fileres,"t"));
1.126     brouard  4328:  fprintf(fichtm,"\
                   4329:  - Standard deviation of period (stable) prevalences: <a href=\"%s\">%s</a> <br>\n",\
                   4330:         subdirf2(fileres,"vpl"),subdirf2(fileres,"vpl"));
                   4331: 
                   4332: /*  if(popforecast==1) fprintf(fichtm,"\n */
                   4333: /*  - Prevalences forecasting: <a href=\"f%s\">f%s</a> <br>\n */
                   4334: /*  - Population forecasting (if popforecast=1): <a href=\"pop%s\">pop%s</a> <br>\n */
                   4335: /*     <br>",fileres,fileres,fileres,fileres); */
                   4336: /*  else  */
                   4337: /*    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); */
                   4338:  fflush(fichtm);
                   4339:  fprintf(fichtm," <ul><li><b>Graphs</b></li><p>");
                   4340: 
1.145     brouard  4341:  m=pow(2,cptcoveff);
1.126     brouard  4342:  if (cptcovn < 1) {m=1;ncodemax[1]=1;}
                   4343: 
                   4344:  jj1=0;
                   4345:  for(k1=1; k1<=m;k1++){
                   4346:    for(i1=1; i1<=ncodemax[k1];i1++){
                   4347:      jj1++;
                   4348:      if (cptcovn > 0) {
                   4349:        fprintf(fichtm,"<hr  size=\"2\" color=\"#EC5E5E\">************ Results for covariates");
                   4350:        for (cpt=1; cpt<=cptcoveff;cpt++) 
                   4351:         fprintf(fichtm," V%d=%d ",Tvaraff[cpt],nbcode[Tvaraff[cpt]][codtab[jj1][cpt]]);
                   4352:        fprintf(fichtm," ************\n<hr size=\"2\" color=\"#EC5E5E\">");
                   4353:      }
                   4354:      for(cpt=1; cpt<=nlstate;cpt++) {
                   4355:        fprintf(fichtm,"<br>- Observed (cross-sectional) and period (incidence based) \
1.145     brouard  4356: prevalence (with 95%% confidence interval) in state (%d): %s%d_%d.png <br>\
                   4357: <img src=\"%s%d_%d.png\">",cpt,subdirf2(optionfilefiname,"v"),cpt,jj1,subdirf2(optionfilefiname,"v"),cpt,jj1);  
1.126     brouard  4358:      }
                   4359:      fprintf(fichtm,"\n<br>- Total life expectancy by age and \
1.128     brouard  4360: health expectancies in states (1) and (2). If popbased=1 the smooth (due to the model) \
                   4361: true period expectancies (those weighted with period prevalences are also\
                   4362:  drawn in addition to the population based expectancies computed using\
                   4363:  observed and cahotic prevalences: %s%d.png<br>\
1.126     brouard  4364: <img src=\"%s%d.png\">",subdirf2(optionfilefiname,"e"),jj1,subdirf2(optionfilefiname,"e"),jj1);
                   4365:    } /* end i1 */
                   4366:  }/* End k1 */
                   4367:  fprintf(fichtm,"</ul>");
                   4368:  fflush(fichtm);
                   4369: }
                   4370: 
                   4371: /******************* Gnuplot file **************/
                   4372: void printinggnuplot(char fileres[], char optionfilefiname[], double ageminpar, double agemaxpar, double fage , char pathc[], double p[]){
                   4373: 
                   4374:   char dirfileres[132],optfileres[132];
1.164     brouard  4375:   int cpt=0,k1=0,i=0,k=0,j=0,jk=0,k2=0,k3=0,ij=0,l=0;
1.130     brouard  4376:   int ng=0;
1.126     brouard  4377: /*   if((ficgp=fopen(optionfilegnuplot,"a"))==NULL) { */
                   4378: /*     printf("Problem with file %s",optionfilegnuplot); */
                   4379: /*     fprintf(ficlog,"Problem with file %s",optionfilegnuplot); */
                   4380: /*   } */
                   4381: 
                   4382:   /*#ifdef windows */
                   4383:   fprintf(ficgp,"cd \"%s\" \n",pathc);
                   4384:     /*#endif */
                   4385:   m=pow(2,cptcoveff);
                   4386: 
                   4387:   strcpy(dirfileres,optionfilefiname);
                   4388:   strcpy(optfileres,"vpl");
                   4389:  /* 1eme*/
1.153     brouard  4390:   fprintf(ficgp,"\n# 1st: Period (stable) prevalence with CI: 'vpl' files\n");
1.126     brouard  4391:   for (cpt=1; cpt<= nlstate ; cpt ++) {
1.145     brouard  4392:     for (k1=1; k1<= m ; k1 ++) { /* plot [100000000000000000000:-100000000000000000000] "mysbiaspar/vplrmysbiaspar.txt to check */
                   4393:      fprintf(ficgp,"\nset out \"%s%d_%d.png\" \n",subdirf2(optionfilefiname,"v"),cpt,k1);
                   4394:      fprintf(ficgp,"\n#set out \"v%s%d_%d.png\" \n",optionfilefiname,cpt,k1);
1.126     brouard  4395:      fprintf(ficgp,"set xlabel \"Age\" \n\
                   4396: set ylabel \"Probability\" \n\
1.145     brouard  4397: set ter png small size 320, 240\n\
1.170     brouard  4398: plot [%.f:%.f] \"%s\" every :::%d::%d u 1:2 \"%%lf",ageminpar,fage,subdirf2(fileres,"vpl"),k1-1,k1-1);
1.126     brouard  4399: 
                   4400:      for (i=1; i<= nlstate ; i ++) {
1.170     brouard  4401:        if (i==cpt) fprintf(ficgp," %%lf (%%lf)");
                   4402:        else        fprintf(ficgp," %%*lf (%%*lf)");
1.126     brouard  4403:      }
1.170     brouard  4404:      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  4405:      for (i=1; i<= nlstate ; i ++) {
1.170     brouard  4406:        if (i==cpt) fprintf(ficgp," %%lf (%%lf)");
                   4407:        else fprintf(ficgp," %%*lf (%%*lf)");
1.126     brouard  4408:      } 
1.170     brouard  4409:      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  4410:      for (i=1; i<= nlstate ; i ++) {
1.170     brouard  4411:        if (i==cpt) fprintf(ficgp," %%lf (%%lf)");
                   4412:        else fprintf(ficgp," %%*lf (%%*lf)");
1.126     brouard  4413:      }  
1.145     brouard  4414:      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  4415:    }
                   4416:   }
                   4417:   /*2 eme*/
1.153     brouard  4418:   fprintf(ficgp,"\n# 2nd: Total life expectancy with CI: 't' files\n");
1.126     brouard  4419:   for (k1=1; k1<= m ; k1 ++) { 
                   4420:     fprintf(ficgp,"\nset out \"%s%d.png\" \n",subdirf2(optionfilefiname,"e"),k1);
1.145     brouard  4421:     fprintf(ficgp,"set ylabel \"Years\" \nset ter png small size 320, 240\nplot [%.f:%.f] ",ageminpar,fage);
1.126     brouard  4422:     
                   4423:     for (i=1; i<= nlstate+1 ; i ++) {
                   4424:       k=2*i;
1.170     brouard  4425:       fprintf(ficgp,"\"%s\" every :::%d::%d u 1:2 \"%%lf",subdirf2(fileres,"t"),k1-1,k1-1);
1.126     brouard  4426:       for (j=1; j<= nlstate+1 ; j ++) {
1.170     brouard  4427:        if (j==i) fprintf(ficgp," %%lf (%%lf)");
                   4428:        else fprintf(ficgp," %%*lf (%%*lf)");
1.126     brouard  4429:       }   
                   4430:       if (i== 1) fprintf(ficgp,"\" t\"TLE\" w l ,");
                   4431:       else fprintf(ficgp,"\" t\"LE in state (%d)\" w l ,",i-1);
1.170     brouard  4432:       fprintf(ficgp,"\"%s\" every :::%d::%d u 1:($2-$3*2) \"%%lf",subdirf2(fileres,"t"),k1-1,k1-1);
1.126     brouard  4433:       for (j=1; j<= nlstate+1 ; j ++) {
1.170     brouard  4434:        if (j==i) fprintf(ficgp," %%lf (%%lf)");
                   4435:        else fprintf(ficgp," %%*lf (%%*lf)");
1.126     brouard  4436:       }   
1.145     brouard  4437:       fprintf(ficgp,"\" t\"\" w l lt 0,");
1.170     brouard  4438:       fprintf(ficgp,"\"%s\" every :::%d::%d u 1:($2+$3*2) \"%%lf",subdirf2(fileres,"t"),k1-1,k1-1);
1.126     brouard  4439:       for (j=1; j<= nlstate+1 ; j ++) {
1.170     brouard  4440:        if (j==i) fprintf(ficgp," %%lf (%%lf)");
                   4441:        else fprintf(ficgp," %%*lf (%%*lf)");
1.126     brouard  4442:       }   
1.145     brouard  4443:       if (i== (nlstate+1)) fprintf(ficgp,"\" t\"\" w l lt 0");
                   4444:       else fprintf(ficgp,"\" t\"\" w l lt 0,");
1.126     brouard  4445:     }
                   4446:   }
                   4447:   
                   4448:   /*3eme*/
                   4449:   
                   4450:   for (k1=1; k1<= m ; k1 ++) { 
                   4451:     for (cpt=1; cpt<= nlstate ; cpt ++) {
                   4452:       /*       k=2+nlstate*(2*cpt-2); */
                   4453:       k=2+(nlstate+1)*(cpt-1);
                   4454:       fprintf(ficgp,"\nset out \"%s%d%d.png\" \n",subdirf2(optionfilefiname,"exp"),cpt,k1);
1.145     brouard  4455:       fprintf(ficgp,"set ter png small size 320, 240\n\
1.126     brouard  4456: 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);
                   4457:       /*fprintf(ficgp,",\"e%s\" every :::%d::%d u 1:($%d-2*$%d) \"\%%lf ",fileres,k1-1,k1-1,k,k+1);
                   4458:        for (i=1; i<= nlstate*2 ; i ++) fprintf(ficgp,"\%%lf (\%%lf) ");
                   4459:        fprintf(ficgp,"\" t \"e%d1\" w l",cpt);
                   4460:        fprintf(ficgp,",\"e%s\" every :::%d::%d u 1:($%d+2*$%d) \"\%%lf ",fileres,k1-1,k1-1,k,k+1);
                   4461:        for (i=1; i<= nlstate*2 ; i ++) fprintf(ficgp,"\%%lf (\%%lf) ");
                   4462:        fprintf(ficgp,"\" t \"e%d1\" w l",cpt);
                   4463:        
                   4464:       */
                   4465:       for (i=1; i< nlstate ; i ++) {
                   4466:        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);
                   4467:        /*      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);*/
                   4468:        
                   4469:       } 
                   4470:       fprintf(ficgp," ,\"%s\" every :::%d::%d u 1:%d t \"e%d.\" w l",subdirf2(fileres,"e"),k1-1,k1-1,k+nlstate,cpt);
                   4471:     }
                   4472:   }
                   4473:   
                   4474:   /* CV preval stable (period) */
1.153     brouard  4475:   for (k1=1; k1<= m ; k1 ++) { /* For each multivariate if any */
                   4476:     for (cpt=1; cpt<=nlstate ; cpt ++) { /* For each life state */
1.126     brouard  4477:       k=3;
1.153     brouard  4478:       fprintf(ficgp,"\n#\n#\n#CV preval stable (period): 'pij' files, cov=%d state=%d",k1, cpt);
1.145     brouard  4479:       fprintf(ficgp,"\nset out \"%s%d_%d.png\" \n",subdirf2(optionfilefiname,"p"),cpt,k1);
1.126     brouard  4480:       fprintf(ficgp,"set xlabel \"Age\" \nset ylabel \"Probability\" \n\
1.145     brouard  4481: set ter png small size 320, 240\n\
1.126     brouard  4482: unset log y\n\
1.153     brouard  4483: plot [%.f:%.f]  ", ageminpar, agemaxpar);
                   4484:       for (i=1; i<= nlstate ; i ++){
                   4485:        if(i==1)
                   4486:          fprintf(ficgp,"\"%s\"",subdirf2(fileres,"pij"));
                   4487:        else
                   4488:          fprintf(ficgp,", '' ");
1.154     brouard  4489:        l=(nlstate+ndeath)*(i-1)+1;
                   4490:        fprintf(ficgp," u ($1==%d ? ($3):1/0):($%d/($%d",k1,k+l+(cpt-1),k+l);
1.153     brouard  4491:        for (j=1; j<= (nlstate-1) ; j ++)
                   4492:          fprintf(ficgp,"+$%d",k+l+j);
                   4493:        fprintf(ficgp,")) t \"prev(%d,%d)\" w l",i,cpt);
                   4494:       } /* nlstate */
                   4495:       fprintf(ficgp,"\n");
                   4496:     } /* end cpt state*/ 
                   4497:   } /* end covariate */  
1.126     brouard  4498:   
                   4499:   /* proba elementaires */
                   4500:   for(i=1,jk=1; i <=nlstate; i++){
                   4501:     for(k=1; k <=(nlstate+ndeath); k++){
                   4502:       if (k != i) {
                   4503:        for(j=1; j <=ncovmodel; j++){
                   4504:          fprintf(ficgp,"p%d=%f ",jk,p[jk]);
                   4505:          jk++; 
                   4506:          fprintf(ficgp,"\n");
                   4507:        }
                   4508:       }
                   4509:     }
                   4510:    }
1.145     brouard  4511:   /*goto avoid;*/
1.126     brouard  4512:    for(ng=1; ng<=2;ng++){ /* Number of graphics: first is probabilities second is incidence per year*/
                   4513:      for(jk=1; jk <=m; jk++) {
1.145     brouard  4514:        fprintf(ficgp,"\nset out \"%s%d_%d.png\" \n",subdirf2(optionfilefiname,"pe"),jk,ng); 
1.126     brouard  4515:        if (ng==2)
                   4516:         fprintf(ficgp,"\nset ylabel \"Quasi-incidence per year\"\n");
                   4517:        else
                   4518:         fprintf(ficgp,"\nset title \"Probability\"\n");
1.145     brouard  4519:        fprintf(ficgp,"\nset ter png small size 320, 240\nset log y\nplot  [%.f:%.f] ",ageminpar,agemaxpar);
1.126     brouard  4520:        i=1;
                   4521:        for(k2=1; k2<=nlstate; k2++) {
                   4522:         k3=i;
                   4523:         for(k=1; k<=(nlstate+ndeath); k++) {
                   4524:           if (k != k2){
                   4525:             if(ng==2)
                   4526:               fprintf(ficgp," %f*exp(p%d+p%d*x",YEARM/stepm,i,i+1);
                   4527:             else
                   4528:               fprintf(ficgp," exp(p%d+p%d*x",i,i+1);
1.141     brouard  4529:             ij=1;/* To be checked else nbcode[0][0] wrong */
1.126     brouard  4530:             for(j=3; j <=ncovmodel; j++) {
1.145     brouard  4531:               /* if(((j-2)==Tage[ij]) &&(ij <=cptcovage)) { /\* Bug valgrind *\/ */
                   4532:               /*        /\*fprintf(ficgp,"+p%d*%d*x",i+j-1,nbcode[Tvar[j-2]][codtab[jk][Tvar[j-2]]]);*\/ */
                   4533:               /*        ij++; */
                   4534:               /* } */
                   4535:               /* else */
1.126     brouard  4536:                 fprintf(ficgp,"+p%d*%d",i+j-1,nbcode[Tvar[j-2]][codtab[jk][j-2]]);
                   4537:             }
                   4538:             fprintf(ficgp,")/(1");
                   4539:             
                   4540:             for(k1=1; k1 <=nlstate; k1++){   
                   4541:               fprintf(ficgp,"+exp(p%d+p%d*x",k3+(k1-1)*ncovmodel,k3+(k1-1)*ncovmodel+1);
                   4542:               ij=1;
                   4543:               for(j=3; j <=ncovmodel; j++){
1.145     brouard  4544:                 /* if(((j-2)==Tage[ij]) &&(ij <=cptcovage)) { */
                   4545:                 /*   fprintf(ficgp,"+p%d*%d*x",k3+(k1-1)*ncovmodel+1+j-2,nbcode[Tvar[j-2]][codtab[jk][Tvar[j-2]]]); */
                   4546:                 /*   ij++; */
                   4547:                 /* } */
                   4548:                 /* else */
1.126     brouard  4549:                   fprintf(ficgp,"+p%d*%d",k3+(k1-1)*ncovmodel+1+j-2,nbcode[Tvar[j-2]][codtab[jk][j-2]]);
                   4550:               }
                   4551:               fprintf(ficgp,")");
                   4552:             }
                   4553:             fprintf(ficgp,") t \"p%d%d\" ", k2,k);
                   4554:             if ((k+k2)!= (nlstate*2+ndeath)) fprintf(ficgp,",");
                   4555:             i=i+ncovmodel;
                   4556:           }
                   4557:         } /* end k */
                   4558:        } /* end k2 */
                   4559:      } /* end jk */
                   4560:    } /* end ng */
1.164     brouard  4561:  /* avoid: */
1.126     brouard  4562:    fflush(ficgp); 
                   4563: }  /* end gnuplot */
                   4564: 
                   4565: 
                   4566: /*************** Moving average **************/
                   4567: int movingaverage(double ***probs, double bage,double fage, double ***mobaverage, int mobilav){
                   4568: 
                   4569:   int i, cpt, cptcod;
                   4570:   int modcovmax =1;
                   4571:   int mobilavrange, mob;
                   4572:   double age;
                   4573: 
                   4574:   modcovmax=2*cptcoveff;/* Max number of modalities. We suppose 
                   4575:                           a covariate has 2 modalities */
                   4576:   if (cptcovn<1) modcovmax=1; /* At least 1 pass */
                   4577: 
                   4578:   if(mobilav==1||mobilav ==3 ||mobilav==5 ||mobilav== 7){
                   4579:     if(mobilav==1) mobilavrange=5; /* default */
                   4580:     else mobilavrange=mobilav;
                   4581:     for (age=bage; age<=fage; age++)
                   4582:       for (i=1; i<=nlstate;i++)
                   4583:        for (cptcod=1;cptcod<=modcovmax;cptcod++)
                   4584:          mobaverage[(int)age][i][cptcod]=probs[(int)age][i][cptcod];
                   4585:     /* We keep the original values on the extreme ages bage, fage and for 
                   4586:        fage+1 and bage-1 we use a 3 terms moving average; for fage+2 bage+2
                   4587:        we use a 5 terms etc. until the borders are no more concerned. 
                   4588:     */ 
                   4589:     for (mob=3;mob <=mobilavrange;mob=mob+2){
                   4590:       for (age=bage+(mob-1)/2; age<=fage-(mob-1)/2; age++){
                   4591:        for (i=1; i<=nlstate;i++){
                   4592:          for (cptcod=1;cptcod<=modcovmax;cptcod++){
                   4593:            mobaverage[(int)age][i][cptcod] =probs[(int)age][i][cptcod];
                   4594:              for (cpt=1;cpt<=(mob-1)/2;cpt++){
                   4595:                mobaverage[(int)age][i][cptcod] +=probs[(int)age-cpt][i][cptcod];
                   4596:                mobaverage[(int)age][i][cptcod] +=probs[(int)age+cpt][i][cptcod];
                   4597:              }
                   4598:            mobaverage[(int)age][i][cptcod]=mobaverage[(int)age][i][cptcod]/mob;
                   4599:          }
                   4600:        }
                   4601:       }/* end age */
                   4602:     }/* end mob */
                   4603:   }else return -1;
                   4604:   return 0;
                   4605: }/* End movingaverage */
                   4606: 
                   4607: 
                   4608: /************** Forecasting ******************/
1.169     brouard  4609: 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  4610:   /* proj1, year, month, day of starting projection 
                   4611:      agemin, agemax range of age
                   4612:      dateprev1 dateprev2 range of dates during which prevalence is computed
                   4613:      anproj2 year of en of projection (same day and month as proj1).
                   4614:   */
1.164     brouard  4615:   int yearp, stepsize, hstepm, nhstepm, j, k, cptcod, i, h, i1;
1.126     brouard  4616:   double agec; /* generic age */
                   4617:   double agelim, ppij, yp,yp1,yp2,jprojmean,mprojmean,anprojmean;
                   4618:   double *popeffectif,*popcount;
                   4619:   double ***p3mat;
                   4620:   double ***mobaverage;
                   4621:   char fileresf[FILENAMELENGTH];
                   4622: 
                   4623:   agelim=AGESUP;
                   4624:   prevalence(probs, ageminpar, agemax, s, agev, nlstate, imx, Tvar, nbcode, ncodemax, mint, anint, dateprev1, dateprev2, firstpass, lastpass);
                   4625:  
                   4626:   strcpy(fileresf,"f"); 
                   4627:   strcat(fileresf,fileres);
                   4628:   if((ficresf=fopen(fileresf,"w"))==NULL) {
                   4629:     printf("Problem with forecast resultfile: %s\n", fileresf);
                   4630:     fprintf(ficlog,"Problem with forecast resultfile: %s\n", fileresf);
                   4631:   }
                   4632:   printf("Computing forecasting: result on file '%s' \n", fileresf);
                   4633:   fprintf(ficlog,"Computing forecasting: result on file '%s' \n", fileresf);
                   4634: 
                   4635:   if (cptcoveff==0) ncodemax[cptcoveff]=1;
                   4636: 
                   4637:   if (mobilav!=0) {
                   4638:     mobaverage= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
                   4639:     if (movingaverage(probs, ageminpar, fage, mobaverage,mobilav)!=0){
                   4640:       fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav);
                   4641:       printf(" Error in movingaverage mobilav=%d\n",mobilav);
                   4642:     }
                   4643:   }
                   4644: 
                   4645:   stepsize=(int) (stepm+YEARM-1)/YEARM;
                   4646:   if (stepm<=12) stepsize=1;
                   4647:   if(estepm < stepm){
                   4648:     printf ("Problem %d lower than %d\n",estepm, stepm);
                   4649:   }
                   4650:   else  hstepm=estepm;   
                   4651: 
                   4652:   hstepm=hstepm/stepm; 
                   4653:   yp1=modf(dateintmean,&yp);/* extracts integral of datemean in yp  and
                   4654:                                fractional in yp1 */
                   4655:   anprojmean=yp;
                   4656:   yp2=modf((yp1*12),&yp);
                   4657:   mprojmean=yp;
                   4658:   yp1=modf((yp2*30.5),&yp);
                   4659:   jprojmean=yp;
                   4660:   if(jprojmean==0) jprojmean=1;
                   4661:   if(mprojmean==0) jprojmean=1;
                   4662: 
                   4663:   i1=cptcoveff;
                   4664:   if (cptcovn < 1){i1=1;}
                   4665:   
                   4666:   fprintf(ficresf,"# Mean day of interviews %.lf/%.lf/%.lf (%.2f) between %.2f and %.2f \n",jprojmean,mprojmean,anprojmean,dateintmean,dateprev1,dateprev2); 
                   4667:   
                   4668:   fprintf(ficresf,"#****** Routine prevforecast **\n");
                   4669: 
                   4670: /*           if (h==(int)(YEARM*yearp)){ */
                   4671:   for(cptcov=1, k=0;cptcov<=i1;cptcov++){
                   4672:     for(cptcod=1;cptcod<=ncodemax[cptcoveff];cptcod++){
                   4673:       k=k+1;
                   4674:       fprintf(ficresf,"\n#******");
                   4675:       for(j=1;j<=cptcoveff;j++) {
                   4676:        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]]);
                   4677:       }
                   4678:       fprintf(ficresf,"******\n");
                   4679:       fprintf(ficresf,"# Covariate valuofcovar yearproj age");
                   4680:       for(j=1; j<=nlstate+ndeath;j++){ 
                   4681:        for(i=1; i<=nlstate;i++)              
                   4682:           fprintf(ficresf," p%d%d",i,j);
                   4683:        fprintf(ficresf," p.%d",j);
                   4684:       }
                   4685:       for (yearp=0; yearp<=(anproj2-anproj1);yearp +=stepsize) { 
                   4686:        fprintf(ficresf,"\n");
                   4687:        fprintf(ficresf,"\n# Forecasting at date %.lf/%.lf/%.lf ",jproj1,mproj1,anproj1+yearp);   
                   4688: 
                   4689:        for (agec=fage; agec>=(ageminpar-1); agec--){ 
                   4690:          nhstepm=(int) rint((agelim-agec)*YEARM/stepm); 
                   4691:          nhstepm = nhstepm/hstepm; 
                   4692:          p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   4693:          oldm=oldms;savm=savms;
                   4694:          hpxij(p3mat,nhstepm,agec,hstepm,p,nlstate,stepm,oldm,savm, k);  
                   4695:        
                   4696:          for (h=0; h<=nhstepm; h++){
                   4697:            if (h*hstepm/YEARM*stepm ==yearp) {
                   4698:               fprintf(ficresf,"\n");
                   4699:               for(j=1;j<=cptcoveff;j++) 
                   4700:                 fprintf(ficresf,"%d %d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
                   4701:              fprintf(ficresf,"%.f %.f ",anproj1+yearp,agec+h*hstepm/YEARM*stepm);
                   4702:            } 
                   4703:            for(j=1; j<=nlstate+ndeath;j++) {
                   4704:              ppij=0.;
                   4705:              for(i=1; i<=nlstate;i++) {
                   4706:                if (mobilav==1) 
                   4707:                  ppij=ppij+p3mat[i][j][h]*mobaverage[(int)agec][i][cptcod];
                   4708:                else {
                   4709:                  ppij=ppij+p3mat[i][j][h]*probs[(int)(agec)][i][cptcod];
                   4710:                }
                   4711:                if (h*hstepm/YEARM*stepm== yearp) {
                   4712:                  fprintf(ficresf," %.3f", p3mat[i][j][h]);
                   4713:                }
                   4714:              } /* end i */
                   4715:              if (h*hstepm/YEARM*stepm==yearp) {
                   4716:                fprintf(ficresf," %.3f", ppij);
                   4717:              }
                   4718:            }/* end j */
                   4719:          } /* end h */
                   4720:          free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   4721:        } /* end agec */
                   4722:       } /* end yearp */
                   4723:     } /* end cptcod */
                   4724:   } /* end  cptcov */
                   4725:        
                   4726:   if (mobilav!=0) free_ma3x(mobaverage,1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
                   4727: 
                   4728:   fclose(ficresf);
                   4729: }
                   4730: 
                   4731: /************** Forecasting *****not tested NB*************/
1.169     brouard  4732: 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  4733:   
                   4734:   int cpt, stepsize, hstepm, nhstepm, j,k,c, cptcod, i,h;
                   4735:   int *popage;
                   4736:   double calagedatem, agelim, kk1, kk2;
                   4737:   double *popeffectif,*popcount;
                   4738:   double ***p3mat,***tabpop,***tabpopprev;
                   4739:   double ***mobaverage;
                   4740:   char filerespop[FILENAMELENGTH];
                   4741: 
                   4742:   tabpop= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
                   4743:   tabpopprev= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
                   4744:   agelim=AGESUP;
                   4745:   calagedatem=(anpyram+mpyram/12.+jpyram/365.-dateintmean)*YEARM;
                   4746:   
                   4747:   prevalence(probs, ageminpar, agemax, s, agev, nlstate, imx, Tvar, nbcode, ncodemax, mint, anint, dateprev1, dateprev2, firstpass, lastpass);
                   4748:   
                   4749:   
                   4750:   strcpy(filerespop,"pop"); 
                   4751:   strcat(filerespop,fileres);
                   4752:   if((ficrespop=fopen(filerespop,"w"))==NULL) {
                   4753:     printf("Problem with forecast resultfile: %s\n", filerespop);
                   4754:     fprintf(ficlog,"Problem with forecast resultfile: %s\n", filerespop);
                   4755:   }
                   4756:   printf("Computing forecasting: result on file '%s' \n", filerespop);
                   4757:   fprintf(ficlog,"Computing forecasting: result on file '%s' \n", filerespop);
                   4758: 
                   4759:   if (cptcoveff==0) ncodemax[cptcoveff]=1;
                   4760: 
                   4761:   if (mobilav!=0) {
                   4762:     mobaverage= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
                   4763:     if (movingaverage(probs, ageminpar, fage, mobaverage,mobilav)!=0){
                   4764:       fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav);
                   4765:       printf(" Error in movingaverage mobilav=%d\n",mobilav);
                   4766:     }
                   4767:   }
                   4768: 
                   4769:   stepsize=(int) (stepm+YEARM-1)/YEARM;
                   4770:   if (stepm<=12) stepsize=1;
                   4771:   
                   4772:   agelim=AGESUP;
                   4773:   
                   4774:   hstepm=1;
                   4775:   hstepm=hstepm/stepm; 
                   4776:   
                   4777:   if (popforecast==1) {
                   4778:     if((ficpop=fopen(popfile,"r"))==NULL) {
                   4779:       printf("Problem with population file : %s\n",popfile);exit(0);
                   4780:       fprintf(ficlog,"Problem with population file : %s\n",popfile);exit(0);
                   4781:     } 
                   4782:     popage=ivector(0,AGESUP);
                   4783:     popeffectif=vector(0,AGESUP);
                   4784:     popcount=vector(0,AGESUP);
                   4785:     
                   4786:     i=1;   
                   4787:     while ((c=fscanf(ficpop,"%d %lf\n",&popage[i],&popcount[i])) != EOF) i=i+1;
                   4788:    
                   4789:     imx=i;
                   4790:     for (i=1; i<imx;i++) popeffectif[popage[i]]=popcount[i];
                   4791:   }
                   4792: 
                   4793:   for(cptcov=1,k=0;cptcov<=i2;cptcov++){
                   4794:    for(cptcod=1;cptcod<=ncodemax[cptcoveff];cptcod++){
                   4795:       k=k+1;
                   4796:       fprintf(ficrespop,"\n#******");
                   4797:       for(j=1;j<=cptcoveff;j++) {
                   4798:        fprintf(ficrespop," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
                   4799:       }
                   4800:       fprintf(ficrespop,"******\n");
                   4801:       fprintf(ficrespop,"# Age");
                   4802:       for(j=1; j<=nlstate+ndeath;j++) fprintf(ficrespop," P.%d",j);
                   4803:       if (popforecast==1)  fprintf(ficrespop," [Population]");
                   4804:       
                   4805:       for (cpt=0; cpt<=0;cpt++) { 
                   4806:        fprintf(ficrespop,"\n\n# Forecasting at date %.lf/%.lf/%.lf ",jpyram,mpyram,anpyram+cpt);   
                   4807:        
                   4808:        for (agedeb=(fage-((int)calagedatem %12/12.)); agedeb>=(ageminpar-((int)calagedatem %12)/12.); agedeb--){ 
                   4809:          nhstepm=(int) rint((agelim-agedeb)*YEARM/stepm); 
                   4810:          nhstepm = nhstepm/hstepm; 
                   4811:          
                   4812:          p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   4813:          oldm=oldms;savm=savms;
                   4814:          hpxij(p3mat,nhstepm,agedeb,hstepm,p,nlstate,stepm,oldm,savm, k);  
                   4815:        
                   4816:          for (h=0; h<=nhstepm; h++){
                   4817:            if (h==(int) (calagedatem+YEARM*cpt)) {
                   4818:              fprintf(ficrespop,"\n %3.f ",agedeb+h*hstepm/YEARM*stepm);
                   4819:            } 
                   4820:            for(j=1; j<=nlstate+ndeath;j++) {
                   4821:              kk1=0.;kk2=0;
                   4822:              for(i=1; i<=nlstate;i++) {              
                   4823:                if (mobilav==1) 
                   4824:                  kk1=kk1+p3mat[i][j][h]*mobaverage[(int)agedeb+1][i][cptcod];
                   4825:                else {
                   4826:                  kk1=kk1+p3mat[i][j][h]*probs[(int)(agedeb+1)][i][cptcod];
                   4827:                }
                   4828:              }
                   4829:              if (h==(int)(calagedatem+12*cpt)){
                   4830:                tabpop[(int)(agedeb)][j][cptcod]=kk1;
                   4831:                  /*fprintf(ficrespop," %.3f", kk1);
                   4832:                    if (popforecast==1) fprintf(ficrespop," [%.f]", kk1*popeffectif[(int)agedeb+1]);*/
                   4833:              }
                   4834:            }
                   4835:            for(i=1; i<=nlstate;i++){
                   4836:              kk1=0.;
                   4837:                for(j=1; j<=nlstate;j++){
                   4838:                  kk1= kk1+tabpop[(int)(agedeb)][j][cptcod]; 
                   4839:                }
                   4840:                  tabpopprev[(int)(agedeb)][i][cptcod]=tabpop[(int)(agedeb)][i][cptcod]/kk1*popeffectif[(int)(agedeb+(calagedatem+12*cpt)*hstepm/YEARM*stepm-1)];
                   4841:            }
                   4842: 
                   4843:            if (h==(int)(calagedatem+12*cpt)) for(j=1; j<=nlstate;j++) 
                   4844:              fprintf(ficrespop," %15.2f",tabpopprev[(int)(agedeb+1)][j][cptcod]);
                   4845:          }
                   4846:          free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   4847:        }
                   4848:       }
                   4849:  
                   4850:   /******/
                   4851: 
                   4852:       for (cpt=1; cpt<=(anpyram1-anpyram);cpt++) { 
                   4853:        fprintf(ficrespop,"\n\n# Forecasting at date %.lf/%.lf/%.lf ",jpyram,mpyram,anpyram+cpt);   
                   4854:        for (agedeb=(fage-((int)calagedatem %12/12.)); agedeb>=(ageminpar-((int)calagedatem %12)/12.); agedeb--){ 
                   4855:          nhstepm=(int) rint((agelim-agedeb)*YEARM/stepm); 
                   4856:          nhstepm = nhstepm/hstepm; 
                   4857:          
                   4858:          p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   4859:          oldm=oldms;savm=savms;
                   4860:          hpxij(p3mat,nhstepm,agedeb,hstepm,p,nlstate,stepm,oldm,savm, k);  
                   4861:          for (h=0; h<=nhstepm; h++){
                   4862:            if (h==(int) (calagedatem+YEARM*cpt)) {
                   4863:              fprintf(ficresf,"\n %3.f ",agedeb+h*hstepm/YEARM*stepm);
                   4864:            } 
                   4865:            for(j=1; j<=nlstate+ndeath;j++) {
                   4866:              kk1=0.;kk2=0;
                   4867:              for(i=1; i<=nlstate;i++) {              
                   4868:                kk1=kk1+p3mat[i][j][h]*tabpopprev[(int)agedeb+1][i][cptcod];    
                   4869:              }
                   4870:              if (h==(int)(calagedatem+12*cpt)) fprintf(ficresf," %15.2f", kk1);        
                   4871:            }
                   4872:          }
                   4873:          free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   4874:        }
                   4875:       }
                   4876:    } 
                   4877:   }
                   4878:  
                   4879:   if (mobilav!=0) free_ma3x(mobaverage,1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
                   4880: 
                   4881:   if (popforecast==1) {
                   4882:     free_ivector(popage,0,AGESUP);
                   4883:     free_vector(popeffectif,0,AGESUP);
                   4884:     free_vector(popcount,0,AGESUP);
                   4885:   }
                   4886:   free_ma3x(tabpop,1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
                   4887:   free_ma3x(tabpopprev,1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
                   4888:   fclose(ficrespop);
                   4889: } /* End of popforecast */
                   4890: 
                   4891: int fileappend(FILE *fichier, char *optionfich)
                   4892: {
                   4893:   if((fichier=fopen(optionfich,"a"))==NULL) {
                   4894:     printf("Problem with file: %s\n", optionfich);
                   4895:     fprintf(ficlog,"Problem with file: %s\n", optionfich);
                   4896:     return (0);
                   4897:   }
                   4898:   fflush(fichier);
                   4899:   return (1);
                   4900: }
                   4901: 
                   4902: 
                   4903: /**************** function prwizard **********************/
                   4904: void prwizard(int ncovmodel, int nlstate, int ndeath,  char model[], FILE *ficparo)
                   4905: {
                   4906: 
                   4907:   /* Wizard to print covariance matrix template */
                   4908: 
1.164     brouard  4909:   char ca[32], cb[32];
                   4910:   int i,j, k, li, lj, lk, ll, jj, npar, itimes;
1.126     brouard  4911:   int numlinepar;
                   4912: 
                   4913:   printf("# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
                   4914:   fprintf(ficparo,"# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
                   4915:   for(i=1; i <=nlstate; i++){
                   4916:     jj=0;
                   4917:     for(j=1; j <=nlstate+ndeath; j++){
                   4918:       if(j==i) continue;
                   4919:       jj++;
                   4920:       /*ca[0]= k+'a'-1;ca[1]='\0';*/
                   4921:       printf("%1d%1d",i,j);
                   4922:       fprintf(ficparo,"%1d%1d",i,j);
                   4923:       for(k=1; k<=ncovmodel;k++){
                   4924:        /*        printf(" %lf",param[i][j][k]); */
                   4925:        /*        fprintf(ficparo," %lf",param[i][j][k]); */
                   4926:        printf(" 0.");
                   4927:        fprintf(ficparo," 0.");
                   4928:       }
                   4929:       printf("\n");
                   4930:       fprintf(ficparo,"\n");
                   4931:     }
                   4932:   }
                   4933:   printf("# Scales (for hessian or gradient estimation)\n");
                   4934:   fprintf(ficparo,"# Scales (for hessian or gradient estimation)\n");
                   4935:   npar= (nlstate+ndeath-1)*nlstate*ncovmodel; /* Number of parameters*/ 
                   4936:   for(i=1; i <=nlstate; i++){
                   4937:     jj=0;
                   4938:     for(j=1; j <=nlstate+ndeath; j++){
                   4939:       if(j==i) continue;
                   4940:       jj++;
                   4941:       fprintf(ficparo,"%1d%1d",i,j);
                   4942:       printf("%1d%1d",i,j);
                   4943:       fflush(stdout);
                   4944:       for(k=1; k<=ncovmodel;k++){
                   4945:        /*      printf(" %le",delti3[i][j][k]); */
                   4946:        /*      fprintf(ficparo," %le",delti3[i][j][k]); */
                   4947:        printf(" 0.");
                   4948:        fprintf(ficparo," 0.");
                   4949:       }
                   4950:       numlinepar++;
                   4951:       printf("\n");
                   4952:       fprintf(ficparo,"\n");
                   4953:     }
                   4954:   }
                   4955:   printf("# Covariance matrix\n");
                   4956: /* # 121 Var(a12)\n\ */
                   4957: /* # 122 Cov(b12,a12) Var(b12)\n\ */
                   4958: /* # 131 Cov(a13,a12) Cov(a13,b12, Var(a13)\n\ */
                   4959: /* # 132 Cov(b13,a12) Cov(b13,b12, Cov(b13,a13) Var(b13)\n\ */
                   4960: /* # 212 Cov(a21,a12) Cov(a21,b12, Cov(a21,a13) Cov(a21,b13) Var(a21)\n\ */
                   4961: /* # 212 Cov(b21,a12) Cov(b21,b12, Cov(b21,a13) Cov(b21,b13) Cov(b21,a21) Var(b21)\n\ */
                   4962: /* # 232 Cov(a23,a12) Cov(a23,b12, Cov(a23,a13) Cov(a23,b13) Cov(a23,a21) Cov(a23,b21) Var(a23)\n\ */
                   4963: /* # 232 Cov(b23,a12) Cov(b23,b12) ... Var (b23)\n" */
                   4964:   fflush(stdout);
                   4965:   fprintf(ficparo,"# Covariance matrix\n");
                   4966:   /* # 121 Var(a12)\n\ */
                   4967:   /* # 122 Cov(b12,a12) Var(b12)\n\ */
                   4968:   /* #   ...\n\ */
                   4969:   /* # 232 Cov(b23,a12)  Cov(b23,b12) ... Var (b23)\n" */
                   4970:   
                   4971:   for(itimes=1;itimes<=2;itimes++){
                   4972:     jj=0;
                   4973:     for(i=1; i <=nlstate; i++){
                   4974:       for(j=1; j <=nlstate+ndeath; j++){
                   4975:        if(j==i) continue;
                   4976:        for(k=1; k<=ncovmodel;k++){
                   4977:          jj++;
                   4978:          ca[0]= k+'a'-1;ca[1]='\0';
                   4979:          if(itimes==1){
                   4980:            printf("#%1d%1d%d",i,j,k);
                   4981:            fprintf(ficparo,"#%1d%1d%d",i,j,k);
                   4982:          }else{
                   4983:            printf("%1d%1d%d",i,j,k);
                   4984:            fprintf(ficparo,"%1d%1d%d",i,j,k);
                   4985:            /*  printf(" %.5le",matcov[i][j]); */
                   4986:          }
                   4987:          ll=0;
                   4988:          for(li=1;li <=nlstate; li++){
                   4989:            for(lj=1;lj <=nlstate+ndeath; lj++){
                   4990:              if(lj==li) continue;
                   4991:              for(lk=1;lk<=ncovmodel;lk++){
                   4992:                ll++;
                   4993:                if(ll<=jj){
                   4994:                  cb[0]= lk +'a'-1;cb[1]='\0';
                   4995:                  if(ll<jj){
                   4996:                    if(itimes==1){
                   4997:                      printf(" Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
                   4998:                      fprintf(ficparo," Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
                   4999:                    }else{
                   5000:                      printf(" 0.");
                   5001:                      fprintf(ficparo," 0.");
                   5002:                    }
                   5003:                  }else{
                   5004:                    if(itimes==1){
                   5005:                      printf(" Var(%s%1d%1d)",ca,i,j);
                   5006:                      fprintf(ficparo," Var(%s%1d%1d)",ca,i,j);
                   5007:                    }else{
                   5008:                      printf(" 0.");
                   5009:                      fprintf(ficparo," 0.");
                   5010:                    }
                   5011:                  }
                   5012:                }
                   5013:              } /* end lk */
                   5014:            } /* end lj */
                   5015:          } /* end li */
                   5016:          printf("\n");
                   5017:          fprintf(ficparo,"\n");
                   5018:          numlinepar++;
                   5019:        } /* end k*/
                   5020:       } /*end j */
                   5021:     } /* end i */
                   5022:   } /* end itimes */
                   5023: 
                   5024: } /* end of prwizard */
                   5025: /******************* Gompertz Likelihood ******************************/
                   5026: double gompertz(double x[])
                   5027: { 
                   5028:   double A,B,L=0.0,sump=0.,num=0.;
                   5029:   int i,n=0; /* n is the size of the sample */
                   5030: 
                   5031:   for (i=0;i<=imx-1 ; i++) {
                   5032:     sump=sump+weight[i];
                   5033:     /*    sump=sump+1;*/
                   5034:     num=num+1;
                   5035:   }
                   5036:  
                   5037:  
                   5038:   /* for (i=0; i<=imx; i++) 
                   5039:      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]);*/
                   5040: 
                   5041:   for (i=1;i<=imx ; i++)
                   5042:     {
                   5043:       if (cens[i] == 1 && wav[i]>1)
                   5044:        A=-x[1]/(x[2])*(exp(x[2]*(agecens[i]-agegomp))-exp(x[2]*(ageexmed[i]-agegomp)));
                   5045:       
                   5046:       if (cens[i] == 0 && wav[i]>1)
                   5047:        A=-x[1]/(x[2])*(exp(x[2]*(agedc[i]-agegomp))-exp(x[2]*(ageexmed[i]-agegomp)))
                   5048:             +log(x[1]/YEARM)+x[2]*(agedc[i]-agegomp)+log(YEARM);  
                   5049:       
                   5050:       /*if (wav[i] > 1 && agecens[i] > 15) {*/ /* ??? */
                   5051:       if (wav[i] > 1 ) { /* ??? */
                   5052:        L=L+A*weight[i];
                   5053:        /*      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]);*/
                   5054:       }
                   5055:     }
                   5056: 
                   5057:  /*printf("x1=%2.9f x2=%2.9f x3=%2.9f L=%f\n",x[1],x[2],x[3],L);*/
                   5058:  
                   5059:   return -2*L*num/sump;
                   5060: }
                   5061: 
1.136     brouard  5062: #ifdef GSL
                   5063: /******************* Gompertz_f Likelihood ******************************/
                   5064: double gompertz_f(const gsl_vector *v, void *params)
                   5065: { 
                   5066:   double A,B,LL=0.0,sump=0.,num=0.;
                   5067:   double *x= (double *) v->data;
                   5068:   int i,n=0; /* n is the size of the sample */
                   5069: 
                   5070:   for (i=0;i<=imx-1 ; i++) {
                   5071:     sump=sump+weight[i];
                   5072:     /*    sump=sump+1;*/
                   5073:     num=num+1;
                   5074:   }
                   5075:  
                   5076:  
                   5077:   /* for (i=0; i<=imx; i++) 
                   5078:      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]);*/
                   5079:   printf("x[0]=%lf x[1]=%lf\n",x[0],x[1]);
                   5080:   for (i=1;i<=imx ; i++)
                   5081:     {
                   5082:       if (cens[i] == 1 && wav[i]>1)
                   5083:        A=-x[0]/(x[1])*(exp(x[1]*(agecens[i]-agegomp))-exp(x[1]*(ageexmed[i]-agegomp)));
                   5084:       
                   5085:       if (cens[i] == 0 && wav[i]>1)
                   5086:        A=-x[0]/(x[1])*(exp(x[1]*(agedc[i]-agegomp))-exp(x[1]*(ageexmed[i]-agegomp)))
                   5087:             +log(x[0]/YEARM)+x[1]*(agedc[i]-agegomp)+log(YEARM);  
                   5088:       
                   5089:       /*if (wav[i] > 1 && agecens[i] > 15) {*/ /* ??? */
                   5090:       if (wav[i] > 1 ) { /* ??? */
                   5091:        LL=LL+A*weight[i];
                   5092:        /*      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]);*/
                   5093:       }
                   5094:     }
                   5095: 
                   5096:  /*printf("x1=%2.9f x2=%2.9f x3=%2.9f L=%f\n",x[1],x[2],x[3],L);*/
                   5097:   printf("x[0]=%lf x[1]=%lf -2*LL*num/sump=%lf\n",x[0],x[1],-2*LL*num/sump);
                   5098:  
                   5099:   return -2*LL*num/sump;
                   5100: }
                   5101: #endif
                   5102: 
1.126     brouard  5103: /******************* Printing html file ***********/
                   5104: void printinghtmlmort(char fileres[], char title[], char datafile[], int firstpass, \
                   5105:                  int lastpass, int stepm, int weightopt, char model[],\
                   5106:                  int imx,  double p[],double **matcov,double agemortsup){
                   5107:   int i,k;
                   5108: 
                   5109:   fprintf(fichtm,"<ul><li><h4>Result files </h4>\n Force of mortality. Parameters of the Gompertz fit (with confidence interval in brackets):<br>");
                   5110:   fprintf(fichtm,"  mu(age) =%lf*exp(%lf*(age-%d)) per year<br><br>",p[1],p[2],agegomp);
                   5111:   for (i=1;i<=2;i++) 
                   5112:     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]));
                   5113:   fprintf(fichtm,"<br><br><img src=\"graphmort.png\">");
                   5114:   fprintf(fichtm,"</ul>");
                   5115: 
                   5116: fprintf(fichtm,"<ul><li><h4>Life table</h4>\n <br>");
                   5117: 
                   5118:  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>");
                   5119: 
                   5120:  for (k=agegomp;k<(agemortsup-2);k++) 
                   5121:    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]);
                   5122: 
                   5123:  
                   5124:   fflush(fichtm);
                   5125: }
                   5126: 
                   5127: /******************* Gnuplot file **************/
                   5128: void printinggnuplotmort(char fileres[], char optionfilefiname[], double ageminpar, double agemaxpar, double fage , char pathc[], double p[]){
                   5129: 
                   5130:   char dirfileres[132],optfileres[132];
1.164     brouard  5131: 
1.126     brouard  5132:   int ng;
                   5133: 
                   5134: 
                   5135:   /*#ifdef windows */
                   5136:   fprintf(ficgp,"cd \"%s\" \n",pathc);
                   5137:     /*#endif */
                   5138: 
                   5139: 
                   5140:   strcpy(dirfileres,optionfilefiname);
                   5141:   strcpy(optfileres,"vpl");
                   5142:   fprintf(ficgp,"set out \"graphmort.png\"\n "); 
                   5143:   fprintf(ficgp,"set xlabel \"Age\"\n set ylabel \"Force of mortality (per year)\" \n "); 
1.145     brouard  5144:   fprintf(ficgp, "set ter png small size 320, 240\n set log y\n"); 
                   5145:   /* fprintf(ficgp, "set size 0.65,0.65\n"); */
1.126     brouard  5146:   fprintf(ficgp,"plot [%d:100] %lf*exp(%lf*(x-%d))",agegomp,p[1],p[2],agegomp);
                   5147: 
                   5148: } 
                   5149: 
1.136     brouard  5150: int readdata(char datafile[], int firstobs, int lastobs, int *imax)
                   5151: {
1.126     brouard  5152: 
1.136     brouard  5153:   /*-------- data file ----------*/
                   5154:   FILE *fic;
                   5155:   char dummy[]="                         ";
1.164     brouard  5156:   int i=0, j=0, n=0;
1.136     brouard  5157:   int linei, month, year,iout;
                   5158:   char line[MAXLINE], linetmp[MAXLINE];
1.164     brouard  5159:   char stra[MAXLINE], strb[MAXLINE];
1.136     brouard  5160:   char *stratrunc;
                   5161:   int lstra;
1.126     brouard  5162: 
                   5163: 
1.136     brouard  5164:   if((fic=fopen(datafile,"r"))==NULL)    {
                   5165:     printf("Problem while opening datafile: %s\n", datafile);return 1;
                   5166:     fprintf(ficlog,"Problem while opening datafile: %s\n", datafile);return 1;
                   5167:   }
1.126     brouard  5168: 
1.136     brouard  5169:   i=1;
                   5170:   linei=0;
                   5171:   while ((fgets(line, MAXLINE, fic) != NULL) &&((i >= firstobs) && (i <=lastobs))) {
                   5172:     linei=linei+1;
                   5173:     for(j=strlen(line); j>=0;j--){  /* Untabifies line */
                   5174:       if(line[j] == '\t')
                   5175:        line[j] = ' ';
                   5176:     }
                   5177:     for(j=strlen(line)-1; (line[j]==' ')||(line[j]==10)||(line[j]==13);j--){
                   5178:       ;
                   5179:     };
                   5180:     line[j+1]=0;  /* Trims blanks at end of line */
                   5181:     if(line[0]=='#'){
                   5182:       fprintf(ficlog,"Comment line\n%s\n",line);
                   5183:       printf("Comment line\n%s\n",line);
                   5184:       continue;
                   5185:     }
                   5186:     trimbb(linetmp,line); /* Trims multiple blanks in line */
1.164     brouard  5187:     strcpy(line, linetmp);
1.136     brouard  5188:   
1.126     brouard  5189: 
1.136     brouard  5190:     for (j=maxwav;j>=1;j--){
1.137     brouard  5191:       cutv(stra, strb, line, ' '); 
1.136     brouard  5192:       if(strb[0]=='.') { /* Missing status */
                   5193:        lval=-1;
                   5194:       }else{
                   5195:        errno=0;
                   5196:        lval=strtol(strb,&endptr,10); 
                   5197:       /*       if (errno == ERANGE && (lval == LONG_MAX || lval == LONG_MIN))*/
                   5198:        if( strb[0]=='\0' || (*endptr != '\0')){
1.141     brouard  5199:          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);
                   5200:          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  5201:          return 1;
                   5202:        }
                   5203:       }
                   5204:       s[j][i]=lval;
                   5205:       
                   5206:       strcpy(line,stra);
                   5207:       cutv(stra, strb,line,' ');
1.169     brouard  5208:       if( (iout=sscanf(strb,"%d/%d",&month, &year)) != 0){
1.136     brouard  5209:       }
1.169     brouard  5210:       else  if( (iout=sscanf(strb,"%s.",dummy)) != 0){
1.136     brouard  5211:        month=99;
                   5212:        year=9999;
                   5213:       }else{
1.141     brouard  5214:        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);
                   5215:        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  5216:        return 1;
                   5217:       }
                   5218:       anint[j][i]= (double) year; 
                   5219:       mint[j][i]= (double)month; 
                   5220:       strcpy(line,stra);
                   5221:     } /* ENd Waves */
                   5222:     
                   5223:     cutv(stra, strb,line,' '); 
1.169     brouard  5224:     if( (iout=sscanf(strb,"%d/%d",&month, &year)) != 0){
1.136     brouard  5225:     }
1.169     brouard  5226:     else  if( (iout=sscanf(strb,"%s.",dummy)) != 0){
1.136     brouard  5227:       month=99;
                   5228:       year=9999;
                   5229:     }else{
1.141     brouard  5230:       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);
                   5231:        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  5232:        return 1;
                   5233:     }
                   5234:     andc[i]=(double) year; 
                   5235:     moisdc[i]=(double) month; 
                   5236:     strcpy(line,stra);
                   5237:     
                   5238:     cutv(stra, strb,line,' '); 
1.169     brouard  5239:     if( (iout=sscanf(strb,"%d/%d",&month, &year)) != 0){
1.136     brouard  5240:     }
1.169     brouard  5241:     else  if( (iout=sscanf(strb,"%s.", dummy)) != 0){
1.136     brouard  5242:       month=99;
                   5243:       year=9999;
                   5244:     }else{
1.141     brouard  5245:       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);
                   5246:       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  5247:        return 1;
                   5248:     }
                   5249:     if (year==9999) {
1.141     brouard  5250:       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);
                   5251:       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  5252:        return 1;
1.126     brouard  5253: 
1.136     brouard  5254:     }
                   5255:     annais[i]=(double)(year);
                   5256:     moisnais[i]=(double)(month); 
                   5257:     strcpy(line,stra);
                   5258:     
                   5259:     cutv(stra, strb,line,' '); 
                   5260:     errno=0;
                   5261:     dval=strtod(strb,&endptr); 
                   5262:     if( strb[0]=='\0' || (*endptr != '\0')){
1.141     brouard  5263:       printf("Error reading data around '%f' at line number %d, \"%s\" for individual %d\nShould be a weight.  Exiting.\n",dval, i,line,linei);
                   5264:       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  5265:       fflush(ficlog);
                   5266:       return 1;
                   5267:     }
                   5268:     weight[i]=dval; 
                   5269:     strcpy(line,stra);
                   5270:     
                   5271:     for (j=ncovcol;j>=1;j--){
                   5272:       cutv(stra, strb,line,' '); 
                   5273:       if(strb[0]=='.') { /* Missing status */
                   5274:        lval=-1;
                   5275:       }else{
                   5276:        errno=0;
                   5277:        lval=strtol(strb,&endptr,10); 
                   5278:        if( strb[0]=='\0' || (*endptr != '\0')){
1.141     brouard  5279:          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);
                   5280:          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  5281:          return 1;
                   5282:        }
                   5283:       }
                   5284:       if(lval <-1 || lval >1){
1.141     brouard  5285:        printf("Error reading data around '%ld' at line number %d for individual %d, '%s'\n \
1.136     brouard  5286:  Should be a value of %d(nth) covariate (0 should be the value for the reference and 1\n \
                   5287:  for the alternative. IMaCh does not build design variables automatically, do it yourself.\n \
                   5288:  For example, for multinomial values like 1, 2 and 3,\n \
                   5289:  build V1=0 V2=0 for the reference value (1),\n \
                   5290:         V1=1 V2=0 for (2) \n \
                   5291:  and V1=0 V2=1 for (3). V1=1 V2=1 should not exist and the corresponding\n \
                   5292:  output of IMaCh is often meaningless.\n \
                   5293:  Exiting.\n",lval,linei, i,line,j);
1.141     brouard  5294:        fprintf(ficlog,"Error reading data around '%ld' at line number %d for individual %d, '%s'\n \
1.136     brouard  5295:  Should be a value of %d(nth) covariate (0 should be the value for the reference and 1\n \
                   5296:  for the alternative. IMaCh does not build design variables automatically, do it yourself.\n \
                   5297:  For example, for multinomial values like 1, 2 and 3,\n \
                   5298:  build V1=0 V2=0 for the reference value (1),\n \
                   5299:         V1=1 V2=0 for (2) \n \
                   5300:  and V1=0 V2=1 for (3). V1=1 V2=1 should not exist and the corresponding\n \
                   5301:  output of IMaCh is often meaningless.\n \
                   5302:  Exiting.\n",lval,linei, i,line,j);fflush(ficlog);
                   5303:        return 1;
                   5304:       }
                   5305:       covar[j][i]=(double)(lval);
                   5306:       strcpy(line,stra);
                   5307:     }  
                   5308:     lstra=strlen(stra);
                   5309:      
                   5310:     if(lstra > 9){ /* More than 2**32 or max of what printf can write with %ld */
                   5311:       stratrunc = &(stra[lstra-9]);
                   5312:       num[i]=atol(stratrunc);
                   5313:     }
                   5314:     else
                   5315:       num[i]=atol(stra);
                   5316:     /*if((s[2][i]==2) && (s[3][i]==-1)&&(s[4][i]==9)){
                   5317:       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;}*/
                   5318:     
                   5319:     i=i+1;
                   5320:   } /* End loop reading  data */
1.126     brouard  5321: 
1.136     brouard  5322:   *imax=i-1; /* Number of individuals */
                   5323:   fclose(fic);
                   5324:  
                   5325:   return (0);
1.164     brouard  5326:   /* endread: */
1.136     brouard  5327:     printf("Exiting readdata: ");
                   5328:     fclose(fic);
                   5329:     return (1);
1.126     brouard  5330: 
                   5331: 
                   5332: 
1.136     brouard  5333: }
1.145     brouard  5334: void removespace(char *str) {
                   5335:   char *p1 = str, *p2 = str;
                   5336:   do
                   5337:     while (*p2 == ' ')
                   5338:       p2++;
1.169     brouard  5339:   while (*p1++ == *p2++);
1.145     brouard  5340: }
                   5341: 
                   5342: int decodemodel ( char model[], int lastobs) /**< This routine decode the model and returns:
                   5343:    * Model  V1+V2+V3+V8+V7*V8+V5*V6+V8*age+V3*age
                   5344:    * - cptcovt total number of covariates of the model nbocc(+)+1 = 8
                   5345:    * - cptcovn or number of covariates k of the models excluding age*products =6
                   5346:    * - cptcovage number of covariates with age*products =2
                   5347:    * - cptcovs number of simple covariates
                   5348:    * - 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
                   5349:    *     which is a new column after the 9 (ncovcol) variables. 
                   5350:    * - if k is a product Vn*Vm covar[k][i] is filled with correct values for each individual
                   5351:    * - Tprod[l] gives the kth covariates of the product Vn*Vm l=1 to cptcovprod-cptcovage
                   5352:    *    Tprod[1]@2 {5, 6}: position of first product V7*V8 is 5, and second V5*V6 is 6.
                   5353:    * - Tvard[k]  p Tvard[1][1]@4 {7, 8, 5, 6} for V7*V8 and V5*V6 .
                   5354:  */
1.136     brouard  5355: {
1.145     brouard  5356:   int i, j, k, ks;
1.164     brouard  5357:   int  j1, k1, k2;
1.136     brouard  5358:   char modelsav[80];
1.145     brouard  5359:   char stra[80], strb[80], strc[80], strd[80],stre[80];
1.136     brouard  5360: 
1.145     brouard  5361:   /*removespace(model);*/
1.136     brouard  5362:   if (strlen(model) >1){ /* If there is at least 1 covariate */
1.145     brouard  5363:     j=0, j1=0, k1=0, k2=-1, ks=0, cptcovn=0;
                   5364:     j=nbocc(model,'+'); /**< j=Number of '+' */
                   5365:     j1=nbocc(model,'*'); /**< j1=Number of '*' */
                   5366:     cptcovs=j+1-j1; /**<  Number of simple covariates V1+V2*age+V3 +V3*V4=> V1 + V3 =2  */
                   5367:     cptcovt= j+1; /* Number of total covariates in the model V1 + V2*age+ V3 + V3*V4=> 4*/
                   5368:                   /* including age products which are counted in cptcovage.
1.169     brouard  5369:                  * but the covariates which are products must be treated separately: ncovn=4- 2=2 (V1+V3). */
1.145     brouard  5370:     cptcovprod=j1; /**< Number of products  V1*V2 +v3*age = 2 */
                   5371:     cptcovprodnoage=0; /**< Number of covariate products without age: V3*V4 =1  */
1.136     brouard  5372:     strcpy(modelsav,model); 
1.137     brouard  5373:     if (strstr(model,"AGE") !=0){
                   5374:       printf("Error. AGE must be in lower case 'age' model=%s ",model);
                   5375:       fprintf(ficlog,"Error. AGE must be in lower case model=%s ",model);fflush(ficlog);
1.136     brouard  5376:       return 1;
                   5377:     }
1.141     brouard  5378:     if (strstr(model,"v") !=0){
                   5379:       printf("Error. 'v' must be in upper case 'V' model=%s ",model);
                   5380:       fprintf(ficlog,"Error. 'v' must be in upper case model=%s ",model);fflush(ficlog);
                   5381:       return 1;
                   5382:     }
1.136     brouard  5383:     
1.145     brouard  5384:     /*   Design
                   5385:      *  V1   V2   V3   V4  V5  V6  V7  V8  V9 Weight
                   5386:      *  <          ncovcol=8                >
                   5387:      * Model V2 + V1 + V3*age + V3 + V5*V6 + V7*V8 + V8*age + V8
                   5388:      *   k=  1    2      3       4     5       6      7        8
                   5389:      *  cptcovn number of covariates (not including constant and age ) = # of + plus 1 = 7+1=8
                   5390:      *  covar[k,i], value of kth covariate if not including age for individual i:
                   5391:      *       covar[1][i]= (V2), covar[4][i]=(V3), covar[8][i]=(V8)
                   5392:      *  Tvar[k] # of the kth covariate:  Tvar[1]=2  Tvar[4]=3 Tvar[8]=8
                   5393:      *       if multiplied by age: V3*age Tvar[3=V3*age]=3 (V3) Tvar[7]=8 and 
                   5394:      *  Tage[++cptcovage]=k
                   5395:      *       if products, new covar are created after ncovcol with k1
                   5396:      *  Tvar[k]=ncovcol+k1; # of the kth covariate product:  Tvar[5]=ncovcol+1=10  Tvar[6]=ncovcol+1=11
                   5397:      *  Tprod[k1]=k; Tprod[1]=5 Tprod[2]= 6; gives the position of the k1th product
                   5398:      *  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
                   5399:      *  Tvar[cptcovn+k2]=Tvard[k1][1];Tvar[cptcovn+k2+1]=Tvard[k1][2];
                   5400:      *  Tvar[8+1]=5;Tvar[8+2]=6;Tvar[8+3]=7;Tvar[8+4]=8 inverted
                   5401:      *  V1   V2   V3   V4  V5  V6  V7  V8  V9  V10  V11
                   5402:      *  <          ncovcol=8                >
                   5403:      *       Model V2 + V1 + V3*age + V3 + V5*V6 + V7*V8 + V8*age + V8    d1   d1   d2  d2
                   5404:      *          k=  1    2      3       4     5       6      7        8    9   10   11  12
                   5405:      *     Tvar[k]= 2    1      3       3    10      11      8        8    5    6    7   8
                   5406:      * p Tvar[1]@12={2,   1,     3,      3,   11,     10,     8,       8,   7,   8,   5,  6}
                   5407:      * p Tprod[1]@2={                         6, 5}
                   5408:      *p Tvard[1][1]@4= {7, 8, 5, 6}
                   5409:      * covar[k][i]= V2   V1      ?      V3    V5*V6?   V7*V8?  ?       V8   
                   5410:      *  cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*cov[2];
                   5411:      *How to reorganize?
                   5412:      * Model V1 + V2 + V3 + V8 + V5*V6 + V7*V8 + V3*age + V8*age
                   5413:      * Tvars {2,   1,     3,      3,   11,     10,     8,       8,   7,   8,   5,  6}
                   5414:      *       {2,   1,     4,      8,    5,      6,     3,       7}
                   5415:      * Struct []
                   5416:      */
                   5417: 
1.136     brouard  5418:     /* This loop fills the array Tvar from the string 'model'.*/
                   5419:     /* j is the number of + signs in the model V1+V2+V3 j=2 i=3 to 1 */
1.137     brouard  5420:     /*   modelsav=V2+V1+V4+age*V3 strb=age*V3 stra=V2+V1+V4  */
                   5421:     /*         k=4 (age*V3) Tvar[k=4]= 3 (from V3) Tage[cptcovage=1]=4 */
                   5422:     /*         k=3 V4 Tvar[k=3]= 4 (from V4) */
                   5423:     /*         k=2 V1 Tvar[k=2]= 1 (from V1) */
                   5424:     /*         k=1 Tvar[1]=2 (from V2) */
                   5425:     /*         k=5 Tvar[5] */
                   5426:     /* for (k=1; k<=cptcovn;k++) { */
                   5427:     /*         cov[2+k]=nbcode[Tvar[k]][codtab[ij][Tvar[k]]]; */
                   5428:     /*         } */
                   5429:     /* for (k=1; k<=cptcovage;k++) cov[2+Tage[k]]=cov[2+Tage[k]]*cov[2]; */
1.145     brouard  5430:     /*
                   5431:      * Treating invertedly V2+V1+V3*age+V2*V4 is as if written V2*V4 +V3*age + V1 + V2 */
                   5432:     for(k=cptcovt; k>=1;k--) /**< Number of covariates */
                   5433:         Tvar[k]=0;
                   5434:     cptcovage=0;
                   5435:     for(k=1; k<=cptcovt;k++){ /* Loop on total covariates of the model */
                   5436:       cutl(stra,strb,modelsav,'+'); /* keeps in strb after the first '+' 
                   5437:                                     modelsav==V2+V1+V4+V3*age strb=V3*age stra=V2+V1+V4 */ 
1.137     brouard  5438:       if (nbocc(modelsav,'+')==0) strcpy(strb,modelsav); /* and analyzes it */
1.136     brouard  5439:       /*      printf("i=%d a=%s b=%s sav=%s\n",i, stra,strb,modelsav);*/
                   5440:       /*scanf("%d",i);*/
1.145     brouard  5441:       if (strchr(strb,'*')) {  /**< Model includes a product V2+V1+V4+V3*age strb=V3*age */
                   5442:        cutl(strc,strd,strb,'*'); /**< strd*strc  Vm*Vn: strb=V3*age(input) strc=age strd=V3 ; V3*V2 strc=V2, strd=V3 */
                   5443:        if (strcmp(strc,"age")==0) { /**< Model includes age: Vn*age */
                   5444:          /* covar is not filled and then is empty */
1.136     brouard  5445:          cptcovprod--;
1.145     brouard  5446:          cutl(stre,strb,strd,'V'); /* strd=V3(input): stre="3" */
                   5447:          Tvar[k]=atoi(stre);  /* V2+V1+V4+V3*age Tvar[4]=3 ; V1+V2*age Tvar[2]=2 */
1.136     brouard  5448:          cptcovage++; /* Sums the number of covariates which include age as a product */
1.137     brouard  5449:          Tage[cptcovage]=k;  /* Tage[1] = 4 */
1.136     brouard  5450:          /*printf("stre=%s ", stre);*/
1.137     brouard  5451:        } else if (strcmp(strd,"age")==0) { /* or age*Vn */
1.136     brouard  5452:          cptcovprod--;
1.145     brouard  5453:          cutl(stre,strb,strc,'V');
1.136     brouard  5454:          Tvar[k]=atoi(stre);
                   5455:          cptcovage++;
                   5456:          Tage[cptcovage]=k;
1.137     brouard  5457:        } else {  /* Age is not in the model product V2+V1+V1*V4+V3*age+V3*V2  strb=V3*V2*/
                   5458:          /* loops on k1=1 (V3*V2) and k1=2 V4*V3 */
1.145     brouard  5459:          cptcovn++;
                   5460:          cptcovprodnoage++;k1++;
                   5461:          cutl(stre,strb,strc,'V'); /* strc= Vn, stre is n; strb=V3*V2 stre=3 strc=*/
                   5462:          Tvar[k]=ncovcol+k1; /* For model-covariate k tells which data-covariate to use but
1.137     brouard  5463:                                  because this model-covariate is a construction we invent a new column
                   5464:                                  ncovcol + k1
                   5465:                                  If already ncovcol=4 and model=V2+V1+V1*V4+age*V3+V3*V2
                   5466:                                  Tvar[3=V1*V4]=4+1 Tvar[5=V3*V2]=4 + 2= 6, etc */
1.145     brouard  5467:          cutl(strc,strb,strd,'V'); /* strd was Vm, strc is m */
1.137     brouard  5468:          Tprod[k1]=k;  /* Tprod[1]=3(=V1*V4) for V2+V1+V1*V4+age*V3+V3*V2  */
1.145     brouard  5469:          Tvard[k1][1] =atoi(strc); /* m 1 for V1*/
                   5470:          Tvard[k1][2] =atoi(stre); /* n 4 for V4*/
                   5471:          k2=k2+2;
                   5472:          Tvar[cptcovt+k2]=Tvard[k1][1]; /* Tvar[(cptcovt=4+k2=1)=5]= 1 (V1) */
                   5473:          Tvar[cptcovt+k2+1]=Tvard[k1][2];  /* Tvar[(cptcovt=4+(k2=1)+1)=6]= 4 (V4) */
1.137     brouard  5474:          for (i=1; i<=lastobs;i++){
                   5475:            /* Computes the new covariate which is a product of
1.145     brouard  5476:               covar[n][i]* covar[m][i] and stores it at ncovol+k1 May not be defined */
1.136     brouard  5477:            covar[ncovcol+k1][i]=covar[atoi(stre)][i]*covar[atoi(strc)][i];
1.137     brouard  5478:          }
                   5479:        } /* End age is not in the model */
                   5480:       } /* End if model includes a product */
1.136     brouard  5481:       else { /* no more sum */
                   5482:        /*printf("d=%s c=%s b=%s\n", strd,strc,strb);*/
                   5483:        /*  scanf("%d",i);*/
1.145     brouard  5484:        cutl(strd,strc,strb,'V');
                   5485:        ks++; /**< Number of simple covariates */
                   5486:        cptcovn++;
                   5487:        Tvar[k]=atoi(strd);
1.136     brouard  5488:       }
1.137     brouard  5489:       strcpy(modelsav,stra);  /* modelsav=V2+V1+V4 stra=V2+V1+V4 */ 
1.136     brouard  5490:       /*printf("a=%s b=%s sav=%s\n", stra,strb,modelsav);
                   5491:        scanf("%d",i);*/
                   5492:     } /* end of loop + */
                   5493:   } /* end model */
                   5494:   
                   5495:   /*The number n of Vn is stored in Tvar. cptcovage =number of age covariate. Tage gives the position of age. cptcovprod= number of products.
                   5496:     If model=V1+V1*age then Tvar[1]=1 Tvar[2]=1 cptcovage=1 Tage[1]=2 cptcovprod=0*/
                   5497: 
                   5498:   /* printf("tvar1=%d tvar2=%d tvar3=%d cptcovage=%d Tage=%d",Tvar[1],Tvar[2],Tvar[3],cptcovage,Tage[1]);
                   5499:   printf("cptcovprod=%d ", cptcovprod);
                   5500:   fprintf(ficlog,"cptcovprod=%d ", cptcovprod);
                   5501: 
                   5502:   scanf("%d ",i);*/
                   5503: 
                   5504: 
1.137     brouard  5505:   return (0); /* with covar[new additional covariate if product] and Tage if age */ 
1.164     brouard  5506:   /*endread:*/
1.136     brouard  5507:     printf("Exiting decodemodel: ");
                   5508:     return (1);
                   5509: }
                   5510: 
1.169     brouard  5511: int calandcheckages(int imx, int maxwav, double *agemin, double *agemax, int *nberr, int *nbwarn )
1.136     brouard  5512: {
                   5513:   int i, m;
                   5514: 
                   5515:   for (i=1; i<=imx; i++) {
                   5516:     for(m=2; (m<= maxwav); m++) {
                   5517:       if (((int)mint[m][i]== 99) && (s[m][i] <= nlstate)){
                   5518:        anint[m][i]=9999;
                   5519:        s[m][i]=-1;
                   5520:       }
                   5521:       if((int)moisdc[i]==99 && (int)andc[i]==9999 && s[m][i]>nlstate){
1.169     brouard  5522:        *nberr = *nberr + 1;
                   5523:        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);
                   5524:        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  5525:        s[m][i]=-1;
                   5526:       }
                   5527:       if((int)moisdc[i]==99 && (int)andc[i]!=9999 && s[m][i]>nlstate){
1.169     brouard  5528:        (*nberr)++;
1.136     brouard  5529:        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]); 
                   5530:        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]); 
                   5531:        s[m][i]=-1; /* We prefer to skip it (and to skip it in version 0.8a1 too */
                   5532:       }
                   5533:     }
                   5534:   }
                   5535: 
                   5536:   for (i=1; i<=imx; i++)  {
                   5537:     agedc[i]=(moisdc[i]/12.+andc[i])-(moisnais[i]/12.+annais[i]);
                   5538:     for(m=firstpass; (m<= lastpass); m++){
                   5539:       if(s[m][i] >0 || s[m][i]==-2 || s[m][i]==-4 || s[m][i]==-5){
                   5540:        if (s[m][i] >= nlstate+1) {
1.169     brouard  5541:          if(agedc[i]>0){
                   5542:            if((int)moisdc[i]!=99 && (int)andc[i]!=9999){
1.136     brouard  5543:              agev[m][i]=agedc[i];
                   5544:          /*if(moisdc[i]==99 && andc[i]==9999) s[m][i]=-1;*/
1.169     brouard  5545:            }else {
1.136     brouard  5546:              if ((int)andc[i]!=9999){
                   5547:                nbwarn++;
                   5548:                printf("Warning negative age at death: %ld line:%d\n",num[i],i);
                   5549:                fprintf(ficlog,"Warning negative age at death: %ld line:%d\n",num[i],i);
                   5550:                agev[m][i]=-1;
                   5551:              }
                   5552:            }
1.169     brouard  5553:          } /* agedc > 0 */
1.136     brouard  5554:        }
                   5555:        else if(s[m][i] !=9){ /* Standard case, age in fractional
                   5556:                                 years but with the precision of a month */
                   5557:          agev[m][i]=(mint[m][i]/12.+1./24.+anint[m][i])-(moisnais[i]/12.+1./24.+annais[i]);
                   5558:          if((int)mint[m][i]==99 || (int)anint[m][i]==9999)
                   5559:            agev[m][i]=1;
                   5560:          else if(agev[m][i] < *agemin){ 
                   5561:            *agemin=agev[m][i];
                   5562:            printf(" Min anint[%d][%d]=%.2f annais[%d]=%.2f, agemin=%.2f\n",m,i,anint[m][i], i,annais[i], *agemin);
                   5563:          }
                   5564:          else if(agev[m][i] >*agemax){
                   5565:            *agemax=agev[m][i];
1.156     brouard  5566:            /* printf(" Max anint[%d][%d]=%.0f annais[%d]=%.0f, agemax=%.2f\n",m,i,anint[m][i], i,annais[i], *agemax);*/
1.136     brouard  5567:          }
                   5568:          /*agev[m][i]=anint[m][i]-annais[i];*/
                   5569:          /*     agev[m][i] = age[i]+2*m;*/
                   5570:        }
                   5571:        else { /* =9 */
                   5572:          agev[m][i]=1;
                   5573:          s[m][i]=-1;
                   5574:        }
                   5575:       }
                   5576:       else /*= 0 Unknown */
                   5577:        agev[m][i]=1;
                   5578:     }
                   5579:     
                   5580:   }
                   5581:   for (i=1; i<=imx; i++)  {
                   5582:     for(m=firstpass; (m<=lastpass); m++){
                   5583:       if (s[m][i] > (nlstate+ndeath)) {
1.169     brouard  5584:        (*nberr)++;
1.136     brouard  5585:        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);     
                   5586:        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);     
                   5587:        return 1;
                   5588:       }
                   5589:     }
                   5590:   }
                   5591: 
                   5592:   /*for (i=1; i<=imx; i++){
                   5593:   for (m=firstpass; (m<lastpass); m++){
                   5594:      printf("%ld %d %.lf %d %d\n", num[i],(covar[1][i]),agev[m][i],s[m][i],s[m+1][i]);
                   5595: }
                   5596: 
                   5597: }*/
                   5598: 
                   5599: 
1.139     brouard  5600:   printf("Total number of individuals= %d, Agemin = %.2f, Agemax= %.2f\n\n", imx, *agemin, *agemax);
                   5601:   fprintf(ficlog,"Total number of individuals= %d, Agemin = %.2f, Agemax= %.2f\n\n", imx, *agemin, *agemax); 
1.136     brouard  5602: 
                   5603:   return (0);
1.164     brouard  5604:  /* endread:*/
1.136     brouard  5605:     printf("Exiting calandcheckages: ");
                   5606:     return (1);
                   5607: }
                   5608: 
1.172     brouard  5609: #if defined(_MSC_VER)
                   5610: /*printf("Visual C++ compiler: %s \n;", _MSC_FULL_VER);*/
                   5611: /*fprintf(ficlog, "Visual C++ compiler: %s \n;", _MSC_FULL_VER);*/
                   5612: //#include "stdafx.h"
                   5613: //#include <stdio.h>
                   5614: //#include <tchar.h>
                   5615: //#include <windows.h>
                   5616: //#include <iostream>
                   5617: typedef BOOL(WINAPI *LPFN_ISWOW64PROCESS) (HANDLE, PBOOL);
                   5618: 
                   5619: LPFN_ISWOW64PROCESS fnIsWow64Process;
                   5620: 
                   5621: BOOL IsWow64()
                   5622: {
                   5623:        BOOL bIsWow64 = FALSE;
                   5624: 
                   5625:        //typedef BOOL (APIENTRY *LPFN_ISWOW64PROCESS)
                   5626:        //  (HANDLE, PBOOL);
                   5627: 
                   5628:        //LPFN_ISWOW64PROCESS fnIsWow64Process;
                   5629: 
                   5630:        HMODULE module = GetModuleHandle(_T("kernel32"));
                   5631:        const char funcName[] = "IsWow64Process";
                   5632:        fnIsWow64Process = (LPFN_ISWOW64PROCESS)
                   5633:                GetProcAddress(module, funcName);
                   5634: 
                   5635:        if (NULL != fnIsWow64Process)
                   5636:        {
                   5637:                if (!fnIsWow64Process(GetCurrentProcess(),
                   5638:                        &bIsWow64))
                   5639:                        //throw std::exception("Unknown error");
                   5640:                        printf("Unknown error\n");
                   5641:        }
                   5642:        return bIsWow64 != FALSE;
                   5643: }
                   5644: #endif
1.177     brouard  5645: 
1.169     brouard  5646: void syscompilerinfo()
1.167     brouard  5647:  {
                   5648:    /* #include "syscompilerinfo.h"*/
1.185   ! brouard  5649:    /* command line Intel compiler 32bit windows, XP compatible:*/
        !          5650:    /* /GS /W3 /Gy
        !          5651:       /Zc:wchar_t /Zi /O2 /Fd"Release\vc120.pdb" /D "WIN32" /D "NDEBUG" /D
        !          5652:       "_CONSOLE" /D "_LIB" /D "_USING_V110_SDK71_" /D "_UNICODE" /D
        !          5653:       "UNICODE" /Qipo /Zc:forScope /Gd /Oi /MT /Fa"Release\" /EHsc /nologo
        !          5654:       /Fo"Release\" /Qprof-dir "Release\" /Fp"Release\IMaCh.pch" 
        !          5655:       /* 64 bits */
        !          5656:    /*
        !          5657:      /GS /W3 /Gy
        !          5658:      /Zc:wchar_t /Zi /O2 /Fd"x64\Release\vc120.pdb" /D "WIN32" /D "NDEBUG"
        !          5659:      /D "_CONSOLE" /D "_LIB" /D "_UNICODE" /D "UNICODE" /Qipo /Zc:forScope
        !          5660:      /Oi /MD /Fa"x64\Release\" /EHsc /nologo /Fo"x64\Release\" /Qprof-dir
        !          5661:      "x64\Release\" /Fp"x64\Release\IMaCh.pch" */
        !          5662:    /* Optimization are useless and O3 is slower than O2 */
        !          5663:    /*
        !          5664:      /GS /W3 /Gy /Zc:wchar_t /Zi /O3 /Fd"x64\Release\vc120.pdb" /D "WIN32" 
        !          5665:      /D "NDEBUG" /D "_CONSOLE" /D "_LIB" /D "_UNICODE" /D "UNICODE" /Qipo 
        !          5666:      /Zc:forScope /Oi /MD /Fa"x64\Release\" /EHsc /nologo /Qparallel 
        !          5667:      /Fo"x64\Release\" /Qprof-dir "x64\Release\" /Fp"x64\Release\IMaCh.pch" 
        !          5668:    */
        !          5669:    /* Link is $/ /* /OUT:"visual studio
        !          5670:       2013\Projects\IMaCh\Release\IMaCh.exe" /MANIFEST /NXCOMPAT
        !          5671:       /PDB:"visual studio
        !          5672:       2013\Projects\IMaCh\Release\IMaCh.pdb" /DYNAMICBASE
        !          5673:       "kernel32.lib" "user32.lib" "gdi32.lib" "winspool.lib"
        !          5674:       "comdlg32.lib" "advapi32.lib" "shell32.lib" "ole32.lib"
        !          5675:       "oleaut32.lib" "uuid.lib" "odbc32.lib" "odbccp32.lib"
        !          5676:       /MACHINE:X86 /OPT:REF /SAFESEH /INCREMENTAL:NO
        !          5677:       /SUBSYSTEM:CONSOLE",5.01" /MANIFESTUAC:"level='asInvoker'
        !          5678:       uiAccess='false'"
        !          5679:       /ManifestFile:"Release\IMaCh.exe.intermediate.manifest" /OPT:ICF
        !          5680:       /NOLOGO /TLBID:1
        !          5681:    */
1.177     brouard  5682: #if defined __INTEL_COMPILER
1.178     brouard  5683: #if defined(__GNUC__)
                   5684:        struct utsname sysInfo;  /* For Intel on Linux and OS/X */
                   5685: #endif
1.177     brouard  5686: #elif defined(__GNUC__) 
1.179     brouard  5687: #ifndef  __APPLE__
1.174     brouard  5688: #include <gnu/libc-version.h>  /* Only on gnu */
1.179     brouard  5689: #endif
1.177     brouard  5690:    struct utsname sysInfo;
1.178     brouard  5691:    int cross = CROSS;
                   5692:    if (cross){
                   5693:           printf("Cross-");
                   5694:           fprintf(ficlog, "Cross-");
                   5695:    }
1.174     brouard  5696: #endif
                   5697: 
1.171     brouard  5698: #include <stdint.h>
1.178     brouard  5699: 
1.169     brouard  5700:    printf("Compiled with:");fprintf(ficlog,"Compiled with:");
                   5701: #if defined(__clang__)
                   5702:    printf(" Clang/LLVM");fprintf(ficlog," Clang/LLVM");        /* Clang/LLVM. ---------------------------------------------- */
                   5703: #endif
                   5704: #if defined(__ICC) || defined(__INTEL_COMPILER)
                   5705:    printf(" Intel ICC/ICPC");fprintf(ficlog," Intel ICC/ICPC");/* Intel ICC/ICPC. ------------------------------------------ */
                   5706: #endif
                   5707: #if defined(__GNUC__) || defined(__GNUG__)
                   5708:    printf(" GNU GCC/G++");fprintf(ficlog," GNU GCC/G++");/* GNU GCC/G++. --------------------------------------------- */
                   5709: #endif
                   5710: #if defined(__HP_cc) || defined(__HP_aCC)
                   5711:    printf(" Hewlett-Packard C/aC++");fprintf(fcilog," Hewlett-Packard C/aC++"); /* Hewlett-Packard C/aC++. ---------------------------------- */
                   5712: #endif
                   5713: #if defined(__IBMC__) || defined(__IBMCPP__)
                   5714:    printf(" IBM XL C/C++"); fprintf(ficlog," IBM XL C/C++");/* IBM XL C/C++. -------------------------------------------- */
                   5715: #endif
                   5716: #if defined(_MSC_VER)
                   5717:    printf(" Microsoft Visual Studio");fprintf(ficlog," Microsoft Visual Studio");/* Microsoft Visual Studio. --------------------------------- */
                   5718: #endif
                   5719: #if defined(__PGI)
                   5720:    printf(" Portland Group PGCC/PGCPP");fprintf(ficlog," Portland Group PGCC/PGCPP");/* Portland Group PGCC/PGCPP. ------------------------------- */
                   5721: #endif
                   5722: #if defined(__SUNPRO_C) || defined(__SUNPRO_CC)
                   5723:    printf(" Oracle Solaris Studio");fprintf(ficlog," Oracle Solaris Studio\n");/* Oracle Solaris Studio. ----------------------------------- */
1.167     brouard  5724: #endif
1.174     brouard  5725:    printf(" for ");fprintf(ficlog," for ");
1.169     brouard  5726:    
1.167     brouard  5727: // http://stackoverflow.com/questions/4605842/how-to-identify-platform-compiler-from-preprocessor-macros
                   5728: #ifdef _WIN32 // note the underscore: without it, it's not msdn official!
                   5729:     // Windows (x64 and x86)
1.174     brouard  5730:    printf("Windows (x64 and x86) ");fprintf(ficlog,"Windows (x64 and x86) ");
1.167     brouard  5731: #elif __unix__ // all unices, not all compilers
                   5732:     // Unix
1.174     brouard  5733:    printf("Unix ");fprintf(ficlog,"Unix ");
1.167     brouard  5734: #elif __linux__
                   5735:     // linux
1.174     brouard  5736:    printf("linux ");fprintf(ficlog,"linux ");
1.167     brouard  5737: #elif __APPLE__
1.174     brouard  5738:     // Mac OS, not sure if this is covered by __posix__ and/or __unix__ though..
                   5739:    printf("Mac OS ");fprintf(ficlog,"Mac OS ");
1.167     brouard  5740: #endif
                   5741: 
                   5742: /*  __MINGW32__          */
                   5743: /*  __CYGWIN__  */
                   5744: /* __MINGW64__  */
                   5745: // http://msdn.microsoft.com/en-us/library/b0084kay.aspx
                   5746: /* _MSC_VER  //the Visual C++ compiler is 17.00.51106.1, the _MSC_VER macro evaluates to 1700. Type cl /?  */
                   5747: /* _MSC_FULL_VER //the Visual C++ compiler is 15.00.20706.01, the _MSC_FULL_VER macro evaluates to 150020706 */
                   5748: /* _WIN64  // Defined for applications for Win64. */
                   5749: /* _M_X64 // Defined for compilations that target x64 processors. */
                   5750: /* _DEBUG // Defined when you compile with /LDd, /MDd, and /MTd. */
1.171     brouard  5751: 
1.167     brouard  5752: #if UINTPTR_MAX == 0xffffffff
1.174     brouard  5753:    printf(" 32-bit"); fprintf(ficlog," 32-bit");/* 32-bit */
1.167     brouard  5754: #elif UINTPTR_MAX == 0xffffffffffffffff
1.174     brouard  5755:    printf(" 64-bit"); fprintf(ficlog," 64-bit");/* 64-bit */
1.167     brouard  5756: #else
1.174     brouard  5757:    printf(" wtf-bit"); fprintf(ficlog," wtf-bit");/* wtf */
1.167     brouard  5758: #endif
                   5759: 
1.169     brouard  5760: #if defined(__GNUC__)
                   5761: # if defined(__GNUC_PATCHLEVEL__)
                   5762: #  define __GNUC_VERSION__ (__GNUC__ * 10000 \
                   5763:                             + __GNUC_MINOR__ * 100 \
                   5764:                             + __GNUC_PATCHLEVEL__)
                   5765: # else
                   5766: #  define __GNUC_VERSION__ (__GNUC__ * 10000 \
                   5767:                             + __GNUC_MINOR__ * 100)
                   5768: # endif
1.174     brouard  5769:    printf(" using GNU C version %d.\n", __GNUC_VERSION__);
                   5770:    fprintf(ficlog, " using GNU C version %d.\n", __GNUC_VERSION__);
1.176     brouard  5771: 
                   5772:    if (uname(&sysInfo) != -1) {
                   5773:      printf("Running on: %s %s %s %s %s\n",sysInfo.sysname, sysInfo.nodename, sysInfo.release, sysInfo.version, sysInfo.machine);
                   5774:      fprintf(ficlog,"Running on: %s %s %s %s %s\n ",sysInfo.sysname, sysInfo.nodename, sysInfo.release, sysInfo.version, sysInfo.machine);
                   5775:    }
                   5776:    else
                   5777:       perror("uname() error");
1.179     brouard  5778:    //#ifndef __INTEL_COMPILER 
                   5779: #if !defined (__INTEL_COMPILER) && !defined(__APPLE__)
1.174     brouard  5780:    printf("GNU libc version: %s\n", gnu_get_libc_version()); 
1.179     brouard  5781:    fprintf(ficlog,"GNU libc version: %s\n", gnu_get_libc_version());
1.177     brouard  5782: #endif
1.169     brouard  5783: #endif
1.172     brouard  5784: 
                   5785:    //   void main()
                   5786:    //   {
1.169     brouard  5787: #if defined(_MSC_VER)
1.174     brouard  5788:    if (IsWow64()){
1.176     brouard  5789:           printf("The program (probably compiled for 32bit) is running under WOW64 (64bit) emulation.\n");
                   5790:           fprintf(ficlog, "The program (probably compiled for 32bit) is running under WOW64 (64bit) emulation.\n");
1.174     brouard  5791:    }
                   5792:    else{
1.176     brouard  5793:           printf("The process is not running under WOW64 (i.e probably on a 64bit Windows).\n");
1.178     brouard  5794:           fprintf(ficlog,"The programm is not running under WOW64 (i.e probably on a 64bit Windows).\n");
1.174     brouard  5795:    }
1.172     brouard  5796:    //     printf("\nPress Enter to continue...");
                   5797:    //     getchar();
                   5798:    //   }
                   5799: 
1.169     brouard  5800: #endif
                   5801:    
1.167     brouard  5802: 
                   5803:  }
1.136     brouard  5804: 
1.180     brouard  5805: int prevalence_limit(double *p, double **prlim, double ageminpar, double agemaxpar){
                   5806:   /*--------------- Prevalence limit  (period or stable prevalence) --------------*/
                   5807:   int i, j, k, i1 ;
                   5808:   double ftolpl = 1.e-10;
                   5809:   double age, agebase, agelim;
                   5810: 
                   5811:     strcpy(filerespl,"pl");
                   5812:     strcat(filerespl,fileres);
                   5813:     if((ficrespl=fopen(filerespl,"w"))==NULL) {
                   5814:       printf("Problem with period (stable) prevalence resultfile: %s\n", filerespl);return 1;
                   5815:       fprintf(ficlog,"Problem with period (stable) prevalence resultfile: %s\n", filerespl);return 1;
                   5816:     }
                   5817:     printf("Computing period (stable) prevalence: result on file '%s' \n", filerespl);
                   5818:     fprintf(ficlog,"Computing period (stable) prevalence: result on file '%s' \n", filerespl);
                   5819:     pstamp(ficrespl);
                   5820:     fprintf(ficrespl,"# Period (stable) prevalence \n");
                   5821:     fprintf(ficrespl,"#Age ");
                   5822:     for(i=1; i<=nlstate;i++) fprintf(ficrespl,"%d-%d ",i,i);
                   5823:     fprintf(ficrespl,"\n");
                   5824:   
                   5825:     /* prlim=matrix(1,nlstate,1,nlstate);*/ /* back in main */
                   5826: 
                   5827:     agebase=ageminpar;
                   5828:     agelim=agemaxpar;
                   5829: 
                   5830:     i1=pow(2,cptcoveff);
                   5831:     if (cptcovn < 1){i1=1;}
                   5832: 
                   5833:     for(cptcov=1,k=0;cptcov<=i1;cptcov++){
                   5834:     /* for(cptcov=1,k=0;cptcov<=1;cptcov++){ */
                   5835:       //for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){
                   5836:        k=k+1;
                   5837:        /* to clean */
                   5838:        //printf("cptcov=%d cptcod=%d codtab=%d\n",cptcov, cptcod,codtab[cptcod][cptcov]);
                   5839:        fprintf(ficrespl,"\n#******");
                   5840:        printf("\n#******");
                   5841:        fprintf(ficlog,"\n#******");
                   5842:        for(j=1;j<=cptcoveff;j++) {
                   5843:          fprintf(ficrespl," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
                   5844:          printf(" V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
                   5845:          fprintf(ficlog," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
                   5846:        }
                   5847:        fprintf(ficrespl,"******\n");
                   5848:        printf("******\n");
                   5849:        fprintf(ficlog,"******\n");
                   5850: 
                   5851:        fprintf(ficrespl,"#Age ");
                   5852:        for(j=1;j<=cptcoveff;j++) {
                   5853:          fprintf(ficrespl,"V%d %d",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
                   5854:        }
                   5855:        for(i=1; i<=nlstate;i++) fprintf(ficrespl,"%d-%d ",i,i);
                   5856:        fprintf(ficrespl,"\n");
                   5857:        
                   5858:        for (age=agebase; age<=agelim; age++){
                   5859:        /* for (age=agebase; age<=agebase; age++){ */
                   5860:          prevalim(prlim, nlstate, p, age, oldm, savm,ftolpl,k);
                   5861:          fprintf(ficrespl,"%.0f ",age );
                   5862:          for(j=1;j<=cptcoveff;j++)
                   5863:            fprintf(ficrespl,"%d %d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
                   5864:          for(i=1; i<=nlstate;i++)
                   5865:            fprintf(ficrespl," %.5f", prlim[i][i]);
                   5866:          fprintf(ficrespl,"\n");
                   5867:        } /* Age */
                   5868:        /* was end of cptcod */
                   5869:     } /* cptcov */
1.184     brouard  5870:        return 0;
1.180     brouard  5871: }
                   5872: 
                   5873: int hPijx(double *p, int bage, int fage){
                   5874:     /*------------- h Pij x at various ages ------------*/
                   5875: 
                   5876:   int stepsize;
                   5877:   int agelim;
                   5878:   int hstepm;
                   5879:   int nhstepm;
                   5880:   int h, i, i1, j, k;
                   5881: 
                   5882:   double agedeb;
                   5883:   double ***p3mat;
                   5884: 
                   5885:     strcpy(filerespij,"pij");  strcat(filerespij,fileres);
                   5886:     if((ficrespij=fopen(filerespij,"w"))==NULL) {
                   5887:       printf("Problem with Pij resultfile: %s\n", filerespij); return 1;
                   5888:       fprintf(ficlog,"Problem with Pij resultfile: %s\n", filerespij); return 1;
                   5889:     }
                   5890:     printf("Computing pij: result on file '%s' \n", filerespij);
                   5891:     fprintf(ficlog,"Computing pij: result on file '%s' \n", filerespij);
                   5892:   
                   5893:     stepsize=(int) (stepm+YEARM-1)/YEARM;
                   5894:     /*if (stepm<=24) stepsize=2;*/
                   5895: 
                   5896:     agelim=AGESUP;
                   5897:     hstepm=stepsize*YEARM; /* Every year of age */
                   5898:     hstepm=hstepm/stepm; /* Typically 2 years, = 2/6 months = 4 */ 
                   5899: 
                   5900:     /* hstepm=1;   aff par mois*/
                   5901:     pstamp(ficrespij);
                   5902:     fprintf(ficrespij,"#****** h Pij x Probability to be in state j at age x+h being in i at x ");
                   5903:     i1= pow(2,cptcoveff);
1.183     brouard  5904:    /* for(cptcov=1,k=0;cptcov<=i1;cptcov++){ */
                   5905:    /*    /\*for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){*\/ */
                   5906:    /*          k=k+1;  */
                   5907:     for (k=1; k <= (int) pow(2,cptcoveff); k++){
                   5908:       fprintf(ficrespij,"\n#****** ");
                   5909:       for(j=1;j<=cptcoveff;j++) 
                   5910:        fprintf(ficrespij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
                   5911:       fprintf(ficrespij,"******\n");
                   5912:       
                   5913:       for (agedeb=fage; agedeb>=bage; agedeb--){ /* If stepm=6 months */
                   5914:        nhstepm=(int) rint((agelim-agedeb)*YEARM/stepm); /* Typically 20 years = 20*12/6=40 */ 
                   5915:        nhstepm = nhstepm/hstepm; /* Typically 40/4=10 */
                   5916:        
                   5917:        /*        nhstepm=nhstepm*YEARM; aff par mois*/
1.180     brouard  5918:        
1.183     brouard  5919:        p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   5920:        oldm=oldms;savm=savms;
                   5921:        hpxij(p3mat,nhstepm,agedeb,hstepm,p,nlstate,stepm,oldm,savm, k);  
                   5922:        fprintf(ficrespij,"# Cov Agex agex+h hpijx with i,j=");
                   5923:        for(i=1; i<=nlstate;i++)
                   5924:          for(j=1; j<=nlstate+ndeath;j++)
                   5925:            fprintf(ficrespij," %1d-%1d",i,j);
                   5926:        fprintf(ficrespij,"\n");
                   5927:        for (h=0; h<=nhstepm; h++){
                   5928:          /*agedebphstep = agedeb + h*hstepm/YEARM*stepm;*/
                   5929:          fprintf(ficrespij,"%d %3.f %3.f",k, agedeb, agedeb + h*hstepm/YEARM*stepm );
1.180     brouard  5930:          for(i=1; i<=nlstate;i++)
                   5931:            for(j=1; j<=nlstate+ndeath;j++)
1.183     brouard  5932:              fprintf(ficrespij," %.5f", p3mat[i][j][h]);
1.180     brouard  5933:          fprintf(ficrespij,"\n");
                   5934:        }
1.183     brouard  5935:        free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   5936:        fprintf(ficrespij,"\n");
                   5937:       }
1.180     brouard  5938:       /*}*/
                   5939:     }
1.184     brouard  5940:        return 0;
1.180     brouard  5941: }
                   5942: 
                   5943: 
1.136     brouard  5944: /***********************************************/
                   5945: /**************** Main Program *****************/
                   5946: /***********************************************/
                   5947: 
                   5948: int main(int argc, char *argv[])
                   5949: {
                   5950: #ifdef GSL
                   5951:   const gsl_multimin_fminimizer_type *T;
                   5952:   size_t iteri = 0, it;
                   5953:   int rval = GSL_CONTINUE;
                   5954:   int status = GSL_SUCCESS;
                   5955:   double ssval;
                   5956: #endif
                   5957:   int movingaverage(double ***probs, double bage,double fage, double ***mobaverage, int mobilav);
1.164     brouard  5958:   int i,j, k, n=MAXN,iter=0,m,size=100, cptcod;
                   5959: 
                   5960:   int jj, ll, li, lj, lk;
1.136     brouard  5961:   int numlinepar=0; /* Current linenumber of parameter file */
                   5962:   int itimes;
                   5963:   int NDIM=2;
                   5964:   int vpopbased=0;
                   5965: 
1.164     brouard  5966:   char ca[32], cb[32];
1.136     brouard  5967:   /*  FILE *fichtm; *//* Html File */
                   5968:   /* FILE *ficgp;*/ /*Gnuplot File */
                   5969:   struct stat info;
1.164     brouard  5970:   double agedeb;
1.136     brouard  5971:   double ageminpar=1.e20,agemin=1.e20, agemaxpar=-1.e20, agemax=-1.e20;
                   5972: 
1.165     brouard  5973:   double fret;
1.136     brouard  5974:   double dum; /* Dummy variable */
                   5975:   double ***p3mat;
                   5976:   double ***mobaverage;
1.164     brouard  5977: 
                   5978:   char line[MAXLINE];
1.136     brouard  5979:   char path[MAXLINE],pathc[MAXLINE],pathcd[MAXLINE],pathtot[MAXLINE],model[MAXLINE];
                   5980:   char pathr[MAXLINE], pathimach[MAXLINE]; 
1.164     brouard  5981:   char *tok, *val; /* pathtot */
1.136     brouard  5982:   int firstobs=1, lastobs=10;
1.164     brouard  5983:   int c,  h , cpt;
                   5984:   int jl;
                   5985:   int i1, j1, jk, stepsize;
                   5986:   int *tab; 
1.136     brouard  5987:   int mobilavproj=0 , prevfcast=0 ; /* moving average of prev, If prevfcast=1 prevalence projection */
                   5988:   int mobilav=0,popforecast=0;
                   5989:   int hstepm, nhstepm;
                   5990:   int agemortsup;
                   5991:   float  sumlpop=0.;
                   5992:   double jprev1=1, mprev1=1,anprev1=2000,jprev2=1, mprev2=1,anprev2=2000;
                   5993:   double jpyram=1, mpyram=1,anpyram=2000,jpyram1=1, mpyram1=1,anpyram1=2000;
                   5994: 
1.164     brouard  5995:   double bage=0, fage=110, age, agelim, agebase;
1.136     brouard  5996:   double ftolpl=FTOL;
                   5997:   double **prlim;
                   5998:   double ***param; /* Matrix of parameters */
                   5999:   double  *p;
                   6000:   double **matcov; /* Matrix of covariance */
                   6001:   double ***delti3; /* Scale */
                   6002:   double *delti; /* Scale */
                   6003:   double ***eij, ***vareij;
                   6004:   double **varpl; /* Variances of prevalence limits by age */
                   6005:   double *epj, vepp;
1.164     brouard  6006: 
1.136     brouard  6007:   double dateprev1, dateprev2,jproj1=1,mproj1=1,anproj1=2000,jproj2=1,mproj2=1,anproj2=2000;
                   6008:   double **ximort;
1.145     brouard  6009:   char *alph[]={"a","a","b","c","d","e"}, str[4]="1234";
1.136     brouard  6010:   int *dcwave;
                   6011: 
1.164     brouard  6012:   char z[1]="c";
1.136     brouard  6013: 
                   6014:   /*char  *strt;*/
                   6015:   char strtend[80];
1.126     brouard  6016: 
1.164     brouard  6017: 
1.126     brouard  6018: /*   setlocale (LC_ALL, ""); */
                   6019: /*   bindtextdomain (PACKAGE, LOCALEDIR); */
                   6020: /*   textdomain (PACKAGE); */
                   6021: /*   setlocale (LC_CTYPE, ""); */
                   6022: /*   setlocale (LC_MESSAGES, ""); */
                   6023: 
                   6024:   /*   gettimeofday(&start_time, (struct timezone*)0); */ /* at first time */
1.157     brouard  6025:   rstart_time = time(NULL);  
                   6026:   /*  (void) gettimeofday(&start_time,&tzp);*/
                   6027:   start_time = *localtime(&rstart_time);
1.126     brouard  6028:   curr_time=start_time;
1.157     brouard  6029:   /*tml = *localtime(&start_time.tm_sec);*/
                   6030:   /* strcpy(strstart,asctime(&tml)); */
                   6031:   strcpy(strstart,asctime(&start_time));
1.126     brouard  6032: 
                   6033: /*  printf("Localtime (at start)=%s",strstart); */
1.157     brouard  6034: /*  tp.tm_sec = tp.tm_sec +86400; */
                   6035: /*  tm = *localtime(&start_time.tm_sec); */
1.126     brouard  6036: /*   tmg.tm_year=tmg.tm_year +dsign*dyear; */
                   6037: /*   tmg.tm_mon=tmg.tm_mon +dsign*dmonth; */
                   6038: /*   tmg.tm_hour=tmg.tm_hour + 1; */
1.157     brouard  6039: /*   tp.tm_sec = mktime(&tmg); */
1.126     brouard  6040: /*   strt=asctime(&tmg); */
                   6041: /*   printf("Time(after) =%s",strstart);  */
                   6042: /*  (void) time (&time_value);
                   6043: *  printf("time=%d,t-=%d\n",time_value,time_value-86400);
                   6044: *  tm = *localtime(&time_value);
                   6045: *  strstart=asctime(&tm);
                   6046: *  printf("tim_value=%d,asctime=%s\n",time_value,strstart); 
                   6047: */
                   6048: 
                   6049:   nberr=0; /* Number of errors and warnings */
                   6050:   nbwarn=0;
1.184     brouard  6051: #ifdef WIN32
                   6052:   _getcwd(pathcd, size);
                   6053: #else
1.126     brouard  6054:   getcwd(pathcd, size);
1.184     brouard  6055: #endif
1.126     brouard  6056: 
                   6057:   printf("\n%s\n%s",version,fullversion);
                   6058:   if(argc <=1){
                   6059:     printf("\nEnter the parameter file name: ");
                   6060:     fgets(pathr,FILENAMELENGTH,stdin);
                   6061:     i=strlen(pathr);
                   6062:     if(pathr[i-1]=='\n')
                   6063:       pathr[i-1]='\0';
1.156     brouard  6064:     i=strlen(pathr);
                   6065:     if(pathr[i-1]==' ') /* This may happen when dragging on oS/X! */
                   6066:       pathr[i-1]='\0';
1.126     brouard  6067:    for (tok = pathr; tok != NULL; ){
                   6068:       printf("Pathr |%s|\n",pathr);
                   6069:       while ((val = strsep(&tok, "\"" )) != NULL && *val == '\0');
                   6070:       printf("val= |%s| pathr=%s\n",val,pathr);
                   6071:       strcpy (pathtot, val);
                   6072:       if(pathr[0] == '\0') break; /* Dirty */
                   6073:     }
                   6074:   }
                   6075:   else{
                   6076:     strcpy(pathtot,argv[1]);
                   6077:   }
                   6078:   /*if(getcwd(pathcd, MAXLINE)!= NULL)printf ("Error pathcd\n");*/
                   6079:   /*cygwin_split_path(pathtot,path,optionfile);
                   6080:     printf("pathtot=%s, path=%s, optionfile=%s\n",pathtot,path,optionfile);*/
                   6081:   /* cutv(path,optionfile,pathtot,'\\');*/
                   6082: 
                   6083:   /* Split argv[0], imach program to get pathimach */
                   6084:   printf("\nargv[0]=%s argv[1]=%s, \n",argv[0],argv[1]);
                   6085:   split(argv[0],pathimach,optionfile,optionfilext,optionfilefiname);
                   6086:   printf("\nargv[0]=%s pathimach=%s, \noptionfile=%s \noptionfilext=%s \noptionfilefiname=%s\n",argv[0],pathimach,optionfile,optionfilext,optionfilefiname);
                   6087:  /*   strcpy(pathimach,argv[0]); */
                   6088:   /* Split argv[1]=pathtot, parameter file name to get path, optionfile, extension and name */
                   6089:   split(pathtot,path,optionfile,optionfilext,optionfilefiname);
                   6090:   printf("\npathtot=%s,\npath=%s,\noptionfile=%s \noptionfilext=%s \noptionfilefiname=%s\n",pathtot,path,optionfile,optionfilext,optionfilefiname);
1.184     brouard  6091: #ifdef WIN32
                   6092:   _chdir(path); /* Can be a relative path */
                   6093:   if(_getcwd(pathcd,MAXLINE) > 0) /* So pathcd is the full path */
                   6094: #else
1.126     brouard  6095:   chdir(path); /* Can be a relative path */
1.184     brouard  6096:   if (getcwd(pathcd, MAXLINE) > 0) /* So pathcd is the full path */
                   6097: #endif
                   6098:   printf("Current directory %s!\n",pathcd);
1.126     brouard  6099:   strcpy(command,"mkdir ");
                   6100:   strcat(command,optionfilefiname);
                   6101:   if((outcmd=system(command)) != 0){
1.169     brouard  6102:     printf("Directory already exists (or can't create it) %s%s, err=%d\n",path,optionfilefiname,outcmd);
1.126     brouard  6103:     /* fprintf(ficlog,"Problem creating directory %s%s\n",path,optionfilefiname); */
                   6104:     /* fclose(ficlog); */
                   6105: /*     exit(1); */
                   6106:   }
                   6107: /*   if((imk=mkdir(optionfilefiname))<0){ */
                   6108: /*     perror("mkdir"); */
                   6109: /*   } */
                   6110: 
                   6111:   /*-------- arguments in the command line --------*/
                   6112: 
                   6113:   /* Log file */
                   6114:   strcat(filelog, optionfilefiname);
                   6115:   strcat(filelog,".log");    /* */
                   6116:   if((ficlog=fopen(filelog,"w"))==NULL)    {
                   6117:     printf("Problem with logfile %s\n",filelog);
                   6118:     goto end;
                   6119:   }
                   6120:   fprintf(ficlog,"Log filename:%s\n",filelog);
                   6121:   fprintf(ficlog,"\n%s\n%s",version,fullversion);
                   6122:   fprintf(ficlog,"\nEnter the parameter file name: \n");
                   6123:   fprintf(ficlog,"pathimach=%s\npathtot=%s\n\
                   6124:  path=%s \n\
                   6125:  optionfile=%s\n\
                   6126:  optionfilext=%s\n\
1.156     brouard  6127:  optionfilefiname='%s'\n",pathimach,pathtot,path,optionfile,optionfilext,optionfilefiname);
1.126     brouard  6128: 
1.167     brouard  6129:   syscompilerinfo();
                   6130: 
1.126     brouard  6131:   printf("Local time (at start):%s",strstart);
                   6132:   fprintf(ficlog,"Local time (at start): %s",strstart);
                   6133:   fflush(ficlog);
                   6134: /*   (void) gettimeofday(&curr_time,&tzp); */
1.157     brouard  6135: /*   printf("Elapsed time %d\n", asc_diff_time(curr_time.tm_sec-start_time.tm_sec,tmpout)); */
1.126     brouard  6136: 
                   6137:   /* */
                   6138:   strcpy(fileres,"r");
                   6139:   strcat(fileres, optionfilefiname);
                   6140:   strcat(fileres,".txt");    /* Other files have txt extension */
                   6141: 
                   6142:   /*---------arguments file --------*/
                   6143: 
                   6144:   if((ficpar=fopen(optionfile,"r"))==NULL)    {
1.155     brouard  6145:     printf("Problem with optionfile '%s' with errno='%s'\n",optionfile,strerror(errno));
                   6146:     fprintf(ficlog,"Problem with optionfile '%s' with errno='%s'\n",optionfile,strerror(errno));
1.126     brouard  6147:     fflush(ficlog);
1.149     brouard  6148:     /* goto end; */
                   6149:     exit(70); 
1.126     brouard  6150:   }
                   6151: 
                   6152: 
                   6153: 
                   6154:   strcpy(filereso,"o");
                   6155:   strcat(filereso,fileres);
                   6156:   if((ficparo=fopen(filereso,"w"))==NULL) { /* opened on subdirectory */
                   6157:     printf("Problem with Output resultfile: %s\n", filereso);
                   6158:     fprintf(ficlog,"Problem with Output resultfile: %s\n", filereso);
                   6159:     fflush(ficlog);
                   6160:     goto end;
                   6161:   }
                   6162: 
                   6163:   /* Reads comments: lines beginning with '#' */
                   6164:   numlinepar=0;
                   6165:   while((c=getc(ficpar))=='#' && c!= EOF){
                   6166:     ungetc(c,ficpar);
                   6167:     fgets(line, MAXLINE, ficpar);
                   6168:     numlinepar++;
1.141     brouard  6169:     fputs(line,stdout);
1.126     brouard  6170:     fputs(line,ficparo);
                   6171:     fputs(line,ficlog);
                   6172:   }
                   6173:   ungetc(c,ficpar);
                   6174: 
                   6175:   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=%s\n",title, datafile, &lastobs, &firstpass,&lastpass,&ftol, &stepm, &ncovcol, &nlstate,&ndeath, &maxwav, &mle, &weightopt,model);
                   6176:   numlinepar++;
                   6177:   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=%s\n", title, datafile, lastobs, firstpass,lastpass,ftol, stepm, ncovcol, nlstate,ndeath, maxwav, mle, weightopt,model);
                   6178:   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=%s\n", title, datafile, lastobs, firstpass,lastpass,ftol,stepm,ncovcol,nlstate,ndeath,maxwav, mle, weightopt,model);
                   6179:   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=%s\n", title, datafile, lastobs, firstpass,lastpass,ftol,stepm,ncovcol,nlstate,ndeath,maxwav, mle, weightopt,model);
                   6180:   fflush(ficlog);
                   6181:   while((c=getc(ficpar))=='#' && c!= EOF){
                   6182:     ungetc(c,ficpar);
                   6183:     fgets(line, MAXLINE, ficpar);
                   6184:     numlinepar++;
1.141     brouard  6185:     fputs(line, stdout);
                   6186:     //puts(line);
1.126     brouard  6187:     fputs(line,ficparo);
                   6188:     fputs(line,ficlog);
                   6189:   }
                   6190:   ungetc(c,ficpar);
                   6191: 
                   6192:    
1.145     brouard  6193:   covar=matrix(0,NCOVMAX,1,n);  /**< used in readdata */
1.136     brouard  6194:   cptcovn=0; /*Number of covariates, i.e. number of '+' in model statement plus one, indepently of n in Vn*/
                   6195:   /* v1+v2+v3+v2*v4+v5*age makes cptcovn = 5
                   6196:      v1+v2*age+v2*v3 makes cptcovn = 3
                   6197:   */
                   6198:   if (strlen(model)>1) 
1.145     brouard  6199:     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*/
                   6200:   else
                   6201:     ncovmodel=2;
1.126     brouard  6202:   nvar=ncovmodel-1; /* Suppressing age as a basic covariate */
1.133     brouard  6203:   nforce= (nlstate+ndeath-1)*nlstate; /* Number of forces ij from state i to j */
                   6204:   npar= nforce*ncovmodel; /* Number of parameters like aij*/
1.131     brouard  6205:   if(npar >MAXPARM || nlstate >NLSTATEMAX || ndeath >NDEATHMAX || ncovmodel>NCOVMAX){
                   6206:     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);
                   6207:     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);
                   6208:     fflush(stdout);
                   6209:     fclose (ficlog);
                   6210:     goto end;
                   6211:   }
1.126     brouard  6212:   delti3= ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel);
                   6213:   delti=delti3[1][1];
                   6214:   /*delti=vector(1,npar); *//* Scale of each paramater (output from hesscov)*/
                   6215:   if(mle==-1){ /* Print a wizard for help writing covariance matrix */
                   6216:     prwizard(ncovmodel, nlstate, ndeath, model, ficparo);
                   6217:     printf(" You choose mle=-1, look at file %s for a template of covariance matrix \n",filereso);
                   6218:     fprintf(ficlog," You choose mle=-1, look at file %s for a template of covariance matrix \n",filereso);
                   6219:     free_ma3x(delti3,1,nlstate,1, nlstate+ndeath-1,1,ncovmodel); 
                   6220:     fclose (ficparo);
                   6221:     fclose (ficlog);
                   6222:     goto end;
                   6223:     exit(0);
                   6224:   }
                   6225:   else if(mle==-3) {
                   6226:     prwizard(ncovmodel, nlstate, ndeath, model, ficparo);
                   6227:     printf(" You choose mle=-3, look at file %s for a template of covariance matrix \n",filereso);
                   6228:     fprintf(ficlog," You choose mle=-3, look at file %s for a template of covariance matrix \n",filereso);
                   6229:     param= ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel);
                   6230:     matcov=matrix(1,npar,1,npar);
                   6231:   }
                   6232:   else{
1.145     brouard  6233:     /* Read guessed parameters */
1.126     brouard  6234:     /* Reads comments: lines beginning with '#' */
                   6235:     while((c=getc(ficpar))=='#' && c!= EOF){
                   6236:       ungetc(c,ficpar);
                   6237:       fgets(line, MAXLINE, ficpar);
                   6238:       numlinepar++;
1.141     brouard  6239:       fputs(line,stdout);
1.126     brouard  6240:       fputs(line,ficparo);
                   6241:       fputs(line,ficlog);
                   6242:     }
                   6243:     ungetc(c,ficpar);
                   6244:     
                   6245:     param= ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel);
                   6246:     for(i=1; i <=nlstate; i++){
                   6247:       j=0;
                   6248:       for(jj=1; jj <=nlstate+ndeath; jj++){
                   6249:        if(jj==i) continue;
                   6250:        j++;
                   6251:        fscanf(ficpar,"%1d%1d",&i1,&j1);
                   6252:        if ((i1 != i) && (j1 != j)){
                   6253:          printf("Error in line parameters number %d, %1d%1d instead of %1d%1d \n \
                   6254: It might be a problem of design; if ncovcol and the model are correct\n \
                   6255: run imach with mle=-1 to get a correct template of the parameter file.\n",numlinepar, i,j, i1, j1);
                   6256:          exit(1);
                   6257:        }
                   6258:        fprintf(ficparo,"%1d%1d",i1,j1);
                   6259:        if(mle==1)
                   6260:          printf("%1d%1d",i,j);
                   6261:        fprintf(ficlog,"%1d%1d",i,j);
                   6262:        for(k=1; k<=ncovmodel;k++){
                   6263:          fscanf(ficpar," %lf",&param[i][j][k]);
                   6264:          if(mle==1){
                   6265:            printf(" %lf",param[i][j][k]);
                   6266:            fprintf(ficlog," %lf",param[i][j][k]);
                   6267:          }
                   6268:          else
                   6269:            fprintf(ficlog," %lf",param[i][j][k]);
                   6270:          fprintf(ficparo," %lf",param[i][j][k]);
                   6271:        }
                   6272:        fscanf(ficpar,"\n");
                   6273:        numlinepar++;
                   6274:        if(mle==1)
                   6275:          printf("\n");
                   6276:        fprintf(ficlog,"\n");
                   6277:        fprintf(ficparo,"\n");
                   6278:       }
                   6279:     }  
                   6280:     fflush(ficlog);
                   6281: 
1.145     brouard  6282:     /* Reads scales values */
1.126     brouard  6283:     p=param[1][1];
                   6284:     
                   6285:     /* Reads comments: lines beginning with '#' */
                   6286:     while((c=getc(ficpar))=='#' && c!= EOF){
                   6287:       ungetc(c,ficpar);
                   6288:       fgets(line, MAXLINE, ficpar);
                   6289:       numlinepar++;
1.141     brouard  6290:       fputs(line,stdout);
1.126     brouard  6291:       fputs(line,ficparo);
                   6292:       fputs(line,ficlog);
                   6293:     }
                   6294:     ungetc(c,ficpar);
                   6295: 
                   6296:     for(i=1; i <=nlstate; i++){
                   6297:       for(j=1; j <=nlstate+ndeath-1; j++){
                   6298:        fscanf(ficpar,"%1d%1d",&i1,&j1);
1.164     brouard  6299:        if ( (i1-i) * (j1-j) != 0){
1.126     brouard  6300:          printf("Error in line parameters number %d, %1d%1d instead of %1d%1d \n",numlinepar, i,j, i1, j1);
                   6301:          exit(1);
                   6302:        }
                   6303:        printf("%1d%1d",i,j);
                   6304:        fprintf(ficparo,"%1d%1d",i1,j1);
                   6305:        fprintf(ficlog,"%1d%1d",i1,j1);
                   6306:        for(k=1; k<=ncovmodel;k++){
                   6307:          fscanf(ficpar,"%le",&delti3[i][j][k]);
                   6308:          printf(" %le",delti3[i][j][k]);
                   6309:          fprintf(ficparo," %le",delti3[i][j][k]);
                   6310:          fprintf(ficlog," %le",delti3[i][j][k]);
                   6311:        }
                   6312:        fscanf(ficpar,"\n");
                   6313:        numlinepar++;
                   6314:        printf("\n");
                   6315:        fprintf(ficparo,"\n");
                   6316:        fprintf(ficlog,"\n");
                   6317:       }
                   6318:     }
                   6319:     fflush(ficlog);
                   6320: 
1.145     brouard  6321:     /* Reads covariance matrix */
1.126     brouard  6322:     delti=delti3[1][1];
                   6323: 
                   6324: 
                   6325:     /* free_ma3x(delti3,1,nlstate,1,nlstate+ndeath-1,1,ncovmodel); */ /* Hasn't to to freed here otherwise delti is no more allocated */
                   6326:   
                   6327:     /* Reads comments: lines beginning with '#' */
                   6328:     while((c=getc(ficpar))=='#' && c!= EOF){
                   6329:       ungetc(c,ficpar);
                   6330:       fgets(line, MAXLINE, ficpar);
                   6331:       numlinepar++;
1.141     brouard  6332:       fputs(line,stdout);
1.126     brouard  6333:       fputs(line,ficparo);
                   6334:       fputs(line,ficlog);
                   6335:     }
                   6336:     ungetc(c,ficpar);
                   6337:   
                   6338:     matcov=matrix(1,npar,1,npar);
1.131     brouard  6339:     for(i=1; i <=npar; i++)
                   6340:       for(j=1; j <=npar; j++) matcov[i][j]=0.;
                   6341:       
1.126     brouard  6342:     for(i=1; i <=npar; i++){
1.145     brouard  6343:       fscanf(ficpar,"%s",str);
1.126     brouard  6344:       if(mle==1)
                   6345:        printf("%s",str);
                   6346:       fprintf(ficlog,"%s",str);
                   6347:       fprintf(ficparo,"%s",str);
                   6348:       for(j=1; j <=i; j++){
                   6349:        fscanf(ficpar," %le",&matcov[i][j]);
                   6350:        if(mle==1){
                   6351:          printf(" %.5le",matcov[i][j]);
                   6352:        }
                   6353:        fprintf(ficlog," %.5le",matcov[i][j]);
                   6354:        fprintf(ficparo," %.5le",matcov[i][j]);
                   6355:       }
                   6356:       fscanf(ficpar,"\n");
                   6357:       numlinepar++;
                   6358:       if(mle==1)
                   6359:        printf("\n");
                   6360:       fprintf(ficlog,"\n");
                   6361:       fprintf(ficparo,"\n");
                   6362:     }
                   6363:     for(i=1; i <=npar; i++)
                   6364:       for(j=i+1;j<=npar;j++)
                   6365:        matcov[i][j]=matcov[j][i];
                   6366:     
                   6367:     if(mle==1)
                   6368:       printf("\n");
                   6369:     fprintf(ficlog,"\n");
                   6370:     
                   6371:     fflush(ficlog);
                   6372:     
                   6373:     /*-------- Rewriting parameter file ----------*/
                   6374:     strcpy(rfileres,"r");    /* "Rparameterfile */
                   6375:     strcat(rfileres,optionfilefiname);    /* Parameter file first name*/
                   6376:     strcat(rfileres,".");    /* */
                   6377:     strcat(rfileres,optionfilext);    /* Other files have txt extension */
                   6378:     if((ficres =fopen(rfileres,"w"))==NULL) {
                   6379:       printf("Problem writing new parameter file: %s\n", fileres);goto end;
                   6380:       fprintf(ficlog,"Problem writing new parameter file: %s\n", fileres);goto end;
                   6381:     }
                   6382:     fprintf(ficres,"#%s\n",version);
                   6383:   }    /* End of mle != -3 */
                   6384: 
                   6385: 
                   6386:   n= lastobs;
                   6387:   num=lvector(1,n);
                   6388:   moisnais=vector(1,n);
                   6389:   annais=vector(1,n);
                   6390:   moisdc=vector(1,n);
                   6391:   andc=vector(1,n);
                   6392:   agedc=vector(1,n);
                   6393:   cod=ivector(1,n);
                   6394:   weight=vector(1,n);
                   6395:   for(i=1;i<=n;i++) weight[i]=1.0; /* Equal weights, 1 by default */
                   6396:   mint=matrix(1,maxwav,1,n);
                   6397:   anint=matrix(1,maxwav,1,n);
1.131     brouard  6398:   s=imatrix(1,maxwav+1,1,n); /* s[i][j] health state for wave i and individual j */ 
1.126     brouard  6399:   tab=ivector(1,NCOVMAX);
1.144     brouard  6400:   ncodemax=ivector(1,NCOVMAX); /* Number of code per covariate; if O and 1 only, 2**ncov; V1+V2+V3+V4=>16 */
1.126     brouard  6401: 
1.136     brouard  6402:   /* Reads data from file datafile */
                   6403:   if (readdata(datafile, firstobs, lastobs, &imx)==1)
                   6404:     goto end;
                   6405: 
                   6406:   /* Calculation of the number of parameters from char model */
1.137     brouard  6407:     /*    modelsav=V2+V1+V4+age*V3 strb=age*V3 stra=V2+V1+V4 
                   6408:        k=4 (age*V3) Tvar[k=4]= 3 (from V3) Tag[cptcovage=1]=4
                   6409:        k=3 V4 Tvar[k=3]= 4 (from V4)
                   6410:        k=2 V1 Tvar[k=2]= 1 (from V1)
                   6411:        k=1 Tvar[1]=2 (from V2)
                   6412:     */
                   6413:   Tvar=ivector(1,NCOVMAX); /* Was 15 changed to NCOVMAX. */
                   6414:   /*  V2+V1+V4+age*V3 is a model with 4 covariates (3 plus signs). 
                   6415:       For each model-covariate stores the data-covariate id. Tvar[1]=2, Tvar[2]=1, Tvar[3]=4, 
                   6416:       Tvar[4=age*V3] is 3 and 'age' is recorded in Tage.
                   6417:   */
                   6418:   /* For model-covariate k tells which data-covariate to use but
                   6419:     because this model-covariate is a construction we invent a new column
                   6420:     ncovcol + k1
                   6421:     If already ncovcol=4 and model=V2+V1+V1*V4+age*V3
                   6422:     Tvar[3=V1*V4]=4+1 etc */
1.145     brouard  6423:   Tprod=ivector(1,NCOVMAX); /* Gives the position of a product */
1.137     brouard  6424:   /* Tprod[k1=1]=3(=V1*V4) for V2+V1+V1*V4+age*V3
                   6425:      if  V2+V1+V1*V4+age*V3+V3*V2   TProd[k1=2]=5 (V3*V2)
                   6426:   */
1.145     brouard  6427:   Tvaraff=ivector(1,NCOVMAX); /* Unclear */
                   6428:   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  6429:                            * For V3*V2 (in V2+V1+V1*V4+age*V3+V3*V2), V3*V2 position is 2nd. 
                   6430:                            * Tvard[k1=2][1]=3 (V3) Tvard[k1=2][2]=2(V2) */
1.145     brouard  6431:   Tage=ivector(1,NCOVMAX); /* Gives the covariate id of covariates associated with age: V2 + V1 + age*V4 + V3*age
1.137     brouard  6432:                         4 covariates (3 plus signs)
                   6433:                         Tage[1=V3*age]= 4; Tage[2=age*V4] = 3
                   6434:                      */  
1.136     brouard  6435: 
                   6436:   if(decodemodel(model, lastobs) == 1)
                   6437:     goto end;
                   6438: 
1.137     brouard  6439:   if((double)(lastobs-imx)/(double)imx > 1.10){
                   6440:     nbwarn++;
                   6441:     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); 
                   6442:     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); 
                   6443:   }
1.136     brouard  6444:     /*  if(mle==1){*/
1.137     brouard  6445:   if (weightopt != 1) { /* Maximisation without weights. We can have weights different from 1 but want no weight*/
                   6446:     for(i=1;i<=imx;i++) weight[i]=1.0; /* changed to imx */
1.136     brouard  6447:   }
                   6448: 
                   6449:     /*-calculation of age at interview from date of interview and age at death -*/
                   6450:   agev=matrix(1,maxwav,1,imx);
                   6451: 
                   6452:   if(calandcheckages(imx, maxwav, &agemin, &agemax, &nberr, &nbwarn) == 1)
                   6453:     goto end;
                   6454: 
1.126     brouard  6455: 
1.136     brouard  6456:   agegomp=(int)agemin;
                   6457:   free_vector(moisnais,1,n);
                   6458:   free_vector(annais,1,n);
1.126     brouard  6459:   /* free_matrix(mint,1,maxwav,1,n);
                   6460:      free_matrix(anint,1,maxwav,1,n);*/
                   6461:   free_vector(moisdc,1,n);
                   6462:   free_vector(andc,1,n);
1.145     brouard  6463:   /* */
                   6464:   
1.126     brouard  6465:   wav=ivector(1,imx);
                   6466:   dh=imatrix(1,lastpass-firstpass+1,1,imx);
                   6467:   bh=imatrix(1,lastpass-firstpass+1,1,imx);
                   6468:   mw=imatrix(1,lastpass-firstpass+1,1,imx);
                   6469:    
                   6470:   /* Concatenates waves */
                   6471:   concatwav(wav, dh, bh, mw, s, agedc, agev,  firstpass, lastpass, imx, nlstate, stepm);
1.145     brouard  6472:   /* */
                   6473:  
1.126     brouard  6474:   /* Routine tricode is to calculate cptcoveff (real number of unique covariates) and to associate covariable number and modality */
                   6475: 
                   6476:   nbcode=imatrix(0,NCOVMAX,0,NCOVMAX); 
                   6477:   ncodemax[1]=1;
1.145     brouard  6478:   Ndum =ivector(-1,NCOVMAX);  
                   6479:   if (ncovmodel > 2)
                   6480:     tricode(Tvar,nbcode,imx, Ndum); /**< Fills nbcode[Tvar[j]][l]; */
                   6481: 
                   6482:   codtab=imatrix(1,100,1,10); /* codtab[h,k]=( (h-1) - mod(k-1,2**(k-1) )/2**(k-1) */
                   6483:   /*printf(" codtab[1,1],codtab[100,10]=%d,%d\n", codtab[1][1],codtab[100][10]);*/
                   6484:   h=0;
                   6485: 
                   6486: 
                   6487:   /*if (cptcovn > 0) */
1.126     brouard  6488:       
1.145     brouard  6489:  
1.126     brouard  6490:   m=pow(2,cptcoveff);
                   6491:  
1.131     brouard  6492:   for(k=1;k<=cptcoveff; k++){ /* scans any effective covariate */
1.143     brouard  6493:     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 */ 
                   6494:       for(j=1; j <= ncodemax[k]; j++){ /* For each modality of this covariate ncodemax=2*/
                   6495:        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  6496:          h++;
1.141     brouard  6497:          if (h>m) 
1.136     brouard  6498:            h=1;
1.144     brouard  6499:          /**< codtab(h,k)  k   = codtab[h,k]=( (h-1) - mod(k-1,2**(k-1) )/2**(k-1) + 1
1.143     brouard  6500:           *     h     1     2     3     4
                   6501:           *______________________________  
                   6502:           *     1 i=1 1 i=1 1 i=1 1 i=1 1
                   6503:           *     2     2     1     1     1
                   6504:           *     3 i=2 1     2     1     1
                   6505:           *     4     2     2     1     1
                   6506:           *     5 i=3 1 i=2 1     2     1
                   6507:           *     6     2     1     2     1
                   6508:           *     7 i=4 1     2     2     1
                   6509:           *     8     2     2     2     1
                   6510:           *     9 i=5 1 i=3 1 i=2 1     1
                   6511:           *    10     2     1     1     1
                   6512:           *    11 i=6 1     2     1     1
                   6513:           *    12     2     2     1     1
                   6514:           *    13 i=7 1 i=4 1     2     1    
                   6515:           *    14     2     1     2     1
                   6516:           *    15 i=8 1     2     2     1
                   6517:           *    16     2     2     2     1
                   6518:           */
1.141     brouard  6519:          codtab[h][k]=j;
1.145     brouard  6520:          /*codtab[h][Tvar[k]]=j;*/
1.130     brouard  6521:          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  6522:        } 
                   6523:       }
                   6524:     }
                   6525:   } 
                   6526:   /* printf("codtab[1][2]=%d codtab[2][2]=%d",codtab[1][2],codtab[2][2]); 
                   6527:      codtab[1][2]=1;codtab[2][2]=2; */
                   6528:   /* for(i=1; i <=m ;i++){ 
                   6529:      for(k=1; k <=cptcovn; k++){
1.131     brouard  6530:        printf("i=%d k=%d %d %d ",i,k,codtab[i][k], cptcoveff);
1.126     brouard  6531:      }
                   6532:      printf("\n");
                   6533:      }
                   6534:      scanf("%d",i);*/
1.145     brouard  6535: 
                   6536:  free_ivector(Ndum,-1,NCOVMAX);
                   6537: 
                   6538: 
1.126     brouard  6539:     
                   6540:   /*------------ gnuplot -------------*/
                   6541:   strcpy(optionfilegnuplot,optionfilefiname);
                   6542:   if(mle==-3)
                   6543:     strcat(optionfilegnuplot,"-mort");
                   6544:   strcat(optionfilegnuplot,".gp");
                   6545: 
                   6546:   if((ficgp=fopen(optionfilegnuplot,"w"))==NULL) {
                   6547:     printf("Problem with file %s",optionfilegnuplot);
                   6548:   }
                   6549:   else{
                   6550:     fprintf(ficgp,"\n# %s\n", version); 
                   6551:     fprintf(ficgp,"# %s\n", optionfilegnuplot); 
1.141     brouard  6552:     //fprintf(ficgp,"set missing 'NaNq'\n");
                   6553:     fprintf(ficgp,"set datafile missing 'NaNq'\n");
1.126     brouard  6554:   }
                   6555:   /*  fclose(ficgp);*/
                   6556:   /*--------- index.htm --------*/
                   6557: 
                   6558:   strcpy(optionfilehtm,optionfilefiname); /* Main html file */
                   6559:   if(mle==-3)
                   6560:     strcat(optionfilehtm,"-mort");
                   6561:   strcat(optionfilehtm,".htm");
                   6562:   if((fichtm=fopen(optionfilehtm,"w"))==NULL)    {
1.131     brouard  6563:     printf("Problem with %s \n",optionfilehtm);
                   6564:     exit(0);
1.126     brouard  6565:   }
                   6566: 
                   6567:   strcpy(optionfilehtmcov,optionfilefiname); /* Only for matrix of covariance */
                   6568:   strcat(optionfilehtmcov,"-cov.htm");
                   6569:   if((fichtmcov=fopen(optionfilehtmcov,"w"))==NULL)    {
                   6570:     printf("Problem with %s \n",optionfilehtmcov), exit(0);
                   6571:   }
                   6572:   else{
                   6573:   fprintf(fichtmcov,"<html><head>\n<title>IMaCh Cov %s</title></head>\n <body><font size=\"2\">%s <br> %s</font> \
                   6574: <hr size=\"2\" color=\"#EC5E5E\"> \n\
                   6575: Title=%s <br>Datafile=%s Firstpass=%d Lastpass=%d Stepm=%d Weight=%d Model=%s<br>\n",\
                   6576:          optionfilehtmcov,version,fullversion,title,datafile,firstpass,lastpass,stepm, weightopt, model);
                   6577:   }
                   6578: 
                   6579:   fprintf(fichtm,"<html><head>\n<title>IMaCh %s</title></head>\n <body><font size=\"2\">%s <br> %s</font> \
                   6580: <hr size=\"2\" color=\"#EC5E5E\"> \n\
                   6581: Title=%s <br>Datafile=%s Firstpass=%d Lastpass=%d Stepm=%d Weight=%d Model=%s<br>\n\
                   6582: \n\
                   6583: <hr  size=\"2\" color=\"#EC5E5E\">\
                   6584:  <ul><li><h4>Parameter files</h4>\n\
                   6585:  - Parameter file: <a href=\"%s.%s\">%s.%s</a><br>\n\
                   6586:  - Copy of the parameter file: <a href=\"o%s\">o%s</a><br>\n\
                   6587:  - Log file of the run: <a href=\"%s\">%s</a><br>\n\
                   6588:  - Gnuplot file name: <a href=\"%s\">%s</a><br>\n\
                   6589:  - Date and time at start: %s</ul>\n",\
                   6590:          optionfilehtm,version,fullversion,title,datafile,firstpass,lastpass,stepm, weightopt, model,\
                   6591:          optionfilefiname,optionfilext,optionfilefiname,optionfilext,\
                   6592:          fileres,fileres,\
                   6593:          filelog,filelog,optionfilegnuplot,optionfilegnuplot,strstart);
                   6594:   fflush(fichtm);
                   6595: 
                   6596:   strcpy(pathr,path);
                   6597:   strcat(pathr,optionfilefiname);
1.184     brouard  6598: #ifdef WIN32
                   6599:   _chdir(optionfilefiname); /* Move to directory named optionfile */
                   6600: #else
1.126     brouard  6601:   chdir(optionfilefiname); /* Move to directory named optionfile */
1.184     brouard  6602: #endif
                   6603:          
1.126     brouard  6604:   
                   6605:   /* Calculates basic frequencies. Computes observed prevalence at single age
                   6606:      and prints on file fileres'p'. */
                   6607:   freqsummary(fileres, agemin, agemax, s, agev, nlstate, imx,Tvaraff,nbcode, ncodemax,mint,anint,strstart);
                   6608: 
                   6609:   fprintf(fichtm,"\n");
                   6610:   fprintf(fichtm,"<br>Total number of observations=%d <br>\n\
                   6611: Youngest age at first (selected) pass %.2f, oldest age %.2f<br>\n\
                   6612: Interval (in months) between two waves: Min=%d Max=%d Mean=%.2lf<br>\n",\
                   6613:          imx,agemin,agemax,jmin,jmax,jmean);
                   6614:   pmmij= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
                   6615:     oldms= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
                   6616:     newms= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
                   6617:     savms= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
                   6618:     oldm=oldms; newm=newms; savm=savms; /* Keeps fixed addresses to free */
                   6619:     
                   6620:    
                   6621:   /* For Powell, parameters are in a vector p[] starting at p[1]
                   6622:      so we point p on param[1][1] so that p[1] maps on param[1][1][1] */
                   6623:   p=param[1][1]; /* *(*(*(param +1)+1)+0) */
                   6624: 
                   6625:   globpr=0; /* To get the number ipmx of contributions and the sum of weights*/
                   6626: 
                   6627:   if (mle==-3){
1.136     brouard  6628:     ximort=matrix(1,NDIM,1,NDIM); 
                   6629: /*     ximort=gsl_matrix_alloc(1,NDIM,1,NDIM); */
1.126     brouard  6630:     cens=ivector(1,n);
                   6631:     ageexmed=vector(1,n);
                   6632:     agecens=vector(1,n);
                   6633:     dcwave=ivector(1,n);
                   6634:  
                   6635:     for (i=1; i<=imx; i++){
                   6636:       dcwave[i]=-1;
                   6637:       for (m=firstpass; m<=lastpass; m++)
                   6638:        if (s[m][i]>nlstate) {
                   6639:          dcwave[i]=m;
                   6640:          /*    printf("i=%d j=%d s=%d dcwave=%d\n",i,j, s[j][i],dcwave[i]);*/
                   6641:          break;
                   6642:        }
                   6643:     }
                   6644: 
                   6645:     for (i=1; i<=imx; i++) {
                   6646:       if (wav[i]>0){
                   6647:        ageexmed[i]=agev[mw[1][i]][i];
                   6648:        j=wav[i];
                   6649:        agecens[i]=1.; 
                   6650: 
                   6651:        if (ageexmed[i]> 1 && wav[i] > 0){
                   6652:          agecens[i]=agev[mw[j][i]][i];
                   6653:          cens[i]= 1;
                   6654:        }else if (ageexmed[i]< 1) 
                   6655:          cens[i]= -1;
                   6656:        if (agedc[i]< AGESUP && agedc[i]>1 && dcwave[i]>firstpass && dcwave[i]<=lastpass)
                   6657:          cens[i]=0 ;
                   6658:       }
                   6659:       else cens[i]=-1;
                   6660:     }
                   6661:     
                   6662:     for (i=1;i<=NDIM;i++) {
                   6663:       for (j=1;j<=NDIM;j++)
                   6664:        ximort[i][j]=(i == j ? 1.0 : 0.0);
                   6665:     }
                   6666:     
1.145     brouard  6667:     /*p[1]=0.0268; p[NDIM]=0.083;*/
1.126     brouard  6668:     /*printf("%lf %lf", p[1], p[2]);*/
                   6669:     
                   6670:     
1.136     brouard  6671: #ifdef GSL
                   6672:     printf("GSL optimization\n");  fprintf(ficlog,"Powell\n");
1.162     brouard  6673: #else
1.126     brouard  6674:     printf("Powell\n");  fprintf(ficlog,"Powell\n");
1.136     brouard  6675: #endif
1.126     brouard  6676:     strcpy(filerespow,"pow-mort"); 
                   6677:     strcat(filerespow,fileres);
                   6678:     if((ficrespow=fopen(filerespow,"w"))==NULL) {
                   6679:       printf("Problem with resultfile: %s\n", filerespow);
                   6680:       fprintf(ficlog,"Problem with resultfile: %s\n", filerespow);
                   6681:     }
1.136     brouard  6682: #ifdef GSL
                   6683:     fprintf(ficrespow,"# GSL optimization\n# iter -2*LL");
1.162     brouard  6684: #else
1.126     brouard  6685:     fprintf(ficrespow,"# Powell\n# iter -2*LL");
1.136     brouard  6686: #endif
1.126     brouard  6687:     /*  for (i=1;i<=nlstate;i++)
                   6688:        for(j=1;j<=nlstate+ndeath;j++)
                   6689:        if(j!=i)fprintf(ficrespow," p%1d%1d",i,j);
                   6690:     */
                   6691:     fprintf(ficrespow,"\n");
1.136     brouard  6692: #ifdef GSL
                   6693:     /* gsl starts here */ 
                   6694:     T = gsl_multimin_fminimizer_nmsimplex;
                   6695:     gsl_multimin_fminimizer *sfm = NULL;
                   6696:     gsl_vector *ss, *x;
                   6697:     gsl_multimin_function minex_func;
                   6698: 
                   6699:     /* Initial vertex size vector */
                   6700:     ss = gsl_vector_alloc (NDIM);
                   6701:     
                   6702:     if (ss == NULL){
                   6703:       GSL_ERROR_VAL ("failed to allocate space for ss", GSL_ENOMEM, 0);
                   6704:     }
                   6705:     /* Set all step sizes to 1 */
                   6706:     gsl_vector_set_all (ss, 0.001);
                   6707: 
                   6708:     /* Starting point */
1.126     brouard  6709:     
1.136     brouard  6710:     x = gsl_vector_alloc (NDIM);
                   6711:     
                   6712:     if (x == NULL){
                   6713:       gsl_vector_free(ss);
                   6714:       GSL_ERROR_VAL ("failed to allocate space for x", GSL_ENOMEM, 0);
                   6715:     }
                   6716:   
                   6717:     /* Initialize method and iterate */
                   6718:     /*     p[1]=0.0268; p[NDIM]=0.083; */
                   6719: /*     gsl_vector_set(x, 0, 0.0268); */
                   6720: /*     gsl_vector_set(x, 1, 0.083); */
                   6721:     gsl_vector_set(x, 0, p[1]);
                   6722:     gsl_vector_set(x, 1, p[2]);
                   6723: 
                   6724:     minex_func.f = &gompertz_f;
                   6725:     minex_func.n = NDIM;
                   6726:     minex_func.params = (void *)&p; /* ??? */
                   6727:     
                   6728:     sfm = gsl_multimin_fminimizer_alloc (T, NDIM);
                   6729:     gsl_multimin_fminimizer_set (sfm, &minex_func, x, ss);
                   6730:     
                   6731:     printf("Iterations beginning .....\n\n");
                   6732:     printf("Iter. #    Intercept       Slope     -Log Likelihood     Simplex size\n");
                   6733: 
                   6734:     iteri=0;
                   6735:     while (rval == GSL_CONTINUE){
                   6736:       iteri++;
                   6737:       status = gsl_multimin_fminimizer_iterate(sfm);
                   6738:       
                   6739:       if (status) printf("error: %s\n", gsl_strerror (status));
                   6740:       fflush(0);
                   6741:       
                   6742:       if (status) 
                   6743:         break;
                   6744:       
                   6745:       rval = gsl_multimin_test_size (gsl_multimin_fminimizer_size (sfm), 1e-6);
                   6746:       ssval = gsl_multimin_fminimizer_size (sfm);
                   6747:       
                   6748:       if (rval == GSL_SUCCESS)
                   6749:         printf ("converged to a local maximum at\n");
                   6750:       
                   6751:       printf("%5d ", iteri);
                   6752:       for (it = 0; it < NDIM; it++){
                   6753:        printf ("%10.5f ", gsl_vector_get (sfm->x, it));
                   6754:       }
                   6755:       printf("f() = %-10.5f ssize = %.7f\n", sfm->fval, ssval);
                   6756:     }
                   6757:     
                   6758:     printf("\n\n Please note: Program should be run many times with varying starting points to detemine global maximum\n\n");
                   6759:     
                   6760:     gsl_vector_free(x); /* initial values */
                   6761:     gsl_vector_free(ss); /* inital step size */
                   6762:     for (it=0; it<NDIM; it++){
                   6763:       p[it+1]=gsl_vector_get(sfm->x,it);
                   6764:       fprintf(ficrespow," %.12lf", p[it]);
                   6765:     }
                   6766:     gsl_multimin_fminimizer_free (sfm); /* p *(sfm.x.data) et p *(sfm.x.data+1)  */
                   6767: #endif
                   6768: #ifdef POWELL
                   6769:      powell(p,ximort,NDIM,ftol,&iter,&fret,gompertz);
                   6770: #endif  
1.126     brouard  6771:     fclose(ficrespow);
                   6772:     
                   6773:     hesscov(matcov, p, NDIM, delti, 1e-4, gompertz); 
                   6774: 
                   6775:     for(i=1; i <=NDIM; i++)
                   6776:       for(j=i+1;j<=NDIM;j++)
                   6777:        matcov[i][j]=matcov[j][i];
                   6778:     
                   6779:     printf("\nCovariance matrix\n ");
                   6780:     for(i=1; i <=NDIM; i++) {
                   6781:       for(j=1;j<=NDIM;j++){ 
                   6782:        printf("%f ",matcov[i][j]);
                   6783:       }
                   6784:       printf("\n ");
                   6785:     }
                   6786:     
                   6787:     printf("iter=%d MLE=%f Eq=%lf*exp(%lf*(age-%d))\n",iter,-gompertz(p),p[1],p[2],agegomp);
                   6788:     for (i=1;i<=NDIM;i++) 
                   6789:       printf("%f [%f ; %f]\n",p[i],p[i]-2*sqrt(matcov[i][i]),p[i]+2*sqrt(matcov[i][i]));
                   6790: 
                   6791:     lsurv=vector(1,AGESUP);
                   6792:     lpop=vector(1,AGESUP);
                   6793:     tpop=vector(1,AGESUP);
                   6794:     lsurv[agegomp]=100000;
                   6795:     
                   6796:     for (k=agegomp;k<=AGESUP;k++) {
                   6797:       agemortsup=k;
                   6798:       if (p[1]*exp(p[2]*(k-agegomp))>1) break;
                   6799:     }
                   6800:     
                   6801:     for (k=agegomp;k<agemortsup;k++)
                   6802:       lsurv[k+1]=lsurv[k]-lsurv[k]*(p[1]*exp(p[2]*(k-agegomp)));
                   6803:     
                   6804:     for (k=agegomp;k<agemortsup;k++){
                   6805:       lpop[k]=(lsurv[k]+lsurv[k+1])/2.;
                   6806:       sumlpop=sumlpop+lpop[k];
                   6807:     }
                   6808:     
                   6809:     tpop[agegomp]=sumlpop;
                   6810:     for (k=agegomp;k<(agemortsup-3);k++){
                   6811:       /*  tpop[k+1]=2;*/
                   6812:       tpop[k+1]=tpop[k]-lpop[k];
                   6813:     }
                   6814:     
                   6815:     
                   6816:     printf("\nAge   lx     qx    dx    Lx     Tx     e(x)\n");
                   6817:     for (k=agegomp;k<(agemortsup-2);k++) 
                   6818:       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]);
                   6819:     
                   6820:     
                   6821:     replace_back_to_slash(pathc,pathcd); /* Even gnuplot wants a / */
                   6822:     printinggnuplotmort(fileres, optionfilefiname,ageminpar,agemaxpar,fage, pathc,p);
                   6823:     
                   6824:     printinghtmlmort(fileres,title,datafile, firstpass, lastpass, \
                   6825:                     stepm, weightopt,\
                   6826:                     model,imx,p,matcov,agemortsup);
                   6827:     
                   6828:     free_vector(lsurv,1,AGESUP);
                   6829:     free_vector(lpop,1,AGESUP);
                   6830:     free_vector(tpop,1,AGESUP);
1.136     brouard  6831: #ifdef GSL
                   6832:     free_ivector(cens,1,n);
                   6833:     free_vector(agecens,1,n);
                   6834:     free_ivector(dcwave,1,n);
                   6835:     free_matrix(ximort,1,NDIM,1,NDIM);
                   6836: #endif
1.126     brouard  6837:   } /* Endof if mle==-3 */
                   6838:   
                   6839:   else{ /* For mle >=1 */
1.132     brouard  6840:     globpr=0;/* debug */
                   6841:     likelione(ficres, p, npar, nlstate, &globpr, &ipmx, &sw, &fretone, funcone); /* Prints the contributions to the likelihood */
1.126     brouard  6842:     printf("First Likeli=%12.6f ipmx=%ld sw=%12.6f",fretone,ipmx,sw);
                   6843:     for (k=1; k<=npar;k++)
                   6844:       printf(" %d %8.5f",k,p[k]);
                   6845:     printf("\n");
                   6846:     globpr=1; /* to print the contributions */
                   6847:     likelione(ficres, p, npar, nlstate, &globpr, &ipmx, &sw, &fretone, funcone); /* Prints the contributions to the likelihood */
                   6848:     printf("Second Likeli=%12.6f ipmx=%ld sw=%12.6f",fretone,ipmx,sw);
                   6849:     for (k=1; k<=npar;k++)
                   6850:       printf(" %d %8.5f",k,p[k]);
                   6851:     printf("\n");
                   6852:     if(mle>=1){ /* Could be 1 or 2 */
                   6853:       mlikeli(ficres,p, npar, ncovmodel, nlstate, ftol, func);
                   6854:     }
                   6855:     
                   6856:     /*--------- results files --------------*/
                   6857:     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=%s\n", title, datafile, lastobs, firstpass,lastpass,ftol, stepm, ncovcol, nlstate, ndeath, maxwav, weightopt,model);
                   6858:     
                   6859:     
                   6860:     fprintf(ficres,"# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
                   6861:     printf("# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
                   6862:     fprintf(ficlog,"# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
                   6863:     for(i=1,jk=1; i <=nlstate; i++){
                   6864:       for(k=1; k <=(nlstate+ndeath); k++){
                   6865:        if (k != i) {
                   6866:          printf("%d%d ",i,k);
                   6867:          fprintf(ficlog,"%d%d ",i,k);
                   6868:          fprintf(ficres,"%1d%1d ",i,k);
                   6869:          for(j=1; j <=ncovmodel; j++){
                   6870:            printf("%lf ",p[jk]);
                   6871:            fprintf(ficlog,"%lf ",p[jk]);
                   6872:            fprintf(ficres,"%lf ",p[jk]);
                   6873:            jk++; 
                   6874:          }
                   6875:          printf("\n");
                   6876:          fprintf(ficlog,"\n");
                   6877:          fprintf(ficres,"\n");
                   6878:        }
                   6879:       }
                   6880:     }
                   6881:     if(mle!=0){
                   6882:       /* Computing hessian and covariance matrix */
                   6883:       ftolhess=ftol; /* Usually correct */
                   6884:       hesscov(matcov, p, npar, delti, ftolhess, func);
                   6885:     }
                   6886:     fprintf(ficres,"# Scales (for hessian or gradient estimation)\n");
                   6887:     printf("# Scales (for hessian or gradient estimation)\n");
                   6888:     fprintf(ficlog,"# Scales (for hessian or gradient estimation)\n");
                   6889:     for(i=1,jk=1; i <=nlstate; i++){
                   6890:       for(j=1; j <=nlstate+ndeath; j++){
                   6891:        if (j!=i) {
                   6892:          fprintf(ficres,"%1d%1d",i,j);
                   6893:          printf("%1d%1d",i,j);
                   6894:          fprintf(ficlog,"%1d%1d",i,j);
                   6895:          for(k=1; k<=ncovmodel;k++){
                   6896:            printf(" %.5e",delti[jk]);
                   6897:            fprintf(ficlog," %.5e",delti[jk]);
                   6898:            fprintf(ficres," %.5e",delti[jk]);
                   6899:            jk++;
                   6900:          }
                   6901:          printf("\n");
                   6902:          fprintf(ficlog,"\n");
                   6903:          fprintf(ficres,"\n");
                   6904:        }
                   6905:       }
                   6906:     }
                   6907:     
                   6908:     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");
                   6909:     if(mle>=1)
                   6910:       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");
                   6911:     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");
                   6912:     /* # 121 Var(a12)\n\ */
                   6913:     /* # 122 Cov(b12,a12) Var(b12)\n\ */
                   6914:     /* # 131 Cov(a13,a12) Cov(a13,b12, Var(a13)\n\ */
                   6915:     /* # 132 Cov(b13,a12) Cov(b13,b12, Cov(b13,a13) Var(b13)\n\ */
                   6916:     /* # 212 Cov(a21,a12) Cov(a21,b12, Cov(a21,a13) Cov(a21,b13) Var(a21)\n\ */
                   6917:     /* # 212 Cov(b21,a12) Cov(b21,b12, Cov(b21,a13) Cov(b21,b13) Cov(b21,a21) Var(b21)\n\ */
                   6918:     /* # 232 Cov(a23,a12) Cov(a23,b12, Cov(a23,a13) Cov(a23,b13) Cov(a23,a21) Cov(a23,b21) Var(a23)\n\ */
                   6919:     /* # 232 Cov(b23,a12) Cov(b23,b12) ... Var (b23)\n" */
                   6920:     
                   6921:     
                   6922:     /* Just to have a covariance matrix which will be more understandable
                   6923:        even is we still don't want to manage dictionary of variables
                   6924:     */
                   6925:     for(itimes=1;itimes<=2;itimes++){
                   6926:       jj=0;
                   6927:       for(i=1; i <=nlstate; i++){
                   6928:        for(j=1; j <=nlstate+ndeath; j++){
                   6929:          if(j==i) continue;
                   6930:          for(k=1; k<=ncovmodel;k++){
                   6931:            jj++;
                   6932:            ca[0]= k+'a'-1;ca[1]='\0';
                   6933:            if(itimes==1){
                   6934:              if(mle>=1)
                   6935:                printf("#%1d%1d%d",i,j,k);
                   6936:              fprintf(ficlog,"#%1d%1d%d",i,j,k);
                   6937:              fprintf(ficres,"#%1d%1d%d",i,j,k);
                   6938:            }else{
                   6939:              if(mle>=1)
                   6940:                printf("%1d%1d%d",i,j,k);
                   6941:              fprintf(ficlog,"%1d%1d%d",i,j,k);
                   6942:              fprintf(ficres,"%1d%1d%d",i,j,k);
                   6943:            }
                   6944:            ll=0;
                   6945:            for(li=1;li <=nlstate; li++){
                   6946:              for(lj=1;lj <=nlstate+ndeath; lj++){
                   6947:                if(lj==li) continue;
                   6948:                for(lk=1;lk<=ncovmodel;lk++){
                   6949:                  ll++;
                   6950:                  if(ll<=jj){
                   6951:                    cb[0]= lk +'a'-1;cb[1]='\0';
                   6952:                    if(ll<jj){
                   6953:                      if(itimes==1){
                   6954:                        if(mle>=1)
                   6955:                          printf(" Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
                   6956:                        fprintf(ficlog," Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
                   6957:                        fprintf(ficres," Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
                   6958:                      }else{
                   6959:                        if(mle>=1)
                   6960:                          printf(" %.5e",matcov[jj][ll]); 
                   6961:                        fprintf(ficlog," %.5e",matcov[jj][ll]); 
                   6962:                        fprintf(ficres," %.5e",matcov[jj][ll]); 
                   6963:                      }
                   6964:                    }else{
                   6965:                      if(itimes==1){
                   6966:                        if(mle>=1)
                   6967:                          printf(" Var(%s%1d%1d)",ca,i,j);
                   6968:                        fprintf(ficlog," Var(%s%1d%1d)",ca,i,j);
                   6969:                        fprintf(ficres," Var(%s%1d%1d)",ca,i,j);
                   6970:                      }else{
                   6971:                        if(mle>=1)
                   6972:                          printf(" %.5e",matcov[jj][ll]); 
                   6973:                        fprintf(ficlog," %.5e",matcov[jj][ll]); 
                   6974:                        fprintf(ficres," %.5e",matcov[jj][ll]); 
                   6975:                      }
                   6976:                    }
                   6977:                  }
                   6978:                } /* end lk */
                   6979:              } /* end lj */
                   6980:            } /* end li */
                   6981:            if(mle>=1)
                   6982:              printf("\n");
                   6983:            fprintf(ficlog,"\n");
                   6984:            fprintf(ficres,"\n");
                   6985:            numlinepar++;
                   6986:          } /* end k*/
                   6987:        } /*end j */
                   6988:       } /* end i */
                   6989:     } /* end itimes */
                   6990:     
                   6991:     fflush(ficlog);
                   6992:     fflush(ficres);
                   6993:     
                   6994:     while((c=getc(ficpar))=='#' && c!= EOF){
                   6995:       ungetc(c,ficpar);
                   6996:       fgets(line, MAXLINE, ficpar);
1.141     brouard  6997:       fputs(line,stdout);
1.126     brouard  6998:       fputs(line,ficparo);
                   6999:     }
                   7000:     ungetc(c,ficpar);
                   7001:     
                   7002:     estepm=0;
                   7003:     fscanf(ficpar,"agemin=%lf agemax=%lf bage=%lf fage=%lf estepm=%d\n",&ageminpar,&agemaxpar, &bage, &fage, &estepm);
                   7004:     if (estepm==0 || estepm < stepm) estepm=stepm;
                   7005:     if (fage <= 2) {
                   7006:       bage = ageminpar;
                   7007:       fage = agemaxpar;
                   7008:     }
                   7009:     
                   7010:     fprintf(ficres,"# agemin agemax for life expectancy, bage fage (if mle==0 ie no data nor Max likelihood).\n");
                   7011:     fprintf(ficres,"agemin=%.0f agemax=%.0f bage=%.0f fage=%.0f estepm=%d\n",ageminpar,agemaxpar,bage,fage, estepm);
                   7012:     fprintf(ficparo,"agemin=%.0f agemax=%.0f bage=%.0f fage=%.0f estepm=%d\n",ageminpar,agemaxpar,bage,fage, estepm);
                   7013:     
                   7014:     while((c=getc(ficpar))=='#' && c!= EOF){
                   7015:       ungetc(c,ficpar);
                   7016:       fgets(line, MAXLINE, ficpar);
1.141     brouard  7017:       fputs(line,stdout);
1.126     brouard  7018:       fputs(line,ficparo);
                   7019:     }
                   7020:     ungetc(c,ficpar);
                   7021:     
                   7022:     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);
                   7023:     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);
                   7024:     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);
                   7025:     printf("begin-prev-date=%.lf/%.lf/%.lf end-prev-date=%.lf/%.lf/%.lf mov_average=%d\n",jprev1, mprev1,anprev1,jprev2, mprev2,anprev2,mobilav);
                   7026:     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);
                   7027:     
                   7028:     while((c=getc(ficpar))=='#' && c!= EOF){
                   7029:       ungetc(c,ficpar);
                   7030:       fgets(line, MAXLINE, ficpar);
1.141     brouard  7031:       fputs(line,stdout);
1.126     brouard  7032:       fputs(line,ficparo);
                   7033:     }
                   7034:     ungetc(c,ficpar);
                   7035:     
                   7036:     
                   7037:     dateprev1=anprev1+(mprev1-1)/12.+(jprev1-1)/365.;
                   7038:     dateprev2=anprev2+(mprev2-1)/12.+(jprev2-1)/365.;
                   7039:     
                   7040:     fscanf(ficpar,"pop_based=%d\n",&popbased);
                   7041:     fprintf(ficparo,"pop_based=%d\n",popbased);   
                   7042:     fprintf(ficres,"pop_based=%d\n",popbased);   
                   7043:     
                   7044:     while((c=getc(ficpar))=='#' && c!= EOF){
                   7045:       ungetc(c,ficpar);
                   7046:       fgets(line, MAXLINE, ficpar);
1.141     brouard  7047:       fputs(line,stdout);
1.126     brouard  7048:       fputs(line,ficparo);
                   7049:     }
                   7050:     ungetc(c,ficpar);
                   7051:     
                   7052:     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);
                   7053:     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);
                   7054:     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);
                   7055:     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);
                   7056:     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);
                   7057:     /* day and month of proj2 are not used but only year anproj2.*/
                   7058:     
                   7059:     
                   7060:     
1.145     brouard  7061:      /* freqsummary(fileres, agemin, agemax, s, agev, nlstate, imx,Tvaraff,nbcode, ncodemax,mint,anint); */
                   7062:     /* ,dateprev1,dateprev2,jprev1, mprev1,anprev1,jprev2, mprev2,anprev2); */
1.126     brouard  7063:     
                   7064:     replace_back_to_slash(pathc,pathcd); /* Even gnuplot wants a / */
                   7065:     printinggnuplot(fileres, optionfilefiname,ageminpar,agemaxpar,fage, pathc,p);
                   7066:     
                   7067:     printinghtml(fileres,title,datafile, firstpass, lastpass, stepm, weightopt,\
                   7068:                 model,imx,jmin,jmax,jmean,rfileres,popforecast,estepm,\
                   7069:                 jprev1,mprev1,anprev1,jprev2,mprev2,anprev2);
                   7070:       
                   7071:    /*------------ free_vector  -------------*/
                   7072:    /*  chdir(path); */
                   7073:  
                   7074:     free_ivector(wav,1,imx);
                   7075:     free_imatrix(dh,1,lastpass-firstpass+1,1,imx);
                   7076:     free_imatrix(bh,1,lastpass-firstpass+1,1,imx);
                   7077:     free_imatrix(mw,1,lastpass-firstpass+1,1,imx);   
                   7078:     free_lvector(num,1,n);
                   7079:     free_vector(agedc,1,n);
                   7080:     /*free_matrix(covar,0,NCOVMAX,1,n);*/
                   7081:     /*free_matrix(covar,1,NCOVMAX,1,n);*/
                   7082:     fclose(ficparo);
                   7083:     fclose(ficres);
                   7084: 
                   7085: 
                   7086:     /*--------------- Prevalence limit  (period or stable prevalence) --------------*/
1.180     brouard  7087:     /*#include "prevlim.h"*/  /* Use ficrespl, ficlog */
                   7088:     prlim=matrix(1,nlstate,1,nlstate);
                   7089:     prevalence_limit(p, prlim,  ageminpar, agemaxpar);
1.126     brouard  7090:     fclose(ficrespl);
                   7091: 
1.145     brouard  7092: #ifdef FREEEXIT2
                   7093: #include "freeexit2.h"
                   7094: #endif
                   7095: 
1.126     brouard  7096:     /*------------- h Pij x at various ages ------------*/
1.180     brouard  7097:     /*#include "hpijx.h"*/
                   7098:     hPijx(p, bage, fage);
1.145     brouard  7099:     fclose(ficrespij);
1.126     brouard  7100: 
1.145     brouard  7101:   /*-------------- Variance of one-step probabilities---*/
                   7102:     k=1;
1.126     brouard  7103:     varprob(optionfilefiname, matcov, p, delti, nlstate, bage, fage,k,Tvar,nbcode, ncodemax,strstart);
                   7104: 
                   7105: 
                   7106:     probs= ma3x(1,AGESUP,1,NCOVMAX, 1,NCOVMAX);
                   7107:     for(i=1;i<=AGESUP;i++)
                   7108:       for(j=1;j<=NCOVMAX;j++)
                   7109:        for(k=1;k<=NCOVMAX;k++)
                   7110:          probs[i][j][k]=0.;
                   7111: 
                   7112:     /*---------- Forecasting ------------------*/
                   7113:     /*if((stepm == 1) && (strcmp(model,".")==0)){*/
                   7114:     if(prevfcast==1){
                   7115:       /*    if(stepm ==1){*/
                   7116:       prevforecast(fileres, anproj1, mproj1, jproj1, agemin, agemax, dateprev1, dateprev2, mobilavproj, bage, fage, firstpass, lastpass, anproj2, p, cptcoveff);
                   7117:       /* (popforecast==1) populforecast(fileres, anpyram,mpyram,jpyram, agemin,agemax, dateprev1, dateprev2,mobilav, agedeb, fage, popforecast, popfile, anpyram1,p, i1);*/
                   7118:       /*      }  */
                   7119:       /*      else{ */
                   7120:       /*        erreur=108; */
                   7121:       /*        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); */
                   7122:       /*        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); */
                   7123:       /*      } */
                   7124:     }
                   7125:   
                   7126: 
1.127     brouard  7127:     /* Computes prevalence between agemin (i.e minimal age computed) and no more ageminpar */
                   7128: 
                   7129:     prevalence(probs, agemin, agemax, s, agev, nlstate, imx, Tvar, nbcode, ncodemax, mint, anint, dateprev1, dateprev2, firstpass, lastpass);
                   7130:     /*  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",\
                   7131:        ageminpar, agemax, s[lastpass][imx], agev[lastpass][imx], nlstate, imx, mint[lastpass][imx],anint[lastpass][imx], dateprev1, dateprev2, firstpass, lastpass);
                   7132:     */
1.126     brouard  7133: 
1.127     brouard  7134:     if (mobilav!=0) {
                   7135:       mobaverage= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
                   7136:       if (movingaverage(probs, bage, fage, mobaverage,mobilav)!=0){
                   7137:        fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav);
                   7138:        printf(" Error in movingaverage mobilav=%d\n",mobilav);
                   7139:       }
1.126     brouard  7140:     }
                   7141: 
                   7142: 
1.127     brouard  7143:     /*---------- Health expectancies, no variances ------------*/
                   7144: 
1.126     brouard  7145:     strcpy(filerese,"e");
                   7146:     strcat(filerese,fileres);
                   7147:     if((ficreseij=fopen(filerese,"w"))==NULL) {
                   7148:       printf("Problem with Health Exp. resultfile: %s\n", filerese); exit(0);
                   7149:       fprintf(ficlog,"Problem with Health Exp. resultfile: %s\n", filerese); exit(0);
                   7150:     }
                   7151:     printf("Computing Health Expectancies: result on file '%s' \n", filerese);
                   7152:     fprintf(ficlog,"Computing Health Expectancies: result on file '%s' \n", filerese);
1.145     brouard  7153:     /*for(cptcov=1,k=0;cptcov<=i1;cptcov++){
                   7154:       for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){*/
                   7155:           
                   7156:     for (k=1; k <= (int) pow(2,cptcoveff); k++){
1.127     brouard  7157:        fprintf(ficreseij,"\n#****** ");
                   7158:        for(j=1;j<=cptcoveff;j++) {
                   7159:          fprintf(ficreseij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
                   7160:        }
                   7161:        fprintf(ficreseij,"******\n");
                   7162: 
                   7163:        eij=ma3x(1,nlstate,1,nlstate,(int) bage, (int) fage);
                   7164:        oldm=oldms;savm=savms;
                   7165:        evsij(eij, p, nlstate, stepm, (int) bage, (int)fage, oldm, savm, k, estepm, strstart);  
                   7166:       
                   7167:        free_ma3x(eij,1,nlstate,1,nlstate,(int) bage, (int)fage);
1.145     brouard  7168:       /*}*/
1.127     brouard  7169:     }
                   7170:     fclose(ficreseij);
                   7171: 
                   7172: 
                   7173:     /*---------- Health expectancies and variances ------------*/
                   7174: 
                   7175: 
                   7176:     strcpy(filerest,"t");
                   7177:     strcat(filerest,fileres);
                   7178:     if((ficrest=fopen(filerest,"w"))==NULL) {
                   7179:       printf("Problem with total LE resultfile: %s\n", filerest);goto end;
                   7180:       fprintf(ficlog,"Problem with total LE resultfile: %s\n", filerest);goto end;
                   7181:     }
                   7182:     printf("Computing Total Life expectancies with their standard errors: file '%s' \n", filerest); 
                   7183:     fprintf(ficlog,"Computing Total Life expectancies with their standard errors: file '%s' \n", filerest); 
                   7184: 
1.126     brouard  7185: 
                   7186:     strcpy(fileresstde,"stde");
                   7187:     strcat(fileresstde,fileres);
                   7188:     if((ficresstdeij=fopen(fileresstde,"w"))==NULL) {
                   7189:       printf("Problem with Health Exp. and std errors resultfile: %s\n", fileresstde); exit(0);
                   7190:       fprintf(ficlog,"Problem with Health Exp. and std errors resultfile: %s\n", fileresstde); exit(0);
                   7191:     }
                   7192:     printf("Computing Health Expectancies and standard errors: result on file '%s' \n", fileresstde);
                   7193:     fprintf(ficlog,"Computing Health Expectancies and standard errors: result on file '%s' \n", fileresstde);
                   7194: 
                   7195:     strcpy(filerescve,"cve");
                   7196:     strcat(filerescve,fileres);
                   7197:     if((ficrescveij=fopen(filerescve,"w"))==NULL) {
                   7198:       printf("Problem with Covar. Health Exp. resultfile: %s\n", filerescve); exit(0);
                   7199:       fprintf(ficlog,"Problem with Covar. Health Exp. resultfile: %s\n", filerescve); exit(0);
                   7200:     }
                   7201:     printf("Computing Covar. of Health Expectancies: result on file '%s' \n", filerescve);
                   7202:     fprintf(ficlog,"Computing Covar. of Health Expectancies: result on file '%s' \n", filerescve);
                   7203: 
                   7204:     strcpy(fileresv,"v");
                   7205:     strcat(fileresv,fileres);
                   7206:     if((ficresvij=fopen(fileresv,"w"))==NULL) {
                   7207:       printf("Problem with variance resultfile: %s\n", fileresv);exit(0);
                   7208:       fprintf(ficlog,"Problem with variance resultfile: %s\n", fileresv);exit(0);
                   7209:     }
                   7210:     printf("Computing Variance-covariance of DFLEs: file '%s' \n", fileresv);
                   7211:     fprintf(ficlog,"Computing Variance-covariance of DFLEs: file '%s' \n", fileresv);
                   7212: 
1.145     brouard  7213:     /*for(cptcov=1,k=0;cptcov<=i1;cptcov++){
                   7214:       for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){*/
                   7215:           
                   7216:     for (k=1; k <= (int) pow(2,cptcoveff); k++){
                   7217:        fprintf(ficrest,"\n#****** ");
1.126     brouard  7218:        for(j=1;j<=cptcoveff;j++) 
                   7219:          fprintf(ficrest,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
                   7220:        fprintf(ficrest,"******\n");
                   7221: 
                   7222:        fprintf(ficresstdeij,"\n#****** ");
                   7223:        fprintf(ficrescveij,"\n#****** ");
                   7224:        for(j=1;j<=cptcoveff;j++) {
                   7225:          fprintf(ficresstdeij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
                   7226:          fprintf(ficrescveij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
                   7227:        }
                   7228:        fprintf(ficresstdeij,"******\n");
                   7229:        fprintf(ficrescveij,"******\n");
                   7230: 
                   7231:        fprintf(ficresvij,"\n#****** ");
                   7232:        for(j=1;j<=cptcoveff;j++) 
                   7233:          fprintf(ficresvij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
                   7234:        fprintf(ficresvij,"******\n");
                   7235: 
                   7236:        eij=ma3x(1,nlstate,1,nlstate,(int) bage, (int) fage);
                   7237:        oldm=oldms;savm=savms;
1.127     brouard  7238:        cvevsij(eij, p, nlstate, stepm, (int) bage, (int)fage, oldm, savm, k, estepm, delti, matcov, strstart);  
1.145     brouard  7239:        /*
                   7240:         */
                   7241:        /* goto endfree; */
1.126     brouard  7242:  
                   7243:        vareij=ma3x(1,nlstate,1,nlstate,(int) bage, (int) fage);
                   7244:        pstamp(ficrest);
1.145     brouard  7245: 
                   7246: 
1.128     brouard  7247:        for(vpopbased=0; vpopbased <= popbased; vpopbased++){ /* Done for vpopbased=0 and vpopbased=1 if popbased==1*/
1.145     brouard  7248:          oldm=oldms;savm=savms; /* Segmentation fault */
1.161     brouard  7249:          cptcod= 0; /* To be deleted */
                   7250:          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  7251:          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  7252:          if(vpopbased==1)
                   7253:            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);
                   7254:          else
                   7255:            fprintf(ficrest,"the age specific period (stable) prevalences in each health state \n");
                   7256:          fprintf(ficrest,"# Age e.. (std) ");
                   7257:          for (i=1;i<=nlstate;i++) fprintf(ficrest,"e.%d (std) ",i);
                   7258:          fprintf(ficrest,"\n");
1.126     brouard  7259: 
1.128     brouard  7260:          epj=vector(1,nlstate+1);
                   7261:          for(age=bage; age <=fage ;age++){
                   7262:            prevalim(prlim, nlstate, p, age, oldm, savm,ftolpl,k);
                   7263:            if (vpopbased==1) {
                   7264:              if(mobilav ==0){
                   7265:                for(i=1; i<=nlstate;i++)
                   7266:                  prlim[i][i]=probs[(int)age][i][k];
                   7267:              }else{ /* mobilav */ 
                   7268:                for(i=1; i<=nlstate;i++)
                   7269:                  prlim[i][i]=mobaverage[(int)age][i][k];
                   7270:              }
1.126     brouard  7271:            }
                   7272:        
1.128     brouard  7273:            fprintf(ficrest," %4.0f",age);
                   7274:            for(j=1, epj[nlstate+1]=0.;j <=nlstate;j++){
                   7275:              for(i=1, epj[j]=0.;i <=nlstate;i++) {
                   7276:                epj[j] += prlim[i][i]*eij[i][j][(int)age];
                   7277:                /*  printf("%lf %lf ", prlim[i][i] ,eij[i][j][(int)age]);*/
                   7278:              }
                   7279:              epj[nlstate+1] +=epj[j];
1.126     brouard  7280:            }
                   7281: 
1.128     brouard  7282:            for(i=1, vepp=0.;i <=nlstate;i++)
                   7283:              for(j=1;j <=nlstate;j++)
                   7284:                vepp += vareij[i][j][(int)age];
                   7285:            fprintf(ficrest," %7.3f (%7.3f)", epj[nlstate+1],sqrt(vepp));
                   7286:            for(j=1;j <=nlstate;j++){
                   7287:              fprintf(ficrest," %7.3f (%7.3f)", epj[j],sqrt(vareij[j][j][(int)age]));
                   7288:            }
                   7289:            fprintf(ficrest,"\n");
1.126     brouard  7290:          }
                   7291:        }
                   7292:        free_ma3x(eij,1,nlstate,1,nlstate,(int) bage, (int)fage);
                   7293:        free_ma3x(vareij,1,nlstate,1,nlstate,(int) bage, (int)fage);
                   7294:        free_vector(epj,1,nlstate+1);
1.145     brouard  7295:       /*}*/
1.126     brouard  7296:     }
                   7297:     free_vector(weight,1,n);
1.145     brouard  7298:     free_imatrix(Tvard,1,NCOVMAX,1,2);
1.126     brouard  7299:     free_imatrix(s,1,maxwav+1,1,n);
                   7300:     free_matrix(anint,1,maxwav,1,n); 
                   7301:     free_matrix(mint,1,maxwav,1,n);
                   7302:     free_ivector(cod,1,n);
                   7303:     free_ivector(tab,1,NCOVMAX);
                   7304:     fclose(ficresstdeij);
                   7305:     fclose(ficrescveij);
                   7306:     fclose(ficresvij);
                   7307:     fclose(ficrest);
                   7308:     fclose(ficpar);
                   7309:   
                   7310:     /*------- Variance of period (stable) prevalence------*/   
                   7311: 
                   7312:     strcpy(fileresvpl,"vpl");
                   7313:     strcat(fileresvpl,fileres);
                   7314:     if((ficresvpl=fopen(fileresvpl,"w"))==NULL) {
                   7315:       printf("Problem with variance of period (stable) prevalence  resultfile: %s\n", fileresvpl);
                   7316:       exit(0);
                   7317:     }
                   7318:     printf("Computing Variance-covariance of period (stable) prevalence: file '%s' \n", fileresvpl);
                   7319: 
1.145     brouard  7320:     /*for(cptcov=1,k=0;cptcov<=i1;cptcov++){
                   7321:       for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){*/
                   7322:           
                   7323:     for (k=1; k <= (int) pow(2,cptcoveff); k++){
                   7324:        fprintf(ficresvpl,"\n#****** ");
1.126     brouard  7325:        for(j=1;j<=cptcoveff;j++) 
                   7326:          fprintf(ficresvpl,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
                   7327:        fprintf(ficresvpl,"******\n");
                   7328:       
                   7329:        varpl=matrix(1,nlstate,(int) bage, (int) fage);
                   7330:        oldm=oldms;savm=savms;
                   7331:        varprevlim(fileres, varpl, matcov, p, delti, nlstate, stepm, (int) bage, (int) fage, oldm, savm, prlim, ftolpl,k,strstart);
                   7332:        free_matrix(varpl,1,nlstate,(int) bage, (int)fage);
1.145     brouard  7333:       /*}*/
1.126     brouard  7334:     }
                   7335: 
                   7336:     fclose(ficresvpl);
                   7337: 
                   7338:     /*---------- End : free ----------------*/
                   7339:     if (mobilav!=0) free_ma3x(mobaverage,1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
                   7340:     free_ma3x(probs,1,AGESUP,1,NCOVMAX, 1,NCOVMAX);
                   7341:   }  /* mle==-3 arrives here for freeing */
1.164     brouard  7342:  /* endfree:*/
1.141     brouard  7343:     free_matrix(prlim,1,nlstate,1,nlstate); /*here or after loop ? */
1.126     brouard  7344:     free_matrix(pmmij,1,nlstate+ndeath,1,nlstate+ndeath);
                   7345:     free_matrix(oldms, 1,nlstate+ndeath,1,nlstate+ndeath);
                   7346:     free_matrix(newms, 1,nlstate+ndeath,1,nlstate+ndeath);
                   7347:     free_matrix(savms, 1,nlstate+ndeath,1,nlstate+ndeath);
                   7348:     free_matrix(covar,0,NCOVMAX,1,n);
                   7349:     free_matrix(matcov,1,npar,1,npar);
                   7350:     /*free_vector(delti,1,npar);*/
                   7351:     free_ma3x(delti3,1,nlstate,1, nlstate+ndeath-1,1,ncovmodel); 
                   7352:     free_matrix(agev,1,maxwav,1,imx);
                   7353:     free_ma3x(param,1,nlstate,1, nlstate+ndeath-1,1,ncovmodel);
                   7354: 
1.145     brouard  7355:     free_ivector(ncodemax,1,NCOVMAX);
                   7356:     free_ivector(Tvar,1,NCOVMAX);
                   7357:     free_ivector(Tprod,1,NCOVMAX);
                   7358:     free_ivector(Tvaraff,1,NCOVMAX);
                   7359:     free_ivector(Tage,1,NCOVMAX);
1.126     brouard  7360: 
                   7361:     free_imatrix(nbcode,0,NCOVMAX,0,NCOVMAX);
                   7362:     free_imatrix(codtab,1,100,1,10);
                   7363:   fflush(fichtm);
                   7364:   fflush(ficgp);
                   7365:   
                   7366: 
                   7367:   if((nberr >0) || (nbwarn>0)){
                   7368:     printf("End of Imach with %d errors and/or %d warnings\n",nberr,nbwarn);
                   7369:     fprintf(ficlog,"End of Imach with %d errors and/or warnings %d\n",nberr,nbwarn);
                   7370:   }else{
                   7371:     printf("End of Imach\n");
                   7372:     fprintf(ficlog,"End of Imach\n");
                   7373:   }
                   7374:   printf("See log file on %s\n",filelog);
                   7375:   /*  gettimeofday(&end_time, (struct timezone*)0);*/  /* after time */
1.157     brouard  7376:   /*(void) gettimeofday(&end_time,&tzp);*/
                   7377:   rend_time = time(NULL);  
                   7378:   end_time = *localtime(&rend_time);
                   7379:   /* tml = *localtime(&end_time.tm_sec); */
                   7380:   strcpy(strtend,asctime(&end_time));
1.126     brouard  7381:   printf("Local time at start %s\nLocal time at end   %s",strstart, strtend); 
                   7382:   fprintf(ficlog,"Local time at start %s\nLocal time at end   %s\n",strstart, strtend); 
1.157     brouard  7383:   printf("Total time used %s\n", asc_diff_time(rend_time -rstart_time,tmpout));
1.126     brouard  7384: 
1.157     brouard  7385:   printf("Total time was %.0lf Sec.\n", difftime(rend_time,rstart_time));
                   7386:   fprintf(ficlog,"Total time used %s\n", asc_diff_time(rend_time -rstart_time,tmpout));
                   7387:   fprintf(ficlog,"Total time was %.0lf Sec.\n", difftime(rend_time,rstart_time));
1.126     brouard  7388:   /*  printf("Total time was %d uSec.\n", total_usecs);*/
                   7389: /*   if(fileappend(fichtm,optionfilehtm)){ */
                   7390:   fprintf(fichtm,"<br>Local time at start %s<br>Local time at end   %s<br>\n</body></html>",strstart, strtend);
                   7391:   fclose(fichtm);
                   7392:   fprintf(fichtmcov,"<br>Local time at start %s<br>Local time at end   %s<br>\n</body></html>",strstart, strtend);
                   7393:   fclose(fichtmcov);
                   7394:   fclose(ficgp);
                   7395:   fclose(ficlog);
                   7396:   /*------ End -----------*/
                   7397: 
                   7398: 
                   7399:    printf("Before Current directory %s!\n",pathcd);
1.184     brouard  7400: #ifdef WIN32
                   7401:    if (_chdir(pathcd) != 0)
                   7402:           printf("Can't move to directory %s!\n",path);
                   7403:    if(_getcwd(pathcd,MAXLINE) > 0)
                   7404: #else
1.126     brouard  7405:    if(chdir(pathcd) != 0)
1.184     brouard  7406:           printf("Can't move to directory %s!\n", path);
                   7407:    if (getcwd(pathcd, MAXLINE) > 0)
                   7408: #endif 
1.126     brouard  7409:     printf("Current directory %s!\n",pathcd);
                   7410:   /*strcat(plotcmd,CHARSEPARATOR);*/
                   7411:   sprintf(plotcmd,"gnuplot");
1.157     brouard  7412: #ifdef _WIN32
1.126     brouard  7413:   sprintf(plotcmd,"\"%sgnuplot.exe\"",pathimach);
                   7414: #endif
                   7415:   if(!stat(plotcmd,&info)){
1.158     brouard  7416:     printf("Error or gnuplot program not found: '%s'\n",plotcmd);fflush(stdout);
1.126     brouard  7417:     if(!stat(getenv("GNUPLOTBIN"),&info)){
1.158     brouard  7418:       printf("Error or gnuplot program not found: '%s' Environment GNUPLOTBIN not set.\n",plotcmd);fflush(stdout);
1.126     brouard  7419:     }else
                   7420:       strcpy(pplotcmd,plotcmd);
1.157     brouard  7421: #ifdef __unix
1.126     brouard  7422:     strcpy(plotcmd,GNUPLOTPROGRAM);
                   7423:     if(!stat(plotcmd,&info)){
1.158     brouard  7424:       printf("Error gnuplot program not found: '%s'\n",plotcmd);fflush(stdout);
1.126     brouard  7425:     }else
                   7426:       strcpy(pplotcmd,plotcmd);
                   7427: #endif
                   7428:   }else
                   7429:     strcpy(pplotcmd,plotcmd);
                   7430:   
                   7431:   sprintf(plotcmd,"%s %s",pplotcmd, optionfilegnuplot);
1.158     brouard  7432:   printf("Starting graphs with: '%s'\n",plotcmd);fflush(stdout);
1.126     brouard  7433: 
                   7434:   if((outcmd=system(plotcmd)) != 0){
1.158     brouard  7435:     printf("gnuplot command might not be in your path: '%s', err=%d\n", plotcmd, outcmd);
1.154     brouard  7436:     printf("\n Trying if gnuplot resides on the same directory that IMaCh\n");
1.152     brouard  7437:     sprintf(plotcmd,"%sgnuplot %s", pathimach, optionfilegnuplot);
1.150     brouard  7438:     if((outcmd=system(plotcmd)) != 0)
1.153     brouard  7439:       printf("\n Still a problem with gnuplot command %s, err=%d\n", plotcmd, outcmd);
1.126     brouard  7440:   }
1.158     brouard  7441:   printf(" Successful, please wait...");
1.126     brouard  7442:   while (z[0] != 'q') {
                   7443:     /* chdir(path); */
1.154     brouard  7444:     printf("\nType e to edit results with your browser, g to graph again and q for exit: ");
1.126     brouard  7445:     scanf("%s",z);
                   7446: /*     if (z[0] == 'c') system("./imach"); */
                   7447:     if (z[0] == 'e') {
1.158     brouard  7448: #ifdef __APPLE__
1.152     brouard  7449:       sprintf(pplotcmd, "open %s", optionfilehtm);
1.157     brouard  7450: #elif __linux
                   7451:       sprintf(pplotcmd, "xdg-open %s", optionfilehtm);
1.153     brouard  7452: #else
1.152     brouard  7453:       sprintf(pplotcmd, "%s", optionfilehtm);
1.153     brouard  7454: #endif
                   7455:       printf("Starting browser with: %s",pplotcmd);fflush(stdout);
                   7456:       system(pplotcmd);
1.126     brouard  7457:     }
                   7458:     else if (z[0] == 'g') system(plotcmd);
                   7459:     else if (z[0] == 'q') exit(0);
                   7460:   }
                   7461:   end:
                   7462:   while (z[0] != 'q') {
                   7463:     printf("\nType  q for exiting: ");
                   7464:     scanf("%s",z);
                   7465:   }
                   7466: }

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