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

1.186   ! brouard     1: /* $Id: imach.c,v 1.185 2015/03/11 13:26:42 brouard Exp $
1.126     brouard     2:   $State: Exp $
1.163     brouard     3:   $Log: imach.c,v $
1.186   ! brouard     4:   Revision 1.185  2015/03/11 13:26:42  brouard
        !             5:   Summary: Inclusion of compile and links command line for Intel Compiler
        !             6: 
1.185     brouard     7:   Revision 1.184  2015/03/11 11:52:39  brouard
                      8:   Summary: Back from Windows 8. Intel Compiler
                      9: 
1.184     brouard    10:   Revision 1.183  2015/03/10 20:34:32  brouard
                     11:   Summary: 0.98q0, trying with directest, mnbrak fixed
                     12: 
                     13:   We use directest instead of original Powell test; probably no
                     14:   incidence on the results, but better justifications;
                     15:   We fixed Numerical Recipes mnbrak routine which was wrong and gave
                     16:   wrong results.
                     17: 
1.183     brouard    18:   Revision 1.182  2015/02/12 08:19:57  brouard
                     19:   Summary: Trying to keep directest which seems simpler and more general
                     20:   Author: Nicolas Brouard
                     21: 
1.182     brouard    22:   Revision 1.181  2015/02/11 23:22:24  brouard
                     23:   Summary: Comments on Powell added
                     24: 
                     25:   Author:
                     26: 
1.181     brouard    27:   Revision 1.180  2015/02/11 17:33:45  brouard
                     28:   Summary: Finishing move from main to function (hpijx and prevalence_limit)
                     29: 
1.180     brouard    30:   Revision 1.179  2015/01/04 09:57:06  brouard
                     31:   Summary: back to OS/X
                     32: 
1.179     brouard    33:   Revision 1.178  2015/01/04 09:35:48  brouard
                     34:   *** empty log message ***
                     35: 
1.178     brouard    36:   Revision 1.177  2015/01/03 18:40:56  brouard
                     37:   Summary: Still testing ilc32 on OSX
                     38: 
1.177     brouard    39:   Revision 1.176  2015/01/03 16:45:04  brouard
                     40:   *** empty log message ***
                     41: 
1.176     brouard    42:   Revision 1.175  2015/01/03 16:33:42  brouard
                     43:   *** empty log message ***
                     44: 
1.175     brouard    45:   Revision 1.174  2015/01/03 16:15:49  brouard
                     46:   Summary: Still in cross-compilation
                     47: 
1.174     brouard    48:   Revision 1.173  2015/01/03 12:06:26  brouard
                     49:   Summary: trying to detect cross-compilation
                     50: 
1.173     brouard    51:   Revision 1.172  2014/12/27 12:07:47  brouard
                     52:   Summary: Back from Visual Studio and Intel, options for compiling for Windows XP
                     53: 
1.172     brouard    54:   Revision 1.171  2014/12/23 13:26:59  brouard
                     55:   Summary: Back from Visual C
                     56: 
                     57:   Still problem with utsname.h on Windows
                     58: 
1.171     brouard    59:   Revision 1.170  2014/12/23 11:17:12  brouard
                     60:   Summary: Cleaning some \%% back to %%
                     61: 
                     62:   The escape was mandatory for a specific compiler (which one?), but too many warnings.
                     63: 
1.170     brouard    64:   Revision 1.169  2014/12/22 23:08:31  brouard
                     65:   Summary: 0.98p
                     66: 
                     67:   Outputs some informations on compiler used, OS etc. Testing on different platforms.
                     68: 
1.169     brouard    69:   Revision 1.168  2014/12/22 15:17:42  brouard
1.170     brouard    70:   Summary: update
1.169     brouard    71: 
1.168     brouard    72:   Revision 1.167  2014/12/22 13:50:56  brouard
                     73:   Summary: Testing uname and compiler version and if compiled 32 or 64
                     74: 
                     75:   Testing on Linux 64
                     76: 
1.167     brouard    77:   Revision 1.166  2014/12/22 11:40:47  brouard
                     78:   *** empty log message ***
                     79: 
1.166     brouard    80:   Revision 1.165  2014/12/16 11:20:36  brouard
                     81:   Summary: After compiling on Visual C
                     82: 
                     83:   * imach.c (Module): Merging 1.61 to 1.162
                     84: 
1.165     brouard    85:   Revision 1.164  2014/12/16 10:52:11  brouard
                     86:   Summary: Merging with Visual C after suppressing some warnings for unused variables. Also fixing Saito's bug 0.98Xn
                     87: 
                     88:   * imach.c (Module): Merging 1.61 to 1.162
                     89: 
1.164     brouard    90:   Revision 1.163  2014/12/16 10:30:11  brouard
                     91:   * imach.c (Module): Merging 1.61 to 1.162
                     92: 
1.163     brouard    93:   Revision 1.162  2014/09/25 11:43:39  brouard
                     94:   Summary: temporary backup 0.99!
                     95: 
1.162     brouard    96:   Revision 1.1  2014/09/16 11:06:58  brouard
                     97:   Summary: With some code (wrong) for nlopt
                     98: 
                     99:   Author:
                    100: 
                    101:   Revision 1.161  2014/09/15 20:41:41  brouard
                    102:   Summary: Problem with macro SQR on Intel compiler
                    103: 
1.161     brouard   104:   Revision 1.160  2014/09/02 09:24:05  brouard
                    105:   *** empty log message ***
                    106: 
1.160     brouard   107:   Revision 1.159  2014/09/01 10:34:10  brouard
                    108:   Summary: WIN32
                    109:   Author: Brouard
                    110: 
1.159     brouard   111:   Revision 1.158  2014/08/27 17:11:51  brouard
                    112:   *** empty log message ***
                    113: 
1.158     brouard   114:   Revision 1.157  2014/08/27 16:26:55  brouard
                    115:   Summary: Preparing windows Visual studio version
                    116:   Author: Brouard
                    117: 
                    118:   In order to compile on Visual studio, time.h is now correct and time_t
                    119:   and tm struct should be used. difftime should be used but sometimes I
                    120:   just make the differences in raw time format (time(&now).
                    121:   Trying to suppress #ifdef LINUX
                    122:   Add xdg-open for __linux in order to open default browser.
                    123: 
1.157     brouard   124:   Revision 1.156  2014/08/25 20:10:10  brouard
                    125:   *** empty log message ***
                    126: 
1.156     brouard   127:   Revision 1.155  2014/08/25 18:32:34  brouard
                    128:   Summary: New compile, minor changes
                    129:   Author: Brouard
                    130: 
1.155     brouard   131:   Revision 1.154  2014/06/20 17:32:08  brouard
                    132:   Summary: Outputs now all graphs of convergence to period prevalence
                    133: 
1.154     brouard   134:   Revision 1.153  2014/06/20 16:45:46  brouard
                    135:   Summary: If 3 live state, convergence to period prevalence on same graph
                    136:   Author: Brouard
                    137: 
1.153     brouard   138:   Revision 1.152  2014/06/18 17:54:09  brouard
                    139:   Summary: open browser, use gnuplot on same dir than imach if not found in the path
                    140: 
1.152     brouard   141:   Revision 1.151  2014/06/18 16:43:30  brouard
                    142:   *** empty log message ***
                    143: 
1.151     brouard   144:   Revision 1.150  2014/06/18 16:42:35  brouard
                    145:   Summary: If gnuplot is not in the path try on same directory than imach binary (OSX)
                    146:   Author: brouard
                    147: 
1.150     brouard   148:   Revision 1.149  2014/06/18 15:51:14  brouard
                    149:   Summary: Some fixes in parameter files errors
                    150:   Author: Nicolas Brouard
                    151: 
1.149     brouard   152:   Revision 1.148  2014/06/17 17:38:48  brouard
                    153:   Summary: Nothing new
                    154:   Author: Brouard
                    155: 
                    156:   Just a new packaging for OS/X version 0.98nS
                    157: 
1.148     brouard   158:   Revision 1.147  2014/06/16 10:33:11  brouard
                    159:   *** empty log message ***
                    160: 
1.147     brouard   161:   Revision 1.146  2014/06/16 10:20:28  brouard
                    162:   Summary: Merge
                    163:   Author: Brouard
                    164: 
                    165:   Merge, before building revised version.
                    166: 
1.146     brouard   167:   Revision 1.145  2014/06/10 21:23:15  brouard
                    168:   Summary: Debugging with valgrind
                    169:   Author: Nicolas Brouard
                    170: 
                    171:   Lot of changes in order to output the results with some covariates
                    172:   After the Edimburgh REVES conference 2014, it seems mandatory to
                    173:   improve the code.
                    174:   No more memory valgrind error but a lot has to be done in order to
                    175:   continue the work of splitting the code into subroutines.
                    176:   Also, decodemodel has been improved. Tricode is still not
                    177:   optimal. nbcode should be improved. Documentation has been added in
                    178:   the source code.
                    179: 
1.144     brouard   180:   Revision 1.143  2014/01/26 09:45:38  brouard
                    181:   Summary: Version 0.98nR (to be improved, but gives same optimization results as 0.98k. Nice, promising
                    182: 
                    183:   * imach.c (Module): Trying to merge old staffs together while being at Tokyo. Not tested...
                    184:   (Module): Version 0.98nR Running ok, but output format still only works for three covariates.
                    185: 
1.143     brouard   186:   Revision 1.142  2014/01/26 03:57:36  brouard
                    187:   Summary: gnuplot changed plot w l 1 has to be changed to plot w l lt 2
                    188: 
                    189:   * imach.c (Module): Trying to merge old staffs together while being at Tokyo. Not tested...
                    190: 
1.142     brouard   191:   Revision 1.141  2014/01/26 02:42:01  brouard
                    192:   * imach.c (Module): Trying to merge old staffs together while being at Tokyo. Not tested...
                    193: 
1.141     brouard   194:   Revision 1.140  2011/09/02 10:37:54  brouard
                    195:   Summary: times.h is ok with mingw32 now.
                    196: 
1.140     brouard   197:   Revision 1.139  2010/06/14 07:50:17  brouard
                    198:   After the theft of my laptop, I probably lost some lines of codes which were not uploaded to the CVS tree.
                    199:   I remember having already fixed agemin agemax which are pointers now but not cvs saved.
                    200: 
1.139     brouard   201:   Revision 1.138  2010/04/30 18:19:40  brouard
                    202:   *** empty log message ***
                    203: 
1.138     brouard   204:   Revision 1.137  2010/04/29 18:11:38  brouard
                    205:   (Module): Checking covariates for more complex models
                    206:   than V1+V2. A lot of change to be done. Unstable.
                    207: 
1.137     brouard   208:   Revision 1.136  2010/04/26 20:30:53  brouard
                    209:   (Module): merging some libgsl code. Fixing computation
                    210:   of likelione (using inter/intrapolation if mle = 0) in order to
                    211:   get same likelihood as if mle=1.
                    212:   Some cleaning of code and comments added.
                    213: 
1.136     brouard   214:   Revision 1.135  2009/10/29 15:33:14  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.135     brouard   217:   Revision 1.134  2009/10/29 13:18:53  brouard
                    218:   (Module): Now imach stops if date of birth, at least year of birth, is not given. Some cleaning of the code.
                    219: 
1.134     brouard   220:   Revision 1.133  2009/07/06 10:21:25  brouard
                    221:   just nforces
                    222: 
1.133     brouard   223:   Revision 1.132  2009/07/06 08:22:05  brouard
                    224:   Many tings
                    225: 
1.132     brouard   226:   Revision 1.131  2009/06/20 16:22:47  brouard
                    227:   Some dimensions resccaled
                    228: 
1.131     brouard   229:   Revision 1.130  2009/05/26 06:44:34  brouard
                    230:   (Module): Max Covariate is now set to 20 instead of 8. A
                    231:   lot of cleaning with variables initialized to 0. Trying to make
                    232:   V2+V3*age+V1+V4 strb=V3*age+V1+V4 working better.
                    233: 
1.130     brouard   234:   Revision 1.129  2007/08/31 13:49:27  lievre
                    235:   Modification of the way of exiting when the covariate is not binary in order to see on the window the error message before exiting
                    236: 
1.129     lievre    237:   Revision 1.128  2006/06/30 13:02:05  brouard
                    238:   (Module): Clarifications on computing e.j
                    239: 
1.128     brouard   240:   Revision 1.127  2006/04/28 18:11:50  brouard
                    241:   (Module): Yes the sum of survivors was wrong since
                    242:   imach-114 because nhstepm was no more computed in the age
                    243:   loop. Now we define nhstepma in the age loop.
                    244:   (Module): In order to speed up (in case of numerous covariates) we
                    245:   compute health expectancies (without variances) in a first step
                    246:   and then all the health expectancies with variances or standard
                    247:   deviation (needs data from the Hessian matrices) which slows the
                    248:   computation.
                    249:   In the future we should be able to stop the program is only health
                    250:   expectancies and graph are needed without standard deviations.
                    251: 
1.127     brouard   252:   Revision 1.126  2006/04/28 17:23:28  brouard
                    253:   (Module): Yes the sum of survivors was wrong since
                    254:   imach-114 because nhstepm was no more computed in the age
                    255:   loop. Now we define nhstepma in the age loop.
                    256:   Version 0.98h
                    257: 
1.126     brouard   258:   Revision 1.125  2006/04/04 15:20:31  lievre
                    259:   Errors in calculation of health expectancies. Age was not initialized.
                    260:   Forecasting file added.
                    261: 
                    262:   Revision 1.124  2006/03/22 17:13:53  lievre
                    263:   Parameters are printed with %lf instead of %f (more numbers after the comma).
                    264:   The log-likelihood is printed in the log file
                    265: 
                    266:   Revision 1.123  2006/03/20 10:52:43  brouard
                    267:   * imach.c (Module): <title> changed, corresponds to .htm file
                    268:   name. <head> headers where missing.
                    269: 
                    270:   * imach.c (Module): Weights can have a decimal point as for
                    271:   English (a comma might work with a correct LC_NUMERIC environment,
                    272:   otherwise the weight is truncated).
                    273:   Modification of warning when the covariates values are not 0 or
                    274:   1.
                    275:   Version 0.98g
                    276: 
                    277:   Revision 1.122  2006/03/20 09:45:41  brouard
                    278:   (Module): Weights can have a decimal point as for
                    279:   English (a comma might work with a correct LC_NUMERIC environment,
                    280:   otherwise the weight is truncated).
                    281:   Modification of warning when the covariates values are not 0 or
                    282:   1.
                    283:   Version 0.98g
                    284: 
                    285:   Revision 1.121  2006/03/16 17:45:01  lievre
                    286:   * imach.c (Module): Comments concerning covariates added
                    287: 
                    288:   * imach.c (Module): refinements in the computation of lli if
                    289:   status=-2 in order to have more reliable computation if stepm is
                    290:   not 1 month. Version 0.98f
                    291: 
                    292:   Revision 1.120  2006/03/16 15:10:38  lievre
                    293:   (Module): refinements in the computation of lli if
                    294:   status=-2 in order to have more reliable computation if stepm is
                    295:   not 1 month. Version 0.98f
                    296: 
                    297:   Revision 1.119  2006/03/15 17:42:26  brouard
                    298:   (Module): Bug if status = -2, the loglikelihood was
                    299:   computed as likelihood omitting the logarithm. Version O.98e
                    300: 
                    301:   Revision 1.118  2006/03/14 18:20:07  brouard
                    302:   (Module): varevsij Comments added explaining the second
                    303:   table of variances if popbased=1 .
                    304:   (Module): Covariances of eij, ekl added, graphs fixed, new html link.
                    305:   (Module): Function pstamp added
                    306:   (Module): Version 0.98d
                    307: 
                    308:   Revision 1.117  2006/03/14 17:16:22  brouard
                    309:   (Module): varevsij Comments added explaining the second
                    310:   table of variances if popbased=1 .
                    311:   (Module): Covariances of eij, ekl added, graphs fixed, new html link.
                    312:   (Module): Function pstamp added
                    313:   (Module): Version 0.98d
                    314: 
                    315:   Revision 1.116  2006/03/06 10:29:27  brouard
                    316:   (Module): Variance-covariance wrong links and
                    317:   varian-covariance of ej. is needed (Saito).
                    318: 
                    319:   Revision 1.115  2006/02/27 12:17:45  brouard
                    320:   (Module): One freematrix added in mlikeli! 0.98c
                    321: 
                    322:   Revision 1.114  2006/02/26 12:57:58  brouard
                    323:   (Module): Some improvements in processing parameter
                    324:   filename with strsep.
                    325: 
                    326:   Revision 1.113  2006/02/24 14:20:24  brouard
                    327:   (Module): Memory leaks checks with valgrind and:
                    328:   datafile was not closed, some imatrix were not freed and on matrix
                    329:   allocation too.
                    330: 
                    331:   Revision 1.112  2006/01/30 09:55:26  brouard
                    332:   (Module): Back to gnuplot.exe instead of wgnuplot.exe
                    333: 
                    334:   Revision 1.111  2006/01/25 20:38:18  brouard
                    335:   (Module): Lots of cleaning and bugs added (Gompertz)
                    336:   (Module): Comments can be added in data file. Missing date values
                    337:   can be a simple dot '.'.
                    338: 
                    339:   Revision 1.110  2006/01/25 00:51:50  brouard
                    340:   (Module): Lots of cleaning and bugs added (Gompertz)
                    341: 
                    342:   Revision 1.109  2006/01/24 19:37:15  brouard
                    343:   (Module): Comments (lines starting with a #) are allowed in data.
                    344: 
                    345:   Revision 1.108  2006/01/19 18:05:42  lievre
                    346:   Gnuplot problem appeared...
                    347:   To be fixed
                    348: 
                    349:   Revision 1.107  2006/01/19 16:20:37  brouard
                    350:   Test existence of gnuplot in imach path
                    351: 
                    352:   Revision 1.106  2006/01/19 13:24:36  brouard
                    353:   Some cleaning and links added in html output
                    354: 
                    355:   Revision 1.105  2006/01/05 20:23:19  lievre
                    356:   *** empty log message ***
                    357: 
                    358:   Revision 1.104  2005/09/30 16:11:43  lievre
                    359:   (Module): sump fixed, loop imx fixed, and simplifications.
                    360:   (Module): If the status is missing at the last wave but we know
                    361:   that the person is alive, then we can code his/her status as -2
                    362:   (instead of missing=-1 in earlier versions) and his/her
                    363:   contributions to the likelihood is 1 - Prob of dying from last
                    364:   health status (= 1-p13= p11+p12 in the easiest case of somebody in
                    365:   the healthy state at last known wave). Version is 0.98
                    366: 
                    367:   Revision 1.103  2005/09/30 15:54:49  lievre
                    368:   (Module): sump fixed, loop imx fixed, and simplifications.
                    369: 
                    370:   Revision 1.102  2004/09/15 17:31:30  brouard
                    371:   Add the possibility to read data file including tab characters.
                    372: 
                    373:   Revision 1.101  2004/09/15 10:38:38  brouard
                    374:   Fix on curr_time
                    375: 
                    376:   Revision 1.100  2004/07/12 18:29:06  brouard
                    377:   Add version for Mac OS X. Just define UNIX in Makefile
                    378: 
                    379:   Revision 1.99  2004/06/05 08:57:40  brouard
                    380:   *** empty log message ***
                    381: 
                    382:   Revision 1.98  2004/05/16 15:05:56  brouard
                    383:   New version 0.97 . First attempt to estimate force of mortality
                    384:   directly from the data i.e. without the need of knowing the health
                    385:   state at each age, but using a Gompertz model: log u =a + b*age .
                    386:   This is the basic analysis of mortality and should be done before any
                    387:   other analysis, in order to test if the mortality estimated from the
                    388:   cross-longitudinal survey is different from the mortality estimated
                    389:   from other sources like vital statistic data.
                    390: 
                    391:   The same imach parameter file can be used but the option for mle should be -3.
                    392: 
1.133     brouard   393:   Agnès, who wrote this part of the code, tried to keep most of the
1.126     brouard   394:   former routines in order to include the new code within the former code.
                    395: 
                    396:   The output is very simple: only an estimate of the intercept and of
                    397:   the slope with 95% confident intervals.
                    398: 
                    399:   Current limitations:
                    400:   A) Even if you enter covariates, i.e. with the
                    401:   model= V1+V2 equation for example, the programm does only estimate a unique global model without covariates.
                    402:   B) There is no computation of Life Expectancy nor Life Table.
                    403: 
                    404:   Revision 1.97  2004/02/20 13:25:42  lievre
                    405:   Version 0.96d. Population forecasting command line is (temporarily)
                    406:   suppressed.
                    407: 
                    408:   Revision 1.96  2003/07/15 15:38:55  brouard
                    409:   * imach.c (Repository): Errors in subdirf, 2, 3 while printing tmpout is
                    410:   rewritten within the same printf. Workaround: many printfs.
                    411: 
                    412:   Revision 1.95  2003/07/08 07:54:34  brouard
                    413:   * imach.c (Repository):
                    414:   (Repository): Using imachwizard code to output a more meaningful covariance
                    415:   matrix (cov(a12,c31) instead of numbers.
                    416: 
                    417:   Revision 1.94  2003/06/27 13:00:02  brouard
                    418:   Just cleaning
                    419: 
                    420:   Revision 1.93  2003/06/25 16:33:55  brouard
                    421:   (Module): On windows (cygwin) function asctime_r doesn't
                    422:   exist so I changed back to asctime which exists.
                    423:   (Module): Version 0.96b
                    424: 
                    425:   Revision 1.92  2003/06/25 16:30:45  brouard
                    426:   (Module): On windows (cygwin) function asctime_r doesn't
                    427:   exist so I changed back to asctime which exists.
                    428: 
                    429:   Revision 1.91  2003/06/25 15:30:29  brouard
                    430:   * imach.c (Repository): Duplicated warning errors corrected.
                    431:   (Repository): Elapsed time after each iteration is now output. It
                    432:   helps to forecast when convergence will be reached. Elapsed time
                    433:   is stamped in powell.  We created a new html file for the graphs
                    434:   concerning matrix of covariance. It has extension -cov.htm.
                    435: 
                    436:   Revision 1.90  2003/06/24 12:34:15  brouard
                    437:   (Module): Some bugs corrected for windows. Also, when
                    438:   mle=-1 a template is output in file "or"mypar.txt with the design
                    439:   of the covariance matrix to be input.
                    440: 
                    441:   Revision 1.89  2003/06/24 12:30:52  brouard
                    442:   (Module): Some bugs corrected for windows. Also, when
                    443:   mle=-1 a template is output in file "or"mypar.txt with the design
                    444:   of the covariance matrix to be input.
                    445: 
                    446:   Revision 1.88  2003/06/23 17:54:56  brouard
                    447:   * 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.
                    448: 
                    449:   Revision 1.87  2003/06/18 12:26:01  brouard
                    450:   Version 0.96
                    451: 
                    452:   Revision 1.86  2003/06/17 20:04:08  brouard
                    453:   (Module): Change position of html and gnuplot routines and added
                    454:   routine fileappend.
                    455: 
                    456:   Revision 1.85  2003/06/17 13:12:43  brouard
                    457:   * imach.c (Repository): Check when date of death was earlier that
                    458:   current date of interview. It may happen when the death was just
                    459:   prior to the death. In this case, dh was negative and likelihood
                    460:   was wrong (infinity). We still send an "Error" but patch by
                    461:   assuming that the date of death was just one stepm after the
                    462:   interview.
                    463:   (Repository): Because some people have very long ID (first column)
                    464:   we changed int to long in num[] and we added a new lvector for
                    465:   memory allocation. But we also truncated to 8 characters (left
                    466:   truncation)
                    467:   (Repository): No more line truncation errors.
                    468: 
                    469:   Revision 1.84  2003/06/13 21:44:43  brouard
                    470:   * imach.c (Repository): Replace "freqsummary" at a correct
                    471:   place. It differs from routine "prevalence" which may be called
                    472:   many times. Probs is memory consuming and must be used with
                    473:   parcimony.
                    474:   Version 0.95a3 (should output exactly the same maximization than 0.8a2)
                    475: 
                    476:   Revision 1.83  2003/06/10 13:39:11  lievre
                    477:   *** empty log message ***
                    478: 
                    479:   Revision 1.82  2003/06/05 15:57:20  brouard
                    480:   Add log in  imach.c and  fullversion number is now printed.
                    481: 
                    482: */
                    483: /*
                    484:    Interpolated Markov Chain
                    485: 
                    486:   Short summary of the programme:
                    487:   
                    488:   This program computes Healthy Life Expectancies from
                    489:   cross-longitudinal data. Cross-longitudinal data consist in: -1- a
                    490:   first survey ("cross") where individuals from different ages are
                    491:   interviewed on their health status or degree of disability (in the
                    492:   case of a health survey which is our main interest) -2- at least a
                    493:   second wave of interviews ("longitudinal") which measure each change
                    494:   (if any) in individual health status.  Health expectancies are
                    495:   computed from the time spent in each health state according to a
                    496:   model. More health states you consider, more time is necessary to reach the
                    497:   Maximum Likelihood of the parameters involved in the model.  The
                    498:   simplest model is the multinomial logistic model where pij is the
                    499:   probability to be observed in state j at the second wave
                    500:   conditional to be observed in state i at the first wave. Therefore
                    501:   the model is: log(pij/pii)= aij + bij*age+ cij*sex + etc , where
                    502:   'age' is age and 'sex' is a covariate. If you want to have a more
                    503:   complex model than "constant and age", you should modify the program
                    504:   where the markup *Covariates have to be included here again* invites
                    505:   you to do it.  More covariates you add, slower the
                    506:   convergence.
                    507: 
                    508:   The advantage of this computer programme, compared to a simple
                    509:   multinomial logistic model, is clear when the delay between waves is not
                    510:   identical for each individual. Also, if a individual missed an
                    511:   intermediate interview, the information is lost, but taken into
                    512:   account using an interpolation or extrapolation.  
                    513: 
                    514:   hPijx is the probability to be observed in state i at age x+h
                    515:   conditional to the observed state i at age x. The delay 'h' can be
                    516:   split into an exact number (nh*stepm) of unobserved intermediate
                    517:   states. This elementary transition (by month, quarter,
                    518:   semester or year) is modelled as a multinomial logistic.  The hPx
                    519:   matrix is simply the matrix product of nh*stepm elementary matrices
                    520:   and the contribution of each individual to the likelihood is simply
                    521:   hPijx.
                    522: 
                    523:   Also this programme outputs the covariance matrix of the parameters but also
                    524:   of the life expectancies. It also computes the period (stable) prevalence. 
                    525:   
1.133     brouard   526:   Authors: Nicolas Brouard (brouard@ined.fr) and Agnès Lièvre (lievre@ined.fr).
                    527:            Institut national d'études démographiques, Paris.
1.126     brouard   528:   This software have been partly granted by Euro-REVES, a concerted action
                    529:   from the European Union.
                    530:   It is copyrighted identically to a GNU software product, ie programme and
                    531:   software can be distributed freely for non commercial use. Latest version
                    532:   can be accessed at http://euroreves.ined.fr/imach .
                    533: 
                    534:   Help to debug: LD_PRELOAD=/usr/local/lib/libnjamd.so ./imach foo.imach
                    535:   or better on gdb : set env LD_PRELOAD=/usr/local/lib/libnjamd.so
                    536:   
                    537:   **********************************************************************/
                    538: /*
                    539:   main
                    540:   read parameterfile
                    541:   read datafile
                    542:   concatwav
                    543:   freqsummary
                    544:   if (mle >= 1)
                    545:     mlikeli
                    546:   print results files
                    547:   if mle==1 
                    548:      computes hessian
                    549:   read end of parameter file: agemin, agemax, bage, fage, estepm
                    550:       begin-prev-date,...
                    551:   open gnuplot file
                    552:   open html file
1.145     brouard   553:   period (stable) prevalence      | pl_nom    1-1 2-2 etc by covariate
                    554:    for age prevalim()             | #****** V1=0  V2=1  V3=1  V4=0 ******
                    555:                                   | 65 1 0 2 1 3 1 4 0  0.96326 0.03674
                    556:     freexexit2 possible for memory heap.
                    557: 
                    558:   h Pij x                         | pij_nom  ficrestpij
                    559:    # Cov Agex agex+h hpijx with i,j= 1-1 1-2     1-3     2-1     2-2     2-3
                    560:        1  85   85    1.00000             0.00000 0.00000 0.00000 1.00000 0.00000
                    561:        1  85   86    0.68299             0.22291 0.09410 0.71093 0.00000 0.28907
                    562: 
                    563:        1  65   99    0.00364             0.00322 0.99314 0.00350 0.00310 0.99340
                    564:        1  65  100    0.00214             0.00204 0.99581 0.00206 0.00196 0.99597
                    565:   variance of p one-step probabilities varprob  | prob_nom   ficresprob #One-step probabilities and stand. devi in ()
                    566:    Standard deviation of one-step probabilities | probcor_nom   ficresprobcor #One-step probabilities and correlation matrix
                    567:    Matrix of variance covariance of one-step probabilities |  probcov_nom ficresprobcov #One-step probabilities and covariance matrix
                    568: 
1.126     brouard   569:   forecasting if prevfcast==1 prevforecast call prevalence()
                    570:   health expectancies
                    571:   Variance-covariance of DFLE
                    572:   prevalence()
                    573:    movingaverage()
                    574:   varevsij() 
                    575:   if popbased==1 varevsij(,popbased)
                    576:   total life expectancies
                    577:   Variance of period (stable) prevalence
                    578:  end
                    579: */
                    580: 
1.165     brouard   581: #define POWELL /* Instead of NLOPT */
1.186   ! brouard   582: /* #define POWELLORIGINAL /\* Don't use Directest to decide new direction but original Powell test *\/ */
        !           583: /* #define MNBRAKORIGINAL /\* Don't use mnbrak fix *\/ */
1.126     brouard   584: 
                    585: #include <math.h>
                    586: #include <stdio.h>
                    587: #include <stdlib.h>
                    588: #include <string.h>
1.159     brouard   589: 
                    590: #ifdef _WIN32
                    591: #include <io.h>
1.172     brouard   592: #include <windows.h>
                    593: #include <tchar.h>
1.159     brouard   594: #else
1.126     brouard   595: #include <unistd.h>
1.159     brouard   596: #endif
1.126     brouard   597: 
                    598: #include <limits.h>
                    599: #include <sys/types.h>
1.171     brouard   600: 
                    601: #if defined(__GNUC__)
                    602: #include <sys/utsname.h> /* Doesn't work on Windows */
                    603: #endif
                    604: 
1.126     brouard   605: #include <sys/stat.h>
                    606: #include <errno.h>
1.159     brouard   607: /* extern int errno; */
1.126     brouard   608: 
1.157     brouard   609: /* #ifdef LINUX */
                    610: /* #include <time.h> */
                    611: /* #include "timeval.h" */
                    612: /* #else */
                    613: /* #include <sys/time.h> */
                    614: /* #endif */
                    615: 
1.126     brouard   616: #include <time.h>
                    617: 
1.136     brouard   618: #ifdef GSL
                    619: #include <gsl/gsl_errno.h>
                    620: #include <gsl/gsl_multimin.h>
                    621: #endif
                    622: 
1.167     brouard   623: 
1.162     brouard   624: #ifdef NLOPT
                    625: #include <nlopt.h>
                    626: typedef struct {
                    627:   double (* function)(double [] );
                    628: } myfunc_data ;
                    629: #endif
                    630: 
1.126     brouard   631: /* #include <libintl.h> */
                    632: /* #define _(String) gettext (String) */
                    633: 
1.141     brouard   634: #define MAXLINE 1024 /* Was 256. Overflow with 312 with 2 states and 4 covariates. Should be ok */
1.126     brouard   635: 
                    636: #define GNUPLOTPROGRAM "gnuplot"
                    637: /*#define GNUPLOTPROGRAM "..\\gp37mgw\\wgnuplot"*/
                    638: #define FILENAMELENGTH 132
                    639: 
                    640: #define        GLOCK_ERROR_NOPATH              -1      /* empty path */
                    641: #define        GLOCK_ERROR_GETCWD              -2      /* cannot get cwd */
                    642: 
1.144     brouard   643: #define MAXPARM 128 /**< Maximum number of parameters for the optimization */
                    644: #define NPARMAX 64 /**< (nlstate+ndeath-1)*nlstate*ncovmodel */
1.126     brouard   645: 
                    646: #define NINTERVMAX 8
1.144     brouard   647: #define NLSTATEMAX 8 /**< Maximum number of live states (for func) */
                    648: #define NDEATHMAX 8 /**< Maximum number of dead states (for func) */
                    649: #define NCOVMAX 20 /**< Maximum number of covariates, including generated covariates V1*V2 */
1.145     brouard   650: #define codtabm(h,k)  1 & (h-1) >> (k-1) ;
1.126     brouard   651: #define MAXN 20000
1.144     brouard   652: #define YEARM 12. /**< Number of months per year */
1.126     brouard   653: #define AGESUP 130
                    654: #define AGEBASE 40
1.164     brouard   655: #define AGEGOMP 10 /**< Minimal age for Gompertz adjustment */
1.157     brouard   656: #ifdef _WIN32
                    657: #define DIRSEPARATOR '\\'
                    658: #define CHARSEPARATOR "\\"
                    659: #define ODIRSEPARATOR '/'
                    660: #else
1.126     brouard   661: #define DIRSEPARATOR '/'
                    662: #define CHARSEPARATOR "/"
                    663: #define ODIRSEPARATOR '\\'
                    664: #endif
                    665: 
1.186   ! brouard   666: /* $Id: imach.c,v 1.185 2015/03/11 13:26:42 brouard Exp $ */
1.126     brouard   667: /* $State: Exp $ */
                    668: 
1.186   ! brouard   669: char version[]="Imach version 0.98q1, April 2015,INED-EUROREVES-Institut de longevite-Japan Society for the Promotion of Science (Grant-in-Aid for Scientific Research 25293121), Intel Software 2015";
        !           670: char fullversion[]="$Revision: 1.185 $ $Date: 2015/03/11 13:26:42 $"; 
1.126     brouard   671: char strstart[80];
                    672: char optionfilext[10], optionfilefiname[FILENAMELENGTH];
1.130     brouard   673: int erreur=0, nberr=0, nbwarn=0; /* Error number, number of errors number of warnings  */
1.133     brouard   674: int nvar=0, nforce=0; /* Number of variables, number of forces */
1.145     brouard   675: /* Number of covariates model=V2+V1+ V3*age+V2*V4 */
                    676: int cptcovn=0; /**< cptcovn number of covariates added in the model (excepting constant and age and age*product) */
                    677: int cptcovt=0; /**< cptcovt number of covariates added in the model (excepting constant and age) */
                    678: int cptcovs=0; /**< cptcovs number of simple covariates V2+V1 =2 */
                    679: int cptcovage=0; /**< Number of covariates with age: V3*age only =1 */
                    680: int cptcovprodnoage=0; /**< Number of covariate products without age */   
                    681: int cptcoveff=0; /* Total number of covariates to vary for printing results */
                    682: int cptcov=0; /* Working variable */
1.126     brouard   683: int npar=NPARMAX;
                    684: int nlstate=2; /* Number of live states */
                    685: int ndeath=1; /* Number of dead states */
1.130     brouard   686: int ncovmodel=0, ncovcol=0;     /* Total number of covariables including constant a12*1 +b12*x ncovmodel=2 */
1.126     brouard   687: int popbased=0;
                    688: 
                    689: int *wav; /* Number of waves for this individuual 0 is possible */
1.130     brouard   690: int maxwav=0; /* Maxim number of waves */
                    691: int jmin=0, jmax=0; /* min, max spacing between 2 waves */
                    692: int ijmin=0, ijmax=0; /* Individuals having jmin and jmax */ 
                    693: int gipmx=0, gsw=0; /* Global variables on the number of contributions 
1.126     brouard   694:                   to the likelihood and the sum of weights (done by funcone)*/
1.130     brouard   695: int mle=1, weightopt=0;
1.126     brouard   696: int **mw; /* mw[mi][i] is number of the mi wave for this individual */
                    697: int **dh; /* dh[mi][i] is number of steps between mi,mi+1 for this individual */
                    698: int **bh; /* bh[mi][i] is the bias (+ or -) for this individual if the delay between
                    699:           * wave mi and wave mi+1 is not an exact multiple of stepm. */
1.162     brouard   700: int countcallfunc=0;  /* Count the number of calls to func */
1.130     brouard   701: double jmean=1; /* Mean space between 2 waves */
1.145     brouard   702: double **matprod2(); /* test */
1.126     brouard   703: double **oldm, **newm, **savm; /* Working pointers to matrices */
                    704: double **oldms, **newms, **savms; /* Fixed working pointers to matrices */
1.136     brouard   705: /*FILE *fic ; */ /* Used in readdata only */
                    706: FILE *ficpar, *ficparo,*ficres, *ficresp, *ficrespl, *ficrespij, *ficrest,*ficresf,*ficrespop;
1.126     brouard   707: FILE *ficlog, *ficrespow;
1.130     brouard   708: int globpr=0; /* Global variable for printing or not */
1.126     brouard   709: double fretone; /* Only one call to likelihood */
1.130     brouard   710: long ipmx=0; /* Number of contributions */
1.126     brouard   711: double sw; /* Sum of weights */
                    712: char filerespow[FILENAMELENGTH];
                    713: char fileresilk[FILENAMELENGTH]; /* File of individual contributions to the likelihood */
                    714: FILE *ficresilk;
                    715: FILE *ficgp,*ficresprob,*ficpop, *ficresprobcov, *ficresprobcor;
                    716: FILE *ficresprobmorprev;
                    717: FILE *fichtm, *fichtmcov; /* Html File */
                    718: FILE *ficreseij;
                    719: char filerese[FILENAMELENGTH];
                    720: FILE *ficresstdeij;
                    721: char fileresstde[FILENAMELENGTH];
                    722: FILE *ficrescveij;
                    723: char filerescve[FILENAMELENGTH];
                    724: FILE  *ficresvij;
                    725: char fileresv[FILENAMELENGTH];
                    726: FILE  *ficresvpl;
                    727: char fileresvpl[FILENAMELENGTH];
                    728: char title[MAXLINE];
                    729: char optionfile[FILENAMELENGTH], datafile[FILENAMELENGTH],  filerespl[FILENAMELENGTH];
                    730: char plotcmd[FILENAMELENGTH], pplotcmd[FILENAMELENGTH];
                    731: char tmpout[FILENAMELENGTH],  tmpout2[FILENAMELENGTH]; 
                    732: char command[FILENAMELENGTH];
                    733: int  outcmd=0;
                    734: 
                    735: char fileres[FILENAMELENGTH], filerespij[FILENAMELENGTH], filereso[FILENAMELENGTH], rfileres[FILENAMELENGTH];
                    736: 
                    737: char filelog[FILENAMELENGTH]; /* Log file */
                    738: char filerest[FILENAMELENGTH];
                    739: char fileregp[FILENAMELENGTH];
                    740: char popfile[FILENAMELENGTH];
                    741: 
                    742: char optionfilegnuplot[FILENAMELENGTH], optionfilehtm[FILENAMELENGTH], optionfilehtmcov[FILENAMELENGTH] ;
                    743: 
1.157     brouard   744: /* struct timeval start_time, end_time, curr_time, last_time, forecast_time; */
                    745: /* struct timezone tzp; */
                    746: /* extern int gettimeofday(); */
                    747: struct tm tml, *gmtime(), *localtime();
                    748: 
                    749: extern time_t time();
                    750: 
                    751: struct tm start_time, end_time, curr_time, last_time, forecast_time;
                    752: time_t  rstart_time, rend_time, rcurr_time, rlast_time, rforecast_time; /* raw time */
                    753: struct tm tm;
                    754: 
1.126     brouard   755: char strcurr[80], strfor[80];
                    756: 
                    757: char *endptr;
                    758: long lval;
                    759: double dval;
                    760: 
                    761: #define NR_END 1
                    762: #define FREE_ARG char*
                    763: #define FTOL 1.0e-10
                    764: 
                    765: #define NRANSI 
                    766: #define ITMAX 200 
                    767: 
                    768: #define TOL 2.0e-4 
                    769: 
                    770: #define CGOLD 0.3819660 
                    771: #define ZEPS 1.0e-10 
                    772: #define SHFT(a,b,c,d) (a)=(b);(b)=(c);(c)=(d); 
                    773: 
                    774: #define GOLD 1.618034 
                    775: #define GLIMIT 100.0 
                    776: #define TINY 1.0e-20 
                    777: 
                    778: static double maxarg1,maxarg2;
                    779: #define FMAX(a,b) (maxarg1=(a),maxarg2=(b),(maxarg1)>(maxarg2)? (maxarg1):(maxarg2))
                    780: #define FMIN(a,b) (maxarg1=(a),maxarg2=(b),(maxarg1)<(maxarg2)? (maxarg1):(maxarg2))
                    781:   
                    782: #define SIGN(a,b) ((b)>0.0 ? fabs(a) : -fabs(a))
                    783: #define rint(a) floor(a+0.5)
1.166     brouard   784: /* http://www.thphys.uni-heidelberg.de/~robbers/cmbeasy/doc/html/myutils_8h-source.html */
1.183     brouard   785: #define mytinydouble 1.0e-16
1.166     brouard   786: /* #define DEQUAL(a,b) (fabs((a)-(b))<mytinydouble) */
                    787: /* http://www.thphys.uni-heidelberg.de/~robbers/cmbeasy/doc/html/mynrutils_8h-source.html */
                    788: /* static double dsqrarg; */
                    789: /* #define DSQR(a) (DEQUAL((dsqrarg=(a)),0.0) ? 0.0 : dsqrarg*dsqrarg) */
1.126     brouard   790: static double sqrarg;
                    791: #define SQR(a) ((sqrarg=(a)) == 0.0 ? 0.0 :sqrarg*sqrarg)
                    792: #define SWAP(a,b) {temp=(a);(a)=(b);(b)=temp;} 
                    793: int agegomp= AGEGOMP;
                    794: 
                    795: int imx; 
                    796: int stepm=1;
                    797: /* Stepm, step in month: minimum step interpolation*/
                    798: 
                    799: int estepm;
                    800: /* Estepm, step in month to interpolate survival function in order to approximate Life Expectancy*/
                    801: 
                    802: int m,nb;
                    803: long *num;
                    804: int firstpass=0, lastpass=4,*cod, *ncodemax, *Tage,*cens;
                    805: double **agev,*moisnais, *annais, *moisdc, *andc,**mint, **anint;
                    806: double **pmmij, ***probs;
                    807: double *ageexmed,*agecens;
                    808: double dateintmean=0;
                    809: 
                    810: double *weight;
                    811: int **s; /* Status */
1.141     brouard   812: double *agedc;
1.145     brouard   813: double  **covar; /**< covar[j,i], value of jth covariate for individual i,
1.141     brouard   814:                  * covar=matrix(0,NCOVMAX,1,n); 
                    815:                  * cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*cov[2]; */
                    816: double  idx; 
                    817: int **nbcode, *Tvar; /**< model=V2 => Tvar[1]= 2 */
1.145     brouard   818: int *Ndum; /** Freq of modality (tricode */
1.141     brouard   819: int **codtab; /**< codtab=imatrix(1,100,1,10); */
                    820: int **Tvard, *Tprod, cptcovprod, *Tvaraff;
1.126     brouard   821: double *lsurv, *lpop, *tpop;
                    822: 
1.143     brouard   823: double ftol=FTOL; /**< Tolerance for computing Max Likelihood */
                    824: double ftolhess; /**< Tolerance for computing hessian */
1.126     brouard   825: 
                    826: /**************** split *************************/
                    827: static int split( char *path, char *dirc, char *name, char *ext, char *finame )
                    828: {
                    829:   /* From a file name with (full) path (either Unix or Windows) we extract the directory (dirc)
                    830:      the name of the file (name), its extension only (ext) and its first part of the name (finame)
                    831:   */ 
                    832:   char *ss;                            /* pointer */
1.186   ! brouard   833:   int  l1=0, l2=0;                             /* length counters */
1.126     brouard   834: 
                    835:   l1 = strlen(path );                  /* length of path */
                    836:   if ( l1 == 0 ) return( GLOCK_ERROR_NOPATH );
                    837:   ss= strrchr( path, DIRSEPARATOR );           /* find last / */
                    838:   if ( ss == NULL ) {                  /* no directory, so determine current directory */
                    839:     strcpy( name, path );              /* we got the fullname name because no directory */
                    840:     /*if(strrchr(path, ODIRSEPARATOR )==NULL)
                    841:       printf("Warning you should use %s as a separator\n",DIRSEPARATOR);*/
                    842:     /* get current working directory */
                    843:     /*    extern  char* getcwd ( char *buf , int len);*/
1.184     brouard   844: #ifdef WIN32
                    845:     if (_getcwd( dirc, FILENAME_MAX ) == NULL ) {
                    846: #else
                    847:        if (getcwd(dirc, FILENAME_MAX) == NULL) {
                    848: #endif
1.126     brouard   849:       return( GLOCK_ERROR_GETCWD );
                    850:     }
                    851:     /* got dirc from getcwd*/
                    852:     printf(" DIRC = %s \n",dirc);
                    853:   } else {                             /* strip direcotry from path */
                    854:     ss++;                              /* after this, the filename */
                    855:     l2 = strlen( ss );                 /* length of filename */
                    856:     if ( l2 == 0 ) return( GLOCK_ERROR_NOPATH );
                    857:     strcpy( name, ss );                /* save file name */
                    858:     strncpy( dirc, path, l1 - l2 );    /* now the directory */
1.186   ! brouard   859:     dirc[l1-l2] = '\0';                        /* add zero */
1.126     brouard   860:     printf(" DIRC2 = %s \n",dirc);
                    861:   }
                    862:   /* We add a separator at the end of dirc if not exists */
                    863:   l1 = strlen( dirc );                 /* length of directory */
                    864:   if( dirc[l1-1] != DIRSEPARATOR ){
                    865:     dirc[l1] =  DIRSEPARATOR;
                    866:     dirc[l1+1] = 0; 
                    867:     printf(" DIRC3 = %s \n",dirc);
                    868:   }
                    869:   ss = strrchr( name, '.' );           /* find last / */
                    870:   if (ss >0){
                    871:     ss++;
                    872:     strcpy(ext,ss);                    /* save extension */
                    873:     l1= strlen( name);
                    874:     l2= strlen(ss)+1;
                    875:     strncpy( finame, name, l1-l2);
                    876:     finame[l1-l2]= 0;
                    877:   }
                    878: 
                    879:   return( 0 );                         /* we're done */
                    880: }
                    881: 
                    882: 
                    883: /******************************************/
                    884: 
                    885: void replace_back_to_slash(char *s, char*t)
                    886: {
                    887:   int i;
                    888:   int lg=0;
                    889:   i=0;
                    890:   lg=strlen(t);
                    891:   for(i=0; i<= lg; i++) {
                    892:     (s[i] = t[i]);
                    893:     if (t[i]== '\\') s[i]='/';
                    894:   }
                    895: }
                    896: 
1.132     brouard   897: char *trimbb(char *out, char *in)
1.137     brouard   898: { /* Trim multiple blanks in line but keeps first blanks if line starts with blanks */
1.132     brouard   899:   char *s;
                    900:   s=out;
                    901:   while (*in != '\0'){
1.137     brouard   902:     while( *in == ' ' && *(in+1) == ' '){ /* && *(in+1) != '\0'){*/
1.132     brouard   903:       in++;
                    904:     }
                    905:     *out++ = *in++;
                    906:   }
                    907:   *out='\0';
                    908:   return s;
                    909: }
                    910: 
1.145     brouard   911: char *cutl(char *blocc, char *alocc, char *in, char occ)
                    912: {
                    913:   /* cuts string in into blocc and alocc where blocc ends before first occurence of char 'occ' 
                    914:      and alocc starts after first occurence of char 'occ' : ex cutv(blocc,alocc,"abcdef2ghi2j",'2')
                    915:      gives blocc="abcdef2ghi" and alocc="j".
                    916:      If occ is not found blocc is null and alocc is equal to in. Returns blocc
                    917:   */
1.160     brouard   918:   char *s, *t;
1.145     brouard   919:   t=in;s=in;
                    920:   while ((*in != occ) && (*in != '\0')){
                    921:     *alocc++ = *in++;
                    922:   }
                    923:   if( *in == occ){
                    924:     *(alocc)='\0';
                    925:     s=++in;
                    926:   }
                    927:  
                    928:   if (s == t) {/* occ not found */
                    929:     *(alocc-(in-s))='\0';
                    930:     in=s;
                    931:   }
                    932:   while ( *in != '\0'){
                    933:     *blocc++ = *in++;
                    934:   }
                    935: 
                    936:   *blocc='\0';
                    937:   return t;
                    938: }
1.137     brouard   939: char *cutv(char *blocc, char *alocc, char *in, char occ)
                    940: {
                    941:   /* cuts string in into blocc and alocc where blocc ends before last occurence of char 'occ' 
                    942:      and alocc starts after last occurence of char 'occ' : ex cutv(blocc,alocc,"abcdef2ghi2j",'2')
                    943:      gives blocc="abcdef2ghi" and alocc="j".
                    944:      If occ is not found blocc is null and alocc is equal to in. Returns alocc
                    945:   */
                    946:   char *s, *t;
                    947:   t=in;s=in;
                    948:   while (*in != '\0'){
                    949:     while( *in == occ){
                    950:       *blocc++ = *in++;
                    951:       s=in;
                    952:     }
                    953:     *blocc++ = *in++;
                    954:   }
                    955:   if (s == t) /* occ not found */
                    956:     *(blocc-(in-s))='\0';
                    957:   else
                    958:     *(blocc-(in-s)-1)='\0';
                    959:   in=s;
                    960:   while ( *in != '\0'){
                    961:     *alocc++ = *in++;
                    962:   }
                    963: 
                    964:   *alocc='\0';
                    965:   return s;
                    966: }
                    967: 
1.126     brouard   968: int nbocc(char *s, char occ)
                    969: {
                    970:   int i,j=0;
                    971:   int lg=20;
                    972:   i=0;
                    973:   lg=strlen(s);
                    974:   for(i=0; i<= lg; i++) {
                    975:   if  (s[i] == occ ) j++;
                    976:   }
                    977:   return j;
                    978: }
                    979: 
1.137     brouard   980: /* void cutv(char *u,char *v, char*t, char occ) */
                    981: /* { */
                    982: /*   /\* cuts string t into u and v where u ends before last occurence of char 'occ'  */
                    983: /*      and v starts after last occurence of char 'occ' : ex cutv(u,v,"abcdef2ghi2j",'2') */
                    984: /*      gives u="abcdef2ghi" and v="j" *\/ */
                    985: /*   int i,lg,j,p=0; */
                    986: /*   i=0; */
                    987: /*   lg=strlen(t); */
                    988: /*   for(j=0; j<=lg-1; j++) { */
                    989: /*     if((t[j]!= occ) && (t[j+1]== occ)) p=j+1; */
                    990: /*   } */
1.126     brouard   991: 
1.137     brouard   992: /*   for(j=0; j<p; j++) { */
                    993: /*     (u[j] = t[j]); */
                    994: /*   } */
                    995: /*      u[p]='\0'; */
1.126     brouard   996: 
1.137     brouard   997: /*    for(j=0; j<= lg; j++) { */
                    998: /*     if (j>=(p+1))(v[j-p-1] = t[j]); */
                    999: /*   } */
                   1000: /* } */
1.126     brouard  1001: 
1.160     brouard  1002: #ifdef _WIN32
                   1003: char * strsep(char **pp, const char *delim)
                   1004: {
                   1005:   char *p, *q;
                   1006:          
                   1007:   if ((p = *pp) == NULL)
                   1008:     return 0;
                   1009:   if ((q = strpbrk (p, delim)) != NULL)
                   1010:   {
                   1011:     *pp = q + 1;
                   1012:     *q = '\0';
                   1013:   }
                   1014:   else
                   1015:     *pp = 0;
                   1016:   return p;
                   1017: }
                   1018: #endif
                   1019: 
1.126     brouard  1020: /********************** nrerror ********************/
                   1021: 
                   1022: void nrerror(char error_text[])
                   1023: {
                   1024:   fprintf(stderr,"ERREUR ...\n");
                   1025:   fprintf(stderr,"%s\n",error_text);
                   1026:   exit(EXIT_FAILURE);
                   1027: }
                   1028: /*********************** vector *******************/
                   1029: double *vector(int nl, int nh)
                   1030: {
                   1031:   double *v;
                   1032:   v=(double *) malloc((size_t)((nh-nl+1+NR_END)*sizeof(double)));
                   1033:   if (!v) nrerror("allocation failure in vector");
                   1034:   return v-nl+NR_END;
                   1035: }
                   1036: 
                   1037: /************************ free vector ******************/
                   1038: void free_vector(double*v, int nl, int nh)
                   1039: {
                   1040:   free((FREE_ARG)(v+nl-NR_END));
                   1041: }
                   1042: 
                   1043: /************************ivector *******************************/
                   1044: int *ivector(long nl,long nh)
                   1045: {
                   1046:   int *v;
                   1047:   v=(int *) malloc((size_t)((nh-nl+1+NR_END)*sizeof(int)));
                   1048:   if (!v) nrerror("allocation failure in ivector");
                   1049:   return v-nl+NR_END;
                   1050: }
                   1051: 
                   1052: /******************free ivector **************************/
                   1053: void free_ivector(int *v, long nl, long nh)
                   1054: {
                   1055:   free((FREE_ARG)(v+nl-NR_END));
                   1056: }
                   1057: 
                   1058: /************************lvector *******************************/
                   1059: long *lvector(long nl,long nh)
                   1060: {
                   1061:   long *v;
                   1062:   v=(long *) malloc((size_t)((nh-nl+1+NR_END)*sizeof(long)));
                   1063:   if (!v) nrerror("allocation failure in ivector");
                   1064:   return v-nl+NR_END;
                   1065: }
                   1066: 
                   1067: /******************free lvector **************************/
                   1068: void free_lvector(long *v, long nl, long nh)
                   1069: {
                   1070:   free((FREE_ARG)(v+nl-NR_END));
                   1071: }
                   1072: 
                   1073: /******************* imatrix *******************************/
                   1074: int **imatrix(long nrl, long nrh, long ncl, long nch) 
                   1075:      /* allocate a int matrix with subscript range m[nrl..nrh][ncl..nch] */ 
                   1076: { 
                   1077:   long i, nrow=nrh-nrl+1,ncol=nch-ncl+1; 
                   1078:   int **m; 
                   1079:   
                   1080:   /* allocate pointers to rows */ 
                   1081:   m=(int **) malloc((size_t)((nrow+NR_END)*sizeof(int*))); 
                   1082:   if (!m) nrerror("allocation failure 1 in matrix()"); 
                   1083:   m += NR_END; 
                   1084:   m -= nrl; 
                   1085:   
                   1086:   
                   1087:   /* allocate rows and set pointers to them */ 
                   1088:   m[nrl]=(int *) malloc((size_t)((nrow*ncol+NR_END)*sizeof(int))); 
                   1089:   if (!m[nrl]) nrerror("allocation failure 2 in matrix()"); 
                   1090:   m[nrl] += NR_END; 
                   1091:   m[nrl] -= ncl; 
                   1092:   
                   1093:   for(i=nrl+1;i<=nrh;i++) m[i]=m[i-1]+ncol; 
                   1094:   
                   1095:   /* return pointer to array of pointers to rows */ 
                   1096:   return m; 
                   1097: } 
                   1098: 
                   1099: /****************** free_imatrix *************************/
                   1100: void free_imatrix(m,nrl,nrh,ncl,nch)
                   1101:       int **m;
                   1102:       long nch,ncl,nrh,nrl; 
                   1103:      /* free an int matrix allocated by imatrix() */ 
                   1104: { 
                   1105:   free((FREE_ARG) (m[nrl]+ncl-NR_END)); 
                   1106:   free((FREE_ARG) (m+nrl-NR_END)); 
                   1107: } 
                   1108: 
                   1109: /******************* matrix *******************************/
                   1110: double **matrix(long nrl, long nrh, long ncl, long nch)
                   1111: {
                   1112:   long i, nrow=nrh-nrl+1, ncol=nch-ncl+1;
                   1113:   double **m;
                   1114: 
                   1115:   m=(double **) malloc((size_t)((nrow+NR_END)*sizeof(double*)));
                   1116:   if (!m) nrerror("allocation failure 1 in matrix()");
                   1117:   m += NR_END;
                   1118:   m -= nrl;
                   1119: 
                   1120:   m[nrl]=(double *) malloc((size_t)((nrow*ncol+NR_END)*sizeof(double)));
                   1121:   if (!m[nrl]) nrerror("allocation failure 2 in matrix()");
                   1122:   m[nrl] += NR_END;
                   1123:   m[nrl] -= ncl;
                   1124: 
                   1125:   for (i=nrl+1; i<=nrh; i++) m[i]=m[i-1]+ncol;
                   1126:   return m;
1.145     brouard  1127:   /* print *(*(m+1)+70) or print m[1][70]; print m+1 or print &(m[1]) or &(m[1][0])
                   1128: m[i] = address of ith row of the table. &(m[i]) is its value which is another adress
                   1129: that of m[i][0]. In order to get the value p m[i][0] but it is unitialized.
1.126     brouard  1130:    */
                   1131: }
                   1132: 
                   1133: /*************************free matrix ************************/
                   1134: void free_matrix(double **m, long nrl, long nrh, long ncl, long nch)
                   1135: {
                   1136:   free((FREE_ARG)(m[nrl]+ncl-NR_END));
                   1137:   free((FREE_ARG)(m+nrl-NR_END));
                   1138: }
                   1139: 
                   1140: /******************* ma3x *******************************/
                   1141: double ***ma3x(long nrl, long nrh, long ncl, long nch, long nll, long nlh)
                   1142: {
                   1143:   long i, j, nrow=nrh-nrl+1, ncol=nch-ncl+1, nlay=nlh-nll+1;
                   1144:   double ***m;
                   1145: 
                   1146:   m=(double ***) malloc((size_t)((nrow+NR_END)*sizeof(double*)));
                   1147:   if (!m) nrerror("allocation failure 1 in matrix()");
                   1148:   m += NR_END;
                   1149:   m -= nrl;
                   1150: 
                   1151:   m[nrl]=(double **) malloc((size_t)((nrow*ncol+NR_END)*sizeof(double)));
                   1152:   if (!m[nrl]) nrerror("allocation failure 2 in matrix()");
                   1153:   m[nrl] += NR_END;
                   1154:   m[nrl] -= ncl;
                   1155: 
                   1156:   for (i=nrl+1; i<=nrh; i++) m[i]=m[i-1]+ncol;
                   1157: 
                   1158:   m[nrl][ncl]=(double *) malloc((size_t)((nrow*ncol*nlay+NR_END)*sizeof(double)));
                   1159:   if (!m[nrl][ncl]) nrerror("allocation failure 3 in matrix()");
                   1160:   m[nrl][ncl] += NR_END;
                   1161:   m[nrl][ncl] -= nll;
                   1162:   for (j=ncl+1; j<=nch; j++) 
                   1163:     m[nrl][j]=m[nrl][j-1]+nlay;
                   1164:   
                   1165:   for (i=nrl+1; i<=nrh; i++) {
                   1166:     m[i][ncl]=m[i-1l][ncl]+ncol*nlay;
                   1167:     for (j=ncl+1; j<=nch; j++) 
                   1168:       m[i][j]=m[i][j-1]+nlay;
                   1169:   }
                   1170:   return m; 
                   1171:   /*  gdb: p *(m+1) <=> p m[1] and p (m+1) <=> p (m+1) <=> p &(m[1])
                   1172:            &(m[i][j][k]) <=> *((*(m+i) + j)+k)
                   1173:   */
                   1174: }
                   1175: 
                   1176: /*************************free ma3x ************************/
                   1177: void free_ma3x(double ***m, long nrl, long nrh, long ncl, long nch,long nll, long nlh)
                   1178: {
                   1179:   free((FREE_ARG)(m[nrl][ncl]+ nll-NR_END));
                   1180:   free((FREE_ARG)(m[nrl]+ncl-NR_END));
                   1181:   free((FREE_ARG)(m+nrl-NR_END));
                   1182: }
                   1183: 
                   1184: /*************** function subdirf ***********/
                   1185: char *subdirf(char fileres[])
                   1186: {
                   1187:   /* Caution optionfilefiname is hidden */
                   1188:   strcpy(tmpout,optionfilefiname);
                   1189:   strcat(tmpout,"/"); /* Add to the right */
                   1190:   strcat(tmpout,fileres);
                   1191:   return tmpout;
                   1192: }
                   1193: 
                   1194: /*************** function subdirf2 ***********/
                   1195: char *subdirf2(char fileres[], char *preop)
                   1196: {
                   1197:   
                   1198:   /* Caution optionfilefiname is hidden */
                   1199:   strcpy(tmpout,optionfilefiname);
                   1200:   strcat(tmpout,"/");
                   1201:   strcat(tmpout,preop);
                   1202:   strcat(tmpout,fileres);
                   1203:   return tmpout;
                   1204: }
                   1205: 
                   1206: /*************** function subdirf3 ***********/
                   1207: char *subdirf3(char fileres[], char *preop, char *preop2)
                   1208: {
                   1209:   
                   1210:   /* Caution optionfilefiname is hidden */
                   1211:   strcpy(tmpout,optionfilefiname);
                   1212:   strcat(tmpout,"/");
                   1213:   strcat(tmpout,preop);
                   1214:   strcat(tmpout,preop2);
                   1215:   strcat(tmpout,fileres);
                   1216:   return tmpout;
                   1217: }
                   1218: 
1.162     brouard  1219: char *asc_diff_time(long time_sec, char ascdiff[])
                   1220: {
                   1221:   long sec_left, days, hours, minutes;
                   1222:   days = (time_sec) / (60*60*24);
                   1223:   sec_left = (time_sec) % (60*60*24);
                   1224:   hours = (sec_left) / (60*60) ;
                   1225:   sec_left = (sec_left) %(60*60);
                   1226:   minutes = (sec_left) /60;
                   1227:   sec_left = (sec_left) % (60);
                   1228:   sprintf(ascdiff,"%ld day(s) %ld hour(s) %ld minute(s) %ld second(s)",days, hours, minutes, sec_left);  
                   1229:   return ascdiff;
                   1230: }
                   1231: 
1.126     brouard  1232: /***************** f1dim *************************/
                   1233: extern int ncom; 
                   1234: extern double *pcom,*xicom;
                   1235: extern double (*nrfunc)(double []); 
                   1236:  
                   1237: double f1dim(double x) 
                   1238: { 
                   1239:   int j; 
                   1240:   double f;
                   1241:   double *xt; 
                   1242:  
                   1243:   xt=vector(1,ncom); 
                   1244:   for (j=1;j<=ncom;j++) xt[j]=pcom[j]+x*xicom[j]; 
                   1245:   f=(*nrfunc)(xt); 
                   1246:   free_vector(xt,1,ncom); 
                   1247:   return f; 
                   1248: } 
                   1249: 
                   1250: /*****************brent *************************/
                   1251: double brent(double ax, double bx, double cx, double (*f)(double), double tol,         double *xmin) 
                   1252: { 
                   1253:   int iter; 
                   1254:   double a,b,d,etemp;
1.159     brouard  1255:   double fu=0,fv,fw,fx;
1.164     brouard  1256:   double ftemp=0.;
1.126     brouard  1257:   double p,q,r,tol1,tol2,u,v,w,x,xm; 
                   1258:   double e=0.0; 
                   1259:  
                   1260:   a=(ax < cx ? ax : cx); 
                   1261:   b=(ax > cx ? ax : cx); 
                   1262:   x=w=v=bx; 
                   1263:   fw=fv=fx=(*f)(x); 
                   1264:   for (iter=1;iter<=ITMAX;iter++) { 
                   1265:     xm=0.5*(a+b); 
                   1266:     tol2=2.0*(tol1=tol*fabs(x)+ZEPS); 
                   1267:     /*         if (2.0*fabs(fp-(*fret)) <= ftol*(fabs(fp)+fabs(*fret)))*/
                   1268:     printf(".");fflush(stdout);
                   1269:     fprintf(ficlog,".");fflush(ficlog);
1.162     brouard  1270: #ifdef DEBUGBRENT
1.126     brouard  1271:     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);
                   1272:     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);
                   1273:     /*         if ((fabs(x-xm) <= (tol2-0.5*(b-a)))||(2.0*fabs(fu-ftemp) <= ftol*1.e-2*(fabs(fu)+fabs(ftemp)))) { */
                   1274: #endif
                   1275:     if (fabs(x-xm) <= (tol2-0.5*(b-a))){ 
                   1276:       *xmin=x; 
                   1277:       return fx; 
                   1278:     } 
                   1279:     ftemp=fu;
                   1280:     if (fabs(e) > tol1) { 
                   1281:       r=(x-w)*(fx-fv); 
                   1282:       q=(x-v)*(fx-fw); 
                   1283:       p=(x-v)*q-(x-w)*r; 
                   1284:       q=2.0*(q-r); 
                   1285:       if (q > 0.0) p = -p; 
                   1286:       q=fabs(q); 
                   1287:       etemp=e; 
                   1288:       e=d; 
                   1289:       if (fabs(p) >= fabs(0.5*q*etemp) || p <= q*(a-x) || p >= q*(b-x)) 
                   1290:        d=CGOLD*(e=(x >= xm ? a-x : b-x)); 
                   1291:       else { 
                   1292:        d=p/q; 
                   1293:        u=x+d; 
                   1294:        if (u-a < tol2 || b-u < tol2) 
                   1295:          d=SIGN(tol1,xm-x); 
                   1296:       } 
                   1297:     } else { 
                   1298:       d=CGOLD*(e=(x >= xm ? a-x : b-x)); 
                   1299:     } 
                   1300:     u=(fabs(d) >= tol1 ? x+d : x+SIGN(tol1,d)); 
                   1301:     fu=(*f)(u); 
                   1302:     if (fu <= fx) { 
                   1303:       if (u >= x) a=x; else b=x; 
                   1304:       SHFT(v,w,x,u) 
1.183     brouard  1305:       SHFT(fv,fw,fx,fu) 
                   1306:     } else { 
                   1307:       if (u < x) a=u; else b=u; 
                   1308:       if (fu <= fw || w == x) { 
                   1309:        v=w; 
                   1310:        w=u; 
                   1311:        fv=fw; 
                   1312:        fw=fu; 
                   1313:       } else if (fu <= fv || v == x || v == w) { 
                   1314:        v=u; 
                   1315:        fv=fu; 
                   1316:       } 
                   1317:     } 
1.126     brouard  1318:   } 
                   1319:   nrerror("Too many iterations in brent"); 
                   1320:   *xmin=x; 
                   1321:   return fx; 
                   1322: } 
                   1323: 
                   1324: /****************** mnbrak ***********************/
                   1325: 
                   1326: void mnbrak(double *ax, double *bx, double *cx, double *fa, double *fb, double *fc, 
                   1327:            double (*func)(double)) 
1.183     brouard  1328: { /* Given a function func , and given distinct initial points ax and bx , this routine searches in
                   1329: the downhill direction (defined by the function as evaluated at the initial points) and returns
                   1330: new points ax , bx , cx that bracket a minimum of the function. Also returned are the function
                   1331: values at the three points, fa, fb , and fc such that fa > fb and fb < fc.
                   1332:    */
1.126     brouard  1333:   double ulim,u,r,q, dum;
                   1334:   double fu; 
                   1335:  
                   1336:   *fa=(*func)(*ax); 
                   1337:   *fb=(*func)(*bx); 
                   1338:   if (*fb > *fa) { 
                   1339:     SHFT(dum,*ax,*bx,dum) 
1.183     brouard  1340:     SHFT(dum,*fb,*fa,dum) 
                   1341:   } 
1.126     brouard  1342:   *cx=(*bx)+GOLD*(*bx-*ax); 
                   1343:   *fc=(*func)(*cx); 
1.183     brouard  1344: #ifdef DEBUG
                   1345:   printf("mnbrak0 *fb=%.12e *fc=%.12e\n",*fb,*fc);
                   1346:   fprintf(ficlog,"mnbrak0 *fb=%.12e *fc=%.12e\n",*fb,*fc);
                   1347: #endif
                   1348:   while (*fb > *fc) { /* Declining a,b,c with fa> fb > fc */
1.126     brouard  1349:     r=(*bx-*ax)*(*fb-*fc); 
                   1350:     q=(*bx-*cx)*(*fb-*fa); 
                   1351:     u=(*bx)-((*bx-*cx)*q-(*bx-*ax)*r)/ 
1.183     brouard  1352:       (2.0*SIGN(FMAX(fabs(q-r),TINY),q-r)); /* Minimum abscissa of a parabolic estimated from (a,fa), (b,fb) and (c,fc). */
                   1353:     ulim=(*bx)+GLIMIT*(*cx-*bx); /* Maximum abscissa where function should be evaluated */
                   1354:     if ((*bx-u)*(u-*cx) > 0.0) { /* if u_p is between b and c */
1.126     brouard  1355:       fu=(*func)(u); 
1.163     brouard  1356: #ifdef DEBUG
                   1357:       /* f(x)=A(x-u)**2+f(u) */
                   1358:       double A, fparabu; 
                   1359:       A= (*fb - *fa)/(*bx-*ax)/(*bx+*ax-2*u);
                   1360:       fparabu= *fa - A*(*ax-u)*(*ax-u);
                   1361:       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);
                   1362:       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  1363:       /* And thus,it can be that fu > *fc even if fparabu < *fc */
                   1364:       /* mnbrak (*ax=7.666299858533, *fa=299039.693133272231), (*bx=8.595447774979, *fb=298976.598289369489),
                   1365:         (*cx=10.098840694817, *fc=298946.631474258087),  (*u=9.852501168332, fu=298948.773013752128, fparabu=298945.434711494134) */
                   1366:       /* In that case, there is no bracket in the output! Routine is wrong with many consequences.*/
1.163     brouard  1367: #endif 
1.184     brouard  1368: #ifdef MNBRAKORIGINAL
1.183     brouard  1369: #else
                   1370:       if (fu > *fc) {
                   1371: #ifdef DEBUG
                   1372:       printf("mnbrak4  fu > fc \n");
                   1373:       fprintf(ficlog, "mnbrak4 fu > fc\n");
                   1374: #endif
                   1375:        /* 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 *\/  */
                   1376:        /* SHFT(*fa,*fc,fu,*fc) /\* (b, u, c) is a bracket while test fb > fc will be fu > fc  will exit *\/ */
                   1377:        dum=u; /* Shifting c and u */
                   1378:        u = *cx;
                   1379:        *cx = dum;
                   1380:        dum = fu;
                   1381:        fu = *fc;
                   1382:        *fc =dum;
                   1383:       } else { /* end */
                   1384: #ifdef DEBUG
                   1385:       printf("mnbrak3  fu < fc \n");
                   1386:       fprintf(ficlog, "mnbrak3 fu < fc\n");
                   1387: #endif
                   1388:        dum=u; /* Shifting c and u */
                   1389:        u = *cx;
                   1390:        *cx = dum;
                   1391:        dum = fu;
                   1392:        fu = *fc;
                   1393:        *fc =dum;
                   1394:       }
                   1395: #endif
1.162     brouard  1396:     } else if ((*cx-u)*(u-ulim) > 0.0) { /* u is after c but before ulim */
1.183     brouard  1397: #ifdef DEBUG
                   1398:       printf("mnbrak2  u after c but before ulim\n");
                   1399:       fprintf(ficlog, "mnbrak2 u after c but before ulim\n");
                   1400: #endif
1.126     brouard  1401:       fu=(*func)(u); 
                   1402:       if (fu < *fc) { 
1.183     brouard  1403: #ifdef DEBUG
                   1404:       printf("mnbrak2  u after c but before ulim AND fu < fc\n");
                   1405:       fprintf(ficlog, "mnbrak2 u after c but before ulim AND fu <fc \n");
                   1406: #endif
1.126     brouard  1407:        SHFT(*bx,*cx,u,*cx+GOLD*(*cx-*bx)) 
1.183     brouard  1408:        SHFT(*fb,*fc,fu,(*func)(u)) 
                   1409:       } 
1.162     brouard  1410:     } else if ((u-ulim)*(ulim-*cx) >= 0.0) { /* u outside ulim (verifying that ulim is beyond c) */
1.183     brouard  1411: #ifdef DEBUG
                   1412:       printf("mnbrak2  u outside ulim (verifying that ulim is beyond c)\n");
                   1413:       fprintf(ficlog, "mnbrak2 u outside ulim (verifying that ulim is beyond c)\n");
                   1414: #endif
1.126     brouard  1415:       u=ulim; 
                   1416:       fu=(*func)(u); 
1.183     brouard  1417:     } else { /* u could be left to b (if r > q parabola has a maximum) */
                   1418: #ifdef DEBUG
                   1419:       printf("mnbrak2  u could be left to b (if r > q parabola has a maximum)\n");
                   1420:       fprintf(ficlog, "mnbrak2  u could be left to b (if r > q parabola has a maximum)\n");
                   1421: #endif
1.126     brouard  1422:       u=(*cx)+GOLD*(*cx-*bx); 
                   1423:       fu=(*func)(u); 
1.183     brouard  1424:     } /* end tests */
1.126     brouard  1425:     SHFT(*ax,*bx,*cx,u) 
1.183     brouard  1426:     SHFT(*fa,*fb,*fc,fu) 
                   1427: #ifdef DEBUG
                   1428:       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);
                   1429:       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);
                   1430: #endif
                   1431:   } /* 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  1432: } 
                   1433: 
                   1434: /*************** linmin ************************/
1.162     brouard  1435: /* Given an n -dimensional point p[1..n] and an n -dimensional direction xi[1..n] , moves and
                   1436: resets p to where the function func(p) takes on a minimum along the direction xi from p ,
                   1437: and replaces xi by the actual vector displacement that p was moved. Also returns as fret
                   1438: the value of func at the returned location p . This is actually all accomplished by calling the
                   1439: routines mnbrak and brent .*/
1.126     brouard  1440: int ncom; 
                   1441: double *pcom,*xicom;
                   1442: double (*nrfunc)(double []); 
                   1443:  
                   1444: void linmin(double p[], double xi[], int n, double *fret,double (*func)(double [])) 
                   1445: { 
                   1446:   double brent(double ax, double bx, double cx, 
                   1447:               double (*f)(double), double tol, double *xmin); 
                   1448:   double f1dim(double x); 
                   1449:   void mnbrak(double *ax, double *bx, double *cx, double *fa, double *fb, 
                   1450:              double *fc, double (*func)(double)); 
                   1451:   int j; 
                   1452:   double xx,xmin,bx,ax; 
                   1453:   double fx,fb,fa;
                   1454:  
                   1455:   ncom=n; 
                   1456:   pcom=vector(1,n); 
                   1457:   xicom=vector(1,n); 
                   1458:   nrfunc=func; 
                   1459:   for (j=1;j<=n;j++) { 
                   1460:     pcom[j]=p[j]; 
                   1461:     xicom[j]=xi[j]; 
                   1462:   } 
                   1463:   ax=0.0; 
                   1464:   xx=1.0; 
1.162     brouard  1465:   mnbrak(&ax,&xx,&bx,&fa,&fx,&fb,f1dim); /* Find a bracket a,x,b in direction n=xi ie xicom */
                   1466:   *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  1467: #ifdef DEBUG
                   1468:   printf("retour brent fret=%.12e xmin=%.12e\n",*fret,xmin);
                   1469:   fprintf(ficlog,"retour brent fret=%.12e xmin=%.12e\n",*fret,xmin);
                   1470: #endif
                   1471:   for (j=1;j<=n;j++) { 
                   1472:     xi[j] *= xmin; 
                   1473:     p[j] += xi[j]; 
                   1474:   } 
                   1475:   free_vector(xicom,1,n); 
                   1476:   free_vector(pcom,1,n); 
                   1477: } 
                   1478: 
                   1479: 
                   1480: /*************** powell ************************/
1.162     brouard  1481: /*
                   1482: Minimization of a function func of n variables. Input consists of an initial starting point
                   1483: p[1..n] ; an initial matrix xi[1..n][1..n] , whose columns contain the initial set of di-
                   1484: rections (usually the n unit vectors); and ftol , the fractional tolerance in the function value
                   1485: such that failure to decrease by more than this amount on one iteration signals doneness. On
                   1486: output, p is set to the best point found, xi is the then-current direction set, fret is the returned
                   1487: function value at p , and iter is the number of iterations taken. The routine linmin is used.
                   1488:  */
1.126     brouard  1489: void powell(double p[], double **xi, int n, double ftol, int *iter, double *fret, 
                   1490:            double (*func)(double [])) 
                   1491: { 
                   1492:   void linmin(double p[], double xi[], int n, double *fret, 
                   1493:              double (*func)(double [])); 
                   1494:   int i,ibig,j; 
                   1495:   double del,t,*pt,*ptt,*xit;
1.181     brouard  1496:   double directest;
1.126     brouard  1497:   double fp,fptt;
                   1498:   double *xits;
                   1499:   int niterf, itmp;
                   1500: 
                   1501:   pt=vector(1,n); 
                   1502:   ptt=vector(1,n); 
                   1503:   xit=vector(1,n); 
                   1504:   xits=vector(1,n); 
                   1505:   *fret=(*func)(p); 
                   1506:   for (j=1;j<=n;j++) pt[j]=p[j]; 
1.157     brouard  1507:     rcurr_time = time(NULL);  
1.126     brouard  1508:   for (*iter=1;;++(*iter)) { 
                   1509:     fp=(*fret); 
                   1510:     ibig=0; 
                   1511:     del=0.0; 
1.157     brouard  1512:     rlast_time=rcurr_time;
                   1513:     /* (void) gettimeofday(&curr_time,&tzp); */
                   1514:     rcurr_time = time(NULL);  
                   1515:     curr_time = *localtime(&rcurr_time);
                   1516:     printf("\nPowell iter=%d -2*LL=%.12f %ld sec. %ld sec.",*iter,*fret, rcurr_time-rlast_time, rcurr_time-rstart_time);fflush(stdout);
                   1517:     fprintf(ficlog,"\nPowell iter=%d -2*LL=%.12f %ld sec. %ld sec.",*iter,*fret,rcurr_time-rlast_time, rcurr_time-rstart_time); fflush(ficlog);
                   1518: /*     fprintf(ficrespow,"%d %.12f %ld",*iter,*fret,curr_time.tm_sec-start_time.tm_sec); */
1.126     brouard  1519:    for (i=1;i<=n;i++) {
                   1520:       printf(" %d %.12f",i, p[i]);
                   1521:       fprintf(ficlog," %d %.12lf",i, p[i]);
                   1522:       fprintf(ficrespow," %.12lf", p[i]);
                   1523:     }
                   1524:     printf("\n");
                   1525:     fprintf(ficlog,"\n");
                   1526:     fprintf(ficrespow,"\n");fflush(ficrespow);
                   1527:     if(*iter <=3){
1.157     brouard  1528:       tml = *localtime(&rcurr_time);
                   1529:       strcpy(strcurr,asctime(&tml));
                   1530:       rforecast_time=rcurr_time; 
1.126     brouard  1531:       itmp = strlen(strcurr);
                   1532:       if(strcurr[itmp-1]=='\n')  /* Windows outputs with a new line */
                   1533:        strcurr[itmp-1]='\0';
1.162     brouard  1534:       printf("\nConsidering the time needed for the last iteration #%d: %ld seconds,\n",*iter,rcurr_time-rlast_time);
1.157     brouard  1535:       fprintf(ficlog,"\nConsidering the time needed for this last iteration #%d: %ld seconds,\n",*iter,rcurr_time-rlast_time);
1.126     brouard  1536:       for(niterf=10;niterf<=30;niterf+=10){
1.157     brouard  1537:        rforecast_time=rcurr_time+(niterf-*iter)*(rcurr_time-rlast_time);
                   1538:        forecast_time = *localtime(&rforecast_time);
                   1539:        strcpy(strfor,asctime(&forecast_time));
1.126     brouard  1540:        itmp = strlen(strfor);
                   1541:        if(strfor[itmp-1]=='\n')
                   1542:        strfor[itmp-1]='\0';
1.157     brouard  1543:        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);
                   1544:        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  1545:       }
                   1546:     }
                   1547:     for (i=1;i<=n;i++) { 
                   1548:       for (j=1;j<=n;j++) xit[j]=xi[j][i]; 
                   1549:       fptt=(*fret); 
                   1550: #ifdef DEBUG
1.164     brouard  1551:          printf("fret=%lf, %lf, %lf \n", *fret, *fret, *fret);
                   1552:          fprintf(ficlog, "fret=%lf, %lf, %lf \n", *fret, *fret, *fret);
1.126     brouard  1553: #endif
                   1554:       printf("%d",i);fflush(stdout);
                   1555:       fprintf(ficlog,"%d",i);fflush(ficlog);
1.183     brouard  1556:       linmin(p,xit,n,fret,func); /* xit[n] has been loaded for direction i */
1.181     brouard  1557:       if (fabs(fptt-(*fret)) > del) { /* We are keeping the max gain on each of the n directions 
                   1558:                                       because that direction will be replaced unless the gain del is small
                   1559:                                      in comparison with the 'probable' gain, mu^2, with the last average direction.
                   1560:                                      Unless the n directions are conjugate some gain in the determinant may be obtained
                   1561:                                      with the new direction.
                   1562:                                      */
1.126     brouard  1563:        del=fabs(fptt-(*fret)); 
                   1564:        ibig=i; 
                   1565:       } 
                   1566: #ifdef DEBUG
                   1567:       printf("%d %.12e",i,(*fret));
                   1568:       fprintf(ficlog,"%d %.12e",i,(*fret));
                   1569:       for (j=1;j<=n;j++) {
                   1570:        xits[j]=FMAX(fabs(p[j]-pt[j]),1.e-5);
                   1571:        printf(" x(%d)=%.12e",j,xit[j]);
                   1572:        fprintf(ficlog," x(%d)=%.12e",j,xit[j]);
                   1573:       }
                   1574:       for(j=1;j<=n;j++) {
1.162     brouard  1575:        printf(" p(%d)=%.12e",j,p[j]);
                   1576:        fprintf(ficlog," p(%d)=%.12e",j,p[j]);
1.126     brouard  1577:       }
                   1578:       printf("\n");
                   1579:       fprintf(ficlog,"\n");
                   1580: #endif
1.162     brouard  1581:     } /* end i */
1.182     brouard  1582:     if (2.0*fabs(fp-(*fret)) <= ftol*(fabs(fp)+fabs(*fret))) { /* Did we reach enough precision? */
1.126     brouard  1583: #ifdef DEBUG
                   1584:       int k[2],l;
                   1585:       k[0]=1;
                   1586:       k[1]=-1;
                   1587:       printf("Max: %.12e",(*func)(p));
                   1588:       fprintf(ficlog,"Max: %.12e",(*func)(p));
                   1589:       for (j=1;j<=n;j++) {
                   1590:        printf(" %.12e",p[j]);
                   1591:        fprintf(ficlog," %.12e",p[j]);
                   1592:       }
                   1593:       printf("\n");
                   1594:       fprintf(ficlog,"\n");
                   1595:       for(l=0;l<=1;l++) {
                   1596:        for (j=1;j<=n;j++) {
                   1597:          ptt[j]=p[j]+(p[j]-pt[j])*k[l];
                   1598:          printf("l=%d j=%d ptt=%.12e, xits=%.12e, p=%.12e, xit=%.12e", l,j,ptt[j],xits[j],p[j],xit[j]);
                   1599:          fprintf(ficlog,"l=%d j=%d ptt=%.12e, xits=%.12e, p=%.12e, xit=%.12e", l,j,ptt[j],xits[j],p[j],xit[j]);
                   1600:        }
                   1601:        printf("func(ptt)=%.12e, deriv=%.12e\n",(*func)(ptt),(ptt[j]-p[j])/((*func)(ptt)-(*func)(p)));
                   1602:        fprintf(ficlog,"func(ptt)=%.12e, deriv=%.12e\n",(*func)(ptt),(ptt[j]-p[j])/((*func)(ptt)-(*func)(p)));
                   1603:       }
                   1604: #endif
                   1605: 
                   1606: 
                   1607:       free_vector(xit,1,n); 
                   1608:       free_vector(xits,1,n); 
                   1609:       free_vector(ptt,1,n); 
                   1610:       free_vector(pt,1,n); 
                   1611:       return; 
                   1612:     } 
                   1613:     if (*iter == ITMAX) nrerror("powell exceeding maximum iterations."); 
1.181     brouard  1614:     for (j=1;j<=n;j++) { /* Computes the extrapolated point P_0 + 2 (P_n-P_0) */
1.126     brouard  1615:       ptt[j]=2.0*p[j]-pt[j]; 
                   1616:       xit[j]=p[j]-pt[j]; 
                   1617:       pt[j]=p[j]; 
                   1618:     } 
1.181     brouard  1619:     fptt=(*func)(ptt); /* f_3 */
1.161     brouard  1620:     if (fptt < fp) { /* If extrapolated point is better, decide if we keep that new direction or not */
1.162     brouard  1621:       /* (x1 f1=fp), (x2 f2=*fret), (x3 f3=fptt), (xm fm) */
1.161     brouard  1622:       /* From x1 (P0) distance of x2 is at h and x3 is 2h */
1.162     brouard  1623:       /* Let f"(x2) be the 2nd derivative equal everywhere.  */
                   1624:       /* Then the parabolic through (x1,f1), (x2,f2) and (x3,f3) */
                   1625:       /* will reach at f3 = fm + h^2/2 f"m  ; f" = (f1 -2f2 +f3 ) / h**2 */
1.181     brouard  1626:       /* Conditional for using this new direction is that mu^2 = (f1-2f2+f3)^2 /2 < del */
1.161     brouard  1627:       /* t=2.0*(fp-2.0*(*fret)+fptt)*SQR(fp-(*fret)-del)-del*SQR(fp-fptt); */
1.183     brouard  1628: #ifdef NRCORIGINAL
                   1629:       t=2.0*(fp-2.0*(*fret)+fptt)*SQR(fp-(*fret)-del)- del*SQR(fp-fptt); /* Original Numerical Recipes in C*/
                   1630: #else
                   1631:       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  1632:       t= t- del*SQR(fp-fptt);
1.183     brouard  1633: #endif
1.182     brouard  1634:       directest = fp-2.0*(*fret)+fptt - 2.0 * del; /* If del was big enough we change it for a new direction */
1.161     brouard  1635: #ifdef DEBUG
1.181     brouard  1636:       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);
                   1637:       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  1638:       printf("t3= %.12lf, t4= %.12lf, t3*= %.12lf, t4*= %.12lf\n",SQR(fp-(*fret)-del),SQR(fp-fptt),
                   1639:             (fp-(*fret)-del)*(fp-(*fret)-del),(fp-fptt)*(fp-fptt));
                   1640:       fprintf(ficlog,"t3= %.12lf, t4= %.12lf, t3*= %.12lf, t4*= %.12lf\n",SQR(fp-(*fret)-del),SQR(fp-fptt),
                   1641:             (fp-(*fret)-del)*(fp-(*fret)-del),(fp-fptt)*(fp-fptt));
                   1642:       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);
                   1643:       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);
                   1644: #endif
1.183     brouard  1645: #ifdef POWELLORIGINAL
                   1646:       if (t < 0.0) { /* Then we use it for new direction */
                   1647: #else
1.182     brouard  1648:       if (directest*t < 0.0) { /* Contradiction between both tests */
1.184     brouard  1649:       printf("directest= %.12lf, t= %.12lf, f1= %.12lf,f2= %.12lf,f3= %.12lf, del= %.12lf\n",directest, t, fp,(*fret),fptt,del);
1.182     brouard  1650:       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  1651:       fprintf(ficlog,"directest= %.12lf, t= %.12lf, f1= %.12lf,f2= %.12lf,f3= %.12lf, del= %.12lf\n",directest, t, fp,(*fret),fptt, del);
1.182     brouard  1652:       fprintf(ficlog,"f1-2f2+f3= %.12lf, f1-f2-del= %.12lf, f1-f3= %.12lf\n",fp-2.0*(*fret)+fptt, fp -(*fret) -del, fp-fptt);
                   1653:     } 
1.181     brouard  1654:       if (directest < 0.0) { /* Then we use it for new direction */
                   1655: #endif
                   1656:        linmin(p,xit,n,fret,func); /* computes minimum on the extrapolated direction.*/
1.126     brouard  1657:        for (j=1;j<=n;j++) { 
1.181     brouard  1658:          xi[j][ibig]=xi[j][n]; /* Replace direction with biggest decrease by last direction n */
                   1659:          xi[j][n]=xit[j];      /* and this nth direction by the by the average p_0 p_n */
1.126     brouard  1660:        }
1.181     brouard  1661:        printf("Gaining to use new average direction of P0 P%d instead of biggest increase direction %d :\n",n,ibig);
                   1662:        fprintf(ficlog,"Gaining to use new average direction of P0 P%d instead of biggest increase direction %d :\n",n,ibig);
1.161     brouard  1663: 
1.126     brouard  1664: #ifdef DEBUG
1.164     brouard  1665:        printf("Direction changed  last moved %d in place of ibig=%d, new last is the average:\n",n,ibig);
                   1666:        fprintf(ficlog,"Direction changed  last moved %d in place of ibig=%d, new last is the average:\n",n,ibig);
1.126     brouard  1667:        for(j=1;j<=n;j++){
                   1668:          printf(" %.12e",xit[j]);
                   1669:          fprintf(ficlog," %.12e",xit[j]);
                   1670:        }
                   1671:        printf("\n");
                   1672:        fprintf(ficlog,"\n");
                   1673: #endif
1.162     brouard  1674:       } /* end of t negative */
                   1675:     } /* end if (fptt < fp)  */
1.126     brouard  1676:   } 
                   1677: } 
                   1678: 
                   1679: /**** Prevalence limit (stable or period prevalence)  ****************/
                   1680: 
                   1681: double **prevalim(double **prlim, int nlstate, double x[], double age, double **oldm, double **savm, double ftolpl, int ij)
                   1682: {
                   1683:   /* Computes the prevalence limit in each live state at age x by left multiplying the unit
                   1684:      matrix by transitions matrix until convergence is reached */
1.169     brouard  1685:   
1.126     brouard  1686:   int i, ii,j,k;
                   1687:   double min, max, maxmin, maxmax,sumnew=0.;
1.145     brouard  1688:   /* double **matprod2(); */ /* test */
1.131     brouard  1689:   double **out, cov[NCOVMAX+1], **pmij();
1.126     brouard  1690:   double **newm;
                   1691:   double agefin, delaymax=50 ; /* Max number of years to converge */
1.169     brouard  1692:   
1.126     brouard  1693:   for (ii=1;ii<=nlstate+ndeath;ii++)
                   1694:     for (j=1;j<=nlstate+ndeath;j++){
                   1695:       oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   1696:     }
1.169     brouard  1697:   
                   1698:   cov[1]=1.;
                   1699:   
                   1700:   /* Even if hstepm = 1, at least one multiplication by the unit matrix */
1.126     brouard  1701:   for(agefin=age-stepm/YEARM; agefin>=age-delaymax; agefin=agefin-stepm/YEARM){
                   1702:     newm=savm;
                   1703:     /* Covariates have to be included here again */
1.138     brouard  1704:     cov[2]=agefin;
                   1705:     
                   1706:     for (k=1; k<=cptcovn;k++) {
                   1707:       cov[2+k]=nbcode[Tvar[k]][codtab[ij][Tvar[k]]];
1.145     brouard  1708:       /*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  1709:     }
1.186   ! brouard  1710:     /*wrong? for (k=1; k<=cptcovage;k++) cov[2+Tage[k]]=cov[2+Tage[k]]*cov[2]; */
        !          1711:     for (k=1; k<=cptcovage;k++) cov[2+Tage[k]]=nbcode[Tvar[k]][codtab[ij][Tvar[k]]]*cov[2];
        !          1712:     for (k=1; k<=cptcovprod;k++) /* Useless */
        !          1713:       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  1714:     
                   1715:     /*printf("ij=%d cptcovprod=%d tvar=%d ", ij, cptcovprod, Tvar[1]);*/
                   1716:     /*printf("ij=%d cov[3]=%lf cov[4]=%lf \n",ij, cov[3],cov[4]);*/
                   1717:     /*printf("ij=%d cov[3]=%lf \n",ij, cov[3]);*/
1.145     brouard  1718:     /* savm=pmij(pmmij,cov,ncovmodel,x,nlstate); */
                   1719:     /* out=matprod2(newm, pmij(pmmij,cov,ncovmodel,x,nlstate),1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, oldm); /\* Bug Valgrind *\/ */
1.142     brouard  1720:     out=matprod2(newm, pmij(pmmij,cov,ncovmodel,x,nlstate),1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, oldm); /* Bug Valgrind */
1.138     brouard  1721:     
1.126     brouard  1722:     savm=oldm;
                   1723:     oldm=newm;
                   1724:     maxmax=0.;
                   1725:     for(j=1;j<=nlstate;j++){
                   1726:       min=1.;
                   1727:       max=0.;
                   1728:       for(i=1; i<=nlstate; i++) {
                   1729:        sumnew=0;
                   1730:        for(k=1; k<=ndeath; k++) sumnew+=newm[i][nlstate+k];
                   1731:        prlim[i][j]= newm[i][j]/(1-sumnew);
1.145     brouard  1732:         /*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  1733:        max=FMAX(max,prlim[i][j]);
                   1734:        min=FMIN(min,prlim[i][j]);
                   1735:       }
                   1736:       maxmin=max-min;
                   1737:       maxmax=FMAX(maxmax,maxmin);
1.169     brouard  1738:     } /* j loop */
1.126     brouard  1739:     if(maxmax < ftolpl){
                   1740:       return prlim;
                   1741:     }
1.169     brouard  1742:   } /* age loop */
                   1743:   return prlim; /* should not reach here */
1.126     brouard  1744: }
                   1745: 
                   1746: /*************** transition probabilities ***************/ 
                   1747: 
                   1748: double **pmij(double **ps, double *cov, int ncovmodel, double *x, int nlstate )
                   1749: {
1.138     brouard  1750:   /* According to parameters values stored in x and the covariate's values stored in cov,
                   1751:      computes the probability to be observed in state j being in state i by appying the
                   1752:      model to the ncovmodel covariates (including constant and age).
                   1753:      lnpijopii=ln(pij/pii)= aij+bij*age+cij*v1+dij*v2+... = sum_nc=1^ncovmodel xij(nc)*cov[nc]
                   1754:      and, according on how parameters are entered, the position of the coefficient xij(nc) of the
                   1755:      ncth covariate in the global vector x is given by the formula:
                   1756:      j<i nc+((i-1)*(nlstate+ndeath-1)+j-1)*ncovmodel
                   1757:      j>=i nc + ((i-1)*(nlstate+ndeath-1)+(j-2))*ncovmodel
                   1758:      Computes ln(pij/pii) (lnpijopii), deduces pij/pii by exponentiation,
                   1759:      sums on j different of i to get 1-pii/pii, deduces pii, and then all pij.
                   1760:      Outputs ps[i][j] the probability to be observed in j being in j according to
                   1761:      the values of the covariates cov[nc] and corresponding parameter values x[nc+shiftij]
                   1762:   */
                   1763:   double s1, lnpijopii;
1.126     brouard  1764:   /*double t34;*/
1.164     brouard  1765:   int i,j, nc, ii, jj;
1.126     brouard  1766: 
                   1767:     for(i=1; i<= nlstate; i++){
                   1768:       for(j=1; j<i;j++){
1.138     brouard  1769:        for (nc=1, lnpijopii=0.;nc <=ncovmodel; nc++){
                   1770:          /*lnpijopii += param[i][j][nc]*cov[nc];*/
                   1771:          lnpijopii += x[nc+((i-1)*(nlstate+ndeath-1)+j-1)*ncovmodel]*cov[nc];
                   1772: /*      printf("Int j<i s1=%.17e, lnpijopii=%.17e\n",s1,lnpijopii); */
1.126     brouard  1773:        }
1.138     brouard  1774:        ps[i][j]=lnpijopii; /* In fact ln(pij/pii) */
                   1775: /*     printf("s1=%.17e, lnpijopii=%.17e\n",s1,lnpijopii); */
1.126     brouard  1776:       }
                   1777:       for(j=i+1; j<=nlstate+ndeath;j++){
1.138     brouard  1778:        for (nc=1, lnpijopii=0.;nc <=ncovmodel; nc++){
                   1779:          /*lnpijopii += x[(i-1)*nlstate*ncovmodel+(j-2)*ncovmodel+nc+(i-1)*(ndeath-1)*ncovmodel]*cov[nc];*/
                   1780:          lnpijopii += x[nc + ((i-1)*(nlstate+ndeath-1)+(j-2))*ncovmodel]*cov[nc];
                   1781: /*       printf("Int j>i s1=%.17e, lnpijopii=%.17e %lx %lx\n",s1,lnpijopii,s1,lnpijopii); */
1.126     brouard  1782:        }
1.138     brouard  1783:        ps[i][j]=lnpijopii; /* In fact ln(pij/pii) */
1.126     brouard  1784:       }
                   1785:     }
                   1786:     
                   1787:     for(i=1; i<= nlstate; i++){
                   1788:       s1=0;
1.131     brouard  1789:       for(j=1; j<i; j++){
1.138     brouard  1790:        s1+=exp(ps[i][j]); /* In fact sums pij/pii */
1.131     brouard  1791:        /*printf("debug1 %d %d ps=%lf exp(ps)=%lf s1+=%lf\n",i,j,ps[i][j],exp(ps[i][j]),s1); */
                   1792:       }
                   1793:       for(j=i+1; j<=nlstate+ndeath; j++){
1.138     brouard  1794:        s1+=exp(ps[i][j]); /* In fact sums pij/pii */
1.131     brouard  1795:        /*printf("debug2 %d %d ps=%lf exp(ps)=%lf s1+=%lf\n",i,j,ps[i][j],exp(ps[i][j]),s1); */
                   1796:       }
1.138     brouard  1797:       /* s1= sum_{j<>i} pij/pii=(1-pii)/pii and thus pii is known from s1 */
1.126     brouard  1798:       ps[i][i]=1./(s1+1.);
1.138     brouard  1799:       /* Computing other pijs */
1.126     brouard  1800:       for(j=1; j<i; j++)
                   1801:        ps[i][j]= exp(ps[i][j])*ps[i][i];
                   1802:       for(j=i+1; j<=nlstate+ndeath; j++)
                   1803:        ps[i][j]= exp(ps[i][j])*ps[i][i];
                   1804:       /* ps[i][nlstate+1]=1.-s1- ps[i][i];*/ /* Sum should be 1 */
                   1805:     } /* end i */
                   1806:     
                   1807:     for(ii=nlstate+1; ii<= nlstate+ndeath; ii++){
                   1808:       for(jj=1; jj<= nlstate+ndeath; jj++){
                   1809:        ps[ii][jj]=0;
                   1810:        ps[ii][ii]=1;
                   1811:       }
                   1812:     }
                   1813:     
1.145     brouard  1814:     
                   1815:     /* for(ii=1; ii<= nlstate+ndeath; ii++){ */
                   1816:     /*   for(jj=1; jj<= nlstate+ndeath; jj++){ */
                   1817:     /*         printf(" pmij  ps[%d][%d]=%lf ",ii,jj,ps[ii][jj]); */
                   1818:     /*   } */
                   1819:     /*   printf("\n "); */
                   1820:     /* } */
                   1821:     /* printf("\n ");printf("%lf ",cov[2]);*/
                   1822:     /*
1.126     brouard  1823:       for(i=1; i<= npar; i++) printf("%f ",x[i]);
                   1824:       goto end;*/
                   1825:     return ps;
                   1826: }
                   1827: 
                   1828: /**************** Product of 2 matrices ******************/
                   1829: 
1.145     brouard  1830: double **matprod2(double **out, double **in,int nrl, int nrh, int ncl, int nch, int ncolol, int ncoloh, double **b)
1.126     brouard  1831: {
                   1832:   /* Computes the matrix product of in(1,nrh-nrl+1)(1,nch-ncl+1) times
                   1833:      b(1,nch-ncl+1)(1,ncoloh-ncolol+1) into out(...) */
                   1834:   /* in, b, out are matrice of pointers which should have been initialized 
                   1835:      before: only the contents of out is modified. The function returns
                   1836:      a pointer to pointers identical to out */
1.145     brouard  1837:   int i, j, k;
1.126     brouard  1838:   for(i=nrl; i<= nrh; i++)
1.145     brouard  1839:     for(k=ncolol; k<=ncoloh; k++){
                   1840:       out[i][k]=0.;
                   1841:       for(j=ncl; j<=nch; j++)
                   1842:        out[i][k] +=in[i][j]*b[j][k];
                   1843:     }
1.126     brouard  1844:   return out;
                   1845: }
                   1846: 
                   1847: 
                   1848: /************* Higher Matrix Product ***************/
                   1849: 
                   1850: double ***hpxij(double ***po, int nhstepm, double age, int hstepm, double *x, int nlstate, int stepm, double **oldm, double **savm, int ij )
                   1851: {
                   1852:   /* Computes the transition matrix starting at age 'age' over 
                   1853:      'nhstepm*hstepm*stepm' months (i.e. until
                   1854:      age (in years)  age+nhstepm*hstepm*stepm/12) by multiplying 
                   1855:      nhstepm*hstepm matrices. 
                   1856:      Output is stored in matrix po[i][j][h] for h every 'hstepm' step 
                   1857:      (typically every 2 years instead of every month which is too big 
                   1858:      for the memory).
                   1859:      Model is determined by parameters x and covariates have to be 
                   1860:      included manually here. 
                   1861: 
                   1862:      */
                   1863: 
                   1864:   int i, j, d, h, k;
1.131     brouard  1865:   double **out, cov[NCOVMAX+1];
1.126     brouard  1866:   double **newm;
                   1867: 
                   1868:   /* Hstepm could be zero and should return the unit matrix */
                   1869:   for (i=1;i<=nlstate+ndeath;i++)
                   1870:     for (j=1;j<=nlstate+ndeath;j++){
                   1871:       oldm[i][j]=(i==j ? 1.0 : 0.0);
                   1872:       po[i][j][0]=(i==j ? 1.0 : 0.0);
                   1873:     }
                   1874:   /* Even if hstepm = 1, at least one multiplication by the unit matrix */
                   1875:   for(h=1; h <=nhstepm; h++){
                   1876:     for(d=1; d <=hstepm; d++){
                   1877:       newm=savm;
                   1878:       /* Covariates have to be included here again */
                   1879:       cov[1]=1.;
                   1880:       cov[2]=age+((h-1)*hstepm + (d-1))*stepm/YEARM;
1.131     brouard  1881:       for (k=1; k<=cptcovn;k++) 
                   1882:        cov[2+k]=nbcode[Tvar[k]][codtab[ij][Tvar[k]]];
1.186   ! brouard  1883:       for (k=1; k<=cptcovage;k++) /* Should start at cptcovn+1 */
        !          1884:        /* cov[2+Tage[k]]=cov[2+Tage[k]]*cov[2]; */
        !          1885:        cov[2+Tage[k]]=nbcode[Tvar[Tage[k]]][codtab[ij][Tvar[Tage[k]]]]*cov[2];
1.145     brouard  1886:       for (k=1; k<=cptcovprod;k++) /* Useless because included in cptcovn */
1.126     brouard  1887:        cov[2+Tprod[k]]=nbcode[Tvard[k][1]][codtab[ij][Tvard[k][1]]]*nbcode[Tvard[k][2]][codtab[ij][Tvard[k][2]]];
                   1888: 
                   1889: 
                   1890:       /*printf("hxi cptcov=%d cptcode=%d\n",cptcov,cptcode);*/
                   1891:       /*printf("h=%d d=%d age=%f cov=%f\n",h,d,age,cov[2]);*/
                   1892:       out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, 
                   1893:                   pmij(pmmij,cov,ncovmodel,x,nlstate));
                   1894:       savm=oldm;
                   1895:       oldm=newm;
                   1896:     }
                   1897:     for(i=1; i<=nlstate+ndeath; i++)
                   1898:       for(j=1;j<=nlstate+ndeath;j++) {
                   1899:        po[i][j][h]=newm[i][j];
1.128     brouard  1900:        /*if(h==nhstepm) printf("po[%d][%d][%d]=%f ",i,j,h,po[i][j][h]);*/
1.126     brouard  1901:       }
1.128     brouard  1902:     /*printf("h=%d ",h);*/
1.126     brouard  1903:   } /* end h */
1.128     brouard  1904: /*     printf("\n H=%d \n",h); */
1.126     brouard  1905:   return po;
                   1906: }
                   1907: 
1.162     brouard  1908: #ifdef NLOPT
                   1909:   double  myfunc(unsigned n, const double *p1, double *grad, void *pd){
                   1910:   double fret;
                   1911:   double *xt;
                   1912:   int j;
                   1913:   myfunc_data *d2 = (myfunc_data *) pd;
                   1914: /* xt = (p1-1); */
                   1915:   xt=vector(1,n); 
                   1916:   for (j=1;j<=n;j++)   xt[j]=p1[j-1]; /* xt[1]=p1[0] */
                   1917: 
                   1918:   fret=(d2->function)(xt); /*  p xt[1]@8 is fine */
                   1919:   /* fret=(*func)(xt); /\*  p xt[1]@8 is fine *\/ */
                   1920:   printf("Function = %.12lf ",fret);
                   1921:   for (j=1;j<=n;j++) printf(" %d %.8lf", j, xt[j]); 
                   1922:   printf("\n");
                   1923:  free_vector(xt,1,n);
                   1924:   return fret;
                   1925: }
                   1926: #endif
1.126     brouard  1927: 
                   1928: /*************** log-likelihood *************/
                   1929: double func( double *x)
                   1930: {
                   1931:   int i, ii, j, k, mi, d, kk;
1.131     brouard  1932:   double l, ll[NLSTATEMAX+1], cov[NCOVMAX+1];
1.126     brouard  1933:   double **out;
                   1934:   double sw; /* Sum of weights */
                   1935:   double lli; /* Individual log likelihood */
                   1936:   int s1, s2;
                   1937:   double bbh, survp;
                   1938:   long ipmx;
                   1939:   /*extern weight */
                   1940:   /* We are differentiating ll according to initial status */
                   1941:   /*  for (i=1;i<=npar;i++) printf("%f ", x[i]);*/
                   1942:   /*for(i=1;i<imx;i++) 
                   1943:     printf(" %d\n",s[4][i]);
                   1944:   */
1.162     brouard  1945: 
                   1946:   ++countcallfunc;
                   1947: 
1.126     brouard  1948:   cov[1]=1.;
                   1949: 
                   1950:   for(k=1; k<=nlstate; k++) ll[k]=0.;
                   1951: 
                   1952:   if(mle==1){
                   1953:     for (i=1,ipmx=0, sw=0.; i<=imx; i++){
1.138     brouard  1954:       /* Computes the values of the ncovmodel covariates of the model
                   1955:         depending if the covariates are fixed or variying (age dependent) and stores them in cov[]
                   1956:         Then computes with function pmij which return a matrix p[i][j] giving the elementary probability
                   1957:         to be observed in j being in i according to the model.
                   1958:        */
1.145     brouard  1959:       for (k=1; k<=cptcovn;k++){ /* Simple and product covariates without age* products */
                   1960:        cov[2+k]=covar[Tvar[k]][i];
                   1961:       }
1.137     brouard  1962:       /* In model V2+V1*V4+age*V3+V3*V2 Tvar[1] is V2, Tvar[2=V1*V4] 
1.138     brouard  1963:         is 6, Tvar[3=age*V3] should not be computed because of age Tvar[4=V3*V2] 
1.137     brouard  1964:         has been calculated etc */
1.126     brouard  1965:       for(mi=1; mi<= wav[i]-1; mi++){
                   1966:        for (ii=1;ii<=nlstate+ndeath;ii++)
                   1967:          for (j=1;j<=nlstate+ndeath;j++){
                   1968:            oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   1969:            savm[ii][j]=(ii==j ? 1.0 : 0.0);
                   1970:          }
                   1971:        for(d=0; d<dh[mi][i]; d++){
                   1972:          newm=savm;
                   1973:          cov[2]=agev[mw[mi][i]][i]+d*stepm/YEARM;
                   1974:          for (kk=1; kk<=cptcovage;kk++) {
1.137     brouard  1975:            cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*cov[2]; /* Tage[kk] gives the data-covariate associated with age */
1.126     brouard  1976:          }
                   1977:          out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
                   1978:                       1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
                   1979:          savm=oldm;
                   1980:          oldm=newm;
                   1981:        } /* end mult */
                   1982:       
                   1983:        /*lli=log(out[s[mw[mi][i]][i]][s[mw[mi+1][i]][i]]);*/ /* Original formula */
                   1984:        /* But now since version 0.9 we anticipate for bias at large stepm.
                   1985:         * If stepm is larger than one month (smallest stepm) and if the exact delay 
                   1986:         * (in months) between two waves is not a multiple of stepm, we rounded to 
                   1987:         * the nearest (and in case of equal distance, to the lowest) interval but now
                   1988:         * we keep into memory the bias bh[mi][i] and also the previous matrix product
                   1989:         * (i.e to dh[mi][i]-1) saved in 'savm'. Then we inter(extra)polate the
                   1990:         * probability in order to take into account the bias as a fraction of the way
                   1991:         * from savm to out if bh is negative or even beyond if bh is positive. bh varies
                   1992:         * -stepm/2 to stepm/2 .
                   1993:         * For stepm=1 the results are the same as for previous versions of Imach.
                   1994:         * For stepm > 1 the results are less biased than in previous versions. 
                   1995:         */
                   1996:        s1=s[mw[mi][i]][i];
                   1997:        s2=s[mw[mi+1][i]][i];
                   1998:        bbh=(double)bh[mi][i]/(double)stepm; 
                   1999:        /* bias bh is positive if real duration
                   2000:         * is higher than the multiple of stepm and negative otherwise.
                   2001:         */
                   2002:        /* lli= (savm[s1][s2]>1.e-8 ?(1.+bbh)*log(out[s1][s2])- bbh*log(savm[s1][s2]):log((1.+bbh)*out[s1][s2]));*/
                   2003:        if( s2 > nlstate){ 
                   2004:          /* i.e. if s2 is a death state and if the date of death is known 
                   2005:             then the contribution to the likelihood is the probability to 
                   2006:             die between last step unit time and current  step unit time, 
                   2007:             which is also equal to probability to die before dh 
                   2008:             minus probability to die before dh-stepm . 
                   2009:             In version up to 0.92 likelihood was computed
                   2010:        as if date of death was unknown. Death was treated as any other
                   2011:        health state: the date of the interview describes the actual state
                   2012:        and not the date of a change in health state. The former idea was
                   2013:        to consider that at each interview the state was recorded
                   2014:        (healthy, disable or death) and IMaCh was corrected; but when we
                   2015:        introduced the exact date of death then we should have modified
                   2016:        the contribution of an exact death to the likelihood. This new
                   2017:        contribution is smaller and very dependent of the step unit
                   2018:        stepm. It is no more the probability to die between last interview
                   2019:        and month of death but the probability to survive from last
                   2020:        interview up to one month before death multiplied by the
                   2021:        probability to die within a month. Thanks to Chris
                   2022:        Jackson for correcting this bug.  Former versions increased
                   2023:        mortality artificially. The bad side is that we add another loop
                   2024:        which slows down the processing. The difference can be up to 10%
                   2025:        lower mortality.
                   2026:          */
1.183     brouard  2027:        /* If, at the beginning of the maximization mostly, the
                   2028:           cumulative probability or probability to be dead is
                   2029:           constant (ie = 1) over time d, the difference is equal to
                   2030:           0.  out[s1][3] = savm[s1][3]: probability, being at state
                   2031:           s1 at precedent wave, to be dead a month before current
                   2032:           wave is equal to probability, being at state s1 at
                   2033:           precedent wave, to be dead at mont of the current
                   2034:           wave. Then the observed probability (that this person died)
                   2035:           is null according to current estimated parameter. In fact,
                   2036:           it should be very low but not zero otherwise the log go to
                   2037:           infinity.
                   2038:        */
                   2039: /* #ifdef INFINITYORIGINAL */
                   2040: /*         lli=log(out[s1][s2] - savm[s1][s2]); */
                   2041: /* #else */
                   2042: /*       if ((out[s1][s2] - savm[s1][s2]) < mytinydouble)  */
                   2043: /*         lli=log(mytinydouble); */
                   2044: /*       else */
                   2045: /*         lli=log(out[s1][s2] - savm[s1][s2]); */
                   2046: /* #endif */
                   2047:            lli=log(out[s1][s2] - savm[s1][s2]);
1.126     brouard  2048: 
                   2049:        } else if  (s2==-2) {
                   2050:          for (j=1,survp=0. ; j<=nlstate; j++) 
                   2051:            survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j];
                   2052:          /*survp += out[s1][j]; */
                   2053:          lli= log(survp);
                   2054:        }
                   2055:        
                   2056:        else if  (s2==-4) { 
                   2057:          for (j=3,survp=0. ; j<=nlstate; j++)  
                   2058:            survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j];
                   2059:          lli= log(survp); 
                   2060:        } 
                   2061: 
                   2062:        else if  (s2==-5) { 
                   2063:          for (j=1,survp=0. ; j<=2; j++)  
                   2064:            survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j];
                   2065:          lli= log(survp); 
                   2066:        } 
                   2067:        
                   2068:        else{
                   2069:          lli= log((1.+bbh)*out[s1][s2]- bbh*savm[s1][s2]); /* linear interpolation */
                   2070:          /*  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 */
                   2071:        } 
                   2072:        /*lli=(1.+bbh)*log(out[s1][s2])- bbh*log(savm[s1][s2]);*/
                   2073:        /*if(lli ==000.0)*/
                   2074:        /*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); */
                   2075:        ipmx +=1;
                   2076:        sw += weight[i];
                   2077:        ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
1.183     brouard  2078:        /* if (lli < log(mytinydouble)){ */
                   2079:        /*   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); */
                   2080:        /*   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]); */
                   2081:        /* } */
1.126     brouard  2082:       } /* end of wave */
                   2083:     } /* end of individual */
                   2084:   }  else if(mle==2){
                   2085:     for (i=1,ipmx=0, sw=0.; i<=imx; i++){
                   2086:       for (k=1; k<=cptcovn;k++) cov[2+k]=covar[Tvar[k]][i];
                   2087:       for(mi=1; mi<= wav[i]-1; mi++){
                   2088:        for (ii=1;ii<=nlstate+ndeath;ii++)
                   2089:          for (j=1;j<=nlstate+ndeath;j++){
                   2090:            oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   2091:            savm[ii][j]=(ii==j ? 1.0 : 0.0);
                   2092:          }
                   2093:        for(d=0; d<=dh[mi][i]; d++){
                   2094:          newm=savm;
                   2095:          cov[2]=agev[mw[mi][i]][i]+d*stepm/YEARM;
                   2096:          for (kk=1; kk<=cptcovage;kk++) {
                   2097:            cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*cov[2];
                   2098:          }
                   2099:          out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
                   2100:                       1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
                   2101:          savm=oldm;
                   2102:          oldm=newm;
                   2103:        } /* end mult */
                   2104:       
                   2105:        s1=s[mw[mi][i]][i];
                   2106:        s2=s[mw[mi+1][i]][i];
                   2107:        bbh=(double)bh[mi][i]/(double)stepm; 
                   2108:        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 */
                   2109:        ipmx +=1;
                   2110:        sw += weight[i];
                   2111:        ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
                   2112:       } /* end of wave */
                   2113:     } /* end of individual */
                   2114:   }  else if(mle==3){  /* exponential inter-extrapolation */
                   2115:     for (i=1,ipmx=0, sw=0.; i<=imx; i++){
                   2116:       for (k=1; k<=cptcovn;k++) cov[2+k]=covar[Tvar[k]][i];
                   2117:       for(mi=1; mi<= wav[i]-1; mi++){
                   2118:        for (ii=1;ii<=nlstate+ndeath;ii++)
                   2119:          for (j=1;j<=nlstate+ndeath;j++){
                   2120:            oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   2121:            savm[ii][j]=(ii==j ? 1.0 : 0.0);
                   2122:          }
                   2123:        for(d=0; d<dh[mi][i]; d++){
                   2124:          newm=savm;
                   2125:          cov[2]=agev[mw[mi][i]][i]+d*stepm/YEARM;
                   2126:          for (kk=1; kk<=cptcovage;kk++) {
                   2127:            cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*cov[2];
                   2128:          }
                   2129:          out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
                   2130:                       1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
                   2131:          savm=oldm;
                   2132:          oldm=newm;
                   2133:        } /* end mult */
                   2134:       
                   2135:        s1=s[mw[mi][i]][i];
                   2136:        s2=s[mw[mi+1][i]][i];
                   2137:        bbh=(double)bh[mi][i]/(double)stepm; 
                   2138:        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 */
                   2139:        ipmx +=1;
                   2140:        sw += weight[i];
                   2141:        ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
                   2142:       } /* end of wave */
                   2143:     } /* end of individual */
                   2144:   }else if (mle==4){  /* ml=4 no inter-extrapolation */
                   2145:     for (i=1,ipmx=0, sw=0.; i<=imx; i++){
                   2146:       for (k=1; k<=cptcovn;k++) cov[2+k]=covar[Tvar[k]][i];
                   2147:       for(mi=1; mi<= wav[i]-1; mi++){
                   2148:        for (ii=1;ii<=nlstate+ndeath;ii++)
                   2149:          for (j=1;j<=nlstate+ndeath;j++){
                   2150:            oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   2151:            savm[ii][j]=(ii==j ? 1.0 : 0.0);
                   2152:          }
                   2153:        for(d=0; d<dh[mi][i]; d++){
                   2154:          newm=savm;
                   2155:          cov[2]=agev[mw[mi][i]][i]+d*stepm/YEARM;
                   2156:          for (kk=1; kk<=cptcovage;kk++) {
                   2157:            cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*cov[2];
                   2158:          }
                   2159:        
                   2160:          out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
                   2161:                       1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
                   2162:          savm=oldm;
                   2163:          oldm=newm;
                   2164:        } /* end mult */
                   2165:       
                   2166:        s1=s[mw[mi][i]][i];
                   2167:        s2=s[mw[mi+1][i]][i];
                   2168:        if( s2 > nlstate){ 
                   2169:          lli=log(out[s1][s2] - savm[s1][s2]);
                   2170:        }else{
                   2171:          lli=log(out[s[mw[mi][i]][i]][s[mw[mi+1][i]][i]]); /* Original formula */
                   2172:        }
                   2173:        ipmx +=1;
                   2174:        sw += weight[i];
                   2175:        ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
                   2176: /*     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]); */
                   2177:       } /* end of wave */
                   2178:     } /* end of individual */
                   2179:   }else{  /* ml=5 no inter-extrapolation no jackson =0.8a */
                   2180:     for (i=1,ipmx=0, sw=0.; i<=imx; i++){
                   2181:       for (k=1; k<=cptcovn;k++) cov[2+k]=covar[Tvar[k]][i];
                   2182:       for(mi=1; mi<= wav[i]-1; mi++){
                   2183:        for (ii=1;ii<=nlstate+ndeath;ii++)
                   2184:          for (j=1;j<=nlstate+ndeath;j++){
                   2185:            oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   2186:            savm[ii][j]=(ii==j ? 1.0 : 0.0);
                   2187:          }
                   2188:        for(d=0; d<dh[mi][i]; d++){
                   2189:          newm=savm;
                   2190:          cov[2]=agev[mw[mi][i]][i]+d*stepm/YEARM;
                   2191:          for (kk=1; kk<=cptcovage;kk++) {
                   2192:            cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*cov[2];
                   2193:          }
                   2194:        
                   2195:          out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
                   2196:                       1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
                   2197:          savm=oldm;
                   2198:          oldm=newm;
                   2199:        } /* end mult */
                   2200:       
                   2201:        s1=s[mw[mi][i]][i];
                   2202:        s2=s[mw[mi+1][i]][i];
                   2203:        lli=log(out[s[mw[mi][i]][i]][s[mw[mi+1][i]][i]]); /* Original formula */
                   2204:        ipmx +=1;
                   2205:        sw += weight[i];
                   2206:        ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
                   2207:        /*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]);*/
                   2208:       } /* end of wave */
                   2209:     } /* end of individual */
                   2210:   } /* End of if */
                   2211:   for(k=1,l=0.; k<=nlstate; k++) l += ll[k];
                   2212:   /* printf("l1=%f l2=%f ",ll[1],ll[2]); */
                   2213:   l= l*ipmx/sw; /* To get the same order of magnitude as if weight=1 for every body */
                   2214:   return -l;
                   2215: }
                   2216: 
                   2217: /*************** log-likelihood *************/
                   2218: double funcone( double *x)
                   2219: {
                   2220:   /* Same as likeli but slower because of a lot of printf and if */
                   2221:   int i, ii, j, k, mi, d, kk;
1.131     brouard  2222:   double l, ll[NLSTATEMAX+1], cov[NCOVMAX+1];
1.126     brouard  2223:   double **out;
                   2224:   double lli; /* Individual log likelihood */
                   2225:   double llt;
                   2226:   int s1, s2;
                   2227:   double bbh, survp;
                   2228:   /*extern weight */
                   2229:   /* We are differentiating ll according to initial status */
                   2230:   /*  for (i=1;i<=npar;i++) printf("%f ", x[i]);*/
                   2231:   /*for(i=1;i<imx;i++) 
                   2232:     printf(" %d\n",s[4][i]);
                   2233:   */
                   2234:   cov[1]=1.;
                   2235: 
                   2236:   for(k=1; k<=nlstate; k++) ll[k]=0.;
                   2237: 
                   2238:   for (i=1,ipmx=0, sw=0.; i<=imx; i++){
                   2239:     for (k=1; k<=cptcovn;k++) cov[2+k]=covar[Tvar[k]][i];
                   2240:     for(mi=1; mi<= wav[i]-1; mi++){
                   2241:       for (ii=1;ii<=nlstate+ndeath;ii++)
                   2242:        for (j=1;j<=nlstate+ndeath;j++){
                   2243:          oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   2244:          savm[ii][j]=(ii==j ? 1.0 : 0.0);
                   2245:        }
                   2246:       for(d=0; d<dh[mi][i]; d++){
                   2247:        newm=savm;
                   2248:        cov[2]=agev[mw[mi][i]][i]+d*stepm/YEARM;
                   2249:        for (kk=1; kk<=cptcovage;kk++) {
                   2250:          cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*cov[2];
                   2251:        }
1.145     brouard  2252:        /* savm=pmij(pmmij,cov,ncovmodel,x,nlstate); */
1.126     brouard  2253:        out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
                   2254:                     1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
1.145     brouard  2255:        /* out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath, */
                   2256:        /*           1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate)); */
1.126     brouard  2257:        savm=oldm;
                   2258:        oldm=newm;
                   2259:       } /* end mult */
                   2260:       
                   2261:       s1=s[mw[mi][i]][i];
                   2262:       s2=s[mw[mi+1][i]][i];
                   2263:       bbh=(double)bh[mi][i]/(double)stepm; 
                   2264:       /* bias is positive if real duration
                   2265:        * is higher than the multiple of stepm and negative otherwise.
                   2266:        */
                   2267:       if( s2 > nlstate && (mle <5) ){  /* Jackson */
                   2268:        lli=log(out[s1][s2] - savm[s1][s2]);
                   2269:       } else if  (s2==-2) {
                   2270:        for (j=1,survp=0. ; j<=nlstate; j++) 
                   2271:          survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j];
                   2272:        lli= log(survp);
                   2273:       }else if (mle==1){
                   2274:        lli= log((1.+bbh)*out[s1][s2]- bbh*savm[s1][s2]); /* linear interpolation */
                   2275:       } else if(mle==2){
                   2276:        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 */
                   2277:       } else if(mle==3){  /* exponential inter-extrapolation */
                   2278:        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 */
                   2279:       } else if (mle==4){  /* mle=4 no inter-extrapolation */
                   2280:        lli=log(out[s1][s2]); /* Original formula */
1.136     brouard  2281:       } else{  /* mle=0 back to 1 */
                   2282:        lli= log((1.+bbh)*out[s1][s2]- bbh*savm[s1][s2]); /* linear interpolation */
                   2283:        /*lli=log(out[s1][s2]); */ /* Original formula */
1.126     brouard  2284:       } /* End of if */
                   2285:       ipmx +=1;
                   2286:       sw += weight[i];
                   2287:       ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
1.132     brouard  2288:       /*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  2289:       if(globpr){
1.141     brouard  2290:        fprintf(ficresilk,"%9ld %6d %2d %2d %1d %1d %3d %11.6f %8.4f\
1.126     brouard  2291:  %11.6f %11.6f %11.6f ", \
                   2292:                num[i],i,s1,s2,mi,mw[mi][i],dh[mi][i],exp(lli),weight[i],
                   2293:                2*weight[i]*lli,out[s1][s2],savm[s1][s2]);
                   2294:        for(k=1,llt=0.,l=0.; k<=nlstate; k++){
                   2295:          llt +=ll[k]*gipmx/gsw;
                   2296:          fprintf(ficresilk," %10.6f",-ll[k]*gipmx/gsw);
                   2297:        }
                   2298:        fprintf(ficresilk," %10.6f\n", -llt);
                   2299:       }
                   2300:     } /* end of wave */
                   2301:   } /* end of individual */
                   2302:   for(k=1,l=0.; k<=nlstate; k++) l += ll[k];
                   2303:   /* printf("l1=%f l2=%f ",ll[1],ll[2]); */
                   2304:   l= l*ipmx/sw; /* To get the same order of magnitude as if weight=1 for every body */
                   2305:   if(globpr==0){ /* First time we count the contributions and weights */
                   2306:     gipmx=ipmx;
                   2307:     gsw=sw;
                   2308:   }
                   2309:   return -l;
                   2310: }
                   2311: 
                   2312: 
                   2313: /*************** function likelione ***********/
                   2314: void likelione(FILE *ficres,double p[], int npar, int nlstate, int *globpri, long *ipmx, double *sw, double *fretone, double (*funcone)(double []))
                   2315: {
                   2316:   /* This routine should help understanding what is done with 
                   2317:      the selection of individuals/waves and
                   2318:      to check the exact contribution to the likelihood.
                   2319:      Plotting could be done.
                   2320:    */
                   2321:   int k;
                   2322: 
                   2323:   if(*globpri !=0){ /* Just counts and sums, no printings */
                   2324:     strcpy(fileresilk,"ilk"); 
                   2325:     strcat(fileresilk,fileres);
                   2326:     if((ficresilk=fopen(fileresilk,"w"))==NULL) {
                   2327:       printf("Problem with resultfile: %s\n", fileresilk);
                   2328:       fprintf(ficlog,"Problem with resultfile: %s\n", fileresilk);
                   2329:     }
                   2330:     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");
                   2331:     fprintf(ficresilk, "#num_i i s1 s2 mi mw dh likeli weight 2wlli out sav ");
                   2332:     /*         i,s1,s2,mi,mw[mi][i],dh[mi][i],exp(lli),weight[i],2*weight[i]*lli,out[s1][s2],savm[s1][s2]); */
                   2333:     for(k=1; k<=nlstate; k++) 
                   2334:       fprintf(ficresilk," -2*gipw/gsw*weight*ll[%d]++",k);
                   2335:     fprintf(ficresilk," -2*gipw/gsw*weight*ll(total)\n");
                   2336:   }
                   2337: 
                   2338:   *fretone=(*funcone)(p);
                   2339:   if(*globpri !=0){
                   2340:     fclose(ficresilk);
                   2341:     fprintf(fichtm,"\n<br>File of contributions to the likelihood: <a href=\"%s\">%s</a><br>\n",subdirf(fileresilk),subdirf(fileresilk));
                   2342:     fflush(fichtm); 
                   2343:   } 
                   2344:   return;
                   2345: }
                   2346: 
                   2347: 
                   2348: /*********** Maximum Likelihood Estimation ***************/
                   2349: 
                   2350: void mlikeli(FILE *ficres,double p[], int npar, int ncovmodel, int nlstate, double ftol, double (*func)(double []))
                   2351: {
1.165     brouard  2352:   int i,j, iter=0;
1.126     brouard  2353:   double **xi;
                   2354:   double fret;
                   2355:   double fretone; /* Only one call to likelihood */
                   2356:   /*  char filerespow[FILENAMELENGTH];*/
1.162     brouard  2357: 
                   2358: #ifdef NLOPT
                   2359:   int creturn;
                   2360:   nlopt_opt opt;
                   2361:   /* double lb[9] = { -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL }; /\* lower bounds *\/ */
                   2362:   double *lb;
                   2363:   double minf; /* the minimum objective value, upon return */
                   2364:   double * p1; /* Shifted parameters from 0 instead of 1 */
                   2365:   myfunc_data dinst, *d = &dinst;
                   2366: #endif
                   2367: 
                   2368: 
1.126     brouard  2369:   xi=matrix(1,npar,1,npar);
                   2370:   for (i=1;i<=npar;i++)
                   2371:     for (j=1;j<=npar;j++)
                   2372:       xi[i][j]=(i==j ? 1.0 : 0.0);
                   2373:   printf("Powell\n");  fprintf(ficlog,"Powell\n");
                   2374:   strcpy(filerespow,"pow"); 
                   2375:   strcat(filerespow,fileres);
                   2376:   if((ficrespow=fopen(filerespow,"w"))==NULL) {
                   2377:     printf("Problem with resultfile: %s\n", filerespow);
                   2378:     fprintf(ficlog,"Problem with resultfile: %s\n", filerespow);
                   2379:   }
                   2380:   fprintf(ficrespow,"# Powell\n# iter -2*LL");
                   2381:   for (i=1;i<=nlstate;i++)
                   2382:     for(j=1;j<=nlstate+ndeath;j++)
                   2383:       if(j!=i)fprintf(ficrespow," p%1d%1d",i,j);
                   2384:   fprintf(ficrespow,"\n");
1.162     brouard  2385: #ifdef POWELL
1.126     brouard  2386:   powell(p,xi,npar,ftol,&iter,&fret,func);
1.162     brouard  2387: #endif
1.126     brouard  2388: 
1.162     brouard  2389: #ifdef NLOPT
                   2390: #ifdef NEWUOA
                   2391:   opt = nlopt_create(NLOPT_LN_NEWUOA,npar);
                   2392: #else
                   2393:   opt = nlopt_create(NLOPT_LN_BOBYQA,npar);
                   2394: #endif
                   2395:   lb=vector(0,npar-1);
                   2396:   for (i=0;i<npar;i++) lb[i]= -HUGE_VAL;
                   2397:   nlopt_set_lower_bounds(opt, lb);
                   2398:   nlopt_set_initial_step1(opt, 0.1);
                   2399:   
                   2400:   p1= (p+1); /*  p *(p+1)@8 and p *(p1)@8 are equal p1[0]=p[1] */
                   2401:   d->function = func;
                   2402:   printf(" Func %.12lf \n",myfunc(npar,p1,NULL,d));
                   2403:   nlopt_set_min_objective(opt, myfunc, d);
                   2404:   nlopt_set_xtol_rel(opt, ftol);
                   2405:   if ((creturn=nlopt_optimize(opt, p1, &minf)) < 0) {
                   2406:     printf("nlopt failed! %d\n",creturn); 
                   2407:   }
                   2408:   else {
                   2409:     printf("found minimum after %d evaluations (NLOPT=%d)\n", countcallfunc ,NLOPT);
                   2410:     printf("found minimum at f(%g,%g) = %0.10g\n", p[0], p[1], minf);
                   2411:     iter=1; /* not equal */
                   2412:   }
                   2413:   nlopt_destroy(opt);
                   2414: #endif
1.126     brouard  2415:   free_matrix(xi,1,npar,1,npar);
                   2416:   fclose(ficrespow);
1.180     brouard  2417:   printf("#Number of iterations & function calls = %d & %d, -2 Log likelihood = %.12f\n",iter, countcallfunc,func(p));
                   2418:   fprintf(ficlog,"#Number of iterations & function calls = %d & %d, -2 Log likelihood = %.12f\n",iter, countcallfunc,func(p));
                   2419:   fprintf(ficres,"#Number of iterations & function calls = %d & %d, -2 Log likelihood = %.12f\n",iter, countcallfunc,func(p));
1.126     brouard  2420: 
                   2421: }
                   2422: 
                   2423: /**** Computes Hessian and covariance matrix ***/
                   2424: void hesscov(double **matcov, double p[], int npar, double delti[], double ftolhess, double (*func)(double []))
                   2425: {
                   2426:   double  **a,**y,*x,pd;
                   2427:   double **hess;
1.164     brouard  2428:   int i, j;
1.126     brouard  2429:   int *indx;
                   2430: 
                   2431:   double hessii(double p[], double delta, int theta, double delti[],double (*func)(double []),int npar);
                   2432:   double hessij(double p[], double delti[], int i, int j,double (*func)(double []),int npar);
                   2433:   void lubksb(double **a, int npar, int *indx, double b[]) ;
                   2434:   void ludcmp(double **a, int npar, int *indx, double *d) ;
                   2435:   double gompertz(double p[]);
                   2436:   hess=matrix(1,npar,1,npar);
                   2437: 
                   2438:   printf("\nCalculation of the hessian matrix. Wait...\n");
                   2439:   fprintf(ficlog,"\nCalculation of the hessian matrix. Wait...\n");
                   2440:   for (i=1;i<=npar;i++){
                   2441:     printf("%d",i);fflush(stdout);
                   2442:     fprintf(ficlog,"%d",i);fflush(ficlog);
                   2443:    
                   2444:      hess[i][i]=hessii(p,ftolhess,i,delti,func,npar);
                   2445:     
                   2446:     /*  printf(" %f ",p[i]);
                   2447:        printf(" %lf %lf %lf",hess[i][i],ftolhess,delti[i]);*/
                   2448:   }
                   2449:   
                   2450:   for (i=1;i<=npar;i++) {
                   2451:     for (j=1;j<=npar;j++)  {
                   2452:       if (j>i) { 
                   2453:        printf(".%d%d",i,j);fflush(stdout);
                   2454:        fprintf(ficlog,".%d%d",i,j);fflush(ficlog);
                   2455:        hess[i][j]=hessij(p,delti,i,j,func,npar);
                   2456:        
                   2457:        hess[j][i]=hess[i][j];    
                   2458:        /*printf(" %lf ",hess[i][j]);*/
                   2459:       }
                   2460:     }
                   2461:   }
                   2462:   printf("\n");
                   2463:   fprintf(ficlog,"\n");
                   2464: 
                   2465:   printf("\nInverting the hessian to get the covariance matrix. Wait...\n");
                   2466:   fprintf(ficlog,"\nInverting the hessian to get the covariance matrix. Wait...\n");
                   2467:   
                   2468:   a=matrix(1,npar,1,npar);
                   2469:   y=matrix(1,npar,1,npar);
                   2470:   x=vector(1,npar);
                   2471:   indx=ivector(1,npar);
                   2472:   for (i=1;i<=npar;i++)
                   2473:     for (j=1;j<=npar;j++) a[i][j]=hess[i][j];
                   2474:   ludcmp(a,npar,indx,&pd);
                   2475: 
                   2476:   for (j=1;j<=npar;j++) {
                   2477:     for (i=1;i<=npar;i++) x[i]=0;
                   2478:     x[j]=1;
                   2479:     lubksb(a,npar,indx,x);
                   2480:     for (i=1;i<=npar;i++){ 
                   2481:       matcov[i][j]=x[i];
                   2482:     }
                   2483:   }
                   2484: 
                   2485:   printf("\n#Hessian matrix#\n");
                   2486:   fprintf(ficlog,"\n#Hessian matrix#\n");
                   2487:   for (i=1;i<=npar;i++) { 
                   2488:     for (j=1;j<=npar;j++) { 
                   2489:       printf("%.3e ",hess[i][j]);
                   2490:       fprintf(ficlog,"%.3e ",hess[i][j]);
                   2491:     }
                   2492:     printf("\n");
                   2493:     fprintf(ficlog,"\n");
                   2494:   }
                   2495: 
                   2496:   /* Recompute Inverse */
                   2497:   for (i=1;i<=npar;i++)
                   2498:     for (j=1;j<=npar;j++) a[i][j]=matcov[i][j];
                   2499:   ludcmp(a,npar,indx,&pd);
                   2500: 
                   2501:   /*  printf("\n#Hessian matrix recomputed#\n");
                   2502: 
                   2503:   for (j=1;j<=npar;j++) {
                   2504:     for (i=1;i<=npar;i++) x[i]=0;
                   2505:     x[j]=1;
                   2506:     lubksb(a,npar,indx,x);
                   2507:     for (i=1;i<=npar;i++){ 
                   2508:       y[i][j]=x[i];
                   2509:       printf("%.3e ",y[i][j]);
                   2510:       fprintf(ficlog,"%.3e ",y[i][j]);
                   2511:     }
                   2512:     printf("\n");
                   2513:     fprintf(ficlog,"\n");
                   2514:   }
                   2515:   */
                   2516: 
                   2517:   free_matrix(a,1,npar,1,npar);
                   2518:   free_matrix(y,1,npar,1,npar);
                   2519:   free_vector(x,1,npar);
                   2520:   free_ivector(indx,1,npar);
                   2521:   free_matrix(hess,1,npar,1,npar);
                   2522: 
                   2523: 
                   2524: }
                   2525: 
                   2526: /*************** hessian matrix ****************/
                   2527: double hessii(double x[], double delta, int theta, double delti[], double (*func)(double []), int npar)
                   2528: {
                   2529:   int i;
                   2530:   int l=1, lmax=20;
                   2531:   double k1,k2;
1.132     brouard  2532:   double p2[MAXPARM+1]; /* identical to x */
1.126     brouard  2533:   double res;
                   2534:   double delt=0.0001, delts, nkhi=10.,nkhif=1., khi=1.e-4;
                   2535:   double fx;
                   2536:   int k=0,kmax=10;
                   2537:   double l1;
                   2538: 
                   2539:   fx=func(x);
                   2540:   for (i=1;i<=npar;i++) p2[i]=x[i];
1.145     brouard  2541:   for(l=0 ; l <=lmax; l++){  /* Enlarging the zone around the Maximum */
1.126     brouard  2542:     l1=pow(10,l);
                   2543:     delts=delt;
                   2544:     for(k=1 ; k <kmax; k=k+1){
                   2545:       delt = delta*(l1*k);
                   2546:       p2[theta]=x[theta] +delt;
1.145     brouard  2547:       k1=func(p2)-fx;   /* Might be negative if too close to the theoretical maximum */
1.126     brouard  2548:       p2[theta]=x[theta]-delt;
                   2549:       k2=func(p2)-fx;
                   2550:       /*res= (k1-2.0*fx+k2)/delt/delt; */
                   2551:       res= (k1+k2)/delt/delt/2.; /* Divided by because L and not 2*L */
                   2552:       
1.132     brouard  2553: #ifdef DEBUGHESS
1.126     brouard  2554:       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);
                   2555:       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);
                   2556: #endif
                   2557:       /*if(fabs(k1-2.0*fx+k2) <1.e-13){ */
                   2558:       if((k1 <khi/nkhi/2.) || (k2 <khi/nkhi/2.)){
                   2559:        k=kmax;
                   2560:       }
                   2561:       else if((k1 >khi/nkhif) || (k2 >khi/nkhif)){ /* Keeps lastvalue before 3.84/2 KHI2 5% 1d.f. */
1.164     brouard  2562:        k=kmax; l=lmax*10;
1.126     brouard  2563:       }
                   2564:       else if((k1 >khi/nkhi) || (k2 >khi/nkhi)){ 
                   2565:        delts=delt;
                   2566:       }
                   2567:     }
                   2568:   }
                   2569:   delti[theta]=delts;
                   2570:   return res; 
                   2571:   
                   2572: }
                   2573: 
                   2574: double hessij( double x[], double delti[], int thetai,int thetaj,double (*func)(double []),int npar)
                   2575: {
                   2576:   int i;
1.164     brouard  2577:   int l=1, lmax=20;
1.126     brouard  2578:   double k1,k2,k3,k4,res,fx;
1.132     brouard  2579:   double p2[MAXPARM+1];
1.126     brouard  2580:   int k;
                   2581: 
                   2582:   fx=func(x);
                   2583:   for (k=1; k<=2; k++) {
                   2584:     for (i=1;i<=npar;i++) p2[i]=x[i];
                   2585:     p2[thetai]=x[thetai]+delti[thetai]/k;
                   2586:     p2[thetaj]=x[thetaj]+delti[thetaj]/k;
                   2587:     k1=func(p2)-fx;
                   2588:   
                   2589:     p2[thetai]=x[thetai]+delti[thetai]/k;
                   2590:     p2[thetaj]=x[thetaj]-delti[thetaj]/k;
                   2591:     k2=func(p2)-fx;
                   2592:   
                   2593:     p2[thetai]=x[thetai]-delti[thetai]/k;
                   2594:     p2[thetaj]=x[thetaj]+delti[thetaj]/k;
                   2595:     k3=func(p2)-fx;
                   2596:   
                   2597:     p2[thetai]=x[thetai]-delti[thetai]/k;
                   2598:     p2[thetaj]=x[thetaj]-delti[thetaj]/k;
                   2599:     k4=func(p2)-fx;
                   2600:     res=(k1-k2-k3+k4)/4.0/delti[thetai]*k/delti[thetaj]*k/2.; /* Because of L not 2*L */
                   2601: #ifdef DEBUG
                   2602:     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);
                   2603:     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);
                   2604: #endif
                   2605:   }
                   2606:   return res;
                   2607: }
                   2608: 
                   2609: /************** Inverse of matrix **************/
                   2610: void ludcmp(double **a, int n, int *indx, double *d) 
                   2611: { 
                   2612:   int i,imax,j,k; 
                   2613:   double big,dum,sum,temp; 
                   2614:   double *vv; 
                   2615:  
                   2616:   vv=vector(1,n); 
                   2617:   *d=1.0; 
                   2618:   for (i=1;i<=n;i++) { 
                   2619:     big=0.0; 
                   2620:     for (j=1;j<=n;j++) 
                   2621:       if ((temp=fabs(a[i][j])) > big) big=temp; 
                   2622:     if (big == 0.0) nrerror("Singular matrix in routine ludcmp"); 
                   2623:     vv[i]=1.0/big; 
                   2624:   } 
                   2625:   for (j=1;j<=n;j++) { 
                   2626:     for (i=1;i<j;i++) { 
                   2627:       sum=a[i][j]; 
                   2628:       for (k=1;k<i;k++) sum -= a[i][k]*a[k][j]; 
                   2629:       a[i][j]=sum; 
                   2630:     } 
                   2631:     big=0.0; 
                   2632:     for (i=j;i<=n;i++) { 
                   2633:       sum=a[i][j]; 
                   2634:       for (k=1;k<j;k++) 
                   2635:        sum -= a[i][k]*a[k][j]; 
                   2636:       a[i][j]=sum; 
                   2637:       if ( (dum=vv[i]*fabs(sum)) >= big) { 
                   2638:        big=dum; 
                   2639:        imax=i; 
                   2640:       } 
                   2641:     } 
                   2642:     if (j != imax) { 
                   2643:       for (k=1;k<=n;k++) { 
                   2644:        dum=a[imax][k]; 
                   2645:        a[imax][k]=a[j][k]; 
                   2646:        a[j][k]=dum; 
                   2647:       } 
                   2648:       *d = -(*d); 
                   2649:       vv[imax]=vv[j]; 
                   2650:     } 
                   2651:     indx[j]=imax; 
                   2652:     if (a[j][j] == 0.0) a[j][j]=TINY; 
                   2653:     if (j != n) { 
                   2654:       dum=1.0/(a[j][j]); 
                   2655:       for (i=j+1;i<=n;i++) a[i][j] *= dum; 
                   2656:     } 
                   2657:   } 
                   2658:   free_vector(vv,1,n);  /* Doesn't work */
                   2659: ;
                   2660: } 
                   2661: 
                   2662: void lubksb(double **a, int n, int *indx, double b[]) 
                   2663: { 
                   2664:   int i,ii=0,ip,j; 
                   2665:   double sum; 
                   2666:  
                   2667:   for (i=1;i<=n;i++) { 
                   2668:     ip=indx[i]; 
                   2669:     sum=b[ip]; 
                   2670:     b[ip]=b[i]; 
                   2671:     if (ii) 
                   2672:       for (j=ii;j<=i-1;j++) sum -= a[i][j]*b[j]; 
                   2673:     else if (sum) ii=i; 
                   2674:     b[i]=sum; 
                   2675:   } 
                   2676:   for (i=n;i>=1;i--) { 
                   2677:     sum=b[i]; 
                   2678:     for (j=i+1;j<=n;j++) sum -= a[i][j]*b[j]; 
                   2679:     b[i]=sum/a[i][i]; 
                   2680:   } 
                   2681: } 
                   2682: 
                   2683: void pstamp(FILE *fichier)
                   2684: {
                   2685:   fprintf(fichier,"# %s.%s\n#%s\n#%s\n# %s", optionfilefiname,optionfilext,version,fullversion,strstart);
                   2686: }
                   2687: 
                   2688: /************ Frequencies ********************/
                   2689: 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[])
                   2690: {  /* Some frequencies */
                   2691:   
1.164     brouard  2692:   int i, m, jk, j1, bool, z1,j;
1.126     brouard  2693:   int first;
                   2694:   double ***freq; /* Frequencies */
                   2695:   double *pp, **prop;
                   2696:   double pos,posprop, k2, dateintsum=0,k2cpt=0;
                   2697:   char fileresp[FILENAMELENGTH];
                   2698:   
                   2699:   pp=vector(1,nlstate);
                   2700:   prop=matrix(1,nlstate,iagemin,iagemax+3);
                   2701:   strcpy(fileresp,"p");
                   2702:   strcat(fileresp,fileres);
                   2703:   if((ficresp=fopen(fileresp,"w"))==NULL) {
                   2704:     printf("Problem with prevalence resultfile: %s\n", fileresp);
                   2705:     fprintf(ficlog,"Problem with prevalence resultfile: %s\n", fileresp);
                   2706:     exit(0);
                   2707:   }
                   2708:   freq= ma3x(-5,nlstate+ndeath,-5,nlstate+ndeath,iagemin,iagemax+3);
                   2709:   j1=0;
                   2710:   
                   2711:   j=cptcoveff;
                   2712:   if (cptcovn<1) {j=1;ncodemax[1]=1;}
                   2713: 
                   2714:   first=1;
                   2715: 
1.169     brouard  2716:   /* for(k1=1; k1<=j ; k1++){ */  /* Loop on covariates */
                   2717:   /*  for(i1=1; i1<=ncodemax[k1];i1++){ */ /* Now it is 2 */
                   2718:   /*    j1++; */
1.145     brouard  2719:   for (j1 = 1; j1 <= (int) pow(2,cptcoveff); j1++){
1.126     brouard  2720:       /*printf("cptcoveff=%d Tvaraff=%d", cptcoveff,Tvaraff[1]);
                   2721:        scanf("%d", i);*/
                   2722:       for (i=-5; i<=nlstate+ndeath; i++)  
                   2723:        for (jk=-5; jk<=nlstate+ndeath; jk++)  
                   2724:          for(m=iagemin; m <= iagemax+3; m++)
                   2725:            freq[i][jk][m]=0;
1.143     brouard  2726:       
                   2727:       for (i=1; i<=nlstate; i++)  
                   2728:        for(m=iagemin; m <= iagemax+3; m++)
                   2729:          prop[i][m]=0;
1.126     brouard  2730:       
                   2731:       dateintsum=0;
                   2732:       k2cpt=0;
                   2733:       for (i=1; i<=imx; i++) {
                   2734:        bool=1;
1.144     brouard  2735:        if  (cptcovn>0) { /* Filter is here: Must be looked at for model=V1+V2+V3+V4 */
                   2736:          for (z1=1; z1<=cptcoveff; z1++)       
                   2737:             if (covar[Tvaraff[z1]][i]!= nbcode[Tvaraff[z1]][codtab[j1][z1]]){
1.145     brouard  2738:                 /* Tests if the value of each of the covariates of i is equal to filter j1 */
1.144     brouard  2739:               bool=0;
1.145     brouard  2740:               /* 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", 
                   2741:                 bool,i,z1, z1, Tvaraff[z1],i,covar[Tvaraff[z1]][i],j1,z1,codtab[j1][z1],
                   2742:                 j1,z1,nbcode[Tvaraff[z1]][codtab[j1][z1]],j1);*/
1.144     brouard  2743:               /* For j1=7 in V1+V2+V3+V4 = 0 1 1 0 and codtab[7][3]=1 and nbcde[3][?]=1*/
                   2744:             } 
1.126     brouard  2745:        }
1.144     brouard  2746:  
1.126     brouard  2747:        if (bool==1){
                   2748:          for(m=firstpass; m<=lastpass; m++){
                   2749:            k2=anint[m][i]+(mint[m][i]/12.);
                   2750:            /*if ((k2>=dateprev1) && (k2<=dateprev2)) {*/
                   2751:              if(agev[m][i]==0) agev[m][i]=iagemax+1;
                   2752:              if(agev[m][i]==1) agev[m][i]=iagemax+2;
                   2753:              if (s[m][i]>0 && s[m][i]<=nlstate) prop[s[m][i]][(int)agev[m][i]] += weight[i];
                   2754:              if (m<lastpass) {
                   2755:                freq[s[m][i]][s[m+1][i]][(int)agev[m][i]] += weight[i];
                   2756:                freq[s[m][i]][s[m+1][i]][iagemax+3] += weight[i];
                   2757:              }
                   2758:              
                   2759:              if ((agev[m][i]>1) && (agev[m][i]< (iagemax+3))) {
                   2760:                dateintsum=dateintsum+k2;
                   2761:                k2cpt++;
                   2762:              }
                   2763:              /*}*/
                   2764:          }
                   2765:        }
1.145     brouard  2766:       } /* end i */
1.126     brouard  2767:        
                   2768:       /*      fprintf(ficresp, "#Count between %.lf/%.lf/%.lf and %.lf/%.lf/%.lf\n",jprev1, mprev1,anprev1,jprev2, mprev2,anprev2);*/
                   2769:       pstamp(ficresp);
                   2770:       if  (cptcovn>0) {
                   2771:        fprintf(ficresp, "\n#********** Variable "); 
                   2772:        for (z1=1; z1<=cptcoveff; z1++) fprintf(ficresp, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtab[j1][z1]]);
                   2773:        fprintf(ficresp, "**********\n#");
1.143     brouard  2774:        fprintf(ficlog, "\n#********** Variable "); 
                   2775:        for (z1=1; z1<=cptcoveff; z1++) fprintf(ficlog, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtab[j1][z1]]);
                   2776:        fprintf(ficlog, "**********\n#");
1.126     brouard  2777:       }
                   2778:       for(i=1; i<=nlstate;i++) 
                   2779:        fprintf(ficresp, " Age Prev(%d) N(%d) N",i,i);
                   2780:       fprintf(ficresp, "\n");
                   2781:       
                   2782:       for(i=iagemin; i <= iagemax+3; i++){
                   2783:        if(i==iagemax+3){
                   2784:          fprintf(ficlog,"Total");
                   2785:        }else{
                   2786:          if(first==1){
                   2787:            first=0;
                   2788:            printf("See log file for details...\n");
                   2789:          }
                   2790:          fprintf(ficlog,"Age %d", i);
                   2791:        }
                   2792:        for(jk=1; jk <=nlstate ; jk++){
                   2793:          for(m=-1, pp[jk]=0; m <=nlstate+ndeath ; m++)
                   2794:            pp[jk] += freq[jk][m][i]; 
                   2795:        }
                   2796:        for(jk=1; jk <=nlstate ; jk++){
                   2797:          for(m=-1, pos=0; m <=0 ; m++)
                   2798:            pos += freq[jk][m][i];
                   2799:          if(pp[jk]>=1.e-10){
                   2800:            if(first==1){
1.132     brouard  2801:              printf(" %d.=%.0f loss[%d]=%.1f%%",jk,pp[jk],jk,100*pos/pp[jk]);
1.126     brouard  2802:            }
                   2803:            fprintf(ficlog," %d.=%.0f loss[%d]=%.1f%%",jk,pp[jk],jk,100*pos/pp[jk]);
                   2804:          }else{
                   2805:            if(first==1)
                   2806:              printf(" %d.=%.0f loss[%d]=NaNQ%%",jk,pp[jk],jk);
                   2807:            fprintf(ficlog," %d.=%.0f loss[%d]=NaNQ%%",jk,pp[jk],jk);
                   2808:          }
                   2809:        }
                   2810: 
                   2811:        for(jk=1; jk <=nlstate ; jk++){
                   2812:          for(m=0, pp[jk]=0; m <=nlstate+ndeath; m++)
                   2813:            pp[jk] += freq[jk][m][i];
                   2814:        }       
                   2815:        for(jk=1,pos=0,posprop=0; jk <=nlstate ; jk++){
                   2816:          pos += pp[jk];
                   2817:          posprop += prop[jk][i];
                   2818:        }
                   2819:        for(jk=1; jk <=nlstate ; jk++){
                   2820:          if(pos>=1.e-5){
                   2821:            if(first==1)
                   2822:              printf(" %d.=%.0f prev[%d]=%.1f%%",jk,pp[jk],jk,100*pp[jk]/pos);
                   2823:            fprintf(ficlog," %d.=%.0f prev[%d]=%.1f%%",jk,pp[jk],jk,100*pp[jk]/pos);
                   2824:          }else{
                   2825:            if(first==1)
                   2826:              printf(" %d.=%.0f prev[%d]=NaNQ%%",jk,pp[jk],jk);
                   2827:            fprintf(ficlog," %d.=%.0f prev[%d]=NaNQ%%",jk,pp[jk],jk);
                   2828:          }
                   2829:          if( i <= iagemax){
                   2830:            if(pos>=1.e-5){
                   2831:              fprintf(ficresp," %d %.5f %.0f %.0f",i,prop[jk][i]/posprop, prop[jk][i],posprop);
                   2832:              /*probs[i][jk][j1]= pp[jk]/pos;*/
                   2833:              /*printf("\ni=%d jk=%d j1=%d %.5f %.0f %.0f %f",i,jk,j1,pp[jk]/pos, pp[jk],pos,probs[i][jk][j1]);*/
                   2834:            }
                   2835:            else
                   2836:              fprintf(ficresp," %d NaNq %.0f %.0f",i,prop[jk][i],posprop);
                   2837:          }
                   2838:        }
                   2839:        
                   2840:        for(jk=-1; jk <=nlstate+ndeath; jk++)
                   2841:          for(m=-1; m <=nlstate+ndeath; m++)
                   2842:            if(freq[jk][m][i] !=0 ) {
                   2843:            if(first==1)
                   2844:              printf(" %d%d=%.0f",jk,m,freq[jk][m][i]);
                   2845:              fprintf(ficlog," %d%d=%.0f",jk,m,freq[jk][m][i]);
                   2846:            }
                   2847:        if(i <= iagemax)
                   2848:          fprintf(ficresp,"\n");
                   2849:        if(first==1)
                   2850:          printf("Others in log...\n");
                   2851:        fprintf(ficlog,"\n");
                   2852:       }
1.145     brouard  2853:       /*}*/
1.126     brouard  2854:   }
                   2855:   dateintmean=dateintsum/k2cpt; 
                   2856:  
                   2857:   fclose(ficresp);
                   2858:   free_ma3x(freq,-5,nlstate+ndeath,-5,nlstate+ndeath, iagemin, iagemax+3);
                   2859:   free_vector(pp,1,nlstate);
                   2860:   free_matrix(prop,1,nlstate,iagemin, iagemax+3);
                   2861:   /* End of Freq */
                   2862: }
                   2863: 
                   2864: /************ Prevalence ********************/
                   2865: 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)
                   2866: {  
                   2867:   /* Compute observed prevalence between dateprev1 and dateprev2 by counting the number of people
                   2868:      in each health status at the date of interview (if between dateprev1 and dateprev2).
                   2869:      We still use firstpass and lastpass as another selection.
                   2870:   */
                   2871:  
1.164     brouard  2872:   int i, m, jk, j1, bool, z1,j;
                   2873: 
                   2874:   double **prop;
                   2875:   double posprop; 
1.126     brouard  2876:   double  y2; /* in fractional years */
                   2877:   int iagemin, iagemax;
1.145     brouard  2878:   int first; /** to stop verbosity which is redirected to log file */
1.126     brouard  2879: 
                   2880:   iagemin= (int) agemin;
                   2881:   iagemax= (int) agemax;
                   2882:   /*pp=vector(1,nlstate);*/
                   2883:   prop=matrix(1,nlstate,iagemin,iagemax+3); 
                   2884:   /*  freq=ma3x(-1,nlstate+ndeath,-1,nlstate+ndeath,iagemin,iagemax+3);*/
                   2885:   j1=0;
                   2886:   
1.145     brouard  2887:   /*j=cptcoveff;*/
1.126     brouard  2888:   if (cptcovn<1) {j=1;ncodemax[1]=1;}
                   2889:   
1.145     brouard  2890:   first=1;
                   2891:   for(j1=1; j1<= (int) pow(2,cptcoveff);j1++){
                   2892:     /*for(i1=1; i1<=ncodemax[k1];i1++){
                   2893:       j1++;*/
1.126     brouard  2894:       
                   2895:       for (i=1; i<=nlstate; i++)  
                   2896:        for(m=iagemin; m <= iagemax+3; m++)
                   2897:          prop[i][m]=0.0;
                   2898:      
                   2899:       for (i=1; i<=imx; i++) { /* Each individual */
                   2900:        bool=1;
                   2901:        if  (cptcovn>0) {
                   2902:          for (z1=1; z1<=cptcoveff; z1++) 
                   2903:            if (covar[Tvaraff[z1]][i]!= nbcode[Tvaraff[z1]][codtab[j1][z1]]) 
                   2904:              bool=0;
                   2905:        } 
                   2906:        if (bool==1) { 
                   2907:          for(m=firstpass; m<=lastpass; m++){/* Other selection (we can limit to certain interviews*/
                   2908:            y2=anint[m][i]+(mint[m][i]/12.); /* Fractional date in year */
                   2909:            if ((y2>=dateprev1) && (y2<=dateprev2)) { /* Here is the main selection (fractional years) */
                   2910:              if(agev[m][i]==0) agev[m][i]=iagemax+1;
                   2911:              if(agev[m][i]==1) agev[m][i]=iagemax+2;
                   2912:              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); 
                   2913:              if (s[m][i]>0 && s[m][i]<=nlstate) { 
                   2914:                /*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]]);*/
                   2915:                prop[s[m][i]][(int)agev[m][i]] += weight[i];
                   2916:                prop[s[m][i]][iagemax+3] += weight[i]; 
                   2917:              } 
                   2918:            }
                   2919:          } /* end selection of waves */
                   2920:        }
                   2921:       }
                   2922:       for(i=iagemin; i <= iagemax+3; i++){  
                   2923:        for(jk=1,posprop=0; jk <=nlstate ; jk++) { 
                   2924:          posprop += prop[jk][i]; 
                   2925:        } 
1.145     brouard  2926:        
1.126     brouard  2927:        for(jk=1; jk <=nlstate ; jk++){     
                   2928:          if( i <=  iagemax){ 
                   2929:            if(posprop>=1.e-5){ 
                   2930:              probs[i][jk][j1]= prop[jk][i]/posprop;
1.145     brouard  2931:            } else{
                   2932:              if(first==1){
                   2933:                first=0;
                   2934:                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]);
                   2935:              }
                   2936:            }
1.126     brouard  2937:          } 
                   2938:        }/* end jk */ 
                   2939:       }/* end i */ 
1.145     brouard  2940:     /*} *//* end i1 */
                   2941:   } /* end j1 */
1.126     brouard  2942:   
                   2943:   /*  free_ma3x(freq,-1,nlstate+ndeath,-1,nlstate+ndeath, iagemin, iagemax+3);*/
                   2944:   /*free_vector(pp,1,nlstate);*/
                   2945:   free_matrix(prop,1,nlstate, iagemin,iagemax+3);
                   2946: }  /* End of prevalence */
                   2947: 
                   2948: /************* Waves Concatenation ***************/
                   2949: 
                   2950: 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)
                   2951: {
                   2952:   /* Concatenates waves: wav[i] is the number of effective (useful waves) of individual i.
                   2953:      Death is a valid wave (if date is known).
                   2954:      mw[mi][i] is the mi (mi=1 to wav[i])  effective wave of individual i
                   2955:      dh[m][i] or dh[mw[mi][i]][i] is the delay between two effective waves m=mw[mi][i]
                   2956:      and mw[mi+1][i]. dh depends on stepm.
                   2957:      */
                   2958: 
                   2959:   int i, mi, m;
                   2960:   /* int j, k=0,jk, ju, jl,jmin=1e+5, jmax=-1;
                   2961:      double sum=0., jmean=0.;*/
                   2962:   int first;
                   2963:   int j, k=0,jk, ju, jl;
                   2964:   double sum=0.;
                   2965:   first=0;
1.164     brouard  2966:   jmin=100000;
1.126     brouard  2967:   jmax=-1;
                   2968:   jmean=0.;
                   2969:   for(i=1; i<=imx; i++){
                   2970:     mi=0;
                   2971:     m=firstpass;
                   2972:     while(s[m][i] <= nlstate){
                   2973:       if(s[m][i]>=1 || s[m][i]==-2 || s[m][i]==-4 || s[m][i]==-5)
                   2974:        mw[++mi][i]=m;
                   2975:       if(m >=lastpass)
                   2976:        break;
                   2977:       else
                   2978:        m++;
                   2979:     }/* end while */
                   2980:     if (s[m][i] > nlstate){
                   2981:       mi++;    /* Death is another wave */
                   2982:       /* if(mi==0)  never been interviewed correctly before death */
                   2983:         /* Only death is a correct wave */
                   2984:       mw[mi][i]=m;
                   2985:     }
                   2986: 
                   2987:     wav[i]=mi;
                   2988:     if(mi==0){
                   2989:       nbwarn++;
                   2990:       if(first==0){
                   2991:        printf("Warning! No valid information for individual %ld line=%d (skipped) and may be others, see log file\n",num[i],i);
                   2992:        first=1;
                   2993:       }
                   2994:       if(first==1){
                   2995:        fprintf(ficlog,"Warning! No valid information for individual %ld line=%d (skipped)\n",num[i],i);
                   2996:       }
                   2997:     } /* end mi==0 */
                   2998:   } /* End individuals */
                   2999: 
                   3000:   for(i=1; i<=imx; i++){
                   3001:     for(mi=1; mi<wav[i];mi++){
                   3002:       if (stepm <=0)
                   3003:        dh[mi][i]=1;
                   3004:       else{
                   3005:        if (s[mw[mi+1][i]][i] > nlstate) { /* A death */
                   3006:          if (agedc[i] < 2*AGESUP) {
                   3007:            j= rint(agedc[i]*12-agev[mw[mi][i]][i]*12); 
                   3008:            if(j==0) j=1;  /* Survives at least one month after exam */
                   3009:            else if(j<0){
                   3010:              nberr++;
                   3011:              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]);
                   3012:              j=1; /* Temporary Dangerous patch */
                   3013:              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);
                   3014:              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]);
                   3015:              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);
                   3016:            }
                   3017:            k=k+1;
                   3018:            if (j >= jmax){
                   3019:              jmax=j;
                   3020:              ijmax=i;
                   3021:            }
                   3022:            if (j <= jmin){
                   3023:              jmin=j;
                   3024:              ijmin=i;
                   3025:            }
                   3026:            sum=sum+j;
                   3027:            /*if (j<0) printf("j=%d num=%d \n",j,i);*/
                   3028:            /*    printf("%d %d %d %d\n", s[mw[mi][i]][i] ,s[mw[mi+1][i]][i],j,i);*/
                   3029:          }
                   3030:        }
                   3031:        else{
                   3032:          j= rint( (agev[mw[mi+1][i]][i]*12 - agev[mw[mi][i]][i]*12));
                   3033: /*       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]); */
                   3034: 
                   3035:          k=k+1;
                   3036:          if (j >= jmax) {
                   3037:            jmax=j;
                   3038:            ijmax=i;
                   3039:          }
                   3040:          else if (j <= jmin){
                   3041:            jmin=j;
                   3042:            ijmin=i;
                   3043:          }
                   3044:          /*        if (j<10) printf("j=%d jmin=%d num=%d ",j,jmin,i); */
                   3045:          /*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]);*/
                   3046:          if(j<0){
                   3047:            nberr++;
                   3048:            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]);
                   3049:            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]);
                   3050:          }
                   3051:          sum=sum+j;
                   3052:        }
                   3053:        jk= j/stepm;
                   3054:        jl= j -jk*stepm;
                   3055:        ju= j -(jk+1)*stepm;
                   3056:        if(mle <=1){ /* only if we use a the linear-interpoloation pseudo-likelihood */
                   3057:          if(jl==0){
                   3058:            dh[mi][i]=jk;
                   3059:            bh[mi][i]=0;
                   3060:          }else{ /* We want a negative bias in order to only have interpolation ie
1.136     brouard  3061:                  * to avoid the price of an extra matrix product in likelihood */
1.126     brouard  3062:            dh[mi][i]=jk+1;
                   3063:            bh[mi][i]=ju;
                   3064:          }
                   3065:        }else{
                   3066:          if(jl <= -ju){
                   3067:            dh[mi][i]=jk;
                   3068:            bh[mi][i]=jl;       /* bias is positive if real duration
                   3069:                                 * is higher than the multiple of stepm and negative otherwise.
                   3070:                                 */
                   3071:          }
                   3072:          else{
                   3073:            dh[mi][i]=jk+1;
                   3074:            bh[mi][i]=ju;
                   3075:          }
                   3076:          if(dh[mi][i]==0){
                   3077:            dh[mi][i]=1; /* At least one step */
                   3078:            bh[mi][i]=ju; /* At least one step */
                   3079:            /*  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);*/
                   3080:          }
                   3081:        } /* end if mle */
                   3082:       }
                   3083:     } /* end wave */
                   3084:   }
                   3085:   jmean=sum/k;
                   3086:   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  3087:   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  3088:  }
                   3089: 
                   3090: /*********** Tricode ****************************/
1.145     brouard  3091: void tricode(int *Tvar, int **nbcode, int imx, int *Ndum)
1.126     brouard  3092: {
1.144     brouard  3093:   /**< Uses cptcovn+2*cptcovprod as the number of covariates */
                   3094:   /*     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  3095:    * Boring subroutine which should only output nbcode[Tvar[j]][k]
1.145     brouard  3096:    * Tvar[5] in V2+V1+V3*age+V2*V4 is 2 (V2)
1.169     brouard  3097:    * nbcode[Tvar[j]][1]= 
1.144     brouard  3098:   */
1.130     brouard  3099: 
1.145     brouard  3100:   int ij=1, k=0, j=0, i=0, maxncov=NCOVMAX;
1.136     brouard  3101:   int modmaxcovj=0; /* Modality max of covariates j */
1.145     brouard  3102:   int cptcode=0; /* Modality max of covariates j */
                   3103:   int modmincovj=0; /* Modality min of covariates j */
                   3104: 
                   3105: 
1.126     brouard  3106:   cptcoveff=0; 
                   3107:  
1.145     brouard  3108:   for (k=-1; k < maxncov; k++) Ndum[k]=0;
1.144     brouard  3109:   for (k=1; k <= maxncov; k++) ncodemax[k]=0; /* Horrible constant again replaced by NCOVMAX */
1.126     brouard  3110: 
1.145     brouard  3111:   /* Loop on covariates without age and products */
1.186   ! brouard  3112:   for (j=1; j<=(cptcovs); j++) { /* From model V1 + V2*age+ V3 + V3*V4 keeps V1 + V3 = 2 only */
        !          3113:     for (i=1; i<=imx; i++) { /* Loop on individuals: reads the data file to get the maximum value of the 
1.136     brouard  3114:                               modality of this covariate Vj*/ 
1.145     brouard  3115:       ij=(int)(covar[Tvar[j]][i]); /* ij=0 or 1 or -1. Value of the covariate Tvar[j] for individual i
                   3116:                                    * If product of Vn*Vm, still boolean *:
                   3117:                                    * If it was coded 1, 2, 3, 4 should be splitted into 3 boolean variables
                   3118:                                    * 1 => 0 0 0, 2 => 0 0 1, 3 => 0 1 1, 4=1 0 0   */
                   3119:       /* Finds for covariate j, n=Tvar[j] of Vn . ij is the
1.136     brouard  3120:                                      modality of the nth covariate of individual i. */
1.145     brouard  3121:       if (ij > modmaxcovj)
                   3122:         modmaxcovj=ij; 
                   3123:       else if (ij < modmincovj) 
                   3124:        modmincovj=ij; 
                   3125:       if ((ij < -1) && (ij > NCOVMAX)){
                   3126:        printf( "Error: minimal is less than -1 or maximal is bigger than %d. Exiting. \n", NCOVMAX );
                   3127:        exit(1);
                   3128:       }else
1.136     brouard  3129:       Ndum[ij]++; /*counts and stores the occurence of this modality 0, 1, -1*/
1.145     brouard  3130:       /*  If coded 1, 2, 3 , counts the number of 1 Ndum[1], number of 2, Ndum[2], etc */
1.126     brouard  3131:       /*printf("i=%d ij=%d Ndum[ij]=%d imx=%d",i,ij,Ndum[ij],imx);*/
1.136     brouard  3132:       /* getting the maximum value of the modality of the covariate
                   3133:         (should be 0 or 1 now) Tvar[j]. If V=sex and male is coded 0 and
                   3134:         female is 1, then modmaxcovj=1.*/
1.126     brouard  3135:     }
1.145     brouard  3136:     printf(" Minimal and maximal values of %d th covariate V%d: min=%d max=%d \n", j, Tvar[j], modmincovj, modmaxcovj);
                   3137:     cptcode=modmaxcovj;
1.137     brouard  3138:     /* Ndum[0] = frequency of 0 for model-covariate j, Ndum[1] frequency of 1 etc. */
1.145     brouard  3139:    /*for (i=0; i<=cptcode; i++) {*/
                   3140:     for (i=modmincovj;  i<=modmaxcovj; i++) { /* i=-1 ? 0 and 1*//* For each value of the modality of model-cov j */
                   3141:       printf("Frequencies of covariates %d V%d %d\n", j, Tvar[j], Ndum[i]);
                   3142:       if( Ndum[i] != 0 ){ /* Counts if nobody answered, empty modality */
                   3143:        ncodemax[j]++;  /* ncodemax[j]= Number of non-null modalities of the j th covariate. */
                   3144:       }
                   3145:       /* In fact  ncodemax[j]=2 (dichotom. variables only) but it could be more for
                   3146:         historical reasons: 3 if coded 1, 2, 3 and 4 and Ndum[2]=0 */
1.131     brouard  3147:     } /* Ndum[-1] number of undefined modalities */
1.126     brouard  3148: 
1.136     brouard  3149:     /* j is a covariate, n=Tvar[j] of Vn; Fills nbcode */
1.186   ! brouard  3150:     /* For covariate j, modalities could be 1, 2, 3, 4, 5, 6, 7. 
        !          3151:        If Ndum[1]=0, Ndum[2]=0, Ndum[3]= 635, Ndum[4]=0, Ndum[5]=0, Ndum[6]=27, Ndum[7]=125;
1.145     brouard  3152:        modmincovj=3; modmaxcovj = 7;
1.186   ! brouard  3153:        There are only 3 modalities non empty 3, 6, 7 (or 2 if 27 is too few) : ncodemax[j]=3;
        !          3154:        which will be coded 0, 1, 2 which in binary on 2=3-1 digits are 0=00 1=01, 2=10;
        !          3155:        defining two dummy variables: variables V1_1 and V1_2.
1.145     brouard  3156:        nbcode[Tvar[j]][ij]=k;
                   3157:        nbcode[Tvar[j]][1]=0;
                   3158:        nbcode[Tvar[j]][2]=1;
                   3159:        nbcode[Tvar[j]][3]=2;
                   3160:     */
                   3161:     ij=1; /* ij is similar to i but can jumps over null modalities */
                   3162:     for (i=modmincovj; i<=modmaxcovj; i++) { /* i= 1 to 2 for dichotomous, or from 1 to 3 */
                   3163:       for (k=0; k<= cptcode; k++) { /* k=-1 ? k=0 to 1 *//* Could be 1 to 4 */
                   3164:        /*recode from 0 */
1.131     brouard  3165:        if (Ndum[k] != 0) { /* If at least one individual responded to this modality k */
1.186   ! brouard  3166:          nbcode[Tvar[j]][ij]=k;  /* stores the modality k in an array nbcode. 
1.131     brouard  3167:                                     k is a modality. If we have model=V1+V1*sex 
                   3168:                                     then: nbcode[1][1]=0 ; nbcode[1][2]=1; nbcode[2][1]=0 ; nbcode[2][2]=1; */
1.126     brouard  3169:          ij++;
                   3170:        }
                   3171:        if (ij > ncodemax[j]) break; 
1.137     brouard  3172:       }  /* end of loop on */
                   3173:     } /* end of loop on modality */ 
                   3174:   } /* end of loop on model-covariate j. nbcode[Tvarj][1]=0 and nbcode[Tvarj][2]=1 sets the value of covariate j*/  
                   3175:   
1.145     brouard  3176:  for (k=-1; k< maxncov; k++) Ndum[k]=0; 
1.137     brouard  3177:   
1.145     brouard  3178:   for (i=1; i<=ncovmodel-2; i++) { /* -2, cste and age */ 
                   3179:    /* Listing of all covariables in statement model to see if some covariates appear twice. For example, V1 appears twice in V1+V1*V2.*/ 
                   3180:    ij=Tvar[i]; /* Tvar might be -1 if status was unknown */ 
                   3181:    Ndum[ij]++; 
                   3182:  } 
1.126     brouard  3183: 
                   3184:  ij=1;
1.145     brouard  3185:  for (i=0; i<=  maxncov-1; i++) { /* modmaxcovj is unknown here. Only Ndum[2(V2),3(age*V3), 5(V3*V2) 6(V1*V4) */
                   3186:    /*printf("Ndum[%d]=%d\n",i, Ndum[i]);*/
1.126     brouard  3187:    if((Ndum[i]!=0) && (i<=ncovcol)){
1.145     brouard  3188:      /*printf("diff Ndum[%d]=%d\n",i, Ndum[i]);*/
                   3189:      Tvaraff[ij]=i; /*For printing (unclear) */
1.126     brouard  3190:      ij++;
1.145     brouard  3191:    }else
                   3192:        Tvaraff[ij]=0;
1.126     brouard  3193:  }
1.131     brouard  3194:  ij--;
1.144     brouard  3195:  cptcoveff=ij; /*Number of total covariates*/
1.145     brouard  3196: 
1.126     brouard  3197: }
                   3198: 
1.145     brouard  3199: 
1.126     brouard  3200: /*********** Health Expectancies ****************/
                   3201: 
1.127     brouard  3202: 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  3203: 
                   3204: {
                   3205:   /* Health expectancies, no variances */
1.164     brouard  3206:   int i, j, nhstepm, hstepm, h, nstepm;
1.126     brouard  3207:   int nhstepma, nstepma; /* Decreasing with age */
                   3208:   double age, agelim, hf;
                   3209:   double ***p3mat;
                   3210:   double eip;
                   3211: 
                   3212:   pstamp(ficreseij);
                   3213:   fprintf(ficreseij,"# (a) Life expectancies by health status at initial age and (b) health expectancies by health status at initial age\n");
                   3214:   fprintf(ficreseij,"# Age");
                   3215:   for(i=1; i<=nlstate;i++){
                   3216:     for(j=1; j<=nlstate;j++){
                   3217:       fprintf(ficreseij," e%1d%1d ",i,j);
                   3218:     }
                   3219:     fprintf(ficreseij," e%1d. ",i);
                   3220:   }
                   3221:   fprintf(ficreseij,"\n");
                   3222: 
                   3223:   
                   3224:   if(estepm < stepm){
                   3225:     printf ("Problem %d lower than %d\n",estepm, stepm);
                   3226:   }
                   3227:   else  hstepm=estepm;   
                   3228:   /* We compute the life expectancy from trapezoids spaced every estepm months
                   3229:    * This is mainly to measure the difference between two models: for example
                   3230:    * if stepm=24 months pijx are given only every 2 years and by summing them
                   3231:    * we are calculating an estimate of the Life Expectancy assuming a linear 
                   3232:    * progression in between and thus overestimating or underestimating according
                   3233:    * to the curvature of the survival function. If, for the same date, we 
                   3234:    * estimate the model with stepm=1 month, we can keep estepm to 24 months
                   3235:    * to compare the new estimate of Life expectancy with the same linear 
                   3236:    * hypothesis. A more precise result, taking into account a more precise
                   3237:    * curvature will be obtained if estepm is as small as stepm. */
                   3238: 
                   3239:   /* For example we decided to compute the life expectancy with the smallest unit */
                   3240:   /* hstepm beeing the number of stepms, if hstepm=1 the length of hstepm is stepm. 
                   3241:      nhstepm is the number of hstepm from age to agelim 
                   3242:      nstepm is the number of stepm from age to agelin. 
                   3243:      Look at hpijx to understand the reason of that which relies in memory size
                   3244:      and note for a fixed period like estepm months */
                   3245:   /* We decided (b) to get a life expectancy respecting the most precise curvature of the
                   3246:      survival function given by stepm (the optimization length). Unfortunately it
                   3247:      means that if the survival funtion is printed only each two years of age and if
                   3248:      you sum them up and add 1 year (area under the trapezoids) you won't get the same 
                   3249:      results. So we changed our mind and took the option of the best precision.
                   3250:   */
                   3251:   hstepm=hstepm/stepm; /* Typically in stepm units, if stepm=6 & estepm=24 , = 24/6 months = 4 */ 
                   3252: 
                   3253:   agelim=AGESUP;
                   3254:   /* If stepm=6 months */
                   3255:     /* Computed by stepm unit matrices, product of hstepm matrices, stored
                   3256:        in an array of nhstepm length: nhstepm=10, hstepm=4, stepm=6 months */
                   3257:     
                   3258: /* nhstepm age range expressed in number of stepm */
                   3259:   nstepm=(int) rint((agelim-bage)*YEARM/stepm); /* Biggest nstepm */
                   3260:   /* Typically if 20 years nstepm = 20*12/6=40 stepm */ 
                   3261:   /* if (stepm >= YEARM) hstepm=1;*/
                   3262:   nhstepm = nstepm/hstepm;/* Expressed in hstepm, typically nhstepm=40/4=10 */
                   3263:   p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   3264: 
                   3265:   for (age=bage; age<=fage; age ++){ 
                   3266:     nstepma=(int) rint((agelim-bage)*YEARM/stepm); /* Biggest nstepm */
                   3267:     /* Typically if 20 years nstepm = 20*12/6=40 stepm */ 
                   3268:     /* if (stepm >= YEARM) hstepm=1;*/
                   3269:     nhstepma = nstepma/hstepm;/* Expressed in hstepm, typically nhstepma=40/4=10 */
                   3270: 
                   3271:     /* If stepm=6 months */
                   3272:     /* Computed by stepm unit matrices, product of hstepma matrices, stored
                   3273:        in an array of nhstepma length: nhstepma=10, hstepm=4, stepm=6 months */
                   3274:     
                   3275:     hpxij(p3mat,nhstepma,age,hstepm,x,nlstate,stepm,oldm, savm, cij);  
                   3276:     
                   3277:     hf=hstepm*stepm/YEARM;  /* Duration of hstepm expressed in year unit. */
                   3278:     
                   3279:     printf("%d|",(int)age);fflush(stdout);
                   3280:     fprintf(ficlog,"%d|",(int)age);fflush(ficlog);
                   3281:     
                   3282:     /* Computing expectancies */
                   3283:     for(i=1; i<=nlstate;i++)
                   3284:       for(j=1; j<=nlstate;j++)
                   3285:        for (h=0, eij[i][j][(int)age]=0; h<=nhstepm-1; h++){
                   3286:          eij[i][j][(int)age] += (p3mat[i][j][h]+p3mat[i][j][h+1])/2.0*hf;
                   3287:          
                   3288:          /* 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]);*/
                   3289: 
                   3290:        }
                   3291: 
                   3292:     fprintf(ficreseij,"%3.0f",age );
                   3293:     for(i=1; i<=nlstate;i++){
                   3294:       eip=0;
                   3295:       for(j=1; j<=nlstate;j++){
                   3296:        eip +=eij[i][j][(int)age];
                   3297:        fprintf(ficreseij,"%9.4f", eij[i][j][(int)age] );
                   3298:       }
                   3299:       fprintf(ficreseij,"%9.4f", eip );
                   3300:     }
                   3301:     fprintf(ficreseij,"\n");
                   3302:     
                   3303:   }
                   3304:   free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   3305:   printf("\n");
                   3306:   fprintf(ficlog,"\n");
                   3307:   
                   3308: }
                   3309: 
1.127     brouard  3310: 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  3311: 
                   3312: {
                   3313:   /* Covariances of health expectancies eij and of total life expectancies according
                   3314:    to initial status i, ei. .
                   3315:   */
                   3316:   int i, j, nhstepm, hstepm, h, nstepm, k, cptj, cptj2, i2, j2, ij, ji;
                   3317:   int nhstepma, nstepma; /* Decreasing with age */
                   3318:   double age, agelim, hf;
                   3319:   double ***p3matp, ***p3matm, ***varhe;
                   3320:   double **dnewm,**doldm;
                   3321:   double *xp, *xm;
                   3322:   double **gp, **gm;
                   3323:   double ***gradg, ***trgradg;
                   3324:   int theta;
                   3325: 
                   3326:   double eip, vip;
                   3327: 
                   3328:   varhe=ma3x(1,nlstate*nlstate,1,nlstate*nlstate,(int) bage, (int) fage);
                   3329:   xp=vector(1,npar);
                   3330:   xm=vector(1,npar);
                   3331:   dnewm=matrix(1,nlstate*nlstate,1,npar);
                   3332:   doldm=matrix(1,nlstate*nlstate,1,nlstate*nlstate);
                   3333:   
                   3334:   pstamp(ficresstdeij);
                   3335:   fprintf(ficresstdeij,"# Health expectancies with standard errors\n");
                   3336:   fprintf(ficresstdeij,"# Age");
                   3337:   for(i=1; i<=nlstate;i++){
                   3338:     for(j=1; j<=nlstate;j++)
                   3339:       fprintf(ficresstdeij," e%1d%1d (SE)",i,j);
                   3340:     fprintf(ficresstdeij," e%1d. ",i);
                   3341:   }
                   3342:   fprintf(ficresstdeij,"\n");
                   3343: 
                   3344:   pstamp(ficrescveij);
                   3345:   fprintf(ficrescveij,"# Subdiagonal matrix of covariances of health expectancies by age: cov(eij,ekl)\n");
                   3346:   fprintf(ficrescveij,"# Age");
                   3347:   for(i=1; i<=nlstate;i++)
                   3348:     for(j=1; j<=nlstate;j++){
                   3349:       cptj= (j-1)*nlstate+i;
                   3350:       for(i2=1; i2<=nlstate;i2++)
                   3351:        for(j2=1; j2<=nlstate;j2++){
                   3352:          cptj2= (j2-1)*nlstate+i2;
                   3353:          if(cptj2 <= cptj)
                   3354:            fprintf(ficrescveij,"  %1d%1d,%1d%1d",i,j,i2,j2);
                   3355:        }
                   3356:     }
                   3357:   fprintf(ficrescveij,"\n");
                   3358:   
                   3359:   if(estepm < stepm){
                   3360:     printf ("Problem %d lower than %d\n",estepm, stepm);
                   3361:   }
                   3362:   else  hstepm=estepm;   
                   3363:   /* We compute the life expectancy from trapezoids spaced every estepm months
                   3364:    * This is mainly to measure the difference between two models: for example
                   3365:    * if stepm=24 months pijx are given only every 2 years and by summing them
                   3366:    * we are calculating an estimate of the Life Expectancy assuming a linear 
                   3367:    * progression in between and thus overestimating or underestimating according
                   3368:    * to the curvature of the survival function. If, for the same date, we 
                   3369:    * estimate the model with stepm=1 month, we can keep estepm to 24 months
                   3370:    * to compare the new estimate of Life expectancy with the same linear 
                   3371:    * hypothesis. A more precise result, taking into account a more precise
                   3372:    * curvature will be obtained if estepm is as small as stepm. */
                   3373: 
                   3374:   /* For example we decided to compute the life expectancy with the smallest unit */
                   3375:   /* hstepm beeing the number of stepms, if hstepm=1 the length of hstepm is stepm. 
                   3376:      nhstepm is the number of hstepm from age to agelim 
                   3377:      nstepm is the number of stepm from age to agelin. 
                   3378:      Look at hpijx to understand the reason of that which relies in memory size
                   3379:      and note for a fixed period like estepm months */
                   3380:   /* We decided (b) to get a life expectancy respecting the most precise curvature of the
                   3381:      survival function given by stepm (the optimization length). Unfortunately it
                   3382:      means that if the survival funtion is printed only each two years of age and if
                   3383:      you sum them up and add 1 year (area under the trapezoids) you won't get the same 
                   3384:      results. So we changed our mind and took the option of the best precision.
                   3385:   */
                   3386:   hstepm=hstepm/stepm; /* Typically in stepm units, if stepm=6 & estepm=24 , = 24/6 months = 4 */ 
                   3387: 
                   3388:   /* If stepm=6 months */
                   3389:   /* nhstepm age range expressed in number of stepm */
                   3390:   agelim=AGESUP;
                   3391:   nstepm=(int) rint((agelim-bage)*YEARM/stepm); 
                   3392:   /* Typically if 20 years nstepm = 20*12/6=40 stepm */ 
                   3393:   /* if (stepm >= YEARM) hstepm=1;*/
                   3394:   nhstepm = nstepm/hstepm;/* Expressed in hstepm, typically nhstepm=40/4=10 */
                   3395:   
                   3396:   p3matp=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   3397:   p3matm=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   3398:   gradg=ma3x(0,nhstepm,1,npar,1,nlstate*nlstate);
                   3399:   trgradg =ma3x(0,nhstepm,1,nlstate*nlstate,1,npar);
                   3400:   gp=matrix(0,nhstepm,1,nlstate*nlstate);
                   3401:   gm=matrix(0,nhstepm,1,nlstate*nlstate);
                   3402: 
                   3403:   for (age=bage; age<=fage; age ++){ 
                   3404:     nstepma=(int) rint((agelim-bage)*YEARM/stepm); /* Biggest nstepm */
                   3405:     /* Typically if 20 years nstepm = 20*12/6=40 stepm */ 
                   3406:     /* if (stepm >= YEARM) hstepm=1;*/
                   3407:     nhstepma = nstepma/hstepm;/* Expressed in hstepm, typically nhstepma=40/4=10 */
                   3408: 
                   3409:     /* If stepm=6 months */
                   3410:     /* Computed by stepm unit matrices, product of hstepma matrices, stored
                   3411:        in an array of nhstepma length: nhstepma=10, hstepm=4, stepm=6 months */
                   3412:     
                   3413:     hf=hstepm*stepm/YEARM;  /* Duration of hstepm expressed in year unit. */
                   3414: 
                   3415:     /* Computing  Variances of health expectancies */
                   3416:     /* Gradient is computed with plus gp and minus gm. Code is duplicated in order to
                   3417:        decrease memory allocation */
                   3418:     for(theta=1; theta <=npar; theta++){
                   3419:       for(i=1; i<=npar; i++){ 
                   3420:        xp[i] = x[i] + (i==theta ?delti[theta]:0);
                   3421:        xm[i] = x[i] - (i==theta ?delti[theta]:0);
                   3422:       }
                   3423:       hpxij(p3matp,nhstepm,age,hstepm,xp,nlstate,stepm,oldm,savm, cij);  
                   3424:       hpxij(p3matm,nhstepm,age,hstepm,xm,nlstate,stepm,oldm,savm, cij);  
                   3425:   
                   3426:       for(j=1; j<= nlstate; j++){
                   3427:        for(i=1; i<=nlstate; i++){
                   3428:          for(h=0; h<=nhstepm-1; h++){
                   3429:            gp[h][(j-1)*nlstate + i] = (p3matp[i][j][h]+p3matp[i][j][h+1])/2.;
                   3430:            gm[h][(j-1)*nlstate + i] = (p3matm[i][j][h]+p3matm[i][j][h+1])/2.;
                   3431:          }
                   3432:        }
                   3433:       }
                   3434:      
                   3435:       for(ij=1; ij<= nlstate*nlstate; ij++)
                   3436:        for(h=0; h<=nhstepm-1; h++){
                   3437:          gradg[h][theta][ij]= (gp[h][ij]-gm[h][ij])/2./delti[theta];
                   3438:        }
                   3439:     }/* End theta */
                   3440:     
                   3441:     
                   3442:     for(h=0; h<=nhstepm-1; h++)
                   3443:       for(j=1; j<=nlstate*nlstate;j++)
                   3444:        for(theta=1; theta <=npar; theta++)
                   3445:          trgradg[h][j][theta]=gradg[h][theta][j];
                   3446:     
                   3447: 
                   3448:      for(ij=1;ij<=nlstate*nlstate;ij++)
                   3449:       for(ji=1;ji<=nlstate*nlstate;ji++)
                   3450:        varhe[ij][ji][(int)age] =0.;
                   3451: 
                   3452:      printf("%d|",(int)age);fflush(stdout);
                   3453:      fprintf(ficlog,"%d|",(int)age);fflush(ficlog);
                   3454:      for(h=0;h<=nhstepm-1;h++){
                   3455:       for(k=0;k<=nhstepm-1;k++){
                   3456:        matprod2(dnewm,trgradg[h],1,nlstate*nlstate,1,npar,1,npar,matcov);
                   3457:        matprod2(doldm,dnewm,1,nlstate*nlstate,1,npar,1,nlstate*nlstate,gradg[k]);
                   3458:        for(ij=1;ij<=nlstate*nlstate;ij++)
                   3459:          for(ji=1;ji<=nlstate*nlstate;ji++)
                   3460:            varhe[ij][ji][(int)age] += doldm[ij][ji]*hf*hf;
                   3461:       }
                   3462:     }
                   3463: 
                   3464:     /* Computing expectancies */
                   3465:     hpxij(p3matm,nhstepm,age,hstepm,x,nlstate,stepm,oldm, savm, cij);  
                   3466:     for(i=1; i<=nlstate;i++)
                   3467:       for(j=1; j<=nlstate;j++)
                   3468:        for (h=0, eij[i][j][(int)age]=0; h<=nhstepm-1; h++){
                   3469:          eij[i][j][(int)age] += (p3matm[i][j][h]+p3matm[i][j][h+1])/2.0*hf;
                   3470:          
                   3471:          /* 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]);*/
                   3472: 
                   3473:        }
                   3474: 
                   3475:     fprintf(ficresstdeij,"%3.0f",age );
                   3476:     for(i=1; i<=nlstate;i++){
                   3477:       eip=0.;
                   3478:       vip=0.;
                   3479:       for(j=1; j<=nlstate;j++){
                   3480:        eip += eij[i][j][(int)age];
                   3481:        for(k=1; k<=nlstate;k++) /* Sum on j and k of cov(eij,eik) */
                   3482:          vip += varhe[(j-1)*nlstate+i][(k-1)*nlstate+i][(int)age];
                   3483:        fprintf(ficresstdeij," %9.4f (%.4f)", eij[i][j][(int)age], sqrt(varhe[(j-1)*nlstate+i][(j-1)*nlstate+i][(int)age]) );
                   3484:       }
                   3485:       fprintf(ficresstdeij," %9.4f (%.4f)", eip, sqrt(vip));
                   3486:     }
                   3487:     fprintf(ficresstdeij,"\n");
                   3488: 
                   3489:     fprintf(ficrescveij,"%3.0f",age );
                   3490:     for(i=1; i<=nlstate;i++)
                   3491:       for(j=1; j<=nlstate;j++){
                   3492:        cptj= (j-1)*nlstate+i;
                   3493:        for(i2=1; i2<=nlstate;i2++)
                   3494:          for(j2=1; j2<=nlstate;j2++){
                   3495:            cptj2= (j2-1)*nlstate+i2;
                   3496:            if(cptj2 <= cptj)
                   3497:              fprintf(ficrescveij," %.4f", varhe[cptj][cptj2][(int)age]);
                   3498:          }
                   3499:       }
                   3500:     fprintf(ficrescveij,"\n");
                   3501:    
                   3502:   }
                   3503:   free_matrix(gm,0,nhstepm,1,nlstate*nlstate);
                   3504:   free_matrix(gp,0,nhstepm,1,nlstate*nlstate);
                   3505:   free_ma3x(gradg,0,nhstepm,1,npar,1,nlstate*nlstate);
                   3506:   free_ma3x(trgradg,0,nhstepm,1,nlstate*nlstate,1,npar);
                   3507:   free_ma3x(p3matm,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   3508:   free_ma3x(p3matp,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   3509:   printf("\n");
                   3510:   fprintf(ficlog,"\n");
                   3511: 
                   3512:   free_vector(xm,1,npar);
                   3513:   free_vector(xp,1,npar);
                   3514:   free_matrix(dnewm,1,nlstate*nlstate,1,npar);
                   3515:   free_matrix(doldm,1,nlstate*nlstate,1,nlstate*nlstate);
                   3516:   free_ma3x(varhe,1,nlstate*nlstate,1,nlstate*nlstate,(int) bage, (int)fage);
                   3517: }
                   3518: 
                   3519: /************ Variance ******************/
                   3520: 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[])
                   3521: {
                   3522:   /* Variance of health expectancies */
                   3523:   /*  double **prevalim(double **prlim, int nlstate, double *xp, double age, double **oldm, double ** savm,double ftolpl);*/
                   3524:   /* double **newm;*/
1.169     brouard  3525:   /* int movingaverage(double ***probs, double bage,double fage, double ***mobaverage, int mobilav)*/
                   3526:   
                   3527:   int movingaverage();
1.126     brouard  3528:   double **dnewm,**doldm;
                   3529:   double **dnewmp,**doldmp;
                   3530:   int i, j, nhstepm, hstepm, h, nstepm ;
1.164     brouard  3531:   int k;
1.126     brouard  3532:   double *xp;
                   3533:   double **gp, **gm;  /* for var eij */
                   3534:   double ***gradg, ***trgradg; /*for var eij */
                   3535:   double **gradgp, **trgradgp; /* for var p point j */
                   3536:   double *gpp, *gmp; /* for var p point j */
                   3537:   double **varppt; /* for var p point j nlstate to nlstate+ndeath */
                   3538:   double ***p3mat;
                   3539:   double age,agelim, hf;
                   3540:   double ***mobaverage;
                   3541:   int theta;
                   3542:   char digit[4];
                   3543:   char digitp[25];
                   3544: 
                   3545:   char fileresprobmorprev[FILENAMELENGTH];
                   3546: 
                   3547:   if(popbased==1){
                   3548:     if(mobilav!=0)
                   3549:       strcpy(digitp,"-populbased-mobilav-");
                   3550:     else strcpy(digitp,"-populbased-nomobil-");
                   3551:   }
                   3552:   else 
                   3553:     strcpy(digitp,"-stablbased-");
                   3554: 
                   3555:   if (mobilav!=0) {
                   3556:     mobaverage= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
                   3557:     if (movingaverage(probs, bage, fage, mobaverage,mobilav)!=0){
                   3558:       fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav);
                   3559:       printf(" Error in movingaverage mobilav=%d\n",mobilav);
                   3560:     }
                   3561:   }
                   3562: 
                   3563:   strcpy(fileresprobmorprev,"prmorprev"); 
                   3564:   sprintf(digit,"%-d",ij);
                   3565:   /*printf("DIGIT=%s, ij=%d ijr=%-d|\n",digit, ij,ij);*/
                   3566:   strcat(fileresprobmorprev,digit); /* Tvar to be done */
                   3567:   strcat(fileresprobmorprev,digitp); /* Popbased or not, mobilav or not */
                   3568:   strcat(fileresprobmorprev,fileres);
                   3569:   if((ficresprobmorprev=fopen(fileresprobmorprev,"w"))==NULL) {
                   3570:     printf("Problem with resultfile: %s\n", fileresprobmorprev);
                   3571:     fprintf(ficlog,"Problem with resultfile: %s\n", fileresprobmorprev);
                   3572:   }
                   3573:   printf("Computing total mortality p.j=w1*p1j+w2*p2j+..: result on file '%s' \n",fileresprobmorprev);
                   3574:  
                   3575:   fprintf(ficlog,"Computing total mortality p.j=w1*p1j+w2*p2j+..: result on file '%s' \n",fileresprobmorprev);
                   3576:   pstamp(ficresprobmorprev);
                   3577:   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);
                   3578:   fprintf(ficresprobmorprev,"# Age cov=%-d",ij);
                   3579:   for(j=nlstate+1; j<=(nlstate+ndeath);j++){
                   3580:     fprintf(ficresprobmorprev," p.%-d SE",j);
                   3581:     for(i=1; i<=nlstate;i++)
                   3582:       fprintf(ficresprobmorprev," w%1d p%-d%-d",i,i,j);
                   3583:   }  
                   3584:   fprintf(ficresprobmorprev,"\n");
                   3585:   fprintf(ficgp,"\n# Routine varevsij");
                   3586:   /* fprintf(fichtm, "#Local time at start: %s", strstart);*/
                   3587:   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");
                   3588:   fprintf(fichtm,"\n<br>%s  <br>\n",digitp);
                   3589: /*   } */
                   3590:   varppt = matrix(nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);
                   3591:   pstamp(ficresvij);
                   3592:   fprintf(ficresvij,"# Variance and covariance of health expectancies e.j \n#  (weighted average of eij where weights are ");
                   3593:   if(popbased==1)
1.128     brouard  3594:     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  3595:   else
                   3596:     fprintf(ficresvij,"the age specific period (stable) prevalences in each health state \n");
                   3597:   fprintf(ficresvij,"# Age");
                   3598:   for(i=1; i<=nlstate;i++)
                   3599:     for(j=1; j<=nlstate;j++)
                   3600:       fprintf(ficresvij," Cov(e.%1d, e.%1d)",i,j);
                   3601:   fprintf(ficresvij,"\n");
                   3602: 
                   3603:   xp=vector(1,npar);
                   3604:   dnewm=matrix(1,nlstate,1,npar);
                   3605:   doldm=matrix(1,nlstate,1,nlstate);
                   3606:   dnewmp= matrix(nlstate+1,nlstate+ndeath,1,npar);
                   3607:   doldmp= matrix(nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);
                   3608: 
                   3609:   gradgp=matrix(1,npar,nlstate+1,nlstate+ndeath);
                   3610:   gpp=vector(nlstate+1,nlstate+ndeath);
                   3611:   gmp=vector(nlstate+1,nlstate+ndeath);
                   3612:   trgradgp =matrix(nlstate+1,nlstate+ndeath,1,npar); /* mu or p point j*/
                   3613:   
                   3614:   if(estepm < stepm){
                   3615:     printf ("Problem %d lower than %d\n",estepm, stepm);
                   3616:   }
                   3617:   else  hstepm=estepm;   
                   3618:   /* For example we decided to compute the life expectancy with the smallest unit */
                   3619:   /* hstepm beeing the number of stepms, if hstepm=1 the length of hstepm is stepm. 
                   3620:      nhstepm is the number of hstepm from age to agelim 
                   3621:      nstepm is the number of stepm from age to agelin. 
1.128     brouard  3622:      Look at function hpijx to understand why (it is linked to memory size questions) */
1.126     brouard  3623:   /* We decided (b) to get a life expectancy respecting the most precise curvature of the
                   3624:      survival function given by stepm (the optimization length). Unfortunately it
                   3625:      means that if the survival funtion is printed every two years of age and if
                   3626:      you sum them up and add 1 year (area under the trapezoids) you won't get the same 
                   3627:      results. So we changed our mind and took the option of the best precision.
                   3628:   */
                   3629:   hstepm=hstepm/stepm; /* Typically in stepm units, if stepm=6 & estepm=24 , = 24/6 months = 4 */ 
                   3630:   agelim = AGESUP;
                   3631:   for (age=bage; age<=fage; age ++){ /* If stepm=6 months */
                   3632:     nstepm=(int) rint((agelim-age)*YEARM/stepm); /* Typically 20 years = 20*12/6=40 */ 
                   3633:     nhstepm = nstepm/hstepm;/* Expressed in hstepm, typically nhstepm=40/4=10 */
                   3634:     p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   3635:     gradg=ma3x(0,nhstepm,1,npar,1,nlstate);
                   3636:     gp=matrix(0,nhstepm,1,nlstate);
                   3637:     gm=matrix(0,nhstepm,1,nlstate);
                   3638: 
                   3639: 
                   3640:     for(theta=1; theta <=npar; theta++){
                   3641:       for(i=1; i<=npar; i++){ /* Computes gradient x + delta*/
                   3642:        xp[i] = x[i] + (i==theta ?delti[theta]:0);
                   3643:       }
                   3644:       hpxij(p3mat,nhstepm,age,hstepm,xp,nlstate,stepm,oldm,savm, ij);  
                   3645:       prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ij);
                   3646: 
                   3647:       if (popbased==1) {
                   3648:        if(mobilav ==0){
                   3649:          for(i=1; i<=nlstate;i++)
                   3650:            prlim[i][i]=probs[(int)age][i][ij];
                   3651:        }else{ /* mobilav */ 
                   3652:          for(i=1; i<=nlstate;i++)
                   3653:            prlim[i][i]=mobaverage[(int)age][i][ij];
                   3654:        }
                   3655:       }
                   3656:   
                   3657:       for(j=1; j<= nlstate; j++){
                   3658:        for(h=0; h<=nhstepm; h++){
                   3659:          for(i=1, gp[h][j]=0.;i<=nlstate;i++)
                   3660:            gp[h][j] += prlim[i][i]*p3mat[i][j][h];
                   3661:        }
                   3662:       }
                   3663:       /* This for computing probability of death (h=1 means
                   3664:          computed over hstepm matrices product = hstepm*stepm months) 
                   3665:          as a weighted average of prlim.
                   3666:       */
                   3667:       for(j=nlstate+1;j<=nlstate+ndeath;j++){
                   3668:        for(i=1,gpp[j]=0.; i<= nlstate; i++)
                   3669:          gpp[j] += prlim[i][i]*p3mat[i][j][1];
                   3670:       }    
                   3671:       /* end probability of death */
                   3672: 
                   3673:       for(i=1; i<=npar; i++) /* Computes gradient x - delta */
                   3674:        xp[i] = x[i] - (i==theta ?delti[theta]:0);
                   3675:       hpxij(p3mat,nhstepm,age,hstepm,xp,nlstate,stepm,oldm,savm, ij);  
                   3676:       prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ij);
                   3677:  
                   3678:       if (popbased==1) {
                   3679:        if(mobilav ==0){
                   3680:          for(i=1; i<=nlstate;i++)
                   3681:            prlim[i][i]=probs[(int)age][i][ij];
                   3682:        }else{ /* mobilav */ 
                   3683:          for(i=1; i<=nlstate;i++)
                   3684:            prlim[i][i]=mobaverage[(int)age][i][ij];
                   3685:        }
                   3686:       }
                   3687: 
1.128     brouard  3688:       for(j=1; j<= nlstate; j++){  /* Sum of wi * eij = e.j */
1.126     brouard  3689:        for(h=0; h<=nhstepm; h++){
                   3690:          for(i=1, gm[h][j]=0.;i<=nlstate;i++)
                   3691:            gm[h][j] += prlim[i][i]*p3mat[i][j][h];
                   3692:        }
                   3693:       }
                   3694:       /* This for computing probability of death (h=1 means
                   3695:          computed over hstepm matrices product = hstepm*stepm months) 
                   3696:          as a weighted average of prlim.
                   3697:       */
                   3698:       for(j=nlstate+1;j<=nlstate+ndeath;j++){
                   3699:        for(i=1,gmp[j]=0.; i<= nlstate; i++)
                   3700:          gmp[j] += prlim[i][i]*p3mat[i][j][1];
                   3701:       }    
                   3702:       /* end probability of death */
                   3703: 
                   3704:       for(j=1; j<= nlstate; j++) /* vareij */
                   3705:        for(h=0; h<=nhstepm; h++){
                   3706:          gradg[h][theta][j]= (gp[h][j]-gm[h][j])/2./delti[theta];
                   3707:        }
                   3708: 
                   3709:       for(j=nlstate+1; j<= nlstate+ndeath; j++){ /* var mu */
                   3710:        gradgp[theta][j]= (gpp[j]-gmp[j])/2./delti[theta];
                   3711:       }
                   3712: 
                   3713:     } /* End theta */
                   3714: 
                   3715:     trgradg =ma3x(0,nhstepm,1,nlstate,1,npar); /* veij */
                   3716: 
                   3717:     for(h=0; h<=nhstepm; h++) /* veij */
                   3718:       for(j=1; j<=nlstate;j++)
                   3719:        for(theta=1; theta <=npar; theta++)
                   3720:          trgradg[h][j][theta]=gradg[h][theta][j];
                   3721: 
                   3722:     for(j=nlstate+1; j<=nlstate+ndeath;j++) /* mu */
                   3723:       for(theta=1; theta <=npar; theta++)
                   3724:        trgradgp[j][theta]=gradgp[theta][j];
                   3725:   
                   3726: 
                   3727:     hf=hstepm*stepm/YEARM;  /* Duration of hstepm expressed in year unit. */
                   3728:     for(i=1;i<=nlstate;i++)
                   3729:       for(j=1;j<=nlstate;j++)
                   3730:        vareij[i][j][(int)age] =0.;
                   3731: 
                   3732:     for(h=0;h<=nhstepm;h++){
                   3733:       for(k=0;k<=nhstepm;k++){
                   3734:        matprod2(dnewm,trgradg[h],1,nlstate,1,npar,1,npar,matcov);
                   3735:        matprod2(doldm,dnewm,1,nlstate,1,npar,1,nlstate,gradg[k]);
                   3736:        for(i=1;i<=nlstate;i++)
                   3737:          for(j=1;j<=nlstate;j++)
                   3738:            vareij[i][j][(int)age] += doldm[i][j]*hf*hf;
                   3739:       }
                   3740:     }
                   3741:   
                   3742:     /* pptj */
                   3743:     matprod2(dnewmp,trgradgp,nlstate+1,nlstate+ndeath,1,npar,1,npar,matcov);
                   3744:     matprod2(doldmp,dnewmp,nlstate+1,nlstate+ndeath,1,npar,nlstate+1,nlstate+ndeath,gradgp);
                   3745:     for(j=nlstate+1;j<=nlstate+ndeath;j++)
                   3746:       for(i=nlstate+1;i<=nlstate+ndeath;i++)
                   3747:        varppt[j][i]=doldmp[j][i];
                   3748:     /* end ppptj */
                   3749:     /*  x centered again */
                   3750:     hpxij(p3mat,nhstepm,age,hstepm,x,nlstate,stepm,oldm,savm, ij);  
                   3751:     prevalim(prlim,nlstate,x,age,oldm,savm,ftolpl,ij);
                   3752:  
                   3753:     if (popbased==1) {
                   3754:       if(mobilav ==0){
                   3755:        for(i=1; i<=nlstate;i++)
                   3756:          prlim[i][i]=probs[(int)age][i][ij];
                   3757:       }else{ /* mobilav */ 
                   3758:        for(i=1; i<=nlstate;i++)
                   3759:          prlim[i][i]=mobaverage[(int)age][i][ij];
                   3760:       }
                   3761:     }
                   3762:              
                   3763:     /* This for computing probability of death (h=1 means
                   3764:        computed over hstepm (estepm) matrices product = hstepm*stepm months) 
                   3765:        as a weighted average of prlim.
                   3766:     */
                   3767:     for(j=nlstate+1;j<=nlstate+ndeath;j++){
                   3768:       for(i=1,gmp[j]=0.;i<= nlstate; i++) 
                   3769:        gmp[j] += prlim[i][i]*p3mat[i][j][1]; 
                   3770:     }    
                   3771:     /* end probability of death */
                   3772: 
                   3773:     fprintf(ficresprobmorprev,"%3d %d ",(int) age, ij);
                   3774:     for(j=nlstate+1; j<=(nlstate+ndeath);j++){
                   3775:       fprintf(ficresprobmorprev," %11.3e %11.3e",gmp[j], sqrt(varppt[j][j]));
                   3776:       for(i=1; i<=nlstate;i++){
                   3777:        fprintf(ficresprobmorprev," %11.3e %11.3e ",prlim[i][i],p3mat[i][j][1]);
                   3778:       }
                   3779:     } 
                   3780:     fprintf(ficresprobmorprev,"\n");
                   3781: 
                   3782:     fprintf(ficresvij,"%.0f ",age );
                   3783:     for(i=1; i<=nlstate;i++)
                   3784:       for(j=1; j<=nlstate;j++){
                   3785:        fprintf(ficresvij," %.4f", vareij[i][j][(int)age]);
                   3786:       }
                   3787:     fprintf(ficresvij,"\n");
                   3788:     free_matrix(gp,0,nhstepm,1,nlstate);
                   3789:     free_matrix(gm,0,nhstepm,1,nlstate);
                   3790:     free_ma3x(gradg,0,nhstepm,1,npar,1,nlstate);
                   3791:     free_ma3x(trgradg,0,nhstepm,1,nlstate,1,npar);
                   3792:     free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   3793:   } /* End age */
                   3794:   free_vector(gpp,nlstate+1,nlstate+ndeath);
                   3795:   free_vector(gmp,nlstate+1,nlstate+ndeath);
                   3796:   free_matrix(gradgp,1,npar,nlstate+1,nlstate+ndeath);
                   3797:   free_matrix(trgradgp,nlstate+1,nlstate+ndeath,1,npar); /* mu or p point j*/
1.145     brouard  3798:   fprintf(ficgp,"\nunset parametric;unset label; set ter png small size 320, 240");
1.126     brouard  3799:   /* for(j=nlstate+1; j<= nlstate+ndeath; j++){ *//* Only the first actually */
1.131     brouard  3800:   fprintf(ficgp,"\n set log y; unset log x;set xlabel \"Age\"; set ylabel \"Force of mortality (year-1)\";");
1.126     brouard  3801: /*   fprintf(ficgp,"\n plot \"%s\"  u 1:($3*%6.3f) not w l 1 ",fileresprobmorprev,YEARM/estepm); */
                   3802: /*   fprintf(ficgp,"\n replot \"%s\"  u 1:(($3+1.96*$4)*%6.3f) t \"95\%% interval\" w l 2 ",fileresprobmorprev,YEARM/estepm); */
                   3803: /*   fprintf(ficgp,"\n replot \"%s\"  u 1:(($3-1.96*$4)*%6.3f) not w l 2 ",fileresprobmorprev,YEARM/estepm); */
1.145     brouard  3804:   fprintf(ficgp,"\n plot \"%s\"  u 1:($3) not w l lt 1 ",subdirf(fileresprobmorprev));
1.170     brouard  3805:   fprintf(ficgp,"\n replot \"%s\"  u 1:(($3+1.96*$4)) t \"95%% interval\" w l lt 2 ",subdirf(fileresprobmorprev));
1.145     brouard  3806:   fprintf(ficgp,"\n replot \"%s\"  u 1:(($3-1.96*$4)) not w l lt 2 ",subdirf(fileresprobmorprev));
1.126     brouard  3807:   fprintf(fichtm,"\n<br> File (multiple files are possible if covariates are present): <A href=\"%s\">%s</a>\n",subdirf(fileresprobmorprev),subdirf(fileresprobmorprev));
                   3808:   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);
                   3809:   /*  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);
                   3810: */
                   3811: /*   fprintf(ficgp,"\nset out \"varmuptjgr%s%s%s.png\";replot;",digitp,optionfilefiname,digit); */
                   3812:   fprintf(ficgp,"\nset out \"%s%s.png\";replot;\n",subdirf3(optionfilefiname,"varmuptjgr",digitp),digit);
                   3813: 
                   3814:   free_vector(xp,1,npar);
                   3815:   free_matrix(doldm,1,nlstate,1,nlstate);
                   3816:   free_matrix(dnewm,1,nlstate,1,npar);
                   3817:   free_matrix(doldmp,nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);
                   3818:   free_matrix(dnewmp,nlstate+1,nlstate+ndeath,1,npar);
                   3819:   free_matrix(varppt,nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);
                   3820:   if (mobilav!=0) free_ma3x(mobaverage,1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
                   3821:   fclose(ficresprobmorprev);
                   3822:   fflush(ficgp);
                   3823:   fflush(fichtm); 
                   3824: }  /* end varevsij */
                   3825: 
                   3826: /************ Variance of prevlim ******************/
                   3827: 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[])
                   3828: {
                   3829:   /* Variance of prevalence limit */
                   3830:   /*  double **prevalim(double **prlim, int nlstate, double *xp, double age, double **oldm, double **savm,double ftolpl);*/
1.164     brouard  3831: 
1.126     brouard  3832:   double **dnewm,**doldm;
                   3833:   int i, j, nhstepm, hstepm;
                   3834:   double *xp;
                   3835:   double *gp, *gm;
                   3836:   double **gradg, **trgradg;
                   3837:   double age,agelim;
                   3838:   int theta;
                   3839:   
                   3840:   pstamp(ficresvpl);
                   3841:   fprintf(ficresvpl,"# Standard deviation of period (stable) prevalences \n");
                   3842:   fprintf(ficresvpl,"# Age");
                   3843:   for(i=1; i<=nlstate;i++)
                   3844:       fprintf(ficresvpl," %1d-%1d",i,i);
                   3845:   fprintf(ficresvpl,"\n");
                   3846: 
                   3847:   xp=vector(1,npar);
                   3848:   dnewm=matrix(1,nlstate,1,npar);
                   3849:   doldm=matrix(1,nlstate,1,nlstate);
                   3850:   
                   3851:   hstepm=1*YEARM; /* Every year of age */
                   3852:   hstepm=hstepm/stepm; /* Typically in stepm units, if j= 2 years, = 2/6 months = 4 */ 
                   3853:   agelim = AGESUP;
                   3854:   for (age=bage; age<=fage; age ++){ /* If stepm=6 months */
                   3855:     nhstepm=(int) rint((agelim-age)*YEARM/stepm); /* Typically 20 years = 20*12/6=40 */ 
                   3856:     if (stepm >= YEARM) hstepm=1;
                   3857:     nhstepm = nhstepm/hstepm; /* Typically 40/4=10 */
                   3858:     gradg=matrix(1,npar,1,nlstate);
                   3859:     gp=vector(1,nlstate);
                   3860:     gm=vector(1,nlstate);
                   3861: 
                   3862:     for(theta=1; theta <=npar; theta++){
                   3863:       for(i=1; i<=npar; i++){ /* Computes gradient */
                   3864:        xp[i] = x[i] + (i==theta ?delti[theta]:0);
                   3865:       }
                   3866:       prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ij);
                   3867:       for(i=1;i<=nlstate;i++)
                   3868:        gp[i] = prlim[i][i];
                   3869:     
                   3870:       for(i=1; i<=npar; i++) /* Computes gradient */
                   3871:        xp[i] = x[i] - (i==theta ?delti[theta]:0);
                   3872:       prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ij);
                   3873:       for(i=1;i<=nlstate;i++)
                   3874:        gm[i] = prlim[i][i];
                   3875: 
                   3876:       for(i=1;i<=nlstate;i++)
                   3877:        gradg[theta][i]= (gp[i]-gm[i])/2./delti[theta];
                   3878:     } /* End theta */
                   3879: 
                   3880:     trgradg =matrix(1,nlstate,1,npar);
                   3881: 
                   3882:     for(j=1; j<=nlstate;j++)
                   3883:       for(theta=1; theta <=npar; theta++)
                   3884:        trgradg[j][theta]=gradg[theta][j];
                   3885: 
                   3886:     for(i=1;i<=nlstate;i++)
                   3887:       varpl[i][(int)age] =0.;
                   3888:     matprod2(dnewm,trgradg,1,nlstate,1,npar,1,npar,matcov);
                   3889:     matprod2(doldm,dnewm,1,nlstate,1,npar,1,nlstate,gradg);
                   3890:     for(i=1;i<=nlstate;i++)
                   3891:       varpl[i][(int)age] = doldm[i][i]; /* Covariances are useless */
                   3892: 
                   3893:     fprintf(ficresvpl,"%.0f ",age );
                   3894:     for(i=1; i<=nlstate;i++)
                   3895:       fprintf(ficresvpl," %.5f (%.5f)",prlim[i][i],sqrt(varpl[i][(int)age]));
                   3896:     fprintf(ficresvpl,"\n");
                   3897:     free_vector(gp,1,nlstate);
                   3898:     free_vector(gm,1,nlstate);
                   3899:     free_matrix(gradg,1,npar,1,nlstate);
                   3900:     free_matrix(trgradg,1,nlstate,1,npar);
                   3901:   } /* End age */
                   3902: 
                   3903:   free_vector(xp,1,npar);
                   3904:   free_matrix(doldm,1,nlstate,1,npar);
                   3905:   free_matrix(dnewm,1,nlstate,1,nlstate);
                   3906: 
                   3907: }
                   3908: 
                   3909: /************ Variance of one-step probabilities  ******************/
                   3910: 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[])
                   3911: {
1.164     brouard  3912:   int i, j=0,  k1, l1, tj;
1.126     brouard  3913:   int k2, l2, j1,  z1;
1.164     brouard  3914:   int k=0, l;
1.145     brouard  3915:   int first=1, first1, first2;
1.126     brouard  3916:   double cv12, mu1, mu2, lc1, lc2, v12, v21, v11, v22,v1,v2, c12, tnalp;
                   3917:   double **dnewm,**doldm;
                   3918:   double *xp;
                   3919:   double *gp, *gm;
                   3920:   double **gradg, **trgradg;
                   3921:   double **mu;
1.164     brouard  3922:   double age, cov[NCOVMAX+1];
1.126     brouard  3923:   double std=2.0; /* Number of standard deviation wide of confidence ellipsoids */
                   3924:   int theta;
                   3925:   char fileresprob[FILENAMELENGTH];
                   3926:   char fileresprobcov[FILENAMELENGTH];
                   3927:   char fileresprobcor[FILENAMELENGTH];
                   3928:   double ***varpij;
                   3929: 
                   3930:   strcpy(fileresprob,"prob"); 
                   3931:   strcat(fileresprob,fileres);
                   3932:   if((ficresprob=fopen(fileresprob,"w"))==NULL) {
                   3933:     printf("Problem with resultfile: %s\n", fileresprob);
                   3934:     fprintf(ficlog,"Problem with resultfile: %s\n", fileresprob);
                   3935:   }
                   3936:   strcpy(fileresprobcov,"probcov"); 
                   3937:   strcat(fileresprobcov,fileres);
                   3938:   if((ficresprobcov=fopen(fileresprobcov,"w"))==NULL) {
                   3939:     printf("Problem with resultfile: %s\n", fileresprobcov);
                   3940:     fprintf(ficlog,"Problem with resultfile: %s\n", fileresprobcov);
                   3941:   }
                   3942:   strcpy(fileresprobcor,"probcor"); 
                   3943:   strcat(fileresprobcor,fileres);
                   3944:   if((ficresprobcor=fopen(fileresprobcor,"w"))==NULL) {
                   3945:     printf("Problem with resultfile: %s\n", fileresprobcor);
                   3946:     fprintf(ficlog,"Problem with resultfile: %s\n", fileresprobcor);
                   3947:   }
                   3948:   printf("Computing standard deviation of one-step probabilities: result on file '%s' \n",fileresprob);
                   3949:   fprintf(ficlog,"Computing standard deviation of one-step probabilities: result on file '%s' \n",fileresprob);
                   3950:   printf("Computing matrix of variance covariance of one-step probabilities: result on file '%s' \n",fileresprobcov);
                   3951:   fprintf(ficlog,"Computing matrix of variance covariance of one-step probabilities: result on file '%s' \n",fileresprobcov);
                   3952:   printf("and correlation matrix of one-step probabilities: result on file '%s' \n",fileresprobcor);
                   3953:   fprintf(ficlog,"and correlation matrix of one-step probabilities: result on file '%s' \n",fileresprobcor);
                   3954:   pstamp(ficresprob);
                   3955:   fprintf(ficresprob,"#One-step probabilities and stand. devi in ()\n");
                   3956:   fprintf(ficresprob,"# Age");
                   3957:   pstamp(ficresprobcov);
                   3958:   fprintf(ficresprobcov,"#One-step probabilities and covariance matrix\n");
                   3959:   fprintf(ficresprobcov,"# Age");
                   3960:   pstamp(ficresprobcor);
                   3961:   fprintf(ficresprobcor,"#One-step probabilities and correlation matrix\n");
                   3962:   fprintf(ficresprobcor,"# Age");
                   3963: 
                   3964: 
                   3965:   for(i=1; i<=nlstate;i++)
                   3966:     for(j=1; j<=(nlstate+ndeath);j++){
                   3967:       fprintf(ficresprob," p%1d-%1d (SE)",i,j);
                   3968:       fprintf(ficresprobcov," p%1d-%1d ",i,j);
                   3969:       fprintf(ficresprobcor," p%1d-%1d ",i,j);
                   3970:     }  
                   3971:  /* fprintf(ficresprob,"\n");
                   3972:   fprintf(ficresprobcov,"\n");
                   3973:   fprintf(ficresprobcor,"\n");
                   3974:  */
1.131     brouard  3975:   xp=vector(1,npar);
1.126     brouard  3976:   dnewm=matrix(1,(nlstate)*(nlstate+ndeath),1,npar);
                   3977:   doldm=matrix(1,(nlstate)*(nlstate+ndeath),1,(nlstate)*(nlstate+ndeath));
                   3978:   mu=matrix(1,(nlstate)*(nlstate+ndeath), (int) bage, (int)fage);
                   3979:   varpij=ma3x(1,nlstate*(nlstate+ndeath),1,nlstate*(nlstate+ndeath),(int) bage, (int) fage);
                   3980:   first=1;
                   3981:   fprintf(ficgp,"\n# Routine varprob");
                   3982:   fprintf(fichtm,"\n<li><h4> Computing and drawing one step probabilities with their confidence intervals</h4></li>\n");
                   3983:   fprintf(fichtm,"\n");
                   3984: 
                   3985:   fprintf(fichtm,"\n<li><h4> <a href=\"%s\">Matrix of variance-covariance of pairs of step probabilities (drawings)</a></h4></li>\n",optionfilehtmcov);
                   3986:   fprintf(fichtmcov,"\n<h4>Matrix of variance-covariance of pairs of step probabilities</h4>\n\
                   3987:   file %s<br>\n",optionfilehtmcov);
                   3988:   fprintf(fichtmcov,"\nEllipsoids of confidence centered on point (p<inf>ij</inf>, p<inf>kl</inf>) are estimated\
                   3989: and drawn. It helps understanding how is the covariance between two incidences.\
                   3990:  They are expressed in year<sup>-1</sup> in order to be less dependent of stepm.<br>\n");
                   3991:   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. \
                   3992: It can be understood this way: if pij and pkl where uncorrelated the (2x2) matrix of covariance \
                   3993: would have been (1/(var pij), 0 , 0, 1/(var pkl)), and the confidence interval would be 2 \
                   3994: standard deviations wide on each axis. <br>\
                   3995:  Now, if both incidences are correlated (usual case) we diagonalised the inverse of the covariance matrix\
                   3996:  and made the appropriate rotation to look at the uncorrelated principal directions.<br>\
                   3997: To be simple, these graphs help to understand the significativity of each parameter in relation to a second other one.<br> \n");
                   3998: 
                   3999:   cov[1]=1;
1.145     brouard  4000:   /* tj=cptcoveff; */
                   4001:   tj = (int) pow(2,cptcoveff);
1.126     brouard  4002:   if (cptcovn<1) {tj=1;ncodemax[1]=1;}
                   4003:   j1=0;
1.145     brouard  4004:   for(j1=1; j1<=tj;j1++){
                   4005:     /*for(i1=1; i1<=ncodemax[t];i1++){ */
                   4006:     /*j1++;*/
1.126     brouard  4007:       if  (cptcovn>0) {
                   4008:        fprintf(ficresprob, "\n#********** Variable "); 
                   4009:        for (z1=1; z1<=cptcoveff; z1++) fprintf(ficresprob, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtab[j1][z1]]);
                   4010:        fprintf(ficresprob, "**********\n#\n");
                   4011:        fprintf(ficresprobcov, "\n#********** Variable "); 
                   4012:        for (z1=1; z1<=cptcoveff; z1++) fprintf(ficresprobcov, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtab[j1][z1]]);
                   4013:        fprintf(ficresprobcov, "**********\n#\n");
                   4014:        
                   4015:        fprintf(ficgp, "\n#********** Variable "); 
                   4016:        for (z1=1; z1<=cptcoveff; z1++) fprintf(ficgp, " V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtab[j1][z1]]);
                   4017:        fprintf(ficgp, "**********\n#\n");
                   4018:        
                   4019:        
                   4020:        fprintf(fichtmcov, "\n<hr  size=\"2\" color=\"#EC5E5E\">********** Variable "); 
                   4021:        for (z1=1; z1<=cptcoveff; z1++) fprintf(fichtm, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtab[j1][z1]]);
                   4022:        fprintf(fichtmcov, "**********\n<hr size=\"2\" color=\"#EC5E5E\">");
                   4023:        
                   4024:        fprintf(ficresprobcor, "\n#********** Variable ");    
                   4025:        for (z1=1; z1<=cptcoveff; z1++) fprintf(ficresprobcor, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtab[j1][z1]]);
                   4026:        fprintf(ficresprobcor, "**********\n#");    
                   4027:       }
                   4028:       
1.145     brouard  4029:       gradg=matrix(1,npar,1,(nlstate)*(nlstate+ndeath));
                   4030:       trgradg=matrix(1,(nlstate)*(nlstate+ndeath),1,npar);
                   4031:       gp=vector(1,(nlstate)*(nlstate+ndeath));
                   4032:       gm=vector(1,(nlstate)*(nlstate+ndeath));
1.126     brouard  4033:       for (age=bage; age<=fage; age ++){ 
                   4034:        cov[2]=age;
                   4035:        for (k=1; k<=cptcovn;k++) {
1.145     brouard  4036:          cov[2+k]=nbcode[Tvar[k]][codtab[j1][Tvar[k]]];/* j1 1 2 3 4
                   4037:                                                         * 1  1 1 1 1
                   4038:                                                         * 2  2 1 1 1
                   4039:                                                         * 3  1 2 1 1
                   4040:                                                         */
                   4041:          /* nbcode[1][1]=0 nbcode[1][2]=1;*/
1.126     brouard  4042:        }
1.186   ! brouard  4043:        /* for (k=1; k<=cptcovage;k++) cov[2+Tage[k]]=cov[2+Tage[k]]*cov[2]; */
        !          4044:        for (k=1; k<=cptcovage;k++) cov[2+Tage[k]]=nbcode[Tvar[Tage[k]]][codtab[ij][Tvar[Tage[k]]]]*cov[2];
1.126     brouard  4045:        for (k=1; k<=cptcovprod;k++)
                   4046:          cov[2+Tprod[k]]=nbcode[Tvard[k][1]][codtab[ij][Tvard[k][1]]]*nbcode[Tvard[k][2]][codtab[ij][Tvard[k][2]]];
                   4047:        
                   4048:     
                   4049:        for(theta=1; theta <=npar; theta++){
                   4050:          for(i=1; i<=npar; i++)
                   4051:            xp[i] = x[i] + (i==theta ?delti[theta]:(double)0);
                   4052:          
                   4053:          pmij(pmmij,cov,ncovmodel,xp,nlstate);
                   4054:          
                   4055:          k=0;
                   4056:          for(i=1; i<= (nlstate); i++){
                   4057:            for(j=1; j<=(nlstate+ndeath);j++){
                   4058:              k=k+1;
                   4059:              gp[k]=pmmij[i][j];
                   4060:            }
                   4061:          }
                   4062:          
                   4063:          for(i=1; i<=npar; i++)
                   4064:            xp[i] = x[i] - (i==theta ?delti[theta]:(double)0);
                   4065:     
                   4066:          pmij(pmmij,cov,ncovmodel,xp,nlstate);
                   4067:          k=0;
                   4068:          for(i=1; i<=(nlstate); i++){
                   4069:            for(j=1; j<=(nlstate+ndeath);j++){
                   4070:              k=k+1;
                   4071:              gm[k]=pmmij[i][j];
                   4072:            }
                   4073:          }
                   4074:      
                   4075:          for(i=1; i<= (nlstate)*(nlstate+ndeath); i++) 
                   4076:            gradg[theta][i]=(gp[i]-gm[i])/(double)2./delti[theta];  
                   4077:        }
                   4078: 
                   4079:        for(j=1; j<=(nlstate)*(nlstate+ndeath);j++)
                   4080:          for(theta=1; theta <=npar; theta++)
                   4081:            trgradg[j][theta]=gradg[theta][j];
                   4082:        
                   4083:        matprod2(dnewm,trgradg,1,(nlstate)*(nlstate+ndeath),1,npar,1,npar,matcov); 
                   4084:        matprod2(doldm,dnewm,1,(nlstate)*(nlstate+ndeath),1,npar,1,(nlstate)*(nlstate+ndeath),gradg);
                   4085: 
                   4086:        pmij(pmmij,cov,ncovmodel,x,nlstate);
                   4087:        
                   4088:        k=0;
                   4089:        for(i=1; i<=(nlstate); i++){
                   4090:          for(j=1; j<=(nlstate+ndeath);j++){
                   4091:            k=k+1;
                   4092:            mu[k][(int) age]=pmmij[i][j];
                   4093:          }
                   4094:        }
                   4095:        for(i=1;i<=(nlstate)*(nlstate+ndeath);i++)
                   4096:          for(j=1;j<=(nlstate)*(nlstate+ndeath);j++)
                   4097:            varpij[i][j][(int)age] = doldm[i][j];
                   4098: 
                   4099:        /*printf("\n%d ",(int)age);
                   4100:          for (i=1; i<=(nlstate)*(nlstate+ndeath);i++){
                   4101:          printf("%e [%e ;%e] ",gm[i],gm[i]-2*sqrt(doldm[i][i]),gm[i]+2*sqrt(doldm[i][i]));
                   4102:          fprintf(ficlog,"%e [%e ;%e] ",gm[i],gm[i]-2*sqrt(doldm[i][i]),gm[i]+2*sqrt(doldm[i][i]));
                   4103:          }*/
                   4104: 
                   4105:        fprintf(ficresprob,"\n%d ",(int)age);
                   4106:        fprintf(ficresprobcov,"\n%d ",(int)age);
                   4107:        fprintf(ficresprobcor,"\n%d ",(int)age);
                   4108: 
                   4109:        for (i=1; i<=(nlstate)*(nlstate+ndeath);i++)
                   4110:          fprintf(ficresprob,"%11.3e (%11.3e) ",mu[i][(int) age],sqrt(varpij[i][i][(int)age]));
                   4111:        for (i=1; i<=(nlstate)*(nlstate+ndeath);i++){
                   4112:          fprintf(ficresprobcov,"%11.3e ",mu[i][(int) age]);
                   4113:          fprintf(ficresprobcor,"%11.3e ",mu[i][(int) age]);
                   4114:        }
                   4115:        i=0;
                   4116:        for (k=1; k<=(nlstate);k++){
                   4117:          for (l=1; l<=(nlstate+ndeath);l++){ 
1.145     brouard  4118:            i++;
1.126     brouard  4119:            fprintf(ficresprobcov,"\n%d %d-%d",(int)age,k,l);
                   4120:            fprintf(ficresprobcor,"\n%d %d-%d",(int)age,k,l);
                   4121:            for (j=1; j<=i;j++){
1.145     brouard  4122:              /* printf(" k=%d l=%d i=%d j=%d\n",k,l,i,j);fflush(stdout); */
1.126     brouard  4123:              fprintf(ficresprobcov," %11.3e",varpij[i][j][(int)age]);
                   4124:              fprintf(ficresprobcor," %11.3e",varpij[i][j][(int) age]/sqrt(varpij[i][i][(int) age])/sqrt(varpij[j][j][(int)age]));
                   4125:            }
                   4126:          }
                   4127:        }/* end of loop for state */
                   4128:       } /* end of loop for age */
1.145     brouard  4129:       free_vector(gp,1,(nlstate+ndeath)*(nlstate+ndeath));
                   4130:       free_vector(gm,1,(nlstate+ndeath)*(nlstate+ndeath));
                   4131:       free_matrix(trgradg,1,(nlstate+ndeath)*(nlstate+ndeath),1,npar);
                   4132:       free_matrix(gradg,1,(nlstate+ndeath)*(nlstate+ndeath),1,npar);
                   4133:       
1.126     brouard  4134:       /* Confidence intervalle of pij  */
                   4135:       /*
1.131     brouard  4136:        fprintf(ficgp,"\nunset parametric;unset label");
1.126     brouard  4137:        fprintf(ficgp,"\nset log y;unset log x; set xlabel \"Age\";set ylabel \"probability (year-1)\"");
                   4138:        fprintf(ficgp,"\nset ter png small\nset size 0.65,0.65");
                   4139:        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);
                   4140:        fprintf(fichtm,"\n<br><img src=\"pijgr%s.png\"> ",optionfilefiname);
                   4141:        fprintf(ficgp,"\nset out \"pijgr%s.png\"",optionfilefiname);
                   4142:        fprintf(ficgp,"\nplot \"%s\" every :::%d::%d u 1:2 \"\%%lf",k1,k2,xfilevarprob);
                   4143:       */
                   4144: 
                   4145:       /* Drawing ellipsoids of confidence of two variables p(k1-l1,k2-l2)*/
1.145     brouard  4146:       first1=1;first2=2;
1.126     brouard  4147:       for (k2=1; k2<=(nlstate);k2++){
                   4148:        for (l2=1; l2<=(nlstate+ndeath);l2++){ 
                   4149:          if(l2==k2) continue;
                   4150:          j=(k2-1)*(nlstate+ndeath)+l2;
                   4151:          for (k1=1; k1<=(nlstate);k1++){
                   4152:            for (l1=1; l1<=(nlstate+ndeath);l1++){ 
                   4153:              if(l1==k1) continue;
                   4154:              i=(k1-1)*(nlstate+ndeath)+l1;
                   4155:              if(i<=j) continue;
                   4156:              for (age=bage; age<=fage; age ++){ 
                   4157:                if ((int)age %5==0){
                   4158:                  v1=varpij[i][i][(int)age]/stepm*YEARM/stepm*YEARM;
                   4159:                  v2=varpij[j][j][(int)age]/stepm*YEARM/stepm*YEARM;
                   4160:                  cv12=varpij[i][j][(int)age]/stepm*YEARM/stepm*YEARM;
                   4161:                  mu1=mu[i][(int) age]/stepm*YEARM ;
                   4162:                  mu2=mu[j][(int) age]/stepm*YEARM;
                   4163:                  c12=cv12/sqrt(v1*v2);
                   4164:                  /* Computing eigen value of matrix of covariance */
                   4165:                  lc1=((v1+v2)+sqrt((v1+v2)*(v1+v2) - 4*(v1*v2-cv12*cv12)))/2.;
                   4166:                  lc2=((v1+v2)-sqrt((v1+v2)*(v1+v2) - 4*(v1*v2-cv12*cv12)))/2.;
1.135     brouard  4167:                  if ((lc2 <0) || (lc1 <0) ){
1.145     brouard  4168:                    if(first2==1){
                   4169:                      first1=0;
                   4170:                    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);
                   4171:                    }
                   4172:                    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);
                   4173:                    /* lc1=fabs(lc1); */ /* If we want to have them positive */
                   4174:                    /* lc2=fabs(lc2); */
1.135     brouard  4175:                  }
                   4176: 
1.126     brouard  4177:                  /* Eigen vectors */
                   4178:                  v11=(1./sqrt(1+(v1-lc1)*(v1-lc1)/cv12/cv12));
                   4179:                  /*v21=sqrt(1.-v11*v11); *//* error */
                   4180:                  v21=(lc1-v1)/cv12*v11;
                   4181:                  v12=-v21;
                   4182:                  v22=v11;
                   4183:                  tnalp=v21/v11;
                   4184:                  if(first1==1){
                   4185:                    first1=0;
                   4186:                    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);
                   4187:                  }
                   4188:                  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);
                   4189:                  /*printf(fignu*/
                   4190:                  /* mu1+ v11*lc1*cost + v12*lc2*sin(t) */
                   4191:                  /* mu2+ v21*lc1*cost + v22*lc2*sin(t) */
                   4192:                  if(first==1){
                   4193:                    first=0;
                   4194:                    fprintf(ficgp,"\nset parametric;unset label");
                   4195:                    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  4196:                    fprintf(ficgp,"\nset ter png small size 320, 240");
1.126     brouard  4197:                    fprintf(fichtmcov,"\n<br>Ellipsoids of confidence cov(p%1d%1d,p%1d%1d) expressed in year<sup>-1</sup>\
                   4198:  :<a href=\"%s%d%1d%1d-%1d%1d.png\">\
                   4199: %s%d%1d%1d-%1d%1d.png</A>, ",k1,l1,k2,l2,\
                   4200:                            subdirf2(optionfilefiname,"varpijgr"), j1,k1,l1,k2,l2,\
                   4201:                            subdirf2(optionfilefiname,"varpijgr"), j1,k1,l1,k2,l2);
                   4202:                    fprintf(fichtmcov,"\n<br><img src=\"%s%d%1d%1d-%1d%1d.png\"> ",subdirf2(optionfilefiname,"varpijgr"), j1,k1,l1,k2,l2);
                   4203:                    fprintf(fichtmcov,"\n<br> Correlation at age %d (%.3f),",(int) age, c12);
                   4204:                    fprintf(ficgp,"\nset out \"%s%d%1d%1d-%1d%1d.png\"",subdirf2(optionfilefiname,"varpijgr"), j1,k1,l1,k2,l2);
                   4205:                    fprintf(ficgp,"\nset label \"%d\" at %11.3e,%11.3e center",(int) age, mu1,mu2);
                   4206:                    fprintf(ficgp,"\n# Age %d, p%1d%1d - p%1d%1d",(int) age, k1,l1,k2,l2);
                   4207:                    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",\
                   4208:                            mu1,std,v11,sqrt(lc1),v12,sqrt(lc2),\
                   4209:                            mu2,std,v21,sqrt(lc1),v22,sqrt(lc2));
                   4210:                  }else{
                   4211:                    first=0;
                   4212:                    fprintf(fichtmcov," %d (%.3f),",(int) age, c12);
                   4213:                    fprintf(ficgp,"\n# Age %d, p%1d%1d - p%1d%1d",(int) age, k1,l1,k2,l2);
                   4214:                    fprintf(ficgp,"\nset label \"%d\" at %11.3e,%11.3e center",(int) age, mu1,mu2);
                   4215:                    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",\
                   4216:                            mu1,std,v11,sqrt(lc1),v12,sqrt(lc2),\
                   4217:                            mu2,std,v21,sqrt(lc1),v22,sqrt(lc2));
                   4218:                  }/* if first */
                   4219:                } /* age mod 5 */
                   4220:              } /* end loop age */
                   4221:              fprintf(ficgp,"\nset out \"%s%d%1d%1d-%1d%1d.png\";replot;",subdirf2(optionfilefiname,"varpijgr"), j1,k1,l1,k2,l2);
                   4222:              first=1;
                   4223:            } /*l12 */
                   4224:          } /* k12 */
                   4225:        } /*l1 */
                   4226:       }/* k1 */
1.169     brouard  4227:       /* } */ /* loop covariates */
1.126     brouard  4228:   }
                   4229:   free_ma3x(varpij,1,nlstate,1,nlstate+ndeath,(int) bage, (int)fage);
                   4230:   free_matrix(mu,1,(nlstate+ndeath)*(nlstate+ndeath),(int) bage, (int)fage);
                   4231:   free_matrix(doldm,1,(nlstate)*(nlstate+ndeath),1,(nlstate)*(nlstate+ndeath));
                   4232:   free_matrix(dnewm,1,(nlstate)*(nlstate+ndeath),1,npar);
                   4233:   free_vector(xp,1,npar);
                   4234:   fclose(ficresprob);
                   4235:   fclose(ficresprobcov);
                   4236:   fclose(ficresprobcor);
                   4237:   fflush(ficgp);
                   4238:   fflush(fichtmcov);
                   4239: }
                   4240: 
                   4241: 
                   4242: /******************* Printing html file ***********/
                   4243: void printinghtml(char fileres[], char title[], char datafile[], int firstpass, \
                   4244:                  int lastpass, int stepm, int weightopt, char model[],\
                   4245:                  int imx,int jmin, int jmax, double jmeanint,char rfileres[],\
                   4246:                  int popforecast, int estepm ,\
                   4247:                  double jprev1, double mprev1,double anprev1, \
                   4248:                  double jprev2, double mprev2,double anprev2){
                   4249:   int jj1, k1, i1, cpt;
                   4250: 
                   4251:    fprintf(fichtm,"<ul><li><a href='#firstorder'>Result files (first order: no variance)</a>\n \
                   4252:    <li><a href='#secondorder'>Result files (second order (variance)</a>\n \
                   4253: </ul>");
                   4254:    fprintf(fichtm,"<ul><li><h4><a name='firstorder'>Result files (first order: no variance)</a></h4>\n \
                   4255:  - Observed prevalence in each state (during the period defined between %.lf/%.lf/%.lf and %.lf/%.lf/%.lf): <a href=\"%s\">%s</a> <br>\n ",
                   4256:           jprev1, mprev1,anprev1,jprev2, mprev2,anprev2,subdirf2(fileres,"p"),subdirf2(fileres,"p"));
                   4257:    fprintf(fichtm,"\
                   4258:  - Estimated transition probabilities over %d (stepm) months: <a href=\"%s\">%s</a><br>\n ",
                   4259:           stepm,subdirf2(fileres,"pij"),subdirf2(fileres,"pij"));
                   4260:    fprintf(fichtm,"\
                   4261:  - Period (stable) prevalence in each health state: <a href=\"%s\">%s</a> <br>\n",
                   4262:           subdirf2(fileres,"pl"),subdirf2(fileres,"pl"));
                   4263:    fprintf(fichtm,"\
1.128     brouard  4264:  - (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  4265:    <a href=\"%s\">%s</a> <br>\n",
                   4266:           estepm,subdirf2(fileres,"e"),subdirf2(fileres,"e"));
                   4267:    fprintf(fichtm,"\
                   4268:  - Population projections by age and states: \
                   4269:    <a href=\"%s\">%s</a> <br>\n</li>", subdirf2(fileres,"f"),subdirf2(fileres,"f"));
                   4270: 
                   4271: fprintf(fichtm," \n<ul><li><b>Graphs</b></li><p>");
                   4272: 
1.145     brouard  4273:  m=pow(2,cptcoveff);
1.126     brouard  4274:  if (cptcovn < 1) {m=1;ncodemax[1]=1;}
                   4275: 
                   4276:  jj1=0;
                   4277:  for(k1=1; k1<=m;k1++){
                   4278:    for(i1=1; i1<=ncodemax[k1];i1++){
                   4279:      jj1++;
                   4280:      if (cptcovn > 0) {
                   4281:        fprintf(fichtm,"<hr  size=\"2\" color=\"#EC5E5E\">************ Results for covariates");
                   4282:        for (cpt=1; cpt<=cptcoveff;cpt++) 
                   4283:         fprintf(fichtm," V%d=%d ",Tvaraff[cpt],nbcode[Tvaraff[cpt]][codtab[jj1][cpt]]);
                   4284:        fprintf(fichtm," ************\n<hr size=\"2\" color=\"#EC5E5E\">");
                   4285:      }
                   4286:      /* Pij */
1.145     brouard  4287:      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> \
                   4288: <img src=\"%s%d_1.png\">",stepm,subdirf2(optionfilefiname,"pe"),jj1,subdirf2(optionfilefiname,"pe"),jj1,subdirf2(optionfilefiname,"pe"),jj1);     
1.126     brouard  4289:      /* Quasi-incidences */
                   4290:      fprintf(fichtm,"<br>- Pij or Conditional probabilities to be observed in state j being in state i %d (stepm) months\
1.145     brouard  4291:  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> \
                   4292: <img src=\"%s%d_2.png\">",stepm,subdirf2(optionfilefiname,"pe"),jj1,subdirf2(optionfilefiname,"pe"),jj1,subdirf2(optionfilefiname,"pe"),jj1); 
1.126     brouard  4293:        /* Period (stable) prevalence in each health state */
1.154     brouard  4294:        for(cpt=1; cpt<=nlstate;cpt++){
1.166     brouard  4295:         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> \
                   4296: <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  4297:        }
                   4298:      for(cpt=1; cpt<=nlstate;cpt++) {
1.154     brouard  4299:         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> \
                   4300: <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  4301:      }
                   4302:    } /* end i1 */
                   4303:  }/* End k1 */
                   4304:  fprintf(fichtm,"</ul>");
                   4305: 
                   4306: 
                   4307:  fprintf(fichtm,"\
                   4308: \n<br><li><h4> <a name='secondorder'>Result files (second order: variances)</a></h4>\n\
                   4309:  - Parameter file with estimated parameters and covariance matrix: <a href=\"%s\">%s</a> <br>\n", rfileres,rfileres);
                   4310: 
                   4311:  fprintf(fichtm," - Variance of one-step probabilities: <a href=\"%s\">%s</a> <br>\n",
                   4312:         subdirf2(fileres,"prob"),subdirf2(fileres,"prob"));
                   4313:  fprintf(fichtm,"\
                   4314:  - Variance-covariance of one-step probabilities: <a href=\"%s\">%s</a> <br>\n",
                   4315:         subdirf2(fileres,"probcov"),subdirf2(fileres,"probcov"));
                   4316: 
                   4317:  fprintf(fichtm,"\
                   4318:  - Correlation matrix of one-step probabilities: <a href=\"%s\">%s</a> <br>\n",
                   4319:         subdirf2(fileres,"probcor"),subdirf2(fileres,"probcor"));
                   4320:  fprintf(fichtm,"\
                   4321:  - 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): \
                   4322:    <a href=\"%s\">%s</a> <br>\n</li>",
                   4323:           estepm,subdirf2(fileres,"cve"),subdirf2(fileres,"cve"));
                   4324:  fprintf(fichtm,"\
                   4325:  - (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): \
                   4326:    <a href=\"%s\">%s</a> <br>\n</li>",
                   4327:           estepm,subdirf2(fileres,"stde"),subdirf2(fileres,"stde"));
                   4328:  fprintf(fichtm,"\
1.128     brouard  4329:  - 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  4330:         estepm, subdirf2(fileres,"v"),subdirf2(fileres,"v"));
                   4331:  fprintf(fichtm,"\
1.128     brouard  4332:  - 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",
                   4333:         estepm, subdirf2(fileres,"t"),subdirf2(fileres,"t"));
1.126     brouard  4334:  fprintf(fichtm,"\
                   4335:  - Standard deviation of period (stable) prevalences: <a href=\"%s\">%s</a> <br>\n",\
                   4336:         subdirf2(fileres,"vpl"),subdirf2(fileres,"vpl"));
                   4337: 
                   4338: /*  if(popforecast==1) fprintf(fichtm,"\n */
                   4339: /*  - Prevalences forecasting: <a href=\"f%s\">f%s</a> <br>\n */
                   4340: /*  - Population forecasting (if popforecast=1): <a href=\"pop%s\">pop%s</a> <br>\n */
                   4341: /*     <br>",fileres,fileres,fileres,fileres); */
                   4342: /*  else  */
                   4343: /*    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); */
                   4344:  fflush(fichtm);
                   4345:  fprintf(fichtm," <ul><li><b>Graphs</b></li><p>");
                   4346: 
1.145     brouard  4347:  m=pow(2,cptcoveff);
1.126     brouard  4348:  if (cptcovn < 1) {m=1;ncodemax[1]=1;}
                   4349: 
                   4350:  jj1=0;
                   4351:  for(k1=1; k1<=m;k1++){
                   4352:    for(i1=1; i1<=ncodemax[k1];i1++){
                   4353:      jj1++;
                   4354:      if (cptcovn > 0) {
                   4355:        fprintf(fichtm,"<hr  size=\"2\" color=\"#EC5E5E\">************ Results for covariates");
                   4356:        for (cpt=1; cpt<=cptcoveff;cpt++) 
                   4357:         fprintf(fichtm," V%d=%d ",Tvaraff[cpt],nbcode[Tvaraff[cpt]][codtab[jj1][cpt]]);
                   4358:        fprintf(fichtm," ************\n<hr size=\"2\" color=\"#EC5E5E\">");
                   4359:      }
                   4360:      for(cpt=1; cpt<=nlstate;cpt++) {
                   4361:        fprintf(fichtm,"<br>- Observed (cross-sectional) and period (incidence based) \
1.145     brouard  4362: prevalence (with 95%% confidence interval) in state (%d): %s%d_%d.png <br>\
                   4363: <img src=\"%s%d_%d.png\">",cpt,subdirf2(optionfilefiname,"v"),cpt,jj1,subdirf2(optionfilefiname,"v"),cpt,jj1);  
1.126     brouard  4364:      }
                   4365:      fprintf(fichtm,"\n<br>- Total life expectancy by age and \
1.128     brouard  4366: health expectancies in states (1) and (2). If popbased=1 the smooth (due to the model) \
                   4367: true period expectancies (those weighted with period prevalences are also\
                   4368:  drawn in addition to the population based expectancies computed using\
                   4369:  observed and cahotic prevalences: %s%d.png<br>\
1.126     brouard  4370: <img src=\"%s%d.png\">",subdirf2(optionfilefiname,"e"),jj1,subdirf2(optionfilefiname,"e"),jj1);
                   4371:    } /* end i1 */
                   4372:  }/* End k1 */
                   4373:  fprintf(fichtm,"</ul>");
                   4374:  fflush(fichtm);
                   4375: }
                   4376: 
                   4377: /******************* Gnuplot file **************/
                   4378: void printinggnuplot(char fileres[], char optionfilefiname[], double ageminpar, double agemaxpar, double fage , char pathc[], double p[]){
                   4379: 
                   4380:   char dirfileres[132],optfileres[132];
1.164     brouard  4381:   int cpt=0,k1=0,i=0,k=0,j=0,jk=0,k2=0,k3=0,ij=0,l=0;
1.130     brouard  4382:   int ng=0;
1.126     brouard  4383: /*   if((ficgp=fopen(optionfilegnuplot,"a"))==NULL) { */
                   4384: /*     printf("Problem with file %s",optionfilegnuplot); */
                   4385: /*     fprintf(ficlog,"Problem with file %s",optionfilegnuplot); */
                   4386: /*   } */
                   4387: 
                   4388:   /*#ifdef windows */
                   4389:   fprintf(ficgp,"cd \"%s\" \n",pathc);
                   4390:     /*#endif */
                   4391:   m=pow(2,cptcoveff);
                   4392: 
                   4393:   strcpy(dirfileres,optionfilefiname);
                   4394:   strcpy(optfileres,"vpl");
                   4395:  /* 1eme*/
1.153     brouard  4396:   fprintf(ficgp,"\n# 1st: Period (stable) prevalence with CI: 'vpl' files\n");
1.126     brouard  4397:   for (cpt=1; cpt<= nlstate ; cpt ++) {
1.145     brouard  4398:     for (k1=1; k1<= m ; k1 ++) { /* plot [100000000000000000000:-100000000000000000000] "mysbiaspar/vplrmysbiaspar.txt to check */
                   4399:      fprintf(ficgp,"\nset out \"%s%d_%d.png\" \n",subdirf2(optionfilefiname,"v"),cpt,k1);
                   4400:      fprintf(ficgp,"\n#set out \"v%s%d_%d.png\" \n",optionfilefiname,cpt,k1);
1.126     brouard  4401:      fprintf(ficgp,"set xlabel \"Age\" \n\
                   4402: set ylabel \"Probability\" \n\
1.145     brouard  4403: set ter png small size 320, 240\n\
1.170     brouard  4404: plot [%.f:%.f] \"%s\" every :::%d::%d u 1:2 \"%%lf",ageminpar,fage,subdirf2(fileres,"vpl"),k1-1,k1-1);
1.126     brouard  4405: 
                   4406:      for (i=1; i<= nlstate ; i ++) {
1.170     brouard  4407:        if (i==cpt) fprintf(ficgp," %%lf (%%lf)");
                   4408:        else        fprintf(ficgp," %%*lf (%%*lf)");
1.126     brouard  4409:      }
1.170     brouard  4410:      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  4411:      for (i=1; i<= nlstate ; i ++) {
1.170     brouard  4412:        if (i==cpt) fprintf(ficgp," %%lf (%%lf)");
                   4413:        else fprintf(ficgp," %%*lf (%%*lf)");
1.126     brouard  4414:      } 
1.170     brouard  4415:      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  4416:      for (i=1; i<= nlstate ; i ++) {
1.170     brouard  4417:        if (i==cpt) fprintf(ficgp," %%lf (%%lf)");
                   4418:        else fprintf(ficgp," %%*lf (%%*lf)");
1.126     brouard  4419:      }  
1.145     brouard  4420:      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  4421:    }
                   4422:   }
                   4423:   /*2 eme*/
1.153     brouard  4424:   fprintf(ficgp,"\n# 2nd: Total life expectancy with CI: 't' files\n");
1.126     brouard  4425:   for (k1=1; k1<= m ; k1 ++) { 
                   4426:     fprintf(ficgp,"\nset out \"%s%d.png\" \n",subdirf2(optionfilefiname,"e"),k1);
1.145     brouard  4427:     fprintf(ficgp,"set ylabel \"Years\" \nset ter png small size 320, 240\nplot [%.f:%.f] ",ageminpar,fage);
1.126     brouard  4428:     
                   4429:     for (i=1; i<= nlstate+1 ; i ++) {
                   4430:       k=2*i;
1.170     brouard  4431:       fprintf(ficgp,"\"%s\" every :::%d::%d u 1:2 \"%%lf",subdirf2(fileres,"t"),k1-1,k1-1);
1.126     brouard  4432:       for (j=1; j<= nlstate+1 ; j ++) {
1.170     brouard  4433:        if (j==i) fprintf(ficgp," %%lf (%%lf)");
                   4434:        else fprintf(ficgp," %%*lf (%%*lf)");
1.126     brouard  4435:       }   
                   4436:       if (i== 1) fprintf(ficgp,"\" t\"TLE\" w l ,");
                   4437:       else fprintf(ficgp,"\" t\"LE in state (%d)\" w l ,",i-1);
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:       fprintf(ficgp,"\" t\"\" w l lt 0,");
1.170     brouard  4444:       fprintf(ficgp,"\"%s\" every :::%d::%d u 1:($2+$3*2) \"%%lf",subdirf2(fileres,"t"),k1-1,k1-1);
1.126     brouard  4445:       for (j=1; j<= nlstate+1 ; j ++) {
1.170     brouard  4446:        if (j==i) fprintf(ficgp," %%lf (%%lf)");
                   4447:        else fprintf(ficgp," %%*lf (%%*lf)");
1.126     brouard  4448:       }   
1.145     brouard  4449:       if (i== (nlstate+1)) fprintf(ficgp,"\" t\"\" w l lt 0");
                   4450:       else fprintf(ficgp,"\" t\"\" w l lt 0,");
1.126     brouard  4451:     }
                   4452:   }
                   4453:   
                   4454:   /*3eme*/
                   4455:   
                   4456:   for (k1=1; k1<= m ; k1 ++) { 
                   4457:     for (cpt=1; cpt<= nlstate ; cpt ++) {
                   4458:       /*       k=2+nlstate*(2*cpt-2); */
                   4459:       k=2+(nlstate+1)*(cpt-1);
                   4460:       fprintf(ficgp,"\nset out \"%s%d%d.png\" \n",subdirf2(optionfilefiname,"exp"),cpt,k1);
1.145     brouard  4461:       fprintf(ficgp,"set ter png small size 320, 240\n\
1.126     brouard  4462: 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);
                   4463:       /*fprintf(ficgp,",\"e%s\" every :::%d::%d u 1:($%d-2*$%d) \"\%%lf ",fileres,k1-1,k1-1,k,k+1);
                   4464:        for (i=1; i<= nlstate*2 ; i ++) fprintf(ficgp,"\%%lf (\%%lf) ");
                   4465:        fprintf(ficgp,"\" t \"e%d1\" w l",cpt);
                   4466:        fprintf(ficgp,",\"e%s\" every :::%d::%d u 1:($%d+2*$%d) \"\%%lf ",fileres,k1-1,k1-1,k,k+1);
                   4467:        for (i=1; i<= nlstate*2 ; i ++) fprintf(ficgp,"\%%lf (\%%lf) ");
                   4468:        fprintf(ficgp,"\" t \"e%d1\" w l",cpt);
                   4469:        
                   4470:       */
                   4471:       for (i=1; i< nlstate ; i ++) {
                   4472:        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);
                   4473:        /*      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);*/
                   4474:        
                   4475:       } 
                   4476:       fprintf(ficgp," ,\"%s\" every :::%d::%d u 1:%d t \"e%d.\" w l",subdirf2(fileres,"e"),k1-1,k1-1,k+nlstate,cpt);
                   4477:     }
                   4478:   }
                   4479:   
                   4480:   /* CV preval stable (period) */
1.153     brouard  4481:   for (k1=1; k1<= m ; k1 ++) { /* For each multivariate if any */
                   4482:     for (cpt=1; cpt<=nlstate ; cpt ++) { /* For each life state */
1.126     brouard  4483:       k=3;
1.153     brouard  4484:       fprintf(ficgp,"\n#\n#\n#CV preval stable (period): 'pij' files, cov=%d state=%d",k1, cpt);
1.145     brouard  4485:       fprintf(ficgp,"\nset out \"%s%d_%d.png\" \n",subdirf2(optionfilefiname,"p"),cpt,k1);
1.126     brouard  4486:       fprintf(ficgp,"set xlabel \"Age\" \nset ylabel \"Probability\" \n\
1.145     brouard  4487: set ter png small size 320, 240\n\
1.126     brouard  4488: unset log y\n\
1.153     brouard  4489: plot [%.f:%.f]  ", ageminpar, agemaxpar);
                   4490:       for (i=1; i<= nlstate ; i ++){
                   4491:        if(i==1)
                   4492:          fprintf(ficgp,"\"%s\"",subdirf2(fileres,"pij"));
                   4493:        else
                   4494:          fprintf(ficgp,", '' ");
1.154     brouard  4495:        l=(nlstate+ndeath)*(i-1)+1;
                   4496:        fprintf(ficgp," u ($1==%d ? ($3):1/0):($%d/($%d",k1,k+l+(cpt-1),k+l);
1.153     brouard  4497:        for (j=1; j<= (nlstate-1) ; j ++)
                   4498:          fprintf(ficgp,"+$%d",k+l+j);
                   4499:        fprintf(ficgp,")) t \"prev(%d,%d)\" w l",i,cpt);
                   4500:       } /* nlstate */
                   4501:       fprintf(ficgp,"\n");
                   4502:     } /* end cpt state*/ 
                   4503:   } /* end covariate */  
1.126     brouard  4504:   
                   4505:   /* proba elementaires */
                   4506:   for(i=1,jk=1; i <=nlstate; i++){
                   4507:     for(k=1; k <=(nlstate+ndeath); k++){
                   4508:       if (k != i) {
                   4509:        for(j=1; j <=ncovmodel; j++){
                   4510:          fprintf(ficgp,"p%d=%f ",jk,p[jk]);
                   4511:          jk++; 
                   4512:          fprintf(ficgp,"\n");
                   4513:        }
                   4514:       }
                   4515:     }
                   4516:    }
1.145     brouard  4517:   /*goto avoid;*/
1.126     brouard  4518:    for(ng=1; ng<=2;ng++){ /* Number of graphics: first is probabilities second is incidence per year*/
                   4519:      for(jk=1; jk <=m; jk++) {
1.145     brouard  4520:        fprintf(ficgp,"\nset out \"%s%d_%d.png\" \n",subdirf2(optionfilefiname,"pe"),jk,ng); 
1.126     brouard  4521:        if (ng==2)
                   4522:         fprintf(ficgp,"\nset ylabel \"Quasi-incidence per year\"\n");
                   4523:        else
                   4524:         fprintf(ficgp,"\nset title \"Probability\"\n");
1.145     brouard  4525:        fprintf(ficgp,"\nset ter png small size 320, 240\nset log y\nplot  [%.f:%.f] ",ageminpar,agemaxpar);
1.126     brouard  4526:        i=1;
                   4527:        for(k2=1; k2<=nlstate; k2++) {
                   4528:         k3=i;
                   4529:         for(k=1; k<=(nlstate+ndeath); k++) {
                   4530:           if (k != k2){
                   4531:             if(ng==2)
                   4532:               fprintf(ficgp," %f*exp(p%d+p%d*x",YEARM/stepm,i,i+1);
                   4533:             else
                   4534:               fprintf(ficgp," exp(p%d+p%d*x",i,i+1);
1.141     brouard  4535:             ij=1;/* To be checked else nbcode[0][0] wrong */
1.126     brouard  4536:             for(j=3; j <=ncovmodel; j++) {
1.186   ! brouard  4537:               if(((j-2)==Tage[ij]) &&(ij <=cptcovage)) { /* Bug valgrind */
        !          4538:                 fprintf(ficgp,"+p%d*%d*x",i+j-1,nbcode[Tvar[j-2]][codtab[jk][Tvar[j-2]]]);
        !          4539:                 ij++;
        !          4540:               }
        !          4541:               else
1.126     brouard  4542:                 fprintf(ficgp,"+p%d*%d",i+j-1,nbcode[Tvar[j-2]][codtab[jk][j-2]]);
                   4543:             }
                   4544:             fprintf(ficgp,")/(1");
                   4545:             
                   4546:             for(k1=1; k1 <=nlstate; k1++){   
                   4547:               fprintf(ficgp,"+exp(p%d+p%d*x",k3+(k1-1)*ncovmodel,k3+(k1-1)*ncovmodel+1);
                   4548:               ij=1;
                   4549:               for(j=3; j <=ncovmodel; j++){
1.186   ! brouard  4550:                 if(((j-2)==Tage[ij]) &&(ij <=cptcovage)) {
        !          4551:                   fprintf(ficgp,"+p%d*%d*x",k3+(k1-1)*ncovmodel+1+j-2,nbcode[Tvar[j-2]][codtab[jk][Tvar[j-2]]]);
        !          4552:                   ij++;
        !          4553:                 }
        !          4554:                 else
1.126     brouard  4555:                   fprintf(ficgp,"+p%d*%d",k3+(k1-1)*ncovmodel+1+j-2,nbcode[Tvar[j-2]][codtab[jk][j-2]]);
                   4556:               }
                   4557:               fprintf(ficgp,")");
                   4558:             }
                   4559:             fprintf(ficgp,") t \"p%d%d\" ", k2,k);
                   4560:             if ((k+k2)!= (nlstate*2+ndeath)) fprintf(ficgp,",");
                   4561:             i=i+ncovmodel;
                   4562:           }
                   4563:         } /* end k */
                   4564:        } /* end k2 */
                   4565:      } /* end jk */
                   4566:    } /* end ng */
1.164     brouard  4567:  /* avoid: */
1.126     brouard  4568:    fflush(ficgp); 
                   4569: }  /* end gnuplot */
                   4570: 
                   4571: 
                   4572: /*************** Moving average **************/
                   4573: int movingaverage(double ***probs, double bage,double fage, double ***mobaverage, int mobilav){
                   4574: 
                   4575:   int i, cpt, cptcod;
                   4576:   int modcovmax =1;
                   4577:   int mobilavrange, mob;
                   4578:   double age;
                   4579: 
                   4580:   modcovmax=2*cptcoveff;/* Max number of modalities. We suppose 
                   4581:                           a covariate has 2 modalities */
                   4582:   if (cptcovn<1) modcovmax=1; /* At least 1 pass */
                   4583: 
                   4584:   if(mobilav==1||mobilav ==3 ||mobilav==5 ||mobilav== 7){
                   4585:     if(mobilav==1) mobilavrange=5; /* default */
                   4586:     else mobilavrange=mobilav;
                   4587:     for (age=bage; age<=fage; age++)
                   4588:       for (i=1; i<=nlstate;i++)
                   4589:        for (cptcod=1;cptcod<=modcovmax;cptcod++)
                   4590:          mobaverage[(int)age][i][cptcod]=probs[(int)age][i][cptcod];
                   4591:     /* We keep the original values on the extreme ages bage, fage and for 
                   4592:        fage+1 and bage-1 we use a 3 terms moving average; for fage+2 bage+2
                   4593:        we use a 5 terms etc. until the borders are no more concerned. 
                   4594:     */ 
                   4595:     for (mob=3;mob <=mobilavrange;mob=mob+2){
                   4596:       for (age=bage+(mob-1)/2; age<=fage-(mob-1)/2; age++){
                   4597:        for (i=1; i<=nlstate;i++){
                   4598:          for (cptcod=1;cptcod<=modcovmax;cptcod++){
                   4599:            mobaverage[(int)age][i][cptcod] =probs[(int)age][i][cptcod];
                   4600:              for (cpt=1;cpt<=(mob-1)/2;cpt++){
                   4601:                mobaverage[(int)age][i][cptcod] +=probs[(int)age-cpt][i][cptcod];
                   4602:                mobaverage[(int)age][i][cptcod] +=probs[(int)age+cpt][i][cptcod];
                   4603:              }
                   4604:            mobaverage[(int)age][i][cptcod]=mobaverage[(int)age][i][cptcod]/mob;
                   4605:          }
                   4606:        }
                   4607:       }/* end age */
                   4608:     }/* end mob */
                   4609:   }else return -1;
                   4610:   return 0;
                   4611: }/* End movingaverage */
                   4612: 
                   4613: 
                   4614: /************** Forecasting ******************/
1.169     brouard  4615: 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  4616:   /* proj1, year, month, day of starting projection 
                   4617:      agemin, agemax range of age
                   4618:      dateprev1 dateprev2 range of dates during which prevalence is computed
                   4619:      anproj2 year of en of projection (same day and month as proj1).
                   4620:   */
1.164     brouard  4621:   int yearp, stepsize, hstepm, nhstepm, j, k, cptcod, i, h, i1;
1.126     brouard  4622:   double agec; /* generic age */
                   4623:   double agelim, ppij, yp,yp1,yp2,jprojmean,mprojmean,anprojmean;
                   4624:   double *popeffectif,*popcount;
                   4625:   double ***p3mat;
                   4626:   double ***mobaverage;
                   4627:   char fileresf[FILENAMELENGTH];
                   4628: 
                   4629:   agelim=AGESUP;
                   4630:   prevalence(probs, ageminpar, agemax, s, agev, nlstate, imx, Tvar, nbcode, ncodemax, mint, anint, dateprev1, dateprev2, firstpass, lastpass);
                   4631:  
                   4632:   strcpy(fileresf,"f"); 
                   4633:   strcat(fileresf,fileres);
                   4634:   if((ficresf=fopen(fileresf,"w"))==NULL) {
                   4635:     printf("Problem with forecast resultfile: %s\n", fileresf);
                   4636:     fprintf(ficlog,"Problem with forecast resultfile: %s\n", fileresf);
                   4637:   }
                   4638:   printf("Computing forecasting: result on file '%s' \n", fileresf);
                   4639:   fprintf(ficlog,"Computing forecasting: result on file '%s' \n", fileresf);
                   4640: 
                   4641:   if (cptcoveff==0) ncodemax[cptcoveff]=1;
                   4642: 
                   4643:   if (mobilav!=0) {
                   4644:     mobaverage= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
                   4645:     if (movingaverage(probs, ageminpar, fage, mobaverage,mobilav)!=0){
                   4646:       fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav);
                   4647:       printf(" Error in movingaverage mobilav=%d\n",mobilav);
                   4648:     }
                   4649:   }
                   4650: 
                   4651:   stepsize=(int) (stepm+YEARM-1)/YEARM;
                   4652:   if (stepm<=12) stepsize=1;
                   4653:   if(estepm < stepm){
                   4654:     printf ("Problem %d lower than %d\n",estepm, stepm);
                   4655:   }
                   4656:   else  hstepm=estepm;   
                   4657: 
                   4658:   hstepm=hstepm/stepm; 
                   4659:   yp1=modf(dateintmean,&yp);/* extracts integral of datemean in yp  and
                   4660:                                fractional in yp1 */
                   4661:   anprojmean=yp;
                   4662:   yp2=modf((yp1*12),&yp);
                   4663:   mprojmean=yp;
                   4664:   yp1=modf((yp2*30.5),&yp);
                   4665:   jprojmean=yp;
                   4666:   if(jprojmean==0) jprojmean=1;
                   4667:   if(mprojmean==0) jprojmean=1;
                   4668: 
                   4669:   i1=cptcoveff;
                   4670:   if (cptcovn < 1){i1=1;}
                   4671:   
                   4672:   fprintf(ficresf,"# Mean day of interviews %.lf/%.lf/%.lf (%.2f) between %.2f and %.2f \n",jprojmean,mprojmean,anprojmean,dateintmean,dateprev1,dateprev2); 
                   4673:   
                   4674:   fprintf(ficresf,"#****** Routine prevforecast **\n");
                   4675: 
                   4676: /*           if (h==(int)(YEARM*yearp)){ */
                   4677:   for(cptcov=1, k=0;cptcov<=i1;cptcov++){
                   4678:     for(cptcod=1;cptcod<=ncodemax[cptcoveff];cptcod++){
                   4679:       k=k+1;
                   4680:       fprintf(ficresf,"\n#******");
                   4681:       for(j=1;j<=cptcoveff;j++) {
                   4682:        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]]);
                   4683:       }
                   4684:       fprintf(ficresf,"******\n");
                   4685:       fprintf(ficresf,"# Covariate valuofcovar yearproj age");
                   4686:       for(j=1; j<=nlstate+ndeath;j++){ 
                   4687:        for(i=1; i<=nlstate;i++)              
                   4688:           fprintf(ficresf," p%d%d",i,j);
                   4689:        fprintf(ficresf," p.%d",j);
                   4690:       }
                   4691:       for (yearp=0; yearp<=(anproj2-anproj1);yearp +=stepsize) { 
                   4692:        fprintf(ficresf,"\n");
                   4693:        fprintf(ficresf,"\n# Forecasting at date %.lf/%.lf/%.lf ",jproj1,mproj1,anproj1+yearp);   
                   4694: 
                   4695:        for (agec=fage; agec>=(ageminpar-1); agec--){ 
                   4696:          nhstepm=(int) rint((agelim-agec)*YEARM/stepm); 
                   4697:          nhstepm = nhstepm/hstepm; 
                   4698:          p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   4699:          oldm=oldms;savm=savms;
                   4700:          hpxij(p3mat,nhstepm,agec,hstepm,p,nlstate,stepm,oldm,savm, k);  
                   4701:        
                   4702:          for (h=0; h<=nhstepm; h++){
                   4703:            if (h*hstepm/YEARM*stepm ==yearp) {
                   4704:               fprintf(ficresf,"\n");
                   4705:               for(j=1;j<=cptcoveff;j++) 
                   4706:                 fprintf(ficresf,"%d %d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
                   4707:              fprintf(ficresf,"%.f %.f ",anproj1+yearp,agec+h*hstepm/YEARM*stepm);
                   4708:            } 
                   4709:            for(j=1; j<=nlstate+ndeath;j++) {
                   4710:              ppij=0.;
                   4711:              for(i=1; i<=nlstate;i++) {
                   4712:                if (mobilav==1) 
                   4713:                  ppij=ppij+p3mat[i][j][h]*mobaverage[(int)agec][i][cptcod];
                   4714:                else {
                   4715:                  ppij=ppij+p3mat[i][j][h]*probs[(int)(agec)][i][cptcod];
                   4716:                }
                   4717:                if (h*hstepm/YEARM*stepm== yearp) {
                   4718:                  fprintf(ficresf," %.3f", p3mat[i][j][h]);
                   4719:                }
                   4720:              } /* end i */
                   4721:              if (h*hstepm/YEARM*stepm==yearp) {
                   4722:                fprintf(ficresf," %.3f", ppij);
                   4723:              }
                   4724:            }/* end j */
                   4725:          } /* end h */
                   4726:          free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   4727:        } /* end agec */
                   4728:       } /* end yearp */
                   4729:     } /* end cptcod */
                   4730:   } /* end  cptcov */
                   4731:        
                   4732:   if (mobilav!=0) free_ma3x(mobaverage,1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
                   4733: 
                   4734:   fclose(ficresf);
                   4735: }
                   4736: 
                   4737: /************** Forecasting *****not tested NB*************/
1.169     brouard  4738: 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  4739:   
                   4740:   int cpt, stepsize, hstepm, nhstepm, j,k,c, cptcod, i,h;
                   4741:   int *popage;
                   4742:   double calagedatem, agelim, kk1, kk2;
                   4743:   double *popeffectif,*popcount;
                   4744:   double ***p3mat,***tabpop,***tabpopprev;
                   4745:   double ***mobaverage;
                   4746:   char filerespop[FILENAMELENGTH];
                   4747: 
                   4748:   tabpop= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
                   4749:   tabpopprev= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
                   4750:   agelim=AGESUP;
                   4751:   calagedatem=(anpyram+mpyram/12.+jpyram/365.-dateintmean)*YEARM;
                   4752:   
                   4753:   prevalence(probs, ageminpar, agemax, s, agev, nlstate, imx, Tvar, nbcode, ncodemax, mint, anint, dateprev1, dateprev2, firstpass, lastpass);
                   4754:   
                   4755:   
                   4756:   strcpy(filerespop,"pop"); 
                   4757:   strcat(filerespop,fileres);
                   4758:   if((ficrespop=fopen(filerespop,"w"))==NULL) {
                   4759:     printf("Problem with forecast resultfile: %s\n", filerespop);
                   4760:     fprintf(ficlog,"Problem with forecast resultfile: %s\n", filerespop);
                   4761:   }
                   4762:   printf("Computing forecasting: result on file '%s' \n", filerespop);
                   4763:   fprintf(ficlog,"Computing forecasting: result on file '%s' \n", filerespop);
                   4764: 
                   4765:   if (cptcoveff==0) ncodemax[cptcoveff]=1;
                   4766: 
                   4767:   if (mobilav!=0) {
                   4768:     mobaverage= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
                   4769:     if (movingaverage(probs, ageminpar, fage, mobaverage,mobilav)!=0){
                   4770:       fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav);
                   4771:       printf(" Error in movingaverage mobilav=%d\n",mobilav);
                   4772:     }
                   4773:   }
                   4774: 
                   4775:   stepsize=(int) (stepm+YEARM-1)/YEARM;
                   4776:   if (stepm<=12) stepsize=1;
                   4777:   
                   4778:   agelim=AGESUP;
                   4779:   
                   4780:   hstepm=1;
                   4781:   hstepm=hstepm/stepm; 
                   4782:   
                   4783:   if (popforecast==1) {
                   4784:     if((ficpop=fopen(popfile,"r"))==NULL) {
                   4785:       printf("Problem with population file : %s\n",popfile);exit(0);
                   4786:       fprintf(ficlog,"Problem with population file : %s\n",popfile);exit(0);
                   4787:     } 
                   4788:     popage=ivector(0,AGESUP);
                   4789:     popeffectif=vector(0,AGESUP);
                   4790:     popcount=vector(0,AGESUP);
                   4791:     
                   4792:     i=1;   
                   4793:     while ((c=fscanf(ficpop,"%d %lf\n",&popage[i],&popcount[i])) != EOF) i=i+1;
                   4794:    
                   4795:     imx=i;
                   4796:     for (i=1; i<imx;i++) popeffectif[popage[i]]=popcount[i];
                   4797:   }
                   4798: 
                   4799:   for(cptcov=1,k=0;cptcov<=i2;cptcov++){
                   4800:    for(cptcod=1;cptcod<=ncodemax[cptcoveff];cptcod++){
                   4801:       k=k+1;
                   4802:       fprintf(ficrespop,"\n#******");
                   4803:       for(j=1;j<=cptcoveff;j++) {
                   4804:        fprintf(ficrespop," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
                   4805:       }
                   4806:       fprintf(ficrespop,"******\n");
                   4807:       fprintf(ficrespop,"# Age");
                   4808:       for(j=1; j<=nlstate+ndeath;j++) fprintf(ficrespop," P.%d",j);
                   4809:       if (popforecast==1)  fprintf(ficrespop," [Population]");
                   4810:       
                   4811:       for (cpt=0; cpt<=0;cpt++) { 
                   4812:        fprintf(ficrespop,"\n\n# Forecasting at date %.lf/%.lf/%.lf ",jpyram,mpyram,anpyram+cpt);   
                   4813:        
                   4814:        for (agedeb=(fage-((int)calagedatem %12/12.)); agedeb>=(ageminpar-((int)calagedatem %12)/12.); agedeb--){ 
                   4815:          nhstepm=(int) rint((agelim-agedeb)*YEARM/stepm); 
                   4816:          nhstepm = nhstepm/hstepm; 
                   4817:          
                   4818:          p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   4819:          oldm=oldms;savm=savms;
                   4820:          hpxij(p3mat,nhstepm,agedeb,hstepm,p,nlstate,stepm,oldm,savm, k);  
                   4821:        
                   4822:          for (h=0; h<=nhstepm; h++){
                   4823:            if (h==(int) (calagedatem+YEARM*cpt)) {
                   4824:              fprintf(ficrespop,"\n %3.f ",agedeb+h*hstepm/YEARM*stepm);
                   4825:            } 
                   4826:            for(j=1; j<=nlstate+ndeath;j++) {
                   4827:              kk1=0.;kk2=0;
                   4828:              for(i=1; i<=nlstate;i++) {              
                   4829:                if (mobilav==1) 
                   4830:                  kk1=kk1+p3mat[i][j][h]*mobaverage[(int)agedeb+1][i][cptcod];
                   4831:                else {
                   4832:                  kk1=kk1+p3mat[i][j][h]*probs[(int)(agedeb+1)][i][cptcod];
                   4833:                }
                   4834:              }
                   4835:              if (h==(int)(calagedatem+12*cpt)){
                   4836:                tabpop[(int)(agedeb)][j][cptcod]=kk1;
                   4837:                  /*fprintf(ficrespop," %.3f", kk1);
                   4838:                    if (popforecast==1) fprintf(ficrespop," [%.f]", kk1*popeffectif[(int)agedeb+1]);*/
                   4839:              }
                   4840:            }
                   4841:            for(i=1; i<=nlstate;i++){
                   4842:              kk1=0.;
                   4843:                for(j=1; j<=nlstate;j++){
                   4844:                  kk1= kk1+tabpop[(int)(agedeb)][j][cptcod]; 
                   4845:                }
                   4846:                  tabpopprev[(int)(agedeb)][i][cptcod]=tabpop[(int)(agedeb)][i][cptcod]/kk1*popeffectif[(int)(agedeb+(calagedatem+12*cpt)*hstepm/YEARM*stepm-1)];
                   4847:            }
                   4848: 
                   4849:            if (h==(int)(calagedatem+12*cpt)) for(j=1; j<=nlstate;j++) 
                   4850:              fprintf(ficrespop," %15.2f",tabpopprev[(int)(agedeb+1)][j][cptcod]);
                   4851:          }
                   4852:          free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   4853:        }
                   4854:       }
                   4855:  
                   4856:   /******/
                   4857: 
                   4858:       for (cpt=1; cpt<=(anpyram1-anpyram);cpt++) { 
                   4859:        fprintf(ficrespop,"\n\n# Forecasting at date %.lf/%.lf/%.lf ",jpyram,mpyram,anpyram+cpt);   
                   4860:        for (agedeb=(fage-((int)calagedatem %12/12.)); agedeb>=(ageminpar-((int)calagedatem %12)/12.); agedeb--){ 
                   4861:          nhstepm=(int) rint((agelim-agedeb)*YEARM/stepm); 
                   4862:          nhstepm = nhstepm/hstepm; 
                   4863:          
                   4864:          p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   4865:          oldm=oldms;savm=savms;
                   4866:          hpxij(p3mat,nhstepm,agedeb,hstepm,p,nlstate,stepm,oldm,savm, k);  
                   4867:          for (h=0; h<=nhstepm; h++){
                   4868:            if (h==(int) (calagedatem+YEARM*cpt)) {
                   4869:              fprintf(ficresf,"\n %3.f ",agedeb+h*hstepm/YEARM*stepm);
                   4870:            } 
                   4871:            for(j=1; j<=nlstate+ndeath;j++) {
                   4872:              kk1=0.;kk2=0;
                   4873:              for(i=1; i<=nlstate;i++) {              
                   4874:                kk1=kk1+p3mat[i][j][h]*tabpopprev[(int)agedeb+1][i][cptcod];    
                   4875:              }
                   4876:              if (h==(int)(calagedatem+12*cpt)) fprintf(ficresf," %15.2f", kk1);        
                   4877:            }
                   4878:          }
                   4879:          free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   4880:        }
                   4881:       }
                   4882:    } 
                   4883:   }
                   4884:  
                   4885:   if (mobilav!=0) free_ma3x(mobaverage,1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
                   4886: 
                   4887:   if (popforecast==1) {
                   4888:     free_ivector(popage,0,AGESUP);
                   4889:     free_vector(popeffectif,0,AGESUP);
                   4890:     free_vector(popcount,0,AGESUP);
                   4891:   }
                   4892:   free_ma3x(tabpop,1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
                   4893:   free_ma3x(tabpopprev,1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
                   4894:   fclose(ficrespop);
                   4895: } /* End of popforecast */
                   4896: 
                   4897: int fileappend(FILE *fichier, char *optionfich)
                   4898: {
                   4899:   if((fichier=fopen(optionfich,"a"))==NULL) {
                   4900:     printf("Problem with file: %s\n", optionfich);
                   4901:     fprintf(ficlog,"Problem with file: %s\n", optionfich);
                   4902:     return (0);
                   4903:   }
                   4904:   fflush(fichier);
                   4905:   return (1);
                   4906: }
                   4907: 
                   4908: 
                   4909: /**************** function prwizard **********************/
                   4910: void prwizard(int ncovmodel, int nlstate, int ndeath,  char model[], FILE *ficparo)
                   4911: {
                   4912: 
                   4913:   /* Wizard to print covariance matrix template */
                   4914: 
1.164     brouard  4915:   char ca[32], cb[32];
                   4916:   int i,j, k, li, lj, lk, ll, jj, npar, itimes;
1.126     brouard  4917:   int numlinepar;
                   4918: 
                   4919:   printf("# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
                   4920:   fprintf(ficparo,"# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
                   4921:   for(i=1; i <=nlstate; i++){
                   4922:     jj=0;
                   4923:     for(j=1; j <=nlstate+ndeath; j++){
                   4924:       if(j==i) continue;
                   4925:       jj++;
                   4926:       /*ca[0]= k+'a'-1;ca[1]='\0';*/
                   4927:       printf("%1d%1d",i,j);
                   4928:       fprintf(ficparo,"%1d%1d",i,j);
                   4929:       for(k=1; k<=ncovmodel;k++){
                   4930:        /*        printf(" %lf",param[i][j][k]); */
                   4931:        /*        fprintf(ficparo," %lf",param[i][j][k]); */
                   4932:        printf(" 0.");
                   4933:        fprintf(ficparo," 0.");
                   4934:       }
                   4935:       printf("\n");
                   4936:       fprintf(ficparo,"\n");
                   4937:     }
                   4938:   }
                   4939:   printf("# Scales (for hessian or gradient estimation)\n");
                   4940:   fprintf(ficparo,"# Scales (for hessian or gradient estimation)\n");
                   4941:   npar= (nlstate+ndeath-1)*nlstate*ncovmodel; /* Number of parameters*/ 
                   4942:   for(i=1; i <=nlstate; i++){
                   4943:     jj=0;
                   4944:     for(j=1; j <=nlstate+ndeath; j++){
                   4945:       if(j==i) continue;
                   4946:       jj++;
                   4947:       fprintf(ficparo,"%1d%1d",i,j);
                   4948:       printf("%1d%1d",i,j);
                   4949:       fflush(stdout);
                   4950:       for(k=1; k<=ncovmodel;k++){
                   4951:        /*      printf(" %le",delti3[i][j][k]); */
                   4952:        /*      fprintf(ficparo," %le",delti3[i][j][k]); */
                   4953:        printf(" 0.");
                   4954:        fprintf(ficparo," 0.");
                   4955:       }
                   4956:       numlinepar++;
                   4957:       printf("\n");
                   4958:       fprintf(ficparo,"\n");
                   4959:     }
                   4960:   }
                   4961:   printf("# Covariance matrix\n");
                   4962: /* # 121 Var(a12)\n\ */
                   4963: /* # 122 Cov(b12,a12) Var(b12)\n\ */
                   4964: /* # 131 Cov(a13,a12) Cov(a13,b12, Var(a13)\n\ */
                   4965: /* # 132 Cov(b13,a12) Cov(b13,b12, Cov(b13,a13) Var(b13)\n\ */
                   4966: /* # 212 Cov(a21,a12) Cov(a21,b12, Cov(a21,a13) Cov(a21,b13) Var(a21)\n\ */
                   4967: /* # 212 Cov(b21,a12) Cov(b21,b12, Cov(b21,a13) Cov(b21,b13) Cov(b21,a21) Var(b21)\n\ */
                   4968: /* # 232 Cov(a23,a12) Cov(a23,b12, Cov(a23,a13) Cov(a23,b13) Cov(a23,a21) Cov(a23,b21) Var(a23)\n\ */
                   4969: /* # 232 Cov(b23,a12) Cov(b23,b12) ... Var (b23)\n" */
                   4970:   fflush(stdout);
                   4971:   fprintf(ficparo,"# Covariance matrix\n");
                   4972:   /* # 121 Var(a12)\n\ */
                   4973:   /* # 122 Cov(b12,a12) Var(b12)\n\ */
                   4974:   /* #   ...\n\ */
                   4975:   /* # 232 Cov(b23,a12)  Cov(b23,b12) ... Var (b23)\n" */
                   4976:   
                   4977:   for(itimes=1;itimes<=2;itimes++){
                   4978:     jj=0;
                   4979:     for(i=1; i <=nlstate; i++){
                   4980:       for(j=1; j <=nlstate+ndeath; j++){
                   4981:        if(j==i) continue;
                   4982:        for(k=1; k<=ncovmodel;k++){
                   4983:          jj++;
                   4984:          ca[0]= k+'a'-1;ca[1]='\0';
                   4985:          if(itimes==1){
                   4986:            printf("#%1d%1d%d",i,j,k);
                   4987:            fprintf(ficparo,"#%1d%1d%d",i,j,k);
                   4988:          }else{
                   4989:            printf("%1d%1d%d",i,j,k);
                   4990:            fprintf(ficparo,"%1d%1d%d",i,j,k);
                   4991:            /*  printf(" %.5le",matcov[i][j]); */
                   4992:          }
                   4993:          ll=0;
                   4994:          for(li=1;li <=nlstate; li++){
                   4995:            for(lj=1;lj <=nlstate+ndeath; lj++){
                   4996:              if(lj==li) continue;
                   4997:              for(lk=1;lk<=ncovmodel;lk++){
                   4998:                ll++;
                   4999:                if(ll<=jj){
                   5000:                  cb[0]= lk +'a'-1;cb[1]='\0';
                   5001:                  if(ll<jj){
                   5002:                    if(itimes==1){
                   5003:                      printf(" Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
                   5004:                      fprintf(ficparo," Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
                   5005:                    }else{
                   5006:                      printf(" 0.");
                   5007:                      fprintf(ficparo," 0.");
                   5008:                    }
                   5009:                  }else{
                   5010:                    if(itimes==1){
                   5011:                      printf(" Var(%s%1d%1d)",ca,i,j);
                   5012:                      fprintf(ficparo," Var(%s%1d%1d)",ca,i,j);
                   5013:                    }else{
                   5014:                      printf(" 0.");
                   5015:                      fprintf(ficparo," 0.");
                   5016:                    }
                   5017:                  }
                   5018:                }
                   5019:              } /* end lk */
                   5020:            } /* end lj */
                   5021:          } /* end li */
                   5022:          printf("\n");
                   5023:          fprintf(ficparo,"\n");
                   5024:          numlinepar++;
                   5025:        } /* end k*/
                   5026:       } /*end j */
                   5027:     } /* end i */
                   5028:   } /* end itimes */
                   5029: 
                   5030: } /* end of prwizard */
                   5031: /******************* Gompertz Likelihood ******************************/
                   5032: double gompertz(double x[])
                   5033: { 
                   5034:   double A,B,L=0.0,sump=0.,num=0.;
                   5035:   int i,n=0; /* n is the size of the sample */
                   5036: 
                   5037:   for (i=0;i<=imx-1 ; i++) {
                   5038:     sump=sump+weight[i];
                   5039:     /*    sump=sump+1;*/
                   5040:     num=num+1;
                   5041:   }
                   5042:  
                   5043:  
                   5044:   /* for (i=0; i<=imx; i++) 
                   5045:      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]);*/
                   5046: 
                   5047:   for (i=1;i<=imx ; i++)
                   5048:     {
                   5049:       if (cens[i] == 1 && wav[i]>1)
                   5050:        A=-x[1]/(x[2])*(exp(x[2]*(agecens[i]-agegomp))-exp(x[2]*(ageexmed[i]-agegomp)));
                   5051:       
                   5052:       if (cens[i] == 0 && wav[i]>1)
                   5053:        A=-x[1]/(x[2])*(exp(x[2]*(agedc[i]-agegomp))-exp(x[2]*(ageexmed[i]-agegomp)))
                   5054:             +log(x[1]/YEARM)+x[2]*(agedc[i]-agegomp)+log(YEARM);  
                   5055:       
                   5056:       /*if (wav[i] > 1 && agecens[i] > 15) {*/ /* ??? */
                   5057:       if (wav[i] > 1 ) { /* ??? */
                   5058:        L=L+A*weight[i];
                   5059:        /*      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]);*/
                   5060:       }
                   5061:     }
                   5062: 
                   5063:  /*printf("x1=%2.9f x2=%2.9f x3=%2.9f L=%f\n",x[1],x[2],x[3],L);*/
                   5064:  
                   5065:   return -2*L*num/sump;
                   5066: }
                   5067: 
1.136     brouard  5068: #ifdef GSL
                   5069: /******************* Gompertz_f Likelihood ******************************/
                   5070: double gompertz_f(const gsl_vector *v, void *params)
                   5071: { 
                   5072:   double A,B,LL=0.0,sump=0.,num=0.;
                   5073:   double *x= (double *) v->data;
                   5074:   int i,n=0; /* n is the size of the sample */
                   5075: 
                   5076:   for (i=0;i<=imx-1 ; i++) {
                   5077:     sump=sump+weight[i];
                   5078:     /*    sump=sump+1;*/
                   5079:     num=num+1;
                   5080:   }
                   5081:  
                   5082:  
                   5083:   /* for (i=0; i<=imx; i++) 
                   5084:      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]);*/
                   5085:   printf("x[0]=%lf x[1]=%lf\n",x[0],x[1]);
                   5086:   for (i=1;i<=imx ; i++)
                   5087:     {
                   5088:       if (cens[i] == 1 && wav[i]>1)
                   5089:        A=-x[0]/(x[1])*(exp(x[1]*(agecens[i]-agegomp))-exp(x[1]*(ageexmed[i]-agegomp)));
                   5090:       
                   5091:       if (cens[i] == 0 && wav[i]>1)
                   5092:        A=-x[0]/(x[1])*(exp(x[1]*(agedc[i]-agegomp))-exp(x[1]*(ageexmed[i]-agegomp)))
                   5093:             +log(x[0]/YEARM)+x[1]*(agedc[i]-agegomp)+log(YEARM);  
                   5094:       
                   5095:       /*if (wav[i] > 1 && agecens[i] > 15) {*/ /* ??? */
                   5096:       if (wav[i] > 1 ) { /* ??? */
                   5097:        LL=LL+A*weight[i];
                   5098:        /*      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]);*/
                   5099:       }
                   5100:     }
                   5101: 
                   5102:  /*printf("x1=%2.9f x2=%2.9f x3=%2.9f L=%f\n",x[1],x[2],x[3],L);*/
                   5103:   printf("x[0]=%lf x[1]=%lf -2*LL*num/sump=%lf\n",x[0],x[1],-2*LL*num/sump);
                   5104:  
                   5105:   return -2*LL*num/sump;
                   5106: }
                   5107: #endif
                   5108: 
1.126     brouard  5109: /******************* Printing html file ***********/
                   5110: void printinghtmlmort(char fileres[], char title[], char datafile[], int firstpass, \
                   5111:                  int lastpass, int stepm, int weightopt, char model[],\
                   5112:                  int imx,  double p[],double **matcov,double agemortsup){
                   5113:   int i,k;
                   5114: 
                   5115:   fprintf(fichtm,"<ul><li><h4>Result files </h4>\n Force of mortality. Parameters of the Gompertz fit (with confidence interval in brackets):<br>");
                   5116:   fprintf(fichtm,"  mu(age) =%lf*exp(%lf*(age-%d)) per year<br><br>",p[1],p[2],agegomp);
                   5117:   for (i=1;i<=2;i++) 
                   5118:     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]));
                   5119:   fprintf(fichtm,"<br><br><img src=\"graphmort.png\">");
                   5120:   fprintf(fichtm,"</ul>");
                   5121: 
                   5122: fprintf(fichtm,"<ul><li><h4>Life table</h4>\n <br>");
                   5123: 
                   5124:  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>");
                   5125: 
                   5126:  for (k=agegomp;k<(agemortsup-2);k++) 
                   5127:    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]);
                   5128: 
                   5129:  
                   5130:   fflush(fichtm);
                   5131: }
                   5132: 
                   5133: /******************* Gnuplot file **************/
                   5134: void printinggnuplotmort(char fileres[], char optionfilefiname[], double ageminpar, double agemaxpar, double fage , char pathc[], double p[]){
                   5135: 
                   5136:   char dirfileres[132],optfileres[132];
1.164     brouard  5137: 
1.126     brouard  5138:   int ng;
                   5139: 
                   5140: 
                   5141:   /*#ifdef windows */
                   5142:   fprintf(ficgp,"cd \"%s\" \n",pathc);
                   5143:     /*#endif */
                   5144: 
                   5145: 
                   5146:   strcpy(dirfileres,optionfilefiname);
                   5147:   strcpy(optfileres,"vpl");
                   5148:   fprintf(ficgp,"set out \"graphmort.png\"\n "); 
                   5149:   fprintf(ficgp,"set xlabel \"Age\"\n set ylabel \"Force of mortality (per year)\" \n "); 
1.145     brouard  5150:   fprintf(ficgp, "set ter png small size 320, 240\n set log y\n"); 
                   5151:   /* fprintf(ficgp, "set size 0.65,0.65\n"); */
1.126     brouard  5152:   fprintf(ficgp,"plot [%d:100] %lf*exp(%lf*(x-%d))",agegomp,p[1],p[2],agegomp);
                   5153: 
                   5154: } 
                   5155: 
1.136     brouard  5156: int readdata(char datafile[], int firstobs, int lastobs, int *imax)
                   5157: {
1.126     brouard  5158: 
1.136     brouard  5159:   /*-------- data file ----------*/
                   5160:   FILE *fic;
                   5161:   char dummy[]="                         ";
1.164     brouard  5162:   int i=0, j=0, n=0;
1.136     brouard  5163:   int linei, month, year,iout;
                   5164:   char line[MAXLINE], linetmp[MAXLINE];
1.164     brouard  5165:   char stra[MAXLINE], strb[MAXLINE];
1.136     brouard  5166:   char *stratrunc;
                   5167:   int lstra;
1.126     brouard  5168: 
                   5169: 
1.136     brouard  5170:   if((fic=fopen(datafile,"r"))==NULL)    {
                   5171:     printf("Problem while opening datafile: %s\n", datafile);return 1;
                   5172:     fprintf(ficlog,"Problem while opening datafile: %s\n", datafile);return 1;
                   5173:   }
1.126     brouard  5174: 
1.136     brouard  5175:   i=1;
                   5176:   linei=0;
                   5177:   while ((fgets(line, MAXLINE, fic) != NULL) &&((i >= firstobs) && (i <=lastobs))) {
                   5178:     linei=linei+1;
                   5179:     for(j=strlen(line); j>=0;j--){  /* Untabifies line */
                   5180:       if(line[j] == '\t')
                   5181:        line[j] = ' ';
                   5182:     }
                   5183:     for(j=strlen(line)-1; (line[j]==' ')||(line[j]==10)||(line[j]==13);j--){
                   5184:       ;
                   5185:     };
                   5186:     line[j+1]=0;  /* Trims blanks at end of line */
                   5187:     if(line[0]=='#'){
                   5188:       fprintf(ficlog,"Comment line\n%s\n",line);
                   5189:       printf("Comment line\n%s\n",line);
                   5190:       continue;
                   5191:     }
                   5192:     trimbb(linetmp,line); /* Trims multiple blanks in line */
1.164     brouard  5193:     strcpy(line, linetmp);
1.136     brouard  5194:   
1.126     brouard  5195: 
1.136     brouard  5196:     for (j=maxwav;j>=1;j--){
1.137     brouard  5197:       cutv(stra, strb, line, ' '); 
1.136     brouard  5198:       if(strb[0]=='.') { /* Missing status */
                   5199:        lval=-1;
                   5200:       }else{
                   5201:        errno=0;
                   5202:        lval=strtol(strb,&endptr,10); 
                   5203:       /*       if (errno == ERANGE && (lval == LONG_MAX || lval == LONG_MIN))*/
                   5204:        if( strb[0]=='\0' || (*endptr != '\0')){
1.141     brouard  5205:          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);
                   5206:          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  5207:          return 1;
                   5208:        }
                   5209:       }
                   5210:       s[j][i]=lval;
                   5211:       
                   5212:       strcpy(line,stra);
                   5213:       cutv(stra, strb,line,' ');
1.169     brouard  5214:       if( (iout=sscanf(strb,"%d/%d",&month, &year)) != 0){
1.136     brouard  5215:       }
1.169     brouard  5216:       else  if( (iout=sscanf(strb,"%s.",dummy)) != 0){
1.136     brouard  5217:        month=99;
                   5218:        year=9999;
                   5219:       }else{
1.141     brouard  5220:        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);
                   5221:        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  5222:        return 1;
                   5223:       }
                   5224:       anint[j][i]= (double) year; 
                   5225:       mint[j][i]= (double)month; 
                   5226:       strcpy(line,stra);
                   5227:     } /* ENd Waves */
                   5228:     
                   5229:     cutv(stra, strb,line,' '); 
1.169     brouard  5230:     if( (iout=sscanf(strb,"%d/%d",&month, &year)) != 0){
1.136     brouard  5231:     }
1.169     brouard  5232:     else  if( (iout=sscanf(strb,"%s.",dummy)) != 0){
1.136     brouard  5233:       month=99;
                   5234:       year=9999;
                   5235:     }else{
1.141     brouard  5236:       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);
                   5237:        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  5238:        return 1;
                   5239:     }
                   5240:     andc[i]=(double) year; 
                   5241:     moisdc[i]=(double) month; 
                   5242:     strcpy(line,stra);
                   5243:     
                   5244:     cutv(stra, strb,line,' '); 
1.169     brouard  5245:     if( (iout=sscanf(strb,"%d/%d",&month, &year)) != 0){
1.136     brouard  5246:     }
1.169     brouard  5247:     else  if( (iout=sscanf(strb,"%s.", dummy)) != 0){
1.136     brouard  5248:       month=99;
                   5249:       year=9999;
                   5250:     }else{
1.141     brouard  5251:       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);
                   5252:       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  5253:        return 1;
                   5254:     }
                   5255:     if (year==9999) {
1.141     brouard  5256:       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);
                   5257:       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  5258:        return 1;
1.126     brouard  5259: 
1.136     brouard  5260:     }
                   5261:     annais[i]=(double)(year);
                   5262:     moisnais[i]=(double)(month); 
                   5263:     strcpy(line,stra);
                   5264:     
                   5265:     cutv(stra, strb,line,' '); 
                   5266:     errno=0;
                   5267:     dval=strtod(strb,&endptr); 
                   5268:     if( strb[0]=='\0' || (*endptr != '\0')){
1.141     brouard  5269:       printf("Error reading data around '%f' at line number %d, \"%s\" for individual %d\nShould be a weight.  Exiting.\n",dval, i,line,linei);
                   5270:       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  5271:       fflush(ficlog);
                   5272:       return 1;
                   5273:     }
                   5274:     weight[i]=dval; 
                   5275:     strcpy(line,stra);
                   5276:     
                   5277:     for (j=ncovcol;j>=1;j--){
                   5278:       cutv(stra, strb,line,' '); 
                   5279:       if(strb[0]=='.') { /* Missing status */
                   5280:        lval=-1;
                   5281:       }else{
                   5282:        errno=0;
                   5283:        lval=strtol(strb,&endptr,10); 
                   5284:        if( strb[0]=='\0' || (*endptr != '\0')){
1.141     brouard  5285:          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);
                   5286:          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  5287:          return 1;
                   5288:        }
                   5289:       }
                   5290:       if(lval <-1 || lval >1){
1.141     brouard  5291:        printf("Error reading data around '%ld' at line number %d for individual %d, '%s'\n \
1.136     brouard  5292:  Should be a value of %d(nth) covariate (0 should be the value for the reference and 1\n \
                   5293:  for the alternative. IMaCh does not build design variables automatically, do it yourself.\n \
                   5294:  For example, for multinomial values like 1, 2 and 3,\n \
                   5295:  build V1=0 V2=0 for the reference value (1),\n \
                   5296:         V1=1 V2=0 for (2) \n \
                   5297:  and V1=0 V2=1 for (3). V1=1 V2=1 should not exist and the corresponding\n \
                   5298:  output of IMaCh is often meaningless.\n \
                   5299:  Exiting.\n",lval,linei, i,line,j);
1.141     brouard  5300:        fprintf(ficlog,"Error reading data around '%ld' at line number %d for individual %d, '%s'\n \
1.136     brouard  5301:  Should be a value of %d(nth) covariate (0 should be the value for the reference and 1\n \
                   5302:  for the alternative. IMaCh does not build design variables automatically, do it yourself.\n \
                   5303:  For example, for multinomial values like 1, 2 and 3,\n \
                   5304:  build V1=0 V2=0 for the reference value (1),\n \
                   5305:         V1=1 V2=0 for (2) \n \
                   5306:  and V1=0 V2=1 for (3). V1=1 V2=1 should not exist and the corresponding\n \
                   5307:  output of IMaCh is often meaningless.\n \
                   5308:  Exiting.\n",lval,linei, i,line,j);fflush(ficlog);
                   5309:        return 1;
                   5310:       }
                   5311:       covar[j][i]=(double)(lval);
                   5312:       strcpy(line,stra);
                   5313:     }  
                   5314:     lstra=strlen(stra);
                   5315:      
                   5316:     if(lstra > 9){ /* More than 2**32 or max of what printf can write with %ld */
                   5317:       stratrunc = &(stra[lstra-9]);
                   5318:       num[i]=atol(stratrunc);
                   5319:     }
                   5320:     else
                   5321:       num[i]=atol(stra);
                   5322:     /*if((s[2][i]==2) && (s[3][i]==-1)&&(s[4][i]==9)){
                   5323:       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;}*/
                   5324:     
                   5325:     i=i+1;
                   5326:   } /* End loop reading  data */
1.126     brouard  5327: 
1.136     brouard  5328:   *imax=i-1; /* Number of individuals */
                   5329:   fclose(fic);
                   5330:  
                   5331:   return (0);
1.164     brouard  5332:   /* endread: */
1.136     brouard  5333:     printf("Exiting readdata: ");
                   5334:     fclose(fic);
                   5335:     return (1);
1.126     brouard  5336: 
                   5337: 
                   5338: 
1.136     brouard  5339: }
1.145     brouard  5340: void removespace(char *str) {
                   5341:   char *p1 = str, *p2 = str;
                   5342:   do
                   5343:     while (*p2 == ' ')
                   5344:       p2++;
1.169     brouard  5345:   while (*p1++ == *p2++);
1.145     brouard  5346: }
                   5347: 
                   5348: int decodemodel ( char model[], int lastobs) /**< This routine decode the model and returns:
                   5349:    * Model  V1+V2+V3+V8+V7*V8+V5*V6+V8*age+V3*age
                   5350:    * - cptcovt total number of covariates of the model nbocc(+)+1 = 8
                   5351:    * - cptcovn or number of covariates k of the models excluding age*products =6
                   5352:    * - cptcovage number of covariates with age*products =2
                   5353:    * - cptcovs number of simple covariates
                   5354:    * - 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
                   5355:    *     which is a new column after the 9 (ncovcol) variables. 
                   5356:    * - if k is a product Vn*Vm covar[k][i] is filled with correct values for each individual
                   5357:    * - Tprod[l] gives the kth covariates of the product Vn*Vm l=1 to cptcovprod-cptcovage
                   5358:    *    Tprod[1]@2 {5, 6}: position of first product V7*V8 is 5, and second V5*V6 is 6.
                   5359:    * - Tvard[k]  p Tvard[1][1]@4 {7, 8, 5, 6} for V7*V8 and V5*V6 .
                   5360:  */
1.136     brouard  5361: {
1.145     brouard  5362:   int i, j, k, ks;
1.164     brouard  5363:   int  j1, k1, k2;
1.136     brouard  5364:   char modelsav[80];
1.145     brouard  5365:   char stra[80], strb[80], strc[80], strd[80],stre[80];
1.136     brouard  5366: 
1.145     brouard  5367:   /*removespace(model);*/
1.136     brouard  5368:   if (strlen(model) >1){ /* If there is at least 1 covariate */
1.145     brouard  5369:     j=0, j1=0, k1=0, k2=-1, ks=0, cptcovn=0;
                   5370:     j=nbocc(model,'+'); /**< j=Number of '+' */
                   5371:     j1=nbocc(model,'*'); /**< j1=Number of '*' */
                   5372:     cptcovs=j+1-j1; /**<  Number of simple covariates V1+V2*age+V3 +V3*V4=> V1 + V3 =2  */
                   5373:     cptcovt= j+1; /* Number of total covariates in the model V1 + V2*age+ V3 + V3*V4=> 4*/
                   5374:                   /* including age products which are counted in cptcovage.
1.169     brouard  5375:                  * but the covariates which are products must be treated separately: ncovn=4- 2=2 (V1+V3). */
1.145     brouard  5376:     cptcovprod=j1; /**< Number of products  V1*V2 +v3*age = 2 */
                   5377:     cptcovprodnoage=0; /**< Number of covariate products without age: V3*V4 =1  */
1.136     brouard  5378:     strcpy(modelsav,model); 
1.137     brouard  5379:     if (strstr(model,"AGE") !=0){
                   5380:       printf("Error. AGE must be in lower case 'age' model=%s ",model);
                   5381:       fprintf(ficlog,"Error. AGE must be in lower case model=%s ",model);fflush(ficlog);
1.136     brouard  5382:       return 1;
                   5383:     }
1.141     brouard  5384:     if (strstr(model,"v") !=0){
                   5385:       printf("Error. 'v' must be in upper case 'V' model=%s ",model);
                   5386:       fprintf(ficlog,"Error. 'v' must be in upper case model=%s ",model);fflush(ficlog);
                   5387:       return 1;
                   5388:     }
1.136     brouard  5389:     
1.145     brouard  5390:     /*   Design
                   5391:      *  V1   V2   V3   V4  V5  V6  V7  V8  V9 Weight
                   5392:      *  <          ncovcol=8                >
                   5393:      * Model V2 + V1 + V3*age + V3 + V5*V6 + V7*V8 + V8*age + V8
                   5394:      *   k=  1    2      3       4     5       6      7        8
                   5395:      *  cptcovn number of covariates (not including constant and age ) = # of + plus 1 = 7+1=8
                   5396:      *  covar[k,i], value of kth covariate if not including age for individual i:
                   5397:      *       covar[1][i]= (V2), covar[4][i]=(V3), covar[8][i]=(V8)
                   5398:      *  Tvar[k] # of the kth covariate:  Tvar[1]=2  Tvar[4]=3 Tvar[8]=8
                   5399:      *       if multiplied by age: V3*age Tvar[3=V3*age]=3 (V3) Tvar[7]=8 and 
                   5400:      *  Tage[++cptcovage]=k
                   5401:      *       if products, new covar are created after ncovcol with k1
                   5402:      *  Tvar[k]=ncovcol+k1; # of the kth covariate product:  Tvar[5]=ncovcol+1=10  Tvar[6]=ncovcol+1=11
                   5403:      *  Tprod[k1]=k; Tprod[1]=5 Tprod[2]= 6; gives the position of the k1th product
                   5404:      *  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
                   5405:      *  Tvar[cptcovn+k2]=Tvard[k1][1];Tvar[cptcovn+k2+1]=Tvard[k1][2];
                   5406:      *  Tvar[8+1]=5;Tvar[8+2]=6;Tvar[8+3]=7;Tvar[8+4]=8 inverted
                   5407:      *  V1   V2   V3   V4  V5  V6  V7  V8  V9  V10  V11
                   5408:      *  <          ncovcol=8                >
                   5409:      *       Model V2 + V1 + V3*age + V3 + V5*V6 + V7*V8 + V8*age + V8    d1   d1   d2  d2
                   5410:      *          k=  1    2      3       4     5       6      7        8    9   10   11  12
                   5411:      *     Tvar[k]= 2    1      3       3    10      11      8        8    5    6    7   8
                   5412:      * p Tvar[1]@12={2,   1,     3,      3,   11,     10,     8,       8,   7,   8,   5,  6}
                   5413:      * p Tprod[1]@2={                         6, 5}
                   5414:      *p Tvard[1][1]@4= {7, 8, 5, 6}
                   5415:      * covar[k][i]= V2   V1      ?      V3    V5*V6?   V7*V8?  ?       V8   
                   5416:      *  cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*cov[2];
                   5417:      *How to reorganize?
                   5418:      * Model V1 + V2 + V3 + V8 + V5*V6 + V7*V8 + V3*age + V8*age
                   5419:      * Tvars {2,   1,     3,      3,   11,     10,     8,       8,   7,   8,   5,  6}
                   5420:      *       {2,   1,     4,      8,    5,      6,     3,       7}
                   5421:      * Struct []
                   5422:      */
                   5423: 
1.136     brouard  5424:     /* This loop fills the array Tvar from the string 'model'.*/
                   5425:     /* j is the number of + signs in the model V1+V2+V3 j=2 i=3 to 1 */
1.137     brouard  5426:     /*   modelsav=V2+V1+V4+age*V3 strb=age*V3 stra=V2+V1+V4  */
                   5427:     /*         k=4 (age*V3) Tvar[k=4]= 3 (from V3) Tage[cptcovage=1]=4 */
                   5428:     /*         k=3 V4 Tvar[k=3]= 4 (from V4) */
                   5429:     /*         k=2 V1 Tvar[k=2]= 1 (from V1) */
                   5430:     /*         k=1 Tvar[1]=2 (from V2) */
                   5431:     /*         k=5 Tvar[5] */
                   5432:     /* for (k=1; k<=cptcovn;k++) { */
                   5433:     /*         cov[2+k]=nbcode[Tvar[k]][codtab[ij][Tvar[k]]]; */
                   5434:     /*         } */
1.186   ! brouard  5435:     /* for (k=1; k<=cptcovage;k++) cov[2+Tage[k]]=nbcode[Tvar[Tage[k]]][codtab[ij][Tvar[Tage[k]]]]*cov[2]; */
1.145     brouard  5436:     /*
                   5437:      * Treating invertedly V2+V1+V3*age+V2*V4 is as if written V2*V4 +V3*age + V1 + V2 */
                   5438:     for(k=cptcovt; k>=1;k--) /**< Number of covariates */
                   5439:         Tvar[k]=0;
                   5440:     cptcovage=0;
                   5441:     for(k=1; k<=cptcovt;k++){ /* Loop on total covariates of the model */
                   5442:       cutl(stra,strb,modelsav,'+'); /* keeps in strb after the first '+' 
                   5443:                                     modelsav==V2+V1+V4+V3*age strb=V3*age stra=V2+V1+V4 */ 
1.137     brouard  5444:       if (nbocc(modelsav,'+')==0) strcpy(strb,modelsav); /* and analyzes it */
1.136     brouard  5445:       /*      printf("i=%d a=%s b=%s sav=%s\n",i, stra,strb,modelsav);*/
                   5446:       /*scanf("%d",i);*/
1.145     brouard  5447:       if (strchr(strb,'*')) {  /**< Model includes a product V2+V1+V4+V3*age strb=V3*age */
                   5448:        cutl(strc,strd,strb,'*'); /**< strd*strc  Vm*Vn: strb=V3*age(input) strc=age strd=V3 ; V3*V2 strc=V2, strd=V3 */
                   5449:        if (strcmp(strc,"age")==0) { /**< Model includes age: Vn*age */
                   5450:          /* covar is not filled and then is empty */
1.136     brouard  5451:          cptcovprod--;
1.145     brouard  5452:          cutl(stre,strb,strd,'V'); /* strd=V3(input): stre="3" */
                   5453:          Tvar[k]=atoi(stre);  /* V2+V1+V4+V3*age Tvar[4]=3 ; V1+V2*age Tvar[2]=2 */
1.136     brouard  5454:          cptcovage++; /* Sums the number of covariates which include age as a product */
1.186   ! brouard  5455:          Tage[cptcovage]=k;  /* Tvar[4]=3, Tage[1] = 4 or V1+V1*age Tvar[2]=1, Tage[1]=2 */
1.136     brouard  5456:          /*printf("stre=%s ", stre);*/
1.137     brouard  5457:        } else if (strcmp(strd,"age")==0) { /* or age*Vn */
1.136     brouard  5458:          cptcovprod--;
1.145     brouard  5459:          cutl(stre,strb,strc,'V');
1.136     brouard  5460:          Tvar[k]=atoi(stre);
                   5461:          cptcovage++;
                   5462:          Tage[cptcovage]=k;
1.137     brouard  5463:        } else {  /* Age is not in the model product V2+V1+V1*V4+V3*age+V3*V2  strb=V3*V2*/
                   5464:          /* loops on k1=1 (V3*V2) and k1=2 V4*V3 */
1.145     brouard  5465:          cptcovn++;
                   5466:          cptcovprodnoage++;k1++;
                   5467:          cutl(stre,strb,strc,'V'); /* strc= Vn, stre is n; strb=V3*V2 stre=3 strc=*/
                   5468:          Tvar[k]=ncovcol+k1; /* For model-covariate k tells which data-covariate to use but
1.137     brouard  5469:                                  because this model-covariate is a construction we invent a new column
                   5470:                                  ncovcol + k1
                   5471:                                  If already ncovcol=4 and model=V2+V1+V1*V4+age*V3+V3*V2
                   5472:                                  Tvar[3=V1*V4]=4+1 Tvar[5=V3*V2]=4 + 2= 6, etc */
1.145     brouard  5473:          cutl(strc,strb,strd,'V'); /* strd was Vm, strc is m */
1.137     brouard  5474:          Tprod[k1]=k;  /* Tprod[1]=3(=V1*V4) for V2+V1+V1*V4+age*V3+V3*V2  */
1.145     brouard  5475:          Tvard[k1][1] =atoi(strc); /* m 1 for V1*/
                   5476:          Tvard[k1][2] =atoi(stre); /* n 4 for V4*/
                   5477:          k2=k2+2;
                   5478:          Tvar[cptcovt+k2]=Tvard[k1][1]; /* Tvar[(cptcovt=4+k2=1)=5]= 1 (V1) */
                   5479:          Tvar[cptcovt+k2+1]=Tvard[k1][2];  /* Tvar[(cptcovt=4+(k2=1)+1)=6]= 4 (V4) */
1.137     brouard  5480:          for (i=1; i<=lastobs;i++){
                   5481:            /* Computes the new covariate which is a product of
1.145     brouard  5482:               covar[n][i]* covar[m][i] and stores it at ncovol+k1 May not be defined */
1.136     brouard  5483:            covar[ncovcol+k1][i]=covar[atoi(stre)][i]*covar[atoi(strc)][i];
1.137     brouard  5484:          }
                   5485:        } /* End age is not in the model */
                   5486:       } /* End if model includes a product */
1.136     brouard  5487:       else { /* no more sum */
                   5488:        /*printf("d=%s c=%s b=%s\n", strd,strc,strb);*/
                   5489:        /*  scanf("%d",i);*/
1.145     brouard  5490:        cutl(strd,strc,strb,'V');
                   5491:        ks++; /**< Number of simple covariates */
                   5492:        cptcovn++;
                   5493:        Tvar[k]=atoi(strd);
1.136     brouard  5494:       }
1.137     brouard  5495:       strcpy(modelsav,stra);  /* modelsav=V2+V1+V4 stra=V2+V1+V4 */ 
1.136     brouard  5496:       /*printf("a=%s b=%s sav=%s\n", stra,strb,modelsav);
                   5497:        scanf("%d",i);*/
                   5498:     } /* end of loop + */
                   5499:   } /* end model */
                   5500:   
                   5501:   /*The number n of Vn is stored in Tvar. cptcovage =number of age covariate. Tage gives the position of age. cptcovprod= number of products.
                   5502:     If model=V1+V1*age then Tvar[1]=1 Tvar[2]=1 cptcovage=1 Tage[1]=2 cptcovprod=0*/
                   5503: 
                   5504:   /* printf("tvar1=%d tvar2=%d tvar3=%d cptcovage=%d Tage=%d",Tvar[1],Tvar[2],Tvar[3],cptcovage,Tage[1]);
                   5505:   printf("cptcovprod=%d ", cptcovprod);
                   5506:   fprintf(ficlog,"cptcovprod=%d ", cptcovprod);
                   5507: 
                   5508:   scanf("%d ",i);*/
                   5509: 
                   5510: 
1.137     brouard  5511:   return (0); /* with covar[new additional covariate if product] and Tage if age */ 
1.164     brouard  5512:   /*endread:*/
1.136     brouard  5513:     printf("Exiting decodemodel: ");
                   5514:     return (1);
                   5515: }
                   5516: 
1.169     brouard  5517: int calandcheckages(int imx, int maxwav, double *agemin, double *agemax, int *nberr, int *nbwarn )
1.136     brouard  5518: {
                   5519:   int i, m;
                   5520: 
                   5521:   for (i=1; i<=imx; i++) {
                   5522:     for(m=2; (m<= maxwav); m++) {
                   5523:       if (((int)mint[m][i]== 99) && (s[m][i] <= nlstate)){
                   5524:        anint[m][i]=9999;
                   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 = *nberr + 1;
                   5529:        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);
                   5530:        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  5531:        s[m][i]=-1;
                   5532:       }
                   5533:       if((int)moisdc[i]==99 && (int)andc[i]!=9999 && s[m][i]>nlstate){
1.169     brouard  5534:        (*nberr)++;
1.136     brouard  5535:        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]); 
                   5536:        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]); 
                   5537:        s[m][i]=-1; /* We prefer to skip it (and to skip it in version 0.8a1 too */
                   5538:       }
                   5539:     }
                   5540:   }
                   5541: 
                   5542:   for (i=1; i<=imx; i++)  {
                   5543:     agedc[i]=(moisdc[i]/12.+andc[i])-(moisnais[i]/12.+annais[i]);
                   5544:     for(m=firstpass; (m<= lastpass); m++){
                   5545:       if(s[m][i] >0 || s[m][i]==-2 || s[m][i]==-4 || s[m][i]==-5){
                   5546:        if (s[m][i] >= nlstate+1) {
1.169     brouard  5547:          if(agedc[i]>0){
                   5548:            if((int)moisdc[i]!=99 && (int)andc[i]!=9999){
1.136     brouard  5549:              agev[m][i]=agedc[i];
                   5550:          /*if(moisdc[i]==99 && andc[i]==9999) s[m][i]=-1;*/
1.169     brouard  5551:            }else {
1.136     brouard  5552:              if ((int)andc[i]!=9999){
                   5553:                nbwarn++;
                   5554:                printf("Warning negative age at death: %ld line:%d\n",num[i],i);
                   5555:                fprintf(ficlog,"Warning negative age at death: %ld line:%d\n",num[i],i);
                   5556:                agev[m][i]=-1;
                   5557:              }
                   5558:            }
1.169     brouard  5559:          } /* agedc > 0 */
1.136     brouard  5560:        }
                   5561:        else if(s[m][i] !=9){ /* Standard case, age in fractional
                   5562:                                 years but with the precision of a month */
                   5563:          agev[m][i]=(mint[m][i]/12.+1./24.+anint[m][i])-(moisnais[i]/12.+1./24.+annais[i]);
                   5564:          if((int)mint[m][i]==99 || (int)anint[m][i]==9999)
                   5565:            agev[m][i]=1;
                   5566:          else if(agev[m][i] < *agemin){ 
                   5567:            *agemin=agev[m][i];
                   5568:            printf(" Min anint[%d][%d]=%.2f annais[%d]=%.2f, agemin=%.2f\n",m,i,anint[m][i], i,annais[i], *agemin);
                   5569:          }
                   5570:          else if(agev[m][i] >*agemax){
                   5571:            *agemax=agev[m][i];
1.156     brouard  5572:            /* printf(" Max anint[%d][%d]=%.0f annais[%d]=%.0f, agemax=%.2f\n",m,i,anint[m][i], i,annais[i], *agemax);*/
1.136     brouard  5573:          }
                   5574:          /*agev[m][i]=anint[m][i]-annais[i];*/
                   5575:          /*     agev[m][i] = age[i]+2*m;*/
                   5576:        }
                   5577:        else { /* =9 */
                   5578:          agev[m][i]=1;
                   5579:          s[m][i]=-1;
                   5580:        }
                   5581:       }
                   5582:       else /*= 0 Unknown */
                   5583:        agev[m][i]=1;
                   5584:     }
                   5585:     
                   5586:   }
                   5587:   for (i=1; i<=imx; i++)  {
                   5588:     for(m=firstpass; (m<=lastpass); m++){
                   5589:       if (s[m][i] > (nlstate+ndeath)) {
1.169     brouard  5590:        (*nberr)++;
1.136     brouard  5591:        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);     
                   5592:        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);     
                   5593:        return 1;
                   5594:       }
                   5595:     }
                   5596:   }
                   5597: 
                   5598:   /*for (i=1; i<=imx; i++){
                   5599:   for (m=firstpass; (m<lastpass); m++){
                   5600:      printf("%ld %d %.lf %d %d\n", num[i],(covar[1][i]),agev[m][i],s[m][i],s[m+1][i]);
                   5601: }
                   5602: 
                   5603: }*/
                   5604: 
                   5605: 
1.139     brouard  5606:   printf("Total number of individuals= %d, Agemin = %.2f, Agemax= %.2f\n\n", imx, *agemin, *agemax);
                   5607:   fprintf(ficlog,"Total number of individuals= %d, Agemin = %.2f, Agemax= %.2f\n\n", imx, *agemin, *agemax); 
1.136     brouard  5608: 
                   5609:   return (0);
1.164     brouard  5610:  /* endread:*/
1.136     brouard  5611:     printf("Exiting calandcheckages: ");
                   5612:     return (1);
                   5613: }
                   5614: 
1.172     brouard  5615: #if defined(_MSC_VER)
                   5616: /*printf("Visual C++ compiler: %s \n;", _MSC_FULL_VER);*/
                   5617: /*fprintf(ficlog, "Visual C++ compiler: %s \n;", _MSC_FULL_VER);*/
                   5618: //#include "stdafx.h"
                   5619: //#include <stdio.h>
                   5620: //#include <tchar.h>
                   5621: //#include <windows.h>
                   5622: //#include <iostream>
                   5623: typedef BOOL(WINAPI *LPFN_ISWOW64PROCESS) (HANDLE, PBOOL);
                   5624: 
                   5625: LPFN_ISWOW64PROCESS fnIsWow64Process;
                   5626: 
                   5627: BOOL IsWow64()
                   5628: {
                   5629:        BOOL bIsWow64 = FALSE;
                   5630: 
                   5631:        //typedef BOOL (APIENTRY *LPFN_ISWOW64PROCESS)
                   5632:        //  (HANDLE, PBOOL);
                   5633: 
                   5634:        //LPFN_ISWOW64PROCESS fnIsWow64Process;
                   5635: 
                   5636:        HMODULE module = GetModuleHandle(_T("kernel32"));
                   5637:        const char funcName[] = "IsWow64Process";
                   5638:        fnIsWow64Process = (LPFN_ISWOW64PROCESS)
                   5639:                GetProcAddress(module, funcName);
                   5640: 
                   5641:        if (NULL != fnIsWow64Process)
                   5642:        {
                   5643:                if (!fnIsWow64Process(GetCurrentProcess(),
                   5644:                        &bIsWow64))
                   5645:                        //throw std::exception("Unknown error");
                   5646:                        printf("Unknown error\n");
                   5647:        }
                   5648:        return bIsWow64 != FALSE;
                   5649: }
                   5650: #endif
1.177     brouard  5651: 
1.169     brouard  5652: void syscompilerinfo()
1.167     brouard  5653:  {
                   5654:    /* #include "syscompilerinfo.h"*/
1.185     brouard  5655:    /* command line Intel compiler 32bit windows, XP compatible:*/
                   5656:    /* /GS /W3 /Gy
                   5657:       /Zc:wchar_t /Zi /O2 /Fd"Release\vc120.pdb" /D "WIN32" /D "NDEBUG" /D
                   5658:       "_CONSOLE" /D "_LIB" /D "_USING_V110_SDK71_" /D "_UNICODE" /D
                   5659:       "UNICODE" /Qipo /Zc:forScope /Gd /Oi /MT /Fa"Release\" /EHsc /nologo
1.186   ! brouard  5660:       /Fo"Release\" /Qprof-dir "Release\" /Fp"Release\IMaCh.pch"
        !          5661:    */ 
        !          5662:    /* 64 bits */
1.185     brouard  5663:    /*
                   5664:      /GS /W3 /Gy
                   5665:      /Zc:wchar_t /Zi /O2 /Fd"x64\Release\vc120.pdb" /D "WIN32" /D "NDEBUG"
                   5666:      /D "_CONSOLE" /D "_LIB" /D "_UNICODE" /D "UNICODE" /Qipo /Zc:forScope
                   5667:      /Oi /MD /Fa"x64\Release\" /EHsc /nologo /Fo"x64\Release\" /Qprof-dir
                   5668:      "x64\Release\" /Fp"x64\Release\IMaCh.pch" */
                   5669:    /* Optimization are useless and O3 is slower than O2 */
                   5670:    /*
                   5671:      /GS /W3 /Gy /Zc:wchar_t /Zi /O3 /Fd"x64\Release\vc120.pdb" /D "WIN32" 
                   5672:      /D "NDEBUG" /D "_CONSOLE" /D "_LIB" /D "_UNICODE" /D "UNICODE" /Qipo 
                   5673:      /Zc:forScope /Oi /MD /Fa"x64\Release\" /EHsc /nologo /Qparallel 
                   5674:      /Fo"x64\Release\" /Qprof-dir "x64\Release\" /Fp"x64\Release\IMaCh.pch" 
                   5675:    */
1.186   ! brouard  5676:    /* Link is */ /* /OUT:"visual studio
1.185     brouard  5677:       2013\Projects\IMaCh\Release\IMaCh.exe" /MANIFEST /NXCOMPAT
                   5678:       /PDB:"visual studio
                   5679:       2013\Projects\IMaCh\Release\IMaCh.pdb" /DYNAMICBASE
                   5680:       "kernel32.lib" "user32.lib" "gdi32.lib" "winspool.lib"
                   5681:       "comdlg32.lib" "advapi32.lib" "shell32.lib" "ole32.lib"
                   5682:       "oleaut32.lib" "uuid.lib" "odbc32.lib" "odbccp32.lib"
                   5683:       /MACHINE:X86 /OPT:REF /SAFESEH /INCREMENTAL:NO
                   5684:       /SUBSYSTEM:CONSOLE",5.01" /MANIFESTUAC:"level='asInvoker'
                   5685:       uiAccess='false'"
                   5686:       /ManifestFile:"Release\IMaCh.exe.intermediate.manifest" /OPT:ICF
                   5687:       /NOLOGO /TLBID:1
                   5688:    */
1.177     brouard  5689: #if defined __INTEL_COMPILER
1.178     brouard  5690: #if defined(__GNUC__)
                   5691:        struct utsname sysInfo;  /* For Intel on Linux and OS/X */
                   5692: #endif
1.177     brouard  5693: #elif defined(__GNUC__) 
1.179     brouard  5694: #ifndef  __APPLE__
1.174     brouard  5695: #include <gnu/libc-version.h>  /* Only on gnu */
1.179     brouard  5696: #endif
1.177     brouard  5697:    struct utsname sysInfo;
1.178     brouard  5698:    int cross = CROSS;
                   5699:    if (cross){
                   5700:           printf("Cross-");
                   5701:           fprintf(ficlog, "Cross-");
                   5702:    }
1.174     brouard  5703: #endif
                   5704: 
1.171     brouard  5705: #include <stdint.h>
1.178     brouard  5706: 
1.169     brouard  5707:    printf("Compiled with:");fprintf(ficlog,"Compiled with:");
                   5708: #if defined(__clang__)
                   5709:    printf(" Clang/LLVM");fprintf(ficlog," Clang/LLVM");        /* Clang/LLVM. ---------------------------------------------- */
                   5710: #endif
                   5711: #if defined(__ICC) || defined(__INTEL_COMPILER)
                   5712:    printf(" Intel ICC/ICPC");fprintf(ficlog," Intel ICC/ICPC");/* Intel ICC/ICPC. ------------------------------------------ */
                   5713: #endif
                   5714: #if defined(__GNUC__) || defined(__GNUG__)
                   5715:    printf(" GNU GCC/G++");fprintf(ficlog," GNU GCC/G++");/* GNU GCC/G++. --------------------------------------------- */
                   5716: #endif
                   5717: #if defined(__HP_cc) || defined(__HP_aCC)
                   5718:    printf(" Hewlett-Packard C/aC++");fprintf(fcilog," Hewlett-Packard C/aC++"); /* Hewlett-Packard C/aC++. ---------------------------------- */
                   5719: #endif
                   5720: #if defined(__IBMC__) || defined(__IBMCPP__)
                   5721:    printf(" IBM XL C/C++"); fprintf(ficlog," IBM XL C/C++");/* IBM XL C/C++. -------------------------------------------- */
                   5722: #endif
                   5723: #if defined(_MSC_VER)
                   5724:    printf(" Microsoft Visual Studio");fprintf(ficlog," Microsoft Visual Studio");/* Microsoft Visual Studio. --------------------------------- */
                   5725: #endif
                   5726: #if defined(__PGI)
                   5727:    printf(" Portland Group PGCC/PGCPP");fprintf(ficlog," Portland Group PGCC/PGCPP");/* Portland Group PGCC/PGCPP. ------------------------------- */
                   5728: #endif
                   5729: #if defined(__SUNPRO_C) || defined(__SUNPRO_CC)
                   5730:    printf(" Oracle Solaris Studio");fprintf(ficlog," Oracle Solaris Studio\n");/* Oracle Solaris Studio. ----------------------------------- */
1.167     brouard  5731: #endif
1.174     brouard  5732:    printf(" for ");fprintf(ficlog," for ");
1.169     brouard  5733:    
1.167     brouard  5734: // http://stackoverflow.com/questions/4605842/how-to-identify-platform-compiler-from-preprocessor-macros
                   5735: #ifdef _WIN32 // note the underscore: without it, it's not msdn official!
                   5736:     // Windows (x64 and x86)
1.174     brouard  5737:    printf("Windows (x64 and x86) ");fprintf(ficlog,"Windows (x64 and x86) ");
1.167     brouard  5738: #elif __unix__ // all unices, not all compilers
                   5739:     // Unix
1.174     brouard  5740:    printf("Unix ");fprintf(ficlog,"Unix ");
1.167     brouard  5741: #elif __linux__
                   5742:     // linux
1.174     brouard  5743:    printf("linux ");fprintf(ficlog,"linux ");
1.167     brouard  5744: #elif __APPLE__
1.174     brouard  5745:     // Mac OS, not sure if this is covered by __posix__ and/or __unix__ though..
                   5746:    printf("Mac OS ");fprintf(ficlog,"Mac OS ");
1.167     brouard  5747: #endif
                   5748: 
                   5749: /*  __MINGW32__          */
                   5750: /*  __CYGWIN__  */
                   5751: /* __MINGW64__  */
                   5752: // http://msdn.microsoft.com/en-us/library/b0084kay.aspx
                   5753: /* _MSC_VER  //the Visual C++ compiler is 17.00.51106.1, the _MSC_VER macro evaluates to 1700. Type cl /?  */
                   5754: /* _MSC_FULL_VER //the Visual C++ compiler is 15.00.20706.01, the _MSC_FULL_VER macro evaluates to 150020706 */
                   5755: /* _WIN64  // Defined for applications for Win64. */
                   5756: /* _M_X64 // Defined for compilations that target x64 processors. */
                   5757: /* _DEBUG // Defined when you compile with /LDd, /MDd, and /MTd. */
1.171     brouard  5758: 
1.167     brouard  5759: #if UINTPTR_MAX == 0xffffffff
1.174     brouard  5760:    printf(" 32-bit"); fprintf(ficlog," 32-bit");/* 32-bit */
1.167     brouard  5761: #elif UINTPTR_MAX == 0xffffffffffffffff
1.174     brouard  5762:    printf(" 64-bit"); fprintf(ficlog," 64-bit");/* 64-bit */
1.167     brouard  5763: #else
1.174     brouard  5764:    printf(" wtf-bit"); fprintf(ficlog," wtf-bit");/* wtf */
1.167     brouard  5765: #endif
                   5766: 
1.169     brouard  5767: #if defined(__GNUC__)
                   5768: # if defined(__GNUC_PATCHLEVEL__)
                   5769: #  define __GNUC_VERSION__ (__GNUC__ * 10000 \
                   5770:                             + __GNUC_MINOR__ * 100 \
                   5771:                             + __GNUC_PATCHLEVEL__)
                   5772: # else
                   5773: #  define __GNUC_VERSION__ (__GNUC__ * 10000 \
                   5774:                             + __GNUC_MINOR__ * 100)
                   5775: # endif
1.174     brouard  5776:    printf(" using GNU C version %d.\n", __GNUC_VERSION__);
                   5777:    fprintf(ficlog, " using GNU C version %d.\n", __GNUC_VERSION__);
1.176     brouard  5778: 
                   5779:    if (uname(&sysInfo) != -1) {
                   5780:      printf("Running on: %s %s %s %s %s\n",sysInfo.sysname, sysInfo.nodename, sysInfo.release, sysInfo.version, sysInfo.machine);
                   5781:      fprintf(ficlog,"Running on: %s %s %s %s %s\n ",sysInfo.sysname, sysInfo.nodename, sysInfo.release, sysInfo.version, sysInfo.machine);
                   5782:    }
                   5783:    else
                   5784:       perror("uname() error");
1.179     brouard  5785:    //#ifndef __INTEL_COMPILER 
                   5786: #if !defined (__INTEL_COMPILER) && !defined(__APPLE__)
1.174     brouard  5787:    printf("GNU libc version: %s\n", gnu_get_libc_version()); 
1.179     brouard  5788:    fprintf(ficlog,"GNU libc version: %s\n", gnu_get_libc_version());
1.177     brouard  5789: #endif
1.169     brouard  5790: #endif
1.172     brouard  5791: 
                   5792:    //   void main()
                   5793:    //   {
1.169     brouard  5794: #if defined(_MSC_VER)
1.174     brouard  5795:    if (IsWow64()){
1.176     brouard  5796:           printf("The program (probably compiled for 32bit) is running under WOW64 (64bit) emulation.\n");
                   5797:           fprintf(ficlog, "The program (probably compiled for 32bit) is running under WOW64 (64bit) emulation.\n");
1.174     brouard  5798:    }
                   5799:    else{
1.176     brouard  5800:           printf("The process is not running under WOW64 (i.e probably on a 64bit Windows).\n");
1.178     brouard  5801:           fprintf(ficlog,"The programm is not running under WOW64 (i.e probably on a 64bit Windows).\n");
1.174     brouard  5802:    }
1.172     brouard  5803:    //     printf("\nPress Enter to continue...");
                   5804:    //     getchar();
                   5805:    //   }
                   5806: 
1.169     brouard  5807: #endif
                   5808:    
1.167     brouard  5809: 
                   5810:  }
1.136     brouard  5811: 
1.180     brouard  5812: int prevalence_limit(double *p, double **prlim, double ageminpar, double agemaxpar){
                   5813:   /*--------------- Prevalence limit  (period or stable prevalence) --------------*/
                   5814:   int i, j, k, i1 ;
                   5815:   double ftolpl = 1.e-10;
                   5816:   double age, agebase, agelim;
                   5817: 
                   5818:     strcpy(filerespl,"pl");
                   5819:     strcat(filerespl,fileres);
                   5820:     if((ficrespl=fopen(filerespl,"w"))==NULL) {
                   5821:       printf("Problem with period (stable) prevalence resultfile: %s\n", filerespl);return 1;
                   5822:       fprintf(ficlog,"Problem with period (stable) prevalence resultfile: %s\n", filerespl);return 1;
                   5823:     }
                   5824:     printf("Computing period (stable) prevalence: result on file '%s' \n", filerespl);
                   5825:     fprintf(ficlog,"Computing period (stable) prevalence: result on file '%s' \n", filerespl);
                   5826:     pstamp(ficrespl);
                   5827:     fprintf(ficrespl,"# Period (stable) prevalence \n");
                   5828:     fprintf(ficrespl,"#Age ");
                   5829:     for(i=1; i<=nlstate;i++) fprintf(ficrespl,"%d-%d ",i,i);
                   5830:     fprintf(ficrespl,"\n");
                   5831:   
                   5832:     /* prlim=matrix(1,nlstate,1,nlstate);*/ /* back in main */
                   5833: 
                   5834:     agebase=ageminpar;
                   5835:     agelim=agemaxpar;
                   5836: 
                   5837:     i1=pow(2,cptcoveff);
                   5838:     if (cptcovn < 1){i1=1;}
                   5839: 
                   5840:     for(cptcov=1,k=0;cptcov<=i1;cptcov++){
                   5841:     /* for(cptcov=1,k=0;cptcov<=1;cptcov++){ */
                   5842:       //for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){
                   5843:        k=k+1;
                   5844:        /* to clean */
                   5845:        //printf("cptcov=%d cptcod=%d codtab=%d\n",cptcov, cptcod,codtab[cptcod][cptcov]);
                   5846:        fprintf(ficrespl,"\n#******");
                   5847:        printf("\n#******");
                   5848:        fprintf(ficlog,"\n#******");
                   5849:        for(j=1;j<=cptcoveff;j++) {
                   5850:          fprintf(ficrespl," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
                   5851:          printf(" V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
                   5852:          fprintf(ficlog," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
                   5853:        }
                   5854:        fprintf(ficrespl,"******\n");
                   5855:        printf("******\n");
                   5856:        fprintf(ficlog,"******\n");
                   5857: 
                   5858:        fprintf(ficrespl,"#Age ");
                   5859:        for(j=1;j<=cptcoveff;j++) {
                   5860:          fprintf(ficrespl,"V%d %d",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
                   5861:        }
                   5862:        for(i=1; i<=nlstate;i++) fprintf(ficrespl,"%d-%d ",i,i);
                   5863:        fprintf(ficrespl,"\n");
                   5864:        
                   5865:        for (age=agebase; age<=agelim; age++){
                   5866:        /* for (age=agebase; age<=agebase; age++){ */
                   5867:          prevalim(prlim, nlstate, p, age, oldm, savm,ftolpl,k);
                   5868:          fprintf(ficrespl,"%.0f ",age );
                   5869:          for(j=1;j<=cptcoveff;j++)
                   5870:            fprintf(ficrespl,"%d %d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
                   5871:          for(i=1; i<=nlstate;i++)
                   5872:            fprintf(ficrespl," %.5f", prlim[i][i]);
                   5873:          fprintf(ficrespl,"\n");
                   5874:        } /* Age */
                   5875:        /* was end of cptcod */
                   5876:     } /* cptcov */
1.184     brouard  5877:        return 0;
1.180     brouard  5878: }
                   5879: 
                   5880: int hPijx(double *p, int bage, int fage){
                   5881:     /*------------- h Pij x at various ages ------------*/
                   5882: 
                   5883:   int stepsize;
                   5884:   int agelim;
                   5885:   int hstepm;
                   5886:   int nhstepm;
                   5887:   int h, i, i1, j, k;
                   5888: 
                   5889:   double agedeb;
                   5890:   double ***p3mat;
                   5891: 
                   5892:     strcpy(filerespij,"pij");  strcat(filerespij,fileres);
                   5893:     if((ficrespij=fopen(filerespij,"w"))==NULL) {
                   5894:       printf("Problem with Pij resultfile: %s\n", filerespij); return 1;
                   5895:       fprintf(ficlog,"Problem with Pij resultfile: %s\n", filerespij); return 1;
                   5896:     }
                   5897:     printf("Computing pij: result on file '%s' \n", filerespij);
                   5898:     fprintf(ficlog,"Computing pij: result on file '%s' \n", filerespij);
                   5899:   
                   5900:     stepsize=(int) (stepm+YEARM-1)/YEARM;
                   5901:     /*if (stepm<=24) stepsize=2;*/
                   5902: 
                   5903:     agelim=AGESUP;
                   5904:     hstepm=stepsize*YEARM; /* Every year of age */
                   5905:     hstepm=hstepm/stepm; /* Typically 2 years, = 2/6 months = 4 */ 
                   5906: 
                   5907:     /* hstepm=1;   aff par mois*/
                   5908:     pstamp(ficrespij);
                   5909:     fprintf(ficrespij,"#****** h Pij x Probability to be in state j at age x+h being in i at x ");
                   5910:     i1= pow(2,cptcoveff);
1.183     brouard  5911:    /* for(cptcov=1,k=0;cptcov<=i1;cptcov++){ */
                   5912:    /*    /\*for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){*\/ */
                   5913:    /*          k=k+1;  */
                   5914:     for (k=1; k <= (int) pow(2,cptcoveff); k++){
                   5915:       fprintf(ficrespij,"\n#****** ");
                   5916:       for(j=1;j<=cptcoveff;j++) 
                   5917:        fprintf(ficrespij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
                   5918:       fprintf(ficrespij,"******\n");
                   5919:       
                   5920:       for (agedeb=fage; agedeb>=bage; agedeb--){ /* If stepm=6 months */
                   5921:        nhstepm=(int) rint((agelim-agedeb)*YEARM/stepm); /* Typically 20 years = 20*12/6=40 */ 
                   5922:        nhstepm = nhstepm/hstepm; /* Typically 40/4=10 */
                   5923:        
                   5924:        /*        nhstepm=nhstepm*YEARM; aff par mois*/
1.180     brouard  5925:        
1.183     brouard  5926:        p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   5927:        oldm=oldms;savm=savms;
                   5928:        hpxij(p3mat,nhstepm,agedeb,hstepm,p,nlstate,stepm,oldm,savm, k);  
                   5929:        fprintf(ficrespij,"# Cov Agex agex+h hpijx with i,j=");
                   5930:        for(i=1; i<=nlstate;i++)
                   5931:          for(j=1; j<=nlstate+ndeath;j++)
                   5932:            fprintf(ficrespij," %1d-%1d",i,j);
                   5933:        fprintf(ficrespij,"\n");
                   5934:        for (h=0; h<=nhstepm; h++){
                   5935:          /*agedebphstep = agedeb + h*hstepm/YEARM*stepm;*/
                   5936:          fprintf(ficrespij,"%d %3.f %3.f",k, agedeb, agedeb + h*hstepm/YEARM*stepm );
1.180     brouard  5937:          for(i=1; i<=nlstate;i++)
                   5938:            for(j=1; j<=nlstate+ndeath;j++)
1.183     brouard  5939:              fprintf(ficrespij," %.5f", p3mat[i][j][h]);
1.180     brouard  5940:          fprintf(ficrespij,"\n");
                   5941:        }
1.183     brouard  5942:        free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   5943:        fprintf(ficrespij,"\n");
                   5944:       }
1.180     brouard  5945:       /*}*/
                   5946:     }
1.184     brouard  5947:        return 0;
1.180     brouard  5948: }
                   5949: 
                   5950: 
1.136     brouard  5951: /***********************************************/
                   5952: /**************** Main Program *****************/
                   5953: /***********************************************/
                   5954: 
                   5955: int main(int argc, char *argv[])
                   5956: {
                   5957: #ifdef GSL
                   5958:   const gsl_multimin_fminimizer_type *T;
                   5959:   size_t iteri = 0, it;
                   5960:   int rval = GSL_CONTINUE;
                   5961:   int status = GSL_SUCCESS;
                   5962:   double ssval;
                   5963: #endif
                   5964:   int movingaverage(double ***probs, double bage,double fage, double ***mobaverage, int mobilav);
1.164     brouard  5965:   int i,j, k, n=MAXN,iter=0,m,size=100, cptcod;
                   5966: 
                   5967:   int jj, ll, li, lj, lk;
1.136     brouard  5968:   int numlinepar=0; /* Current linenumber of parameter file */
                   5969:   int itimes;
                   5970:   int NDIM=2;
                   5971:   int vpopbased=0;
                   5972: 
1.164     brouard  5973:   char ca[32], cb[32];
1.136     brouard  5974:   /*  FILE *fichtm; *//* Html File */
                   5975:   /* FILE *ficgp;*/ /*Gnuplot File */
                   5976:   struct stat info;
1.164     brouard  5977:   double agedeb;
1.136     brouard  5978:   double ageminpar=1.e20,agemin=1.e20, agemaxpar=-1.e20, agemax=-1.e20;
                   5979: 
1.165     brouard  5980:   double fret;
1.136     brouard  5981:   double dum; /* Dummy variable */
                   5982:   double ***p3mat;
                   5983:   double ***mobaverage;
1.164     brouard  5984: 
                   5985:   char line[MAXLINE];
1.136     brouard  5986:   char path[MAXLINE],pathc[MAXLINE],pathcd[MAXLINE],pathtot[MAXLINE],model[MAXLINE];
                   5987:   char pathr[MAXLINE], pathimach[MAXLINE]; 
1.164     brouard  5988:   char *tok, *val; /* pathtot */
1.136     brouard  5989:   int firstobs=1, lastobs=10;
1.164     brouard  5990:   int c,  h , cpt;
                   5991:   int jl;
                   5992:   int i1, j1, jk, stepsize;
                   5993:   int *tab; 
1.136     brouard  5994:   int mobilavproj=0 , prevfcast=0 ; /* moving average of prev, If prevfcast=1 prevalence projection */
                   5995:   int mobilav=0,popforecast=0;
                   5996:   int hstepm, nhstepm;
                   5997:   int agemortsup;
                   5998:   float  sumlpop=0.;
                   5999:   double jprev1=1, mprev1=1,anprev1=2000,jprev2=1, mprev2=1,anprev2=2000;
                   6000:   double jpyram=1, mpyram=1,anpyram=2000,jpyram1=1, mpyram1=1,anpyram1=2000;
                   6001: 
1.164     brouard  6002:   double bage=0, fage=110, age, agelim, agebase;
1.136     brouard  6003:   double ftolpl=FTOL;
                   6004:   double **prlim;
                   6005:   double ***param; /* Matrix of parameters */
                   6006:   double  *p;
                   6007:   double **matcov; /* Matrix of covariance */
                   6008:   double ***delti3; /* Scale */
                   6009:   double *delti; /* Scale */
                   6010:   double ***eij, ***vareij;
                   6011:   double **varpl; /* Variances of prevalence limits by age */
                   6012:   double *epj, vepp;
1.164     brouard  6013: 
1.136     brouard  6014:   double dateprev1, dateprev2,jproj1=1,mproj1=1,anproj1=2000,jproj2=1,mproj2=1,anproj2=2000;
                   6015:   double **ximort;
1.145     brouard  6016:   char *alph[]={"a","a","b","c","d","e"}, str[4]="1234";
1.136     brouard  6017:   int *dcwave;
                   6018: 
1.164     brouard  6019:   char z[1]="c";
1.136     brouard  6020: 
                   6021:   /*char  *strt;*/
                   6022:   char strtend[80];
1.126     brouard  6023: 
1.164     brouard  6024: 
1.126     brouard  6025: /*   setlocale (LC_ALL, ""); */
                   6026: /*   bindtextdomain (PACKAGE, LOCALEDIR); */
                   6027: /*   textdomain (PACKAGE); */
                   6028: /*   setlocale (LC_CTYPE, ""); */
                   6029: /*   setlocale (LC_MESSAGES, ""); */
                   6030: 
                   6031:   /*   gettimeofday(&start_time, (struct timezone*)0); */ /* at first time */
1.157     brouard  6032:   rstart_time = time(NULL);  
                   6033:   /*  (void) gettimeofday(&start_time,&tzp);*/
                   6034:   start_time = *localtime(&rstart_time);
1.126     brouard  6035:   curr_time=start_time;
1.157     brouard  6036:   /*tml = *localtime(&start_time.tm_sec);*/
                   6037:   /* strcpy(strstart,asctime(&tml)); */
                   6038:   strcpy(strstart,asctime(&start_time));
1.126     brouard  6039: 
                   6040: /*  printf("Localtime (at start)=%s",strstart); */
1.157     brouard  6041: /*  tp.tm_sec = tp.tm_sec +86400; */
                   6042: /*  tm = *localtime(&start_time.tm_sec); */
1.126     brouard  6043: /*   tmg.tm_year=tmg.tm_year +dsign*dyear; */
                   6044: /*   tmg.tm_mon=tmg.tm_mon +dsign*dmonth; */
                   6045: /*   tmg.tm_hour=tmg.tm_hour + 1; */
1.157     brouard  6046: /*   tp.tm_sec = mktime(&tmg); */
1.126     brouard  6047: /*   strt=asctime(&tmg); */
                   6048: /*   printf("Time(after) =%s",strstart);  */
                   6049: /*  (void) time (&time_value);
                   6050: *  printf("time=%d,t-=%d\n",time_value,time_value-86400);
                   6051: *  tm = *localtime(&time_value);
                   6052: *  strstart=asctime(&tm);
                   6053: *  printf("tim_value=%d,asctime=%s\n",time_value,strstart); 
                   6054: */
                   6055: 
                   6056:   nberr=0; /* Number of errors and warnings */
                   6057:   nbwarn=0;
1.184     brouard  6058: #ifdef WIN32
                   6059:   _getcwd(pathcd, size);
                   6060: #else
1.126     brouard  6061:   getcwd(pathcd, size);
1.184     brouard  6062: #endif
1.126     brouard  6063: 
                   6064:   printf("\n%s\n%s",version,fullversion);
                   6065:   if(argc <=1){
                   6066:     printf("\nEnter the parameter file name: ");
                   6067:     fgets(pathr,FILENAMELENGTH,stdin);
                   6068:     i=strlen(pathr);
                   6069:     if(pathr[i-1]=='\n')
                   6070:       pathr[i-1]='\0';
1.156     brouard  6071:     i=strlen(pathr);
                   6072:     if(pathr[i-1]==' ') /* This may happen when dragging on oS/X! */
                   6073:       pathr[i-1]='\0';
1.126     brouard  6074:    for (tok = pathr; tok != NULL; ){
                   6075:       printf("Pathr |%s|\n",pathr);
                   6076:       while ((val = strsep(&tok, "\"" )) != NULL && *val == '\0');
                   6077:       printf("val= |%s| pathr=%s\n",val,pathr);
                   6078:       strcpy (pathtot, val);
                   6079:       if(pathr[0] == '\0') break; /* Dirty */
                   6080:     }
                   6081:   }
                   6082:   else{
                   6083:     strcpy(pathtot,argv[1]);
                   6084:   }
                   6085:   /*if(getcwd(pathcd, MAXLINE)!= NULL)printf ("Error pathcd\n");*/
                   6086:   /*cygwin_split_path(pathtot,path,optionfile);
                   6087:     printf("pathtot=%s, path=%s, optionfile=%s\n",pathtot,path,optionfile);*/
                   6088:   /* cutv(path,optionfile,pathtot,'\\');*/
                   6089: 
                   6090:   /* Split argv[0], imach program to get pathimach */
                   6091:   printf("\nargv[0]=%s argv[1]=%s, \n",argv[0],argv[1]);
                   6092:   split(argv[0],pathimach,optionfile,optionfilext,optionfilefiname);
                   6093:   printf("\nargv[0]=%s pathimach=%s, \noptionfile=%s \noptionfilext=%s \noptionfilefiname=%s\n",argv[0],pathimach,optionfile,optionfilext,optionfilefiname);
                   6094:  /*   strcpy(pathimach,argv[0]); */
                   6095:   /* Split argv[1]=pathtot, parameter file name to get path, optionfile, extension and name */
                   6096:   split(pathtot,path,optionfile,optionfilext,optionfilefiname);
                   6097:   printf("\npathtot=%s,\npath=%s,\noptionfile=%s \noptionfilext=%s \noptionfilefiname=%s\n",pathtot,path,optionfile,optionfilext,optionfilefiname);
1.184     brouard  6098: #ifdef WIN32
                   6099:   _chdir(path); /* Can be a relative path */
                   6100:   if(_getcwd(pathcd,MAXLINE) > 0) /* So pathcd is the full path */
                   6101: #else
1.126     brouard  6102:   chdir(path); /* Can be a relative path */
1.184     brouard  6103:   if (getcwd(pathcd, MAXLINE) > 0) /* So pathcd is the full path */
                   6104: #endif
                   6105:   printf("Current directory %s!\n",pathcd);
1.126     brouard  6106:   strcpy(command,"mkdir ");
                   6107:   strcat(command,optionfilefiname);
                   6108:   if((outcmd=system(command)) != 0){
1.169     brouard  6109:     printf("Directory already exists (or can't create it) %s%s, err=%d\n",path,optionfilefiname,outcmd);
1.126     brouard  6110:     /* fprintf(ficlog,"Problem creating directory %s%s\n",path,optionfilefiname); */
                   6111:     /* fclose(ficlog); */
                   6112: /*     exit(1); */
                   6113:   }
                   6114: /*   if((imk=mkdir(optionfilefiname))<0){ */
                   6115: /*     perror("mkdir"); */
                   6116: /*   } */
                   6117: 
                   6118:   /*-------- arguments in the command line --------*/
                   6119: 
1.186   ! brouard  6120:   /* Main Log file */
1.126     brouard  6121:   strcat(filelog, optionfilefiname);
                   6122:   strcat(filelog,".log");    /* */
                   6123:   if((ficlog=fopen(filelog,"w"))==NULL)    {
                   6124:     printf("Problem with logfile %s\n",filelog);
                   6125:     goto end;
                   6126:   }
                   6127:   fprintf(ficlog,"Log filename:%s\n",filelog);
                   6128:   fprintf(ficlog,"\n%s\n%s",version,fullversion);
                   6129:   fprintf(ficlog,"\nEnter the parameter file name: \n");
                   6130:   fprintf(ficlog,"pathimach=%s\npathtot=%s\n\
                   6131:  path=%s \n\
                   6132:  optionfile=%s\n\
                   6133:  optionfilext=%s\n\
1.156     brouard  6134:  optionfilefiname='%s'\n",pathimach,pathtot,path,optionfile,optionfilext,optionfilefiname);
1.126     brouard  6135: 
1.167     brouard  6136:   syscompilerinfo();
                   6137: 
1.126     brouard  6138:   printf("Local time (at start):%s",strstart);
                   6139:   fprintf(ficlog,"Local time (at start): %s",strstart);
                   6140:   fflush(ficlog);
                   6141: /*   (void) gettimeofday(&curr_time,&tzp); */
1.157     brouard  6142: /*   printf("Elapsed time %d\n", asc_diff_time(curr_time.tm_sec-start_time.tm_sec,tmpout)); */
1.126     brouard  6143: 
                   6144:   /* */
                   6145:   strcpy(fileres,"r");
                   6146:   strcat(fileres, optionfilefiname);
                   6147:   strcat(fileres,".txt");    /* Other files have txt extension */
                   6148: 
1.186   ! brouard  6149:   /* Main ---------arguments file --------*/
1.126     brouard  6150: 
                   6151:   if((ficpar=fopen(optionfile,"r"))==NULL)    {
1.155     brouard  6152:     printf("Problem with optionfile '%s' with errno='%s'\n",optionfile,strerror(errno));
                   6153:     fprintf(ficlog,"Problem with optionfile '%s' with errno='%s'\n",optionfile,strerror(errno));
1.126     brouard  6154:     fflush(ficlog);
1.149     brouard  6155:     /* goto end; */
                   6156:     exit(70); 
1.126     brouard  6157:   }
                   6158: 
                   6159: 
                   6160: 
                   6161:   strcpy(filereso,"o");
                   6162:   strcat(filereso,fileres);
                   6163:   if((ficparo=fopen(filereso,"w"))==NULL) { /* opened on subdirectory */
                   6164:     printf("Problem with Output resultfile: %s\n", filereso);
                   6165:     fprintf(ficlog,"Problem with Output resultfile: %s\n", filereso);
                   6166:     fflush(ficlog);
                   6167:     goto end;
                   6168:   }
                   6169: 
                   6170:   /* Reads comments: lines beginning with '#' */
                   6171:   numlinepar=0;
                   6172:   while((c=getc(ficpar))=='#' && c!= EOF){
                   6173:     ungetc(c,ficpar);
                   6174:     fgets(line, MAXLINE, ficpar);
                   6175:     numlinepar++;
1.141     brouard  6176:     fputs(line,stdout);
1.126     brouard  6177:     fputs(line,ficparo);
                   6178:     fputs(line,ficlog);
                   6179:   }
                   6180:   ungetc(c,ficpar);
                   6181: 
                   6182:   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);
                   6183:   numlinepar++;
1.186   ! brouard  6184:   /* 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); */
        !          6185:   printf("title=%s datafile=%s lastobs=%d firstpass=%d lastpass=%d\n",title, datafile, lastobs, firstpass,lastpass);
        !          6186:   /*
        !          6187: 
        !          6188: 
        !          6189: 
        !          6190:    */
        !          6191:   printf("\nftol=%e \n", ftol);
        !          6192:   printf("stepm=%d \n", stepm);
        !          6193:   printf("ncovcol=%d nlstate=%d \n", ncovcol, nlstate);
        !          6194:   printf("ndeath=%d maxwav=%d mle=%d weight=%d\n", ndeath, maxwav, mle, weightopt);
        !          6195:   printf("model=%s\n",model);
1.126     brouard  6196:   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);
                   6197:   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);
                   6198:   fflush(ficlog);
                   6199:   while((c=getc(ficpar))=='#' && c!= EOF){
                   6200:     ungetc(c,ficpar);
                   6201:     fgets(line, MAXLINE, ficpar);
                   6202:     numlinepar++;
1.141     brouard  6203:     fputs(line, stdout);
                   6204:     //puts(line);
1.126     brouard  6205:     fputs(line,ficparo);
                   6206:     fputs(line,ficlog);
                   6207:   }
                   6208:   ungetc(c,ficpar);
                   6209: 
                   6210:    
1.145     brouard  6211:   covar=matrix(0,NCOVMAX,1,n);  /**< used in readdata */
1.136     brouard  6212:   cptcovn=0; /*Number of covariates, i.e. number of '+' in model statement plus one, indepently of n in Vn*/
                   6213:   /* v1+v2+v3+v2*v4+v5*age makes cptcovn = 5
                   6214:      v1+v2*age+v2*v3 makes cptcovn = 3
                   6215:   */
                   6216:   if (strlen(model)>1) 
1.145     brouard  6217:     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*/
                   6218:   else
                   6219:     ncovmodel=2;
1.126     brouard  6220:   nvar=ncovmodel-1; /* Suppressing age as a basic covariate */
1.133     brouard  6221:   nforce= (nlstate+ndeath-1)*nlstate; /* Number of forces ij from state i to j */
                   6222:   npar= nforce*ncovmodel; /* Number of parameters like aij*/
1.131     brouard  6223:   if(npar >MAXPARM || nlstate >NLSTATEMAX || ndeath >NDEATHMAX || ncovmodel>NCOVMAX){
                   6224:     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);
                   6225:     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);
                   6226:     fflush(stdout);
                   6227:     fclose (ficlog);
                   6228:     goto end;
                   6229:   }
1.126     brouard  6230:   delti3= ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel);
                   6231:   delti=delti3[1][1];
                   6232:   /*delti=vector(1,npar); *//* Scale of each paramater (output from hesscov)*/
                   6233:   if(mle==-1){ /* Print a wizard for help writing covariance matrix */
                   6234:     prwizard(ncovmodel, nlstate, ndeath, model, ficparo);
                   6235:     printf(" You choose mle=-1, look at file %s for a template of covariance matrix \n",filereso);
                   6236:     fprintf(ficlog," You choose mle=-1, look at file %s for a template of covariance matrix \n",filereso);
                   6237:     free_ma3x(delti3,1,nlstate,1, nlstate+ndeath-1,1,ncovmodel); 
                   6238:     fclose (ficparo);
                   6239:     fclose (ficlog);
                   6240:     goto end;
                   6241:     exit(0);
                   6242:   }
1.186   ! brouard  6243:   else if(mle==-3) { /* Main Wizard */
1.126     brouard  6244:     prwizard(ncovmodel, nlstate, ndeath, model, ficparo);
                   6245:     printf(" You choose mle=-3, look at file %s for a template of covariance matrix \n",filereso);
                   6246:     fprintf(ficlog," You choose mle=-3, look at file %s for a template of covariance matrix \n",filereso);
                   6247:     param= ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel);
                   6248:     matcov=matrix(1,npar,1,npar);
                   6249:   }
                   6250:   else{
1.145     brouard  6251:     /* Read guessed parameters */
1.126     brouard  6252:     /* Reads comments: lines beginning with '#' */
                   6253:     while((c=getc(ficpar))=='#' && c!= EOF){
                   6254:       ungetc(c,ficpar);
                   6255:       fgets(line, MAXLINE, ficpar);
                   6256:       numlinepar++;
1.141     brouard  6257:       fputs(line,stdout);
1.126     brouard  6258:       fputs(line,ficparo);
                   6259:       fputs(line,ficlog);
                   6260:     }
                   6261:     ungetc(c,ficpar);
                   6262:     
                   6263:     param= ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel);
                   6264:     for(i=1; i <=nlstate; i++){
                   6265:       j=0;
                   6266:       for(jj=1; jj <=nlstate+ndeath; jj++){
                   6267:        if(jj==i) continue;
                   6268:        j++;
                   6269:        fscanf(ficpar,"%1d%1d",&i1,&j1);
                   6270:        if ((i1 != i) && (j1 != j)){
                   6271:          printf("Error in line parameters number %d, %1d%1d instead of %1d%1d \n \
                   6272: It might be a problem of design; if ncovcol and the model are correct\n \
                   6273: run imach with mle=-1 to get a correct template of the parameter file.\n",numlinepar, i,j, i1, j1);
                   6274:          exit(1);
                   6275:        }
                   6276:        fprintf(ficparo,"%1d%1d",i1,j1);
                   6277:        if(mle==1)
                   6278:          printf("%1d%1d",i,j);
                   6279:        fprintf(ficlog,"%1d%1d",i,j);
                   6280:        for(k=1; k<=ncovmodel;k++){
                   6281:          fscanf(ficpar," %lf",&param[i][j][k]);
                   6282:          if(mle==1){
                   6283:            printf(" %lf",param[i][j][k]);
                   6284:            fprintf(ficlog," %lf",param[i][j][k]);
                   6285:          }
                   6286:          else
                   6287:            fprintf(ficlog," %lf",param[i][j][k]);
                   6288:          fprintf(ficparo," %lf",param[i][j][k]);
                   6289:        }
                   6290:        fscanf(ficpar,"\n");
                   6291:        numlinepar++;
                   6292:        if(mle==1)
                   6293:          printf("\n");
                   6294:        fprintf(ficlog,"\n");
                   6295:        fprintf(ficparo,"\n");
                   6296:       }
                   6297:     }  
                   6298:     fflush(ficlog);
                   6299: 
1.145     brouard  6300:     /* Reads scales values */
1.126     brouard  6301:     p=param[1][1];
                   6302:     
                   6303:     /* Reads comments: lines beginning with '#' */
                   6304:     while((c=getc(ficpar))=='#' && c!= EOF){
                   6305:       ungetc(c,ficpar);
                   6306:       fgets(line, MAXLINE, ficpar);
                   6307:       numlinepar++;
1.141     brouard  6308:       fputs(line,stdout);
1.126     brouard  6309:       fputs(line,ficparo);
                   6310:       fputs(line,ficlog);
                   6311:     }
                   6312:     ungetc(c,ficpar);
                   6313: 
                   6314:     for(i=1; i <=nlstate; i++){
                   6315:       for(j=1; j <=nlstate+ndeath-1; j++){
                   6316:        fscanf(ficpar,"%1d%1d",&i1,&j1);
1.164     brouard  6317:        if ( (i1-i) * (j1-j) != 0){
1.126     brouard  6318:          printf("Error in line parameters number %d, %1d%1d instead of %1d%1d \n",numlinepar, i,j, i1, j1);
                   6319:          exit(1);
                   6320:        }
                   6321:        printf("%1d%1d",i,j);
                   6322:        fprintf(ficparo,"%1d%1d",i1,j1);
                   6323:        fprintf(ficlog,"%1d%1d",i1,j1);
                   6324:        for(k=1; k<=ncovmodel;k++){
                   6325:          fscanf(ficpar,"%le",&delti3[i][j][k]);
                   6326:          printf(" %le",delti3[i][j][k]);
                   6327:          fprintf(ficparo," %le",delti3[i][j][k]);
                   6328:          fprintf(ficlog," %le",delti3[i][j][k]);
                   6329:        }
                   6330:        fscanf(ficpar,"\n");
                   6331:        numlinepar++;
                   6332:        printf("\n");
                   6333:        fprintf(ficparo,"\n");
                   6334:        fprintf(ficlog,"\n");
                   6335:       }
                   6336:     }
                   6337:     fflush(ficlog);
                   6338: 
1.145     brouard  6339:     /* Reads covariance matrix */
1.126     brouard  6340:     delti=delti3[1][1];
                   6341: 
                   6342: 
                   6343:     /* free_ma3x(delti3,1,nlstate,1,nlstate+ndeath-1,1,ncovmodel); */ /* Hasn't to to freed here otherwise delti is no more allocated */
                   6344:   
                   6345:     /* Reads comments: lines beginning with '#' */
                   6346:     while((c=getc(ficpar))=='#' && c!= EOF){
                   6347:       ungetc(c,ficpar);
                   6348:       fgets(line, MAXLINE, ficpar);
                   6349:       numlinepar++;
1.141     brouard  6350:       fputs(line,stdout);
1.126     brouard  6351:       fputs(line,ficparo);
                   6352:       fputs(line,ficlog);
                   6353:     }
                   6354:     ungetc(c,ficpar);
                   6355:   
                   6356:     matcov=matrix(1,npar,1,npar);
1.131     brouard  6357:     for(i=1; i <=npar; i++)
                   6358:       for(j=1; j <=npar; j++) matcov[i][j]=0.;
                   6359:       
1.126     brouard  6360:     for(i=1; i <=npar; i++){
1.145     brouard  6361:       fscanf(ficpar,"%s",str);
1.126     brouard  6362:       if(mle==1)
                   6363:        printf("%s",str);
                   6364:       fprintf(ficlog,"%s",str);
                   6365:       fprintf(ficparo,"%s",str);
                   6366:       for(j=1; j <=i; j++){
                   6367:        fscanf(ficpar," %le",&matcov[i][j]);
                   6368:        if(mle==1){
                   6369:          printf(" %.5le",matcov[i][j]);
                   6370:        }
                   6371:        fprintf(ficlog," %.5le",matcov[i][j]);
                   6372:        fprintf(ficparo," %.5le",matcov[i][j]);
                   6373:       }
                   6374:       fscanf(ficpar,"\n");
                   6375:       numlinepar++;
                   6376:       if(mle==1)
                   6377:        printf("\n");
                   6378:       fprintf(ficlog,"\n");
                   6379:       fprintf(ficparo,"\n");
                   6380:     }
                   6381:     for(i=1; i <=npar; i++)
                   6382:       for(j=i+1;j<=npar;j++)
                   6383:        matcov[i][j]=matcov[j][i];
                   6384:     
                   6385:     if(mle==1)
                   6386:       printf("\n");
                   6387:     fprintf(ficlog,"\n");
                   6388:     
                   6389:     fflush(ficlog);
                   6390:     
                   6391:     /*-------- Rewriting parameter file ----------*/
                   6392:     strcpy(rfileres,"r");    /* "Rparameterfile */
                   6393:     strcat(rfileres,optionfilefiname);    /* Parameter file first name*/
                   6394:     strcat(rfileres,".");    /* */
                   6395:     strcat(rfileres,optionfilext);    /* Other files have txt extension */
                   6396:     if((ficres =fopen(rfileres,"w"))==NULL) {
                   6397:       printf("Problem writing new parameter file: %s\n", fileres);goto end;
                   6398:       fprintf(ficlog,"Problem writing new parameter file: %s\n", fileres);goto end;
                   6399:     }
                   6400:     fprintf(ficres,"#%s\n",version);
                   6401:   }    /* End of mle != -3 */
                   6402: 
1.186   ! brouard  6403:   /*  Main data
        !          6404:    */
1.126     brouard  6405:   n= lastobs;
                   6406:   num=lvector(1,n);
                   6407:   moisnais=vector(1,n);
                   6408:   annais=vector(1,n);
                   6409:   moisdc=vector(1,n);
                   6410:   andc=vector(1,n);
                   6411:   agedc=vector(1,n);
                   6412:   cod=ivector(1,n);
                   6413:   weight=vector(1,n);
                   6414:   for(i=1;i<=n;i++) weight[i]=1.0; /* Equal weights, 1 by default */
                   6415:   mint=matrix(1,maxwav,1,n);
                   6416:   anint=matrix(1,maxwav,1,n);
1.131     brouard  6417:   s=imatrix(1,maxwav+1,1,n); /* s[i][j] health state for wave i and individual j */ 
1.126     brouard  6418:   tab=ivector(1,NCOVMAX);
1.144     brouard  6419:   ncodemax=ivector(1,NCOVMAX); /* Number of code per covariate; if O and 1 only, 2**ncov; V1+V2+V3+V4=>16 */
1.126     brouard  6420: 
1.136     brouard  6421:   /* Reads data from file datafile */
                   6422:   if (readdata(datafile, firstobs, lastobs, &imx)==1)
                   6423:     goto end;
                   6424: 
                   6425:   /* Calculation of the number of parameters from char model */
1.137     brouard  6426:     /*    modelsav=V2+V1+V4+age*V3 strb=age*V3 stra=V2+V1+V4 
                   6427:        k=4 (age*V3) Tvar[k=4]= 3 (from V3) Tag[cptcovage=1]=4
                   6428:        k=3 V4 Tvar[k=3]= 4 (from V4)
                   6429:        k=2 V1 Tvar[k=2]= 1 (from V1)
                   6430:        k=1 Tvar[1]=2 (from V2)
                   6431:     */
                   6432:   Tvar=ivector(1,NCOVMAX); /* Was 15 changed to NCOVMAX. */
                   6433:   /*  V2+V1+V4+age*V3 is a model with 4 covariates (3 plus signs). 
                   6434:       For each model-covariate stores the data-covariate id. Tvar[1]=2, Tvar[2]=1, Tvar[3]=4, 
                   6435:       Tvar[4=age*V3] is 3 and 'age' is recorded in Tage.
                   6436:   */
                   6437:   /* For model-covariate k tells which data-covariate to use but
                   6438:     because this model-covariate is a construction we invent a new column
                   6439:     ncovcol + k1
                   6440:     If already ncovcol=4 and model=V2+V1+V1*V4+age*V3
                   6441:     Tvar[3=V1*V4]=4+1 etc */
1.145     brouard  6442:   Tprod=ivector(1,NCOVMAX); /* Gives the position of a product */
1.137     brouard  6443:   /* Tprod[k1=1]=3(=V1*V4) for V2+V1+V1*V4+age*V3
                   6444:      if  V2+V1+V1*V4+age*V3+V3*V2   TProd[k1=2]=5 (V3*V2)
                   6445:   */
1.145     brouard  6446:   Tvaraff=ivector(1,NCOVMAX); /* Unclear */
                   6447:   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  6448:                            * For V3*V2 (in V2+V1+V1*V4+age*V3+V3*V2), V3*V2 position is 2nd. 
                   6449:                            * Tvard[k1=2][1]=3 (V3) Tvard[k1=2][2]=2(V2) */
1.145     brouard  6450:   Tage=ivector(1,NCOVMAX); /* Gives the covariate id of covariates associated with age: V2 + V1 + age*V4 + V3*age
1.137     brouard  6451:                         4 covariates (3 plus signs)
                   6452:                         Tage[1=V3*age]= 4; Tage[2=age*V4] = 3
                   6453:                      */  
1.136     brouard  6454: 
1.186   ! brouard  6455: /* Main decodemodel */
        !          6456: 
1.136     brouard  6457:   if(decodemodel(model, lastobs) == 1)
                   6458:     goto end;
                   6459: 
1.137     brouard  6460:   if((double)(lastobs-imx)/(double)imx > 1.10){
                   6461:     nbwarn++;
                   6462:     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); 
                   6463:     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); 
                   6464:   }
1.136     brouard  6465:     /*  if(mle==1){*/
1.137     brouard  6466:   if (weightopt != 1) { /* Maximisation without weights. We can have weights different from 1 but want no weight*/
                   6467:     for(i=1;i<=imx;i++) weight[i]=1.0; /* changed to imx */
1.136     brouard  6468:   }
                   6469: 
                   6470:     /*-calculation of age at interview from date of interview and age at death -*/
                   6471:   agev=matrix(1,maxwav,1,imx);
                   6472: 
                   6473:   if(calandcheckages(imx, maxwav, &agemin, &agemax, &nberr, &nbwarn) == 1)
                   6474:     goto end;
                   6475: 
1.126     brouard  6476: 
1.136     brouard  6477:   agegomp=(int)agemin;
                   6478:   free_vector(moisnais,1,n);
                   6479:   free_vector(annais,1,n);
1.126     brouard  6480:   /* free_matrix(mint,1,maxwav,1,n);
                   6481:      free_matrix(anint,1,maxwav,1,n);*/
                   6482:   free_vector(moisdc,1,n);
                   6483:   free_vector(andc,1,n);
1.145     brouard  6484:   /* */
                   6485:   
1.126     brouard  6486:   wav=ivector(1,imx);
                   6487:   dh=imatrix(1,lastpass-firstpass+1,1,imx);
                   6488:   bh=imatrix(1,lastpass-firstpass+1,1,imx);
                   6489:   mw=imatrix(1,lastpass-firstpass+1,1,imx);
                   6490:    
                   6491:   /* Concatenates waves */
                   6492:   concatwav(wav, dh, bh, mw, s, agedc, agev,  firstpass, lastpass, imx, nlstate, stepm);
1.145     brouard  6493:   /* */
                   6494:  
1.126     brouard  6495:   /* Routine tricode is to calculate cptcoveff (real number of unique covariates) and to associate covariable number and modality */
                   6496: 
                   6497:   nbcode=imatrix(0,NCOVMAX,0,NCOVMAX); 
                   6498:   ncodemax[1]=1;
1.145     brouard  6499:   Ndum =ivector(-1,NCOVMAX);  
                   6500:   if (ncovmodel > 2)
                   6501:     tricode(Tvar,nbcode,imx, Ndum); /**< Fills nbcode[Tvar[j]][l]; */
1.186   ! brouard  6502:   /* Nbcode gives the value of the lth modality of jth covariate, in
        !          6503:      V2+V1*age, there are 3 covariates Tvar[2]=1 (V1).*/
        !          6504:   /* 1 to ncodemax[j] is the maximum value of this jth covariate */
1.145     brouard  6505: 
                   6506:   codtab=imatrix(1,100,1,10); /* codtab[h,k]=( (h-1) - mod(k-1,2**(k-1) )/2**(k-1) */
                   6507:   /*printf(" codtab[1,1],codtab[100,10]=%d,%d\n", codtab[1][1],codtab[100][10]);*/
1.186   ! brouard  6508:   /* codtab gives the value 1 or 2 of the hth combination of k covariates (1 or 2).*/
1.145     brouard  6509:   h=0;
                   6510: 
                   6511: 
                   6512:   /*if (cptcovn > 0) */
1.126     brouard  6513:       
1.145     brouard  6514:  
1.126     brouard  6515:   m=pow(2,cptcoveff);
                   6516:  
1.131     brouard  6517:   for(k=1;k<=cptcoveff; k++){ /* scans any effective covariate */
1.143     brouard  6518:     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 */ 
                   6519:       for(j=1; j <= ncodemax[k]; j++){ /* For each modality of this covariate ncodemax=2*/
                   6520:        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  6521:          h++;
1.141     brouard  6522:          if (h>m) 
1.136     brouard  6523:            h=1;
1.144     brouard  6524:          /**< codtab(h,k)  k   = codtab[h,k]=( (h-1) - mod(k-1,2**(k-1) )/2**(k-1) + 1
1.186   ! brouard  6525:           * For k=4 covariates, h goes from 1 to 2**k
        !          6526:           * codtabm(h,k)=  1 & (h-1) >> (k-1) ;
        !          6527:           *     h\k   1     2     3     4
1.143     brouard  6528:           *______________________________  
                   6529:           *     1 i=1 1 i=1 1 i=1 1 i=1 1
                   6530:           *     2     2     1     1     1
                   6531:           *     3 i=2 1     2     1     1
                   6532:           *     4     2     2     1     1
                   6533:           *     5 i=3 1 i=2 1     2     1
                   6534:           *     6     2     1     2     1
                   6535:           *     7 i=4 1     2     2     1
                   6536:           *     8     2     2     2     1
                   6537:           *     9 i=5 1 i=3 1 i=2 1     1
                   6538:           *    10     2     1     1     1
                   6539:           *    11 i=6 1     2     1     1
                   6540:           *    12     2     2     1     1
                   6541:           *    13 i=7 1 i=4 1     2     1    
                   6542:           *    14     2     1     2     1
                   6543:           *    15 i=8 1     2     2     1
                   6544:           *    16     2     2     2     1
                   6545:           */
1.141     brouard  6546:          codtab[h][k]=j;
1.186   ! brouard  6547:          /* codtab[12][3]=1; */
1.145     brouard  6548:          /*codtab[h][Tvar[k]]=j;*/
1.130     brouard  6549:          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  6550:        } 
                   6551:       }
                   6552:     }
                   6553:   } 
                   6554:   /* printf("codtab[1][2]=%d codtab[2][2]=%d",codtab[1][2],codtab[2][2]); 
                   6555:      codtab[1][2]=1;codtab[2][2]=2; */
                   6556:   /* for(i=1; i <=m ;i++){ 
                   6557:      for(k=1; k <=cptcovn; k++){
1.131     brouard  6558:        printf("i=%d k=%d %d %d ",i,k,codtab[i][k], cptcoveff);
1.126     brouard  6559:      }
                   6560:      printf("\n");
                   6561:      }
                   6562:      scanf("%d",i);*/
1.145     brouard  6563: 
                   6564:  free_ivector(Ndum,-1,NCOVMAX);
                   6565: 
                   6566: 
1.126     brouard  6567:     
1.186   ! brouard  6568:   /* Initialisation of ----------- gnuplot -------------*/
1.126     brouard  6569:   strcpy(optionfilegnuplot,optionfilefiname);
                   6570:   if(mle==-3)
                   6571:     strcat(optionfilegnuplot,"-mort");
                   6572:   strcat(optionfilegnuplot,".gp");
                   6573: 
                   6574:   if((ficgp=fopen(optionfilegnuplot,"w"))==NULL) {
                   6575:     printf("Problem with file %s",optionfilegnuplot);
                   6576:   }
                   6577:   else{
                   6578:     fprintf(ficgp,"\n# %s\n", version); 
                   6579:     fprintf(ficgp,"# %s\n", optionfilegnuplot); 
1.141     brouard  6580:     //fprintf(ficgp,"set missing 'NaNq'\n");
                   6581:     fprintf(ficgp,"set datafile missing 'NaNq'\n");
1.126     brouard  6582:   }
                   6583:   /*  fclose(ficgp);*/
1.186   ! brouard  6584: 
        !          6585: 
        !          6586:   /* Initialisation of --------- index.htm --------*/
1.126     brouard  6587: 
                   6588:   strcpy(optionfilehtm,optionfilefiname); /* Main html file */
                   6589:   if(mle==-3)
                   6590:     strcat(optionfilehtm,"-mort");
                   6591:   strcat(optionfilehtm,".htm");
                   6592:   if((fichtm=fopen(optionfilehtm,"w"))==NULL)    {
1.131     brouard  6593:     printf("Problem with %s \n",optionfilehtm);
                   6594:     exit(0);
1.126     brouard  6595:   }
                   6596: 
                   6597:   strcpy(optionfilehtmcov,optionfilefiname); /* Only for matrix of covariance */
                   6598:   strcat(optionfilehtmcov,"-cov.htm");
                   6599:   if((fichtmcov=fopen(optionfilehtmcov,"w"))==NULL)    {
                   6600:     printf("Problem with %s \n",optionfilehtmcov), exit(0);
                   6601:   }
                   6602:   else{
                   6603:   fprintf(fichtmcov,"<html><head>\n<title>IMaCh Cov %s</title></head>\n <body><font size=\"2\">%s <br> %s</font> \
                   6604: <hr size=\"2\" color=\"#EC5E5E\"> \n\
                   6605: Title=%s <br>Datafile=%s Firstpass=%d Lastpass=%d Stepm=%d Weight=%d Model=%s<br>\n",\
                   6606:          optionfilehtmcov,version,fullversion,title,datafile,firstpass,lastpass,stepm, weightopt, model);
                   6607:   }
                   6608: 
                   6609:   fprintf(fichtm,"<html><head>\n<title>IMaCh %s</title></head>\n <body><font size=\"2\">%s <br> %s</font> \
                   6610: <hr size=\"2\" color=\"#EC5E5E\"> \n\
                   6611: Title=%s <br>Datafile=%s Firstpass=%d Lastpass=%d Stepm=%d Weight=%d Model=%s<br>\n\
                   6612: \n\
                   6613: <hr  size=\"2\" color=\"#EC5E5E\">\
                   6614:  <ul><li><h4>Parameter files</h4>\n\
                   6615:  - Parameter file: <a href=\"%s.%s\">%s.%s</a><br>\n\
                   6616:  - Copy of the parameter file: <a href=\"o%s\">o%s</a><br>\n\
                   6617:  - Log file of the run: <a href=\"%s\">%s</a><br>\n\
                   6618:  - Gnuplot file name: <a href=\"%s\">%s</a><br>\n\
                   6619:  - Date and time at start: %s</ul>\n",\
                   6620:          optionfilehtm,version,fullversion,title,datafile,firstpass,lastpass,stepm, weightopt, model,\
                   6621:          optionfilefiname,optionfilext,optionfilefiname,optionfilext,\
                   6622:          fileres,fileres,\
                   6623:          filelog,filelog,optionfilegnuplot,optionfilegnuplot,strstart);
                   6624:   fflush(fichtm);
                   6625: 
                   6626:   strcpy(pathr,path);
                   6627:   strcat(pathr,optionfilefiname);
1.184     brouard  6628: #ifdef WIN32
                   6629:   _chdir(optionfilefiname); /* Move to directory named optionfile */
                   6630: #else
1.126     brouard  6631:   chdir(optionfilefiname); /* Move to directory named optionfile */
1.184     brouard  6632: #endif
                   6633:          
1.126     brouard  6634:   
                   6635:   /* Calculates basic frequencies. Computes observed prevalence at single age
                   6636:      and prints on file fileres'p'. */
                   6637:   freqsummary(fileres, agemin, agemax, s, agev, nlstate, imx,Tvaraff,nbcode, ncodemax,mint,anint,strstart);
                   6638: 
                   6639:   fprintf(fichtm,"\n");
                   6640:   fprintf(fichtm,"<br>Total number of observations=%d <br>\n\
                   6641: Youngest age at first (selected) pass %.2f, oldest age %.2f<br>\n\
                   6642: Interval (in months) between two waves: Min=%d Max=%d Mean=%.2lf<br>\n",\
                   6643:          imx,agemin,agemax,jmin,jmax,jmean);
                   6644:   pmmij= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
                   6645:     oldms= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
                   6646:     newms= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
                   6647:     savms= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
                   6648:     oldm=oldms; newm=newms; savm=savms; /* Keeps fixed addresses to free */
                   6649:     
                   6650:    
                   6651:   /* For Powell, parameters are in a vector p[] starting at p[1]
                   6652:      so we point p on param[1][1] so that p[1] maps on param[1][1][1] */
                   6653:   p=param[1][1]; /* *(*(*(param +1)+1)+0) */
                   6654: 
                   6655:   globpr=0; /* To get the number ipmx of contributions and the sum of weights*/
1.186   ! brouard  6656:   /* For mortality only */
1.126     brouard  6657:   if (mle==-3){
1.136     brouard  6658:     ximort=matrix(1,NDIM,1,NDIM); 
1.186   ! brouard  6659:     /*     ximort=gsl_matrix_alloc(1,NDIM,1,NDIM); */
1.126     brouard  6660:     cens=ivector(1,n);
                   6661:     ageexmed=vector(1,n);
                   6662:     agecens=vector(1,n);
                   6663:     dcwave=ivector(1,n);
                   6664:  
                   6665:     for (i=1; i<=imx; i++){
                   6666:       dcwave[i]=-1;
                   6667:       for (m=firstpass; m<=lastpass; m++)
                   6668:        if (s[m][i]>nlstate) {
                   6669:          dcwave[i]=m;
                   6670:          /*    printf("i=%d j=%d s=%d dcwave=%d\n",i,j, s[j][i],dcwave[i]);*/
                   6671:          break;
                   6672:        }
                   6673:     }
                   6674: 
                   6675:     for (i=1; i<=imx; i++) {
                   6676:       if (wav[i]>0){
                   6677:        ageexmed[i]=agev[mw[1][i]][i];
                   6678:        j=wav[i];
                   6679:        agecens[i]=1.; 
                   6680: 
                   6681:        if (ageexmed[i]> 1 && wav[i] > 0){
                   6682:          agecens[i]=agev[mw[j][i]][i];
                   6683:          cens[i]= 1;
                   6684:        }else if (ageexmed[i]< 1) 
                   6685:          cens[i]= -1;
                   6686:        if (agedc[i]< AGESUP && agedc[i]>1 && dcwave[i]>firstpass && dcwave[i]<=lastpass)
                   6687:          cens[i]=0 ;
                   6688:       }
                   6689:       else cens[i]=-1;
                   6690:     }
                   6691:     
                   6692:     for (i=1;i<=NDIM;i++) {
                   6693:       for (j=1;j<=NDIM;j++)
                   6694:        ximort[i][j]=(i == j ? 1.0 : 0.0);
                   6695:     }
                   6696:     
1.145     brouard  6697:     /*p[1]=0.0268; p[NDIM]=0.083;*/
1.126     brouard  6698:     /*printf("%lf %lf", p[1], p[2]);*/
                   6699:     
                   6700:     
1.136     brouard  6701: #ifdef GSL
                   6702:     printf("GSL optimization\n");  fprintf(ficlog,"Powell\n");
1.162     brouard  6703: #else
1.126     brouard  6704:     printf("Powell\n");  fprintf(ficlog,"Powell\n");
1.136     brouard  6705: #endif
1.126     brouard  6706:     strcpy(filerespow,"pow-mort"); 
                   6707:     strcat(filerespow,fileres);
                   6708:     if((ficrespow=fopen(filerespow,"w"))==NULL) {
                   6709:       printf("Problem with resultfile: %s\n", filerespow);
                   6710:       fprintf(ficlog,"Problem with resultfile: %s\n", filerespow);
                   6711:     }
1.136     brouard  6712: #ifdef GSL
                   6713:     fprintf(ficrespow,"# GSL optimization\n# iter -2*LL");
1.162     brouard  6714: #else
1.126     brouard  6715:     fprintf(ficrespow,"# Powell\n# iter -2*LL");
1.136     brouard  6716: #endif
1.126     brouard  6717:     /*  for (i=1;i<=nlstate;i++)
                   6718:        for(j=1;j<=nlstate+ndeath;j++)
                   6719:        if(j!=i)fprintf(ficrespow," p%1d%1d",i,j);
                   6720:     */
                   6721:     fprintf(ficrespow,"\n");
1.136     brouard  6722: #ifdef GSL
                   6723:     /* gsl starts here */ 
                   6724:     T = gsl_multimin_fminimizer_nmsimplex;
                   6725:     gsl_multimin_fminimizer *sfm = NULL;
                   6726:     gsl_vector *ss, *x;
                   6727:     gsl_multimin_function minex_func;
                   6728: 
                   6729:     /* Initial vertex size vector */
                   6730:     ss = gsl_vector_alloc (NDIM);
                   6731:     
                   6732:     if (ss == NULL){
                   6733:       GSL_ERROR_VAL ("failed to allocate space for ss", GSL_ENOMEM, 0);
                   6734:     }
                   6735:     /* Set all step sizes to 1 */
                   6736:     gsl_vector_set_all (ss, 0.001);
                   6737: 
                   6738:     /* Starting point */
1.126     brouard  6739:     
1.136     brouard  6740:     x = gsl_vector_alloc (NDIM);
                   6741:     
                   6742:     if (x == NULL){
                   6743:       gsl_vector_free(ss);
                   6744:       GSL_ERROR_VAL ("failed to allocate space for x", GSL_ENOMEM, 0);
                   6745:     }
                   6746:   
                   6747:     /* Initialize method and iterate */
                   6748:     /*     p[1]=0.0268; p[NDIM]=0.083; */
1.186   ! brouard  6749:     /*     gsl_vector_set(x, 0, 0.0268); */
        !          6750:     /*     gsl_vector_set(x, 1, 0.083); */
1.136     brouard  6751:     gsl_vector_set(x, 0, p[1]);
                   6752:     gsl_vector_set(x, 1, p[2]);
                   6753: 
                   6754:     minex_func.f = &gompertz_f;
                   6755:     minex_func.n = NDIM;
                   6756:     minex_func.params = (void *)&p; /* ??? */
                   6757:     
                   6758:     sfm = gsl_multimin_fminimizer_alloc (T, NDIM);
                   6759:     gsl_multimin_fminimizer_set (sfm, &minex_func, x, ss);
                   6760:     
                   6761:     printf("Iterations beginning .....\n\n");
                   6762:     printf("Iter. #    Intercept       Slope     -Log Likelihood     Simplex size\n");
                   6763: 
                   6764:     iteri=0;
                   6765:     while (rval == GSL_CONTINUE){
                   6766:       iteri++;
                   6767:       status = gsl_multimin_fminimizer_iterate(sfm);
                   6768:       
                   6769:       if (status) printf("error: %s\n", gsl_strerror (status));
                   6770:       fflush(0);
                   6771:       
                   6772:       if (status) 
                   6773:         break;
                   6774:       
                   6775:       rval = gsl_multimin_test_size (gsl_multimin_fminimizer_size (sfm), 1e-6);
                   6776:       ssval = gsl_multimin_fminimizer_size (sfm);
                   6777:       
                   6778:       if (rval == GSL_SUCCESS)
                   6779:         printf ("converged to a local maximum at\n");
                   6780:       
                   6781:       printf("%5d ", iteri);
                   6782:       for (it = 0; it < NDIM; it++){
                   6783:        printf ("%10.5f ", gsl_vector_get (sfm->x, it));
                   6784:       }
                   6785:       printf("f() = %-10.5f ssize = %.7f\n", sfm->fval, ssval);
                   6786:     }
                   6787:     
                   6788:     printf("\n\n Please note: Program should be run many times with varying starting points to detemine global maximum\n\n");
                   6789:     
                   6790:     gsl_vector_free(x); /* initial values */
                   6791:     gsl_vector_free(ss); /* inital step size */
                   6792:     for (it=0; it<NDIM; it++){
                   6793:       p[it+1]=gsl_vector_get(sfm->x,it);
                   6794:       fprintf(ficrespow," %.12lf", p[it]);
                   6795:     }
                   6796:     gsl_multimin_fminimizer_free (sfm); /* p *(sfm.x.data) et p *(sfm.x.data+1)  */
                   6797: #endif
                   6798: #ifdef POWELL
                   6799:      powell(p,ximort,NDIM,ftol,&iter,&fret,gompertz);
                   6800: #endif  
1.126     brouard  6801:     fclose(ficrespow);
                   6802:     
                   6803:     hesscov(matcov, p, NDIM, delti, 1e-4, gompertz); 
                   6804: 
                   6805:     for(i=1; i <=NDIM; i++)
                   6806:       for(j=i+1;j<=NDIM;j++)
                   6807:        matcov[i][j]=matcov[j][i];
                   6808:     
                   6809:     printf("\nCovariance matrix\n ");
                   6810:     for(i=1; i <=NDIM; i++) {
                   6811:       for(j=1;j<=NDIM;j++){ 
                   6812:        printf("%f ",matcov[i][j]);
                   6813:       }
                   6814:       printf("\n ");
                   6815:     }
                   6816:     
                   6817:     printf("iter=%d MLE=%f Eq=%lf*exp(%lf*(age-%d))\n",iter,-gompertz(p),p[1],p[2],agegomp);
                   6818:     for (i=1;i<=NDIM;i++) 
                   6819:       printf("%f [%f ; %f]\n",p[i],p[i]-2*sqrt(matcov[i][i]),p[i]+2*sqrt(matcov[i][i]));
                   6820: 
                   6821:     lsurv=vector(1,AGESUP);
                   6822:     lpop=vector(1,AGESUP);
                   6823:     tpop=vector(1,AGESUP);
                   6824:     lsurv[agegomp]=100000;
                   6825:     
                   6826:     for (k=agegomp;k<=AGESUP;k++) {
                   6827:       agemortsup=k;
                   6828:       if (p[1]*exp(p[2]*(k-agegomp))>1) break;
                   6829:     }
                   6830:     
                   6831:     for (k=agegomp;k<agemortsup;k++)
                   6832:       lsurv[k+1]=lsurv[k]-lsurv[k]*(p[1]*exp(p[2]*(k-agegomp)));
                   6833:     
                   6834:     for (k=agegomp;k<agemortsup;k++){
                   6835:       lpop[k]=(lsurv[k]+lsurv[k+1])/2.;
                   6836:       sumlpop=sumlpop+lpop[k];
                   6837:     }
                   6838:     
                   6839:     tpop[agegomp]=sumlpop;
                   6840:     for (k=agegomp;k<(agemortsup-3);k++){
                   6841:       /*  tpop[k+1]=2;*/
                   6842:       tpop[k+1]=tpop[k]-lpop[k];
                   6843:     }
                   6844:     
                   6845:     
                   6846:     printf("\nAge   lx     qx    dx    Lx     Tx     e(x)\n");
                   6847:     for (k=agegomp;k<(agemortsup-2);k++) 
                   6848:       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]);
                   6849:     
                   6850:     
                   6851:     replace_back_to_slash(pathc,pathcd); /* Even gnuplot wants a / */
                   6852:     printinggnuplotmort(fileres, optionfilefiname,ageminpar,agemaxpar,fage, pathc,p);
                   6853:     
                   6854:     printinghtmlmort(fileres,title,datafile, firstpass, lastpass, \
                   6855:                     stepm, weightopt,\
                   6856:                     model,imx,p,matcov,agemortsup);
                   6857:     
                   6858:     free_vector(lsurv,1,AGESUP);
                   6859:     free_vector(lpop,1,AGESUP);
                   6860:     free_vector(tpop,1,AGESUP);
1.136     brouard  6861: #ifdef GSL
                   6862:     free_ivector(cens,1,n);
                   6863:     free_vector(agecens,1,n);
                   6864:     free_ivector(dcwave,1,n);
                   6865:     free_matrix(ximort,1,NDIM,1,NDIM);
                   6866: #endif
1.186   ! brouard  6867:   } /* Endof if mle==-3 mortality only */
        !          6868:   /* Standard maximisation */
1.126     brouard  6869:   else{ /* For mle >=1 */
1.132     brouard  6870:     globpr=0;/* debug */
1.186   ! brouard  6871:     /* Computes likelihood for initial parameters */
1.132     brouard  6872:     likelione(ficres, p, npar, nlstate, &globpr, &ipmx, &sw, &fretone, funcone); /* Prints the contributions to the likelihood */
1.126     brouard  6873:     printf("First Likeli=%12.6f ipmx=%ld sw=%12.6f",fretone,ipmx,sw);
                   6874:     for (k=1; k<=npar;k++)
                   6875:       printf(" %d %8.5f",k,p[k]);
                   6876:     printf("\n");
1.186   ! brouard  6877:     globpr=1; /* again, to print the contributions */
1.126     brouard  6878:     likelione(ficres, p, npar, nlstate, &globpr, &ipmx, &sw, &fretone, funcone); /* Prints the contributions to the likelihood */
                   6879:     printf("Second Likeli=%12.6f ipmx=%ld sw=%12.6f",fretone,ipmx,sw);
                   6880:     for (k=1; k<=npar;k++)
                   6881:       printf(" %d %8.5f",k,p[k]);
                   6882:     printf("\n");
1.186   ! brouard  6883:     if(mle>=1){ /* Could be 1 or 2, Real Maximisation */
1.126     brouard  6884:       mlikeli(ficres,p, npar, ncovmodel, nlstate, ftol, func);
                   6885:     }
                   6886:     
                   6887:     /*--------- results files --------------*/
                   6888:     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);
                   6889:     
                   6890:     
                   6891:     fprintf(ficres,"# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
                   6892:     printf("# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
                   6893:     fprintf(ficlog,"# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
                   6894:     for(i=1,jk=1; i <=nlstate; i++){
                   6895:       for(k=1; k <=(nlstate+ndeath); k++){
                   6896:        if (k != i) {
                   6897:          printf("%d%d ",i,k);
                   6898:          fprintf(ficlog,"%d%d ",i,k);
                   6899:          fprintf(ficres,"%1d%1d ",i,k);
                   6900:          for(j=1; j <=ncovmodel; j++){
                   6901:            printf("%lf ",p[jk]);
                   6902:            fprintf(ficlog,"%lf ",p[jk]);
                   6903:            fprintf(ficres,"%lf ",p[jk]);
                   6904:            jk++; 
                   6905:          }
                   6906:          printf("\n");
                   6907:          fprintf(ficlog,"\n");
                   6908:          fprintf(ficres,"\n");
                   6909:        }
                   6910:       }
                   6911:     }
                   6912:     if(mle!=0){
                   6913:       /* Computing hessian and covariance matrix */
                   6914:       ftolhess=ftol; /* Usually correct */
                   6915:       hesscov(matcov, p, npar, delti, ftolhess, func);
                   6916:     }
                   6917:     fprintf(ficres,"# Scales (for hessian or gradient estimation)\n");
                   6918:     printf("# Scales (for hessian or gradient estimation)\n");
                   6919:     fprintf(ficlog,"# Scales (for hessian or gradient estimation)\n");
                   6920:     for(i=1,jk=1; i <=nlstate; i++){
                   6921:       for(j=1; j <=nlstate+ndeath; j++){
                   6922:        if (j!=i) {
                   6923:          fprintf(ficres,"%1d%1d",i,j);
                   6924:          printf("%1d%1d",i,j);
                   6925:          fprintf(ficlog,"%1d%1d",i,j);
                   6926:          for(k=1; k<=ncovmodel;k++){
                   6927:            printf(" %.5e",delti[jk]);
                   6928:            fprintf(ficlog," %.5e",delti[jk]);
                   6929:            fprintf(ficres," %.5e",delti[jk]);
                   6930:            jk++;
                   6931:          }
                   6932:          printf("\n");
                   6933:          fprintf(ficlog,"\n");
                   6934:          fprintf(ficres,"\n");
                   6935:        }
                   6936:       }
                   6937:     }
                   6938:     
                   6939:     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");
                   6940:     if(mle>=1)
                   6941:       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");
                   6942:     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");
                   6943:     /* # 121 Var(a12)\n\ */
                   6944:     /* # 122 Cov(b12,a12) Var(b12)\n\ */
                   6945:     /* # 131 Cov(a13,a12) Cov(a13,b12, Var(a13)\n\ */
                   6946:     /* # 132 Cov(b13,a12) Cov(b13,b12, Cov(b13,a13) Var(b13)\n\ */
                   6947:     /* # 212 Cov(a21,a12) Cov(a21,b12, Cov(a21,a13) Cov(a21,b13) Var(a21)\n\ */
                   6948:     /* # 212 Cov(b21,a12) Cov(b21,b12, Cov(b21,a13) Cov(b21,b13) Cov(b21,a21) Var(b21)\n\ */
                   6949:     /* # 232 Cov(a23,a12) Cov(a23,b12, Cov(a23,a13) Cov(a23,b13) Cov(a23,a21) Cov(a23,b21) Var(a23)\n\ */
                   6950:     /* # 232 Cov(b23,a12) Cov(b23,b12) ... Var (b23)\n" */
                   6951:     
                   6952:     
                   6953:     /* Just to have a covariance matrix which will be more understandable
                   6954:        even is we still don't want to manage dictionary of variables
                   6955:     */
                   6956:     for(itimes=1;itimes<=2;itimes++){
                   6957:       jj=0;
                   6958:       for(i=1; i <=nlstate; i++){
                   6959:        for(j=1; j <=nlstate+ndeath; j++){
                   6960:          if(j==i) continue;
                   6961:          for(k=1; k<=ncovmodel;k++){
                   6962:            jj++;
                   6963:            ca[0]= k+'a'-1;ca[1]='\0';
                   6964:            if(itimes==1){
                   6965:              if(mle>=1)
                   6966:                printf("#%1d%1d%d",i,j,k);
                   6967:              fprintf(ficlog,"#%1d%1d%d",i,j,k);
                   6968:              fprintf(ficres,"#%1d%1d%d",i,j,k);
                   6969:            }else{
                   6970:              if(mle>=1)
                   6971:                printf("%1d%1d%d",i,j,k);
                   6972:              fprintf(ficlog,"%1d%1d%d",i,j,k);
                   6973:              fprintf(ficres,"%1d%1d%d",i,j,k);
                   6974:            }
                   6975:            ll=0;
                   6976:            for(li=1;li <=nlstate; li++){
                   6977:              for(lj=1;lj <=nlstate+ndeath; lj++){
                   6978:                if(lj==li) continue;
                   6979:                for(lk=1;lk<=ncovmodel;lk++){
                   6980:                  ll++;
                   6981:                  if(ll<=jj){
                   6982:                    cb[0]= lk +'a'-1;cb[1]='\0';
                   6983:                    if(ll<jj){
                   6984:                      if(itimes==1){
                   6985:                        if(mle>=1)
                   6986:                          printf(" Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
                   6987:                        fprintf(ficlog," Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
                   6988:                        fprintf(ficres," Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
                   6989:                      }else{
                   6990:                        if(mle>=1)
                   6991:                          printf(" %.5e",matcov[jj][ll]); 
                   6992:                        fprintf(ficlog," %.5e",matcov[jj][ll]); 
                   6993:                        fprintf(ficres," %.5e",matcov[jj][ll]); 
                   6994:                      }
                   6995:                    }else{
                   6996:                      if(itimes==1){
                   6997:                        if(mle>=1)
                   6998:                          printf(" Var(%s%1d%1d)",ca,i,j);
                   6999:                        fprintf(ficlog," Var(%s%1d%1d)",ca,i,j);
                   7000:                        fprintf(ficres," Var(%s%1d%1d)",ca,i,j);
                   7001:                      }else{
                   7002:                        if(mle>=1)
                   7003:                          printf(" %.5e",matcov[jj][ll]); 
                   7004:                        fprintf(ficlog," %.5e",matcov[jj][ll]); 
                   7005:                        fprintf(ficres," %.5e",matcov[jj][ll]); 
                   7006:                      }
                   7007:                    }
                   7008:                  }
                   7009:                } /* end lk */
                   7010:              } /* end lj */
                   7011:            } /* end li */
                   7012:            if(mle>=1)
                   7013:              printf("\n");
                   7014:            fprintf(ficlog,"\n");
                   7015:            fprintf(ficres,"\n");
                   7016:            numlinepar++;
                   7017:          } /* end k*/
                   7018:        } /*end j */
                   7019:       } /* end i */
                   7020:     } /* end itimes */
                   7021:     
                   7022:     fflush(ficlog);
                   7023:     fflush(ficres);
                   7024:     
                   7025:     while((c=getc(ficpar))=='#' && c!= EOF){
                   7026:       ungetc(c,ficpar);
                   7027:       fgets(line, MAXLINE, ficpar);
1.141     brouard  7028:       fputs(line,stdout);
1.126     brouard  7029:       fputs(line,ficparo);
                   7030:     }
                   7031:     ungetc(c,ficpar);
                   7032:     
                   7033:     estepm=0;
                   7034:     fscanf(ficpar,"agemin=%lf agemax=%lf bage=%lf fage=%lf estepm=%d\n",&ageminpar,&agemaxpar, &bage, &fage, &estepm);
                   7035:     if (estepm==0 || estepm < stepm) estepm=stepm;
                   7036:     if (fage <= 2) {
                   7037:       bage = ageminpar;
                   7038:       fage = agemaxpar;
                   7039:     }
                   7040:     
                   7041:     fprintf(ficres,"# agemin agemax for life expectancy, bage fage (if mle==0 ie no data nor Max likelihood).\n");
                   7042:     fprintf(ficres,"agemin=%.0f agemax=%.0f bage=%.0f fage=%.0f estepm=%d\n",ageminpar,agemaxpar,bage,fage, estepm);
                   7043:     fprintf(ficparo,"agemin=%.0f agemax=%.0f bage=%.0f fage=%.0f estepm=%d\n",ageminpar,agemaxpar,bage,fage, estepm);
1.186   ! brouard  7044: 
        !          7045:     /* Other stuffs, more or less useful */    
1.126     brouard  7046:     while((c=getc(ficpar))=='#' && c!= EOF){
                   7047:       ungetc(c,ficpar);
                   7048:       fgets(line, MAXLINE, ficpar);
1.141     brouard  7049:       fputs(line,stdout);
1.126     brouard  7050:       fputs(line,ficparo);
                   7051:     }
                   7052:     ungetc(c,ficpar);
                   7053:     
                   7054:     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);
                   7055:     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);
                   7056:     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);
                   7057:     printf("begin-prev-date=%.lf/%.lf/%.lf end-prev-date=%.lf/%.lf/%.lf mov_average=%d\n",jprev1, mprev1,anprev1,jprev2, mprev2,anprev2,mobilav);
                   7058:     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);
                   7059:     
                   7060:     while((c=getc(ficpar))=='#' && c!= EOF){
                   7061:       ungetc(c,ficpar);
                   7062:       fgets(line, MAXLINE, ficpar);
1.141     brouard  7063:       fputs(line,stdout);
1.126     brouard  7064:       fputs(line,ficparo);
                   7065:     }
                   7066:     ungetc(c,ficpar);
                   7067:     
                   7068:     
                   7069:     dateprev1=anprev1+(mprev1-1)/12.+(jprev1-1)/365.;
                   7070:     dateprev2=anprev2+(mprev2-1)/12.+(jprev2-1)/365.;
                   7071:     
                   7072:     fscanf(ficpar,"pop_based=%d\n",&popbased);
                   7073:     fprintf(ficparo,"pop_based=%d\n",popbased);   
                   7074:     fprintf(ficres,"pop_based=%d\n",popbased);   
                   7075:     
                   7076:     while((c=getc(ficpar))=='#' && c!= EOF){
                   7077:       ungetc(c,ficpar);
                   7078:       fgets(line, MAXLINE, ficpar);
1.141     brouard  7079:       fputs(line,stdout);
1.126     brouard  7080:       fputs(line,ficparo);
                   7081:     }
                   7082:     ungetc(c,ficpar);
                   7083:     
                   7084:     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);
                   7085:     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);
                   7086:     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);
                   7087:     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);
                   7088:     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);
                   7089:     /* day and month of proj2 are not used but only year anproj2.*/
                   7090:     
                   7091:     
                   7092:     
1.145     brouard  7093:      /* freqsummary(fileres, agemin, agemax, s, agev, nlstate, imx,Tvaraff,nbcode, ncodemax,mint,anint); */
                   7094:     /* ,dateprev1,dateprev2,jprev1, mprev1,anprev1,jprev2, mprev2,anprev2); */
1.126     brouard  7095:     
                   7096:     replace_back_to_slash(pathc,pathcd); /* Even gnuplot wants a / */
                   7097:     printinggnuplot(fileres, optionfilefiname,ageminpar,agemaxpar,fage, pathc,p);
                   7098:     
                   7099:     printinghtml(fileres,title,datafile, firstpass, lastpass, stepm, weightopt,\
                   7100:                 model,imx,jmin,jmax,jmean,rfileres,popforecast,estepm,\
                   7101:                 jprev1,mprev1,anprev1,jprev2,mprev2,anprev2);
                   7102:       
                   7103:    /*------------ free_vector  -------------*/
                   7104:    /*  chdir(path); */
                   7105:  
                   7106:     free_ivector(wav,1,imx);
                   7107:     free_imatrix(dh,1,lastpass-firstpass+1,1,imx);
                   7108:     free_imatrix(bh,1,lastpass-firstpass+1,1,imx);
                   7109:     free_imatrix(mw,1,lastpass-firstpass+1,1,imx);   
                   7110:     free_lvector(num,1,n);
                   7111:     free_vector(agedc,1,n);
                   7112:     /*free_matrix(covar,0,NCOVMAX,1,n);*/
                   7113:     /*free_matrix(covar,1,NCOVMAX,1,n);*/
                   7114:     fclose(ficparo);
                   7115:     fclose(ficres);
                   7116: 
                   7117: 
1.186   ! brouard  7118:     /* Other results (useful)*/
        !          7119: 
        !          7120: 
1.126     brouard  7121:     /*--------------- Prevalence limit  (period or stable prevalence) --------------*/
1.180     brouard  7122:     /*#include "prevlim.h"*/  /* Use ficrespl, ficlog */
                   7123:     prlim=matrix(1,nlstate,1,nlstate);
                   7124:     prevalence_limit(p, prlim,  ageminpar, agemaxpar);
1.126     brouard  7125:     fclose(ficrespl);
                   7126: 
1.145     brouard  7127: #ifdef FREEEXIT2
                   7128: #include "freeexit2.h"
                   7129: #endif
                   7130: 
1.126     brouard  7131:     /*------------- h Pij x at various ages ------------*/
1.180     brouard  7132:     /*#include "hpijx.h"*/
                   7133:     hPijx(p, bage, fage);
1.145     brouard  7134:     fclose(ficrespij);
1.126     brouard  7135: 
1.145     brouard  7136:   /*-------------- Variance of one-step probabilities---*/
                   7137:     k=1;
1.126     brouard  7138:     varprob(optionfilefiname, matcov, p, delti, nlstate, bage, fage,k,Tvar,nbcode, ncodemax,strstart);
                   7139: 
                   7140: 
                   7141:     probs= ma3x(1,AGESUP,1,NCOVMAX, 1,NCOVMAX);
                   7142:     for(i=1;i<=AGESUP;i++)
                   7143:       for(j=1;j<=NCOVMAX;j++)
                   7144:        for(k=1;k<=NCOVMAX;k++)
                   7145:          probs[i][j][k]=0.;
                   7146: 
                   7147:     /*---------- Forecasting ------------------*/
                   7148:     /*if((stepm == 1) && (strcmp(model,".")==0)){*/
                   7149:     if(prevfcast==1){
                   7150:       /*    if(stepm ==1){*/
                   7151:       prevforecast(fileres, anproj1, mproj1, jproj1, agemin, agemax, dateprev1, dateprev2, mobilavproj, bage, fage, firstpass, lastpass, anproj2, p, cptcoveff);
                   7152:       /* (popforecast==1) populforecast(fileres, anpyram,mpyram,jpyram, agemin,agemax, dateprev1, dateprev2,mobilav, agedeb, fage, popforecast, popfile, anpyram1,p, i1);*/
                   7153:       /*      }  */
                   7154:       /*      else{ */
                   7155:       /*        erreur=108; */
                   7156:       /*        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); */
                   7157:       /*        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); */
                   7158:       /*      } */
                   7159:     }
1.186   ! brouard  7160:  
        !          7161:     /* ------ Other prevalence ratios------------ */
1.126     brouard  7162: 
1.127     brouard  7163:     /* Computes prevalence between agemin (i.e minimal age computed) and no more ageminpar */
                   7164: 
                   7165:     prevalence(probs, agemin, agemax, s, agev, nlstate, imx, Tvar, nbcode, ncodemax, mint, anint, dateprev1, dateprev2, firstpass, lastpass);
                   7166:     /*  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",\
                   7167:        ageminpar, agemax, s[lastpass][imx], agev[lastpass][imx], nlstate, imx, mint[lastpass][imx],anint[lastpass][imx], dateprev1, dateprev2, firstpass, lastpass);
                   7168:     */
1.126     brouard  7169: 
1.127     brouard  7170:     if (mobilav!=0) {
                   7171:       mobaverage= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
                   7172:       if (movingaverage(probs, bage, fage, mobaverage,mobilav)!=0){
                   7173:        fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav);
                   7174:        printf(" Error in movingaverage mobilav=%d\n",mobilav);
                   7175:       }
1.126     brouard  7176:     }
                   7177: 
                   7178: 
1.127     brouard  7179:     /*---------- Health expectancies, no variances ------------*/
                   7180: 
1.126     brouard  7181:     strcpy(filerese,"e");
                   7182:     strcat(filerese,fileres);
                   7183:     if((ficreseij=fopen(filerese,"w"))==NULL) {
                   7184:       printf("Problem with Health Exp. resultfile: %s\n", filerese); exit(0);
                   7185:       fprintf(ficlog,"Problem with Health Exp. resultfile: %s\n", filerese); exit(0);
                   7186:     }
                   7187:     printf("Computing Health Expectancies: result on file '%s' \n", filerese);
                   7188:     fprintf(ficlog,"Computing Health Expectancies: result on file '%s' \n", filerese);
1.145     brouard  7189:     /*for(cptcov=1,k=0;cptcov<=i1;cptcov++){
                   7190:       for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){*/
                   7191:           
                   7192:     for (k=1; k <= (int) pow(2,cptcoveff); k++){
1.127     brouard  7193:        fprintf(ficreseij,"\n#****** ");
                   7194:        for(j=1;j<=cptcoveff;j++) {
                   7195:          fprintf(ficreseij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
                   7196:        }
                   7197:        fprintf(ficreseij,"******\n");
                   7198: 
                   7199:        eij=ma3x(1,nlstate,1,nlstate,(int) bage, (int) fage);
                   7200:        oldm=oldms;savm=savms;
                   7201:        evsij(eij, p, nlstate, stepm, (int) bage, (int)fage, oldm, savm, k, estepm, strstart);  
                   7202:       
                   7203:        free_ma3x(eij,1,nlstate,1,nlstate,(int) bage, (int)fage);
1.145     brouard  7204:       /*}*/
1.127     brouard  7205:     }
                   7206:     fclose(ficreseij);
                   7207: 
                   7208: 
                   7209:     /*---------- Health expectancies and variances ------------*/
                   7210: 
                   7211: 
                   7212:     strcpy(filerest,"t");
                   7213:     strcat(filerest,fileres);
                   7214:     if((ficrest=fopen(filerest,"w"))==NULL) {
                   7215:       printf("Problem with total LE resultfile: %s\n", filerest);goto end;
                   7216:       fprintf(ficlog,"Problem with total LE resultfile: %s\n", filerest);goto end;
                   7217:     }
                   7218:     printf("Computing Total Life expectancies with their standard errors: file '%s' \n", filerest); 
                   7219:     fprintf(ficlog,"Computing Total Life expectancies with their standard errors: file '%s' \n", filerest); 
                   7220: 
1.126     brouard  7221: 
                   7222:     strcpy(fileresstde,"stde");
                   7223:     strcat(fileresstde,fileres);
                   7224:     if((ficresstdeij=fopen(fileresstde,"w"))==NULL) {
                   7225:       printf("Problem with Health Exp. and std errors resultfile: %s\n", fileresstde); exit(0);
                   7226:       fprintf(ficlog,"Problem with Health Exp. and std errors resultfile: %s\n", fileresstde); exit(0);
                   7227:     }
                   7228:     printf("Computing Health Expectancies and standard errors: result on file '%s' \n", fileresstde);
                   7229:     fprintf(ficlog,"Computing Health Expectancies and standard errors: result on file '%s' \n", fileresstde);
                   7230: 
                   7231:     strcpy(filerescve,"cve");
                   7232:     strcat(filerescve,fileres);
                   7233:     if((ficrescveij=fopen(filerescve,"w"))==NULL) {
                   7234:       printf("Problem with Covar. Health Exp. resultfile: %s\n", filerescve); exit(0);
                   7235:       fprintf(ficlog,"Problem with Covar. Health Exp. resultfile: %s\n", filerescve); exit(0);
                   7236:     }
                   7237:     printf("Computing Covar. of Health Expectancies: result on file '%s' \n", filerescve);
                   7238:     fprintf(ficlog,"Computing Covar. of Health Expectancies: result on file '%s' \n", filerescve);
                   7239: 
                   7240:     strcpy(fileresv,"v");
                   7241:     strcat(fileresv,fileres);
                   7242:     if((ficresvij=fopen(fileresv,"w"))==NULL) {
                   7243:       printf("Problem with variance resultfile: %s\n", fileresv);exit(0);
                   7244:       fprintf(ficlog,"Problem with variance resultfile: %s\n", fileresv);exit(0);
                   7245:     }
                   7246:     printf("Computing Variance-covariance of DFLEs: file '%s' \n", fileresv);
                   7247:     fprintf(ficlog,"Computing Variance-covariance of DFLEs: file '%s' \n", fileresv);
                   7248: 
1.145     brouard  7249:     /*for(cptcov=1,k=0;cptcov<=i1;cptcov++){
                   7250:       for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){*/
                   7251:           
                   7252:     for (k=1; k <= (int) pow(2,cptcoveff); k++){
                   7253:        fprintf(ficrest,"\n#****** ");
1.126     brouard  7254:        for(j=1;j<=cptcoveff;j++) 
                   7255:          fprintf(ficrest,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
                   7256:        fprintf(ficrest,"******\n");
                   7257: 
                   7258:        fprintf(ficresstdeij,"\n#****** ");
                   7259:        fprintf(ficrescveij,"\n#****** ");
                   7260:        for(j=1;j<=cptcoveff;j++) {
                   7261:          fprintf(ficresstdeij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
                   7262:          fprintf(ficrescveij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
                   7263:        }
                   7264:        fprintf(ficresstdeij,"******\n");
                   7265:        fprintf(ficrescveij,"******\n");
                   7266: 
                   7267:        fprintf(ficresvij,"\n#****** ");
                   7268:        for(j=1;j<=cptcoveff;j++) 
                   7269:          fprintf(ficresvij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
                   7270:        fprintf(ficresvij,"******\n");
                   7271: 
                   7272:        eij=ma3x(1,nlstate,1,nlstate,(int) bage, (int) fage);
                   7273:        oldm=oldms;savm=savms;
1.127     brouard  7274:        cvevsij(eij, p, nlstate, stepm, (int) bage, (int)fage, oldm, savm, k, estepm, delti, matcov, strstart);  
1.145     brouard  7275:        /*
                   7276:         */
                   7277:        /* goto endfree; */
1.126     brouard  7278:  
                   7279:        vareij=ma3x(1,nlstate,1,nlstate,(int) bage, (int) fage);
                   7280:        pstamp(ficrest);
1.145     brouard  7281: 
                   7282: 
1.128     brouard  7283:        for(vpopbased=0; vpopbased <= popbased; vpopbased++){ /* Done for vpopbased=0 and vpopbased=1 if popbased==1*/
1.145     brouard  7284:          oldm=oldms;savm=savms; /* Segmentation fault */
1.161     brouard  7285:          cptcod= 0; /* To be deleted */
                   7286:          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  7287:          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  7288:          if(vpopbased==1)
                   7289:            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);
                   7290:          else
                   7291:            fprintf(ficrest,"the age specific period (stable) prevalences in each health state \n");
                   7292:          fprintf(ficrest,"# Age e.. (std) ");
                   7293:          for (i=1;i<=nlstate;i++) fprintf(ficrest,"e.%d (std) ",i);
                   7294:          fprintf(ficrest,"\n");
1.126     brouard  7295: 
1.128     brouard  7296:          epj=vector(1,nlstate+1);
                   7297:          for(age=bage; age <=fage ;age++){
                   7298:            prevalim(prlim, nlstate, p, age, oldm, savm,ftolpl,k);
                   7299:            if (vpopbased==1) {
                   7300:              if(mobilav ==0){
                   7301:                for(i=1; i<=nlstate;i++)
                   7302:                  prlim[i][i]=probs[(int)age][i][k];
                   7303:              }else{ /* mobilav */ 
                   7304:                for(i=1; i<=nlstate;i++)
                   7305:                  prlim[i][i]=mobaverage[(int)age][i][k];
                   7306:              }
1.126     brouard  7307:            }
                   7308:        
1.128     brouard  7309:            fprintf(ficrest," %4.0f",age);
                   7310:            for(j=1, epj[nlstate+1]=0.;j <=nlstate;j++){
                   7311:              for(i=1, epj[j]=0.;i <=nlstate;i++) {
                   7312:                epj[j] += prlim[i][i]*eij[i][j][(int)age];
                   7313:                /*  printf("%lf %lf ", prlim[i][i] ,eij[i][j][(int)age]);*/
                   7314:              }
                   7315:              epj[nlstate+1] +=epj[j];
1.126     brouard  7316:            }
                   7317: 
1.128     brouard  7318:            for(i=1, vepp=0.;i <=nlstate;i++)
                   7319:              for(j=1;j <=nlstate;j++)
                   7320:                vepp += vareij[i][j][(int)age];
                   7321:            fprintf(ficrest," %7.3f (%7.3f)", epj[nlstate+1],sqrt(vepp));
                   7322:            for(j=1;j <=nlstate;j++){
                   7323:              fprintf(ficrest," %7.3f (%7.3f)", epj[j],sqrt(vareij[j][j][(int)age]));
                   7324:            }
                   7325:            fprintf(ficrest,"\n");
1.126     brouard  7326:          }
                   7327:        }
                   7328:        free_ma3x(eij,1,nlstate,1,nlstate,(int) bage, (int)fage);
                   7329:        free_ma3x(vareij,1,nlstate,1,nlstate,(int) bage, (int)fage);
                   7330:        free_vector(epj,1,nlstate+1);
1.145     brouard  7331:       /*}*/
1.126     brouard  7332:     }
                   7333:     free_vector(weight,1,n);
1.145     brouard  7334:     free_imatrix(Tvard,1,NCOVMAX,1,2);
1.126     brouard  7335:     free_imatrix(s,1,maxwav+1,1,n);
                   7336:     free_matrix(anint,1,maxwav,1,n); 
                   7337:     free_matrix(mint,1,maxwav,1,n);
                   7338:     free_ivector(cod,1,n);
                   7339:     free_ivector(tab,1,NCOVMAX);
                   7340:     fclose(ficresstdeij);
                   7341:     fclose(ficrescveij);
                   7342:     fclose(ficresvij);
                   7343:     fclose(ficrest);
                   7344:     fclose(ficpar);
                   7345:   
                   7346:     /*------- Variance of period (stable) prevalence------*/   
                   7347: 
                   7348:     strcpy(fileresvpl,"vpl");
                   7349:     strcat(fileresvpl,fileres);
                   7350:     if((ficresvpl=fopen(fileresvpl,"w"))==NULL) {
                   7351:       printf("Problem with variance of period (stable) prevalence  resultfile: %s\n", fileresvpl);
                   7352:       exit(0);
                   7353:     }
                   7354:     printf("Computing Variance-covariance of period (stable) prevalence: file '%s' \n", fileresvpl);
                   7355: 
1.145     brouard  7356:     /*for(cptcov=1,k=0;cptcov<=i1;cptcov++){
                   7357:       for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){*/
                   7358:           
                   7359:     for (k=1; k <= (int) pow(2,cptcoveff); k++){
                   7360:        fprintf(ficresvpl,"\n#****** ");
1.126     brouard  7361:        for(j=1;j<=cptcoveff;j++) 
                   7362:          fprintf(ficresvpl,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
                   7363:        fprintf(ficresvpl,"******\n");
                   7364:       
                   7365:        varpl=matrix(1,nlstate,(int) bage, (int) fage);
                   7366:        oldm=oldms;savm=savms;
                   7367:        varprevlim(fileres, varpl, matcov, p, delti, nlstate, stepm, (int) bage, (int) fage, oldm, savm, prlim, ftolpl,k,strstart);
                   7368:        free_matrix(varpl,1,nlstate,(int) bage, (int)fage);
1.145     brouard  7369:       /*}*/
1.126     brouard  7370:     }
                   7371: 
                   7372:     fclose(ficresvpl);
                   7373: 
                   7374:     /*---------- End : free ----------------*/
                   7375:     if (mobilav!=0) free_ma3x(mobaverage,1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
                   7376:     free_ma3x(probs,1,AGESUP,1,NCOVMAX, 1,NCOVMAX);
                   7377:   }  /* mle==-3 arrives here for freeing */
1.164     brouard  7378:  /* endfree:*/
1.141     brouard  7379:     free_matrix(prlim,1,nlstate,1,nlstate); /*here or after loop ? */
1.126     brouard  7380:     free_matrix(pmmij,1,nlstate+ndeath,1,nlstate+ndeath);
                   7381:     free_matrix(oldms, 1,nlstate+ndeath,1,nlstate+ndeath);
                   7382:     free_matrix(newms, 1,nlstate+ndeath,1,nlstate+ndeath);
                   7383:     free_matrix(savms, 1,nlstate+ndeath,1,nlstate+ndeath);
                   7384:     free_matrix(covar,0,NCOVMAX,1,n);
                   7385:     free_matrix(matcov,1,npar,1,npar);
                   7386:     /*free_vector(delti,1,npar);*/
                   7387:     free_ma3x(delti3,1,nlstate,1, nlstate+ndeath-1,1,ncovmodel); 
                   7388:     free_matrix(agev,1,maxwav,1,imx);
                   7389:     free_ma3x(param,1,nlstate,1, nlstate+ndeath-1,1,ncovmodel);
                   7390: 
1.145     brouard  7391:     free_ivector(ncodemax,1,NCOVMAX);
                   7392:     free_ivector(Tvar,1,NCOVMAX);
                   7393:     free_ivector(Tprod,1,NCOVMAX);
                   7394:     free_ivector(Tvaraff,1,NCOVMAX);
                   7395:     free_ivector(Tage,1,NCOVMAX);
1.126     brouard  7396: 
                   7397:     free_imatrix(nbcode,0,NCOVMAX,0,NCOVMAX);
                   7398:     free_imatrix(codtab,1,100,1,10);
                   7399:   fflush(fichtm);
                   7400:   fflush(ficgp);
                   7401:   
                   7402: 
                   7403:   if((nberr >0) || (nbwarn>0)){
                   7404:     printf("End of Imach with %d errors and/or %d warnings\n",nberr,nbwarn);
                   7405:     fprintf(ficlog,"End of Imach with %d errors and/or warnings %d\n",nberr,nbwarn);
                   7406:   }else{
                   7407:     printf("End of Imach\n");
                   7408:     fprintf(ficlog,"End of Imach\n");
                   7409:   }
                   7410:   printf("See log file on %s\n",filelog);
                   7411:   /*  gettimeofday(&end_time, (struct timezone*)0);*/  /* after time */
1.157     brouard  7412:   /*(void) gettimeofday(&end_time,&tzp);*/
                   7413:   rend_time = time(NULL);  
                   7414:   end_time = *localtime(&rend_time);
                   7415:   /* tml = *localtime(&end_time.tm_sec); */
                   7416:   strcpy(strtend,asctime(&end_time));
1.126     brouard  7417:   printf("Local time at start %s\nLocal time at end   %s",strstart, strtend); 
                   7418:   fprintf(ficlog,"Local time at start %s\nLocal time at end   %s\n",strstart, strtend); 
1.157     brouard  7419:   printf("Total time used %s\n", asc_diff_time(rend_time -rstart_time,tmpout));
1.126     brouard  7420: 
1.157     brouard  7421:   printf("Total time was %.0lf Sec.\n", difftime(rend_time,rstart_time));
                   7422:   fprintf(ficlog,"Total time used %s\n", asc_diff_time(rend_time -rstart_time,tmpout));
                   7423:   fprintf(ficlog,"Total time was %.0lf Sec.\n", difftime(rend_time,rstart_time));
1.126     brouard  7424:   /*  printf("Total time was %d uSec.\n", total_usecs);*/
                   7425: /*   if(fileappend(fichtm,optionfilehtm)){ */
                   7426:   fprintf(fichtm,"<br>Local time at start %s<br>Local time at end   %s<br>\n</body></html>",strstart, strtend);
                   7427:   fclose(fichtm);
                   7428:   fprintf(fichtmcov,"<br>Local time at start %s<br>Local time at end   %s<br>\n</body></html>",strstart, strtend);
                   7429:   fclose(fichtmcov);
                   7430:   fclose(ficgp);
                   7431:   fclose(ficlog);
                   7432:   /*------ End -----------*/
                   7433: 
                   7434: 
                   7435:    printf("Before Current directory %s!\n",pathcd);
1.184     brouard  7436: #ifdef WIN32
                   7437:    if (_chdir(pathcd) != 0)
                   7438:           printf("Can't move to directory %s!\n",path);
                   7439:    if(_getcwd(pathcd,MAXLINE) > 0)
                   7440: #else
1.126     brouard  7441:    if(chdir(pathcd) != 0)
1.184     brouard  7442:           printf("Can't move to directory %s!\n", path);
                   7443:    if (getcwd(pathcd, MAXLINE) > 0)
                   7444: #endif 
1.126     brouard  7445:     printf("Current directory %s!\n",pathcd);
                   7446:   /*strcat(plotcmd,CHARSEPARATOR);*/
                   7447:   sprintf(plotcmd,"gnuplot");
1.157     brouard  7448: #ifdef _WIN32
1.126     brouard  7449:   sprintf(plotcmd,"\"%sgnuplot.exe\"",pathimach);
                   7450: #endif
                   7451:   if(!stat(plotcmd,&info)){
1.158     brouard  7452:     printf("Error or gnuplot program not found: '%s'\n",plotcmd);fflush(stdout);
1.126     brouard  7453:     if(!stat(getenv("GNUPLOTBIN"),&info)){
1.158     brouard  7454:       printf("Error or gnuplot program not found: '%s' Environment GNUPLOTBIN not set.\n",plotcmd);fflush(stdout);
1.126     brouard  7455:     }else
                   7456:       strcpy(pplotcmd,plotcmd);
1.157     brouard  7457: #ifdef __unix
1.126     brouard  7458:     strcpy(plotcmd,GNUPLOTPROGRAM);
                   7459:     if(!stat(plotcmd,&info)){
1.158     brouard  7460:       printf("Error gnuplot program not found: '%s'\n",plotcmd);fflush(stdout);
1.126     brouard  7461:     }else
                   7462:       strcpy(pplotcmd,plotcmd);
                   7463: #endif
                   7464:   }else
                   7465:     strcpy(pplotcmd,plotcmd);
                   7466:   
                   7467:   sprintf(plotcmd,"%s %s",pplotcmd, optionfilegnuplot);
1.158     brouard  7468:   printf("Starting graphs with: '%s'\n",plotcmd);fflush(stdout);
1.126     brouard  7469: 
                   7470:   if((outcmd=system(plotcmd)) != 0){
1.158     brouard  7471:     printf("gnuplot command might not be in your path: '%s', err=%d\n", plotcmd, outcmd);
1.154     brouard  7472:     printf("\n Trying if gnuplot resides on the same directory that IMaCh\n");
1.152     brouard  7473:     sprintf(plotcmd,"%sgnuplot %s", pathimach, optionfilegnuplot);
1.150     brouard  7474:     if((outcmd=system(plotcmd)) != 0)
1.153     brouard  7475:       printf("\n Still a problem with gnuplot command %s, err=%d\n", plotcmd, outcmd);
1.126     brouard  7476:   }
1.158     brouard  7477:   printf(" Successful, please wait...");
1.126     brouard  7478:   while (z[0] != 'q') {
                   7479:     /* chdir(path); */
1.154     brouard  7480:     printf("\nType e to edit results with your browser, g to graph again and q for exit: ");
1.126     brouard  7481:     scanf("%s",z);
                   7482: /*     if (z[0] == 'c') system("./imach"); */
                   7483:     if (z[0] == 'e') {
1.158     brouard  7484: #ifdef __APPLE__
1.152     brouard  7485:       sprintf(pplotcmd, "open %s", optionfilehtm);
1.157     brouard  7486: #elif __linux
                   7487:       sprintf(pplotcmd, "xdg-open %s", optionfilehtm);
1.153     brouard  7488: #else
1.152     brouard  7489:       sprintf(pplotcmd, "%s", optionfilehtm);
1.153     brouard  7490: #endif
                   7491:       printf("Starting browser with: %s",pplotcmd);fflush(stdout);
                   7492:       system(pplotcmd);
1.126     brouard  7493:     }
                   7494:     else if (z[0] == 'g') system(plotcmd);
                   7495:     else if (z[0] == 'q') exit(0);
                   7496:   }
                   7497:   end:
                   7498:   while (z[0] != 'q') {
                   7499:     printf("\nType  q for exiting: ");
                   7500:     scanf("%s",z);
                   7501:   }
                   7502: }

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