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

1.187   ! brouard     1: /* $Id: imach.c,v 1.186 2015/04/23 12:01:52 brouard Exp $
1.126     brouard     2:   $State: Exp $
1.163     brouard     3:   $Log: imach.c,v $
1.187   ! brouard     4:   Revision 1.186  2015/04/23 12:01:52  brouard
        !             5:   Summary: V1*age is working now, version 0.98q1
        !             6: 
        !             7:   Some codes had been disabled in order to simplify and Vn*age was
        !             8:   working in the optimization phase, ie, giving correct MLE parameters,
        !             9:   but, as usual, outputs were not correct and program core dumped.
        !            10: 
1.186     brouard    11:   Revision 1.185  2015/03/11 13:26:42  brouard
                     12:   Summary: Inclusion of compile and links command line for Intel Compiler
                     13: 
1.185     brouard    14:   Revision 1.184  2015/03/11 11:52:39  brouard
                     15:   Summary: Back from Windows 8. Intel Compiler
                     16: 
1.184     brouard    17:   Revision 1.183  2015/03/10 20:34:32  brouard
                     18:   Summary: 0.98q0, trying with directest, mnbrak fixed
                     19: 
                     20:   We use directest instead of original Powell test; probably no
                     21:   incidence on the results, but better justifications;
                     22:   We fixed Numerical Recipes mnbrak routine which was wrong and gave
                     23:   wrong results.
                     24: 
1.183     brouard    25:   Revision 1.182  2015/02/12 08:19:57  brouard
                     26:   Summary: Trying to keep directest which seems simpler and more general
                     27:   Author: Nicolas Brouard
                     28: 
1.182     brouard    29:   Revision 1.181  2015/02/11 23:22:24  brouard
                     30:   Summary: Comments on Powell added
                     31: 
                     32:   Author:
                     33: 
1.181     brouard    34:   Revision 1.180  2015/02/11 17:33:45  brouard
                     35:   Summary: Finishing move from main to function (hpijx and prevalence_limit)
                     36: 
1.180     brouard    37:   Revision 1.179  2015/01/04 09:57:06  brouard
                     38:   Summary: back to OS/X
                     39: 
1.179     brouard    40:   Revision 1.178  2015/01/04 09:35:48  brouard
                     41:   *** empty log message ***
                     42: 
1.178     brouard    43:   Revision 1.177  2015/01/03 18:40:56  brouard
                     44:   Summary: Still testing ilc32 on OSX
                     45: 
1.177     brouard    46:   Revision 1.176  2015/01/03 16:45:04  brouard
                     47:   *** empty log message ***
                     48: 
1.176     brouard    49:   Revision 1.175  2015/01/03 16:33:42  brouard
                     50:   *** empty log message ***
                     51: 
1.175     brouard    52:   Revision 1.174  2015/01/03 16:15:49  brouard
                     53:   Summary: Still in cross-compilation
                     54: 
1.174     brouard    55:   Revision 1.173  2015/01/03 12:06:26  brouard
                     56:   Summary: trying to detect cross-compilation
                     57: 
1.173     brouard    58:   Revision 1.172  2014/12/27 12:07:47  brouard
                     59:   Summary: Back from Visual Studio and Intel, options for compiling for Windows XP
                     60: 
1.172     brouard    61:   Revision 1.171  2014/12/23 13:26:59  brouard
                     62:   Summary: Back from Visual C
                     63: 
                     64:   Still problem with utsname.h on Windows
                     65: 
1.171     brouard    66:   Revision 1.170  2014/12/23 11:17:12  brouard
                     67:   Summary: Cleaning some \%% back to %%
                     68: 
                     69:   The escape was mandatory for a specific compiler (which one?), but too many warnings.
                     70: 
1.170     brouard    71:   Revision 1.169  2014/12/22 23:08:31  brouard
                     72:   Summary: 0.98p
                     73: 
                     74:   Outputs some informations on compiler used, OS etc. Testing on different platforms.
                     75: 
1.169     brouard    76:   Revision 1.168  2014/12/22 15:17:42  brouard
1.170     brouard    77:   Summary: update
1.169     brouard    78: 
1.168     brouard    79:   Revision 1.167  2014/12/22 13:50:56  brouard
                     80:   Summary: Testing uname and compiler version and if compiled 32 or 64
                     81: 
                     82:   Testing on Linux 64
                     83: 
1.167     brouard    84:   Revision 1.166  2014/12/22 11:40:47  brouard
                     85:   *** empty log message ***
                     86: 
1.166     brouard    87:   Revision 1.165  2014/12/16 11:20:36  brouard
                     88:   Summary: After compiling on Visual C
                     89: 
                     90:   * imach.c (Module): Merging 1.61 to 1.162
                     91: 
1.165     brouard    92:   Revision 1.164  2014/12/16 10:52:11  brouard
                     93:   Summary: Merging with Visual C after suppressing some warnings for unused variables. Also fixing Saito's bug 0.98Xn
                     94: 
                     95:   * imach.c (Module): Merging 1.61 to 1.162
                     96: 
1.164     brouard    97:   Revision 1.163  2014/12/16 10:30:11  brouard
                     98:   * imach.c (Module): Merging 1.61 to 1.162
                     99: 
1.163     brouard   100:   Revision 1.162  2014/09/25 11:43:39  brouard
                    101:   Summary: temporary backup 0.99!
                    102: 
1.162     brouard   103:   Revision 1.1  2014/09/16 11:06:58  brouard
                    104:   Summary: With some code (wrong) for nlopt
                    105: 
                    106:   Author:
                    107: 
                    108:   Revision 1.161  2014/09/15 20:41:41  brouard
                    109:   Summary: Problem with macro SQR on Intel compiler
                    110: 
1.161     brouard   111:   Revision 1.160  2014/09/02 09:24:05  brouard
                    112:   *** empty log message ***
                    113: 
1.160     brouard   114:   Revision 1.159  2014/09/01 10:34:10  brouard
                    115:   Summary: WIN32
                    116:   Author: Brouard
                    117: 
1.159     brouard   118:   Revision 1.158  2014/08/27 17:11:51  brouard
                    119:   *** empty log message ***
                    120: 
1.158     brouard   121:   Revision 1.157  2014/08/27 16:26:55  brouard
                    122:   Summary: Preparing windows Visual studio version
                    123:   Author: Brouard
                    124: 
                    125:   In order to compile on Visual studio, time.h is now correct and time_t
                    126:   and tm struct should be used. difftime should be used but sometimes I
                    127:   just make the differences in raw time format (time(&now).
                    128:   Trying to suppress #ifdef LINUX
                    129:   Add xdg-open for __linux in order to open default browser.
                    130: 
1.157     brouard   131:   Revision 1.156  2014/08/25 20:10:10  brouard
                    132:   *** empty log message ***
                    133: 
1.156     brouard   134:   Revision 1.155  2014/08/25 18:32:34  brouard
                    135:   Summary: New compile, minor changes
                    136:   Author: Brouard
                    137: 
1.155     brouard   138:   Revision 1.154  2014/06/20 17:32:08  brouard
                    139:   Summary: Outputs now all graphs of convergence to period prevalence
                    140: 
1.154     brouard   141:   Revision 1.153  2014/06/20 16:45:46  brouard
                    142:   Summary: If 3 live state, convergence to period prevalence on same graph
                    143:   Author: Brouard
                    144: 
1.153     brouard   145:   Revision 1.152  2014/06/18 17:54:09  brouard
                    146:   Summary: open browser, use gnuplot on same dir than imach if not found in the path
                    147: 
1.152     brouard   148:   Revision 1.151  2014/06/18 16:43:30  brouard
                    149:   *** empty log message ***
                    150: 
1.151     brouard   151:   Revision 1.150  2014/06/18 16:42:35  brouard
                    152:   Summary: If gnuplot is not in the path try on same directory than imach binary (OSX)
                    153:   Author: brouard
                    154: 
1.150     brouard   155:   Revision 1.149  2014/06/18 15:51:14  brouard
                    156:   Summary: Some fixes in parameter files errors
                    157:   Author: Nicolas Brouard
                    158: 
1.149     brouard   159:   Revision 1.148  2014/06/17 17:38:48  brouard
                    160:   Summary: Nothing new
                    161:   Author: Brouard
                    162: 
                    163:   Just a new packaging for OS/X version 0.98nS
                    164: 
1.148     brouard   165:   Revision 1.147  2014/06/16 10:33:11  brouard
                    166:   *** empty log message ***
                    167: 
1.147     brouard   168:   Revision 1.146  2014/06/16 10:20:28  brouard
                    169:   Summary: Merge
                    170:   Author: Brouard
                    171: 
                    172:   Merge, before building revised version.
                    173: 
1.146     brouard   174:   Revision 1.145  2014/06/10 21:23:15  brouard
                    175:   Summary: Debugging with valgrind
                    176:   Author: Nicolas Brouard
                    177: 
                    178:   Lot of changes in order to output the results with some covariates
                    179:   After the Edimburgh REVES conference 2014, it seems mandatory to
                    180:   improve the code.
                    181:   No more memory valgrind error but a lot has to be done in order to
                    182:   continue the work of splitting the code into subroutines.
                    183:   Also, decodemodel has been improved. Tricode is still not
                    184:   optimal. nbcode should be improved. Documentation has been added in
                    185:   the source code.
                    186: 
1.144     brouard   187:   Revision 1.143  2014/01/26 09:45:38  brouard
                    188:   Summary: Version 0.98nR (to be improved, but gives same optimization results as 0.98k. Nice, promising
                    189: 
                    190:   * imach.c (Module): Trying to merge old staffs together while being at Tokyo. Not tested...
                    191:   (Module): Version 0.98nR Running ok, but output format still only works for three covariates.
                    192: 
1.143     brouard   193:   Revision 1.142  2014/01/26 03:57:36  brouard
                    194:   Summary: gnuplot changed plot w l 1 has to be changed to plot w l lt 2
                    195: 
                    196:   * imach.c (Module): Trying to merge old staffs together while being at Tokyo. Not tested...
                    197: 
1.142     brouard   198:   Revision 1.141  2014/01/26 02:42:01  brouard
                    199:   * imach.c (Module): Trying to merge old staffs together while being at Tokyo. Not tested...
                    200: 
1.141     brouard   201:   Revision 1.140  2011/09/02 10:37:54  brouard
                    202:   Summary: times.h is ok with mingw32 now.
                    203: 
1.140     brouard   204:   Revision 1.139  2010/06/14 07:50:17  brouard
                    205:   After the theft of my laptop, I probably lost some lines of codes which were not uploaded to the CVS tree.
                    206:   I remember having already fixed agemin agemax which are pointers now but not cvs saved.
                    207: 
1.139     brouard   208:   Revision 1.138  2010/04/30 18:19:40  brouard
                    209:   *** empty log message ***
                    210: 
1.138     brouard   211:   Revision 1.137  2010/04/29 18:11:38  brouard
                    212:   (Module): Checking covariates for more complex models
                    213:   than V1+V2. A lot of change to be done. Unstable.
                    214: 
1.137     brouard   215:   Revision 1.136  2010/04/26 20:30:53  brouard
                    216:   (Module): merging some libgsl code. Fixing computation
                    217:   of likelione (using inter/intrapolation if mle = 0) in order to
                    218:   get same likelihood as if mle=1.
                    219:   Some cleaning of code and comments added.
                    220: 
1.136     brouard   221:   Revision 1.135  2009/10/29 15:33:14  brouard
                    222:   (Module): Now imach stops if date of birth, at least year of birth, is not given. Some cleaning of the code.
                    223: 
1.135     brouard   224:   Revision 1.134  2009/10/29 13:18:53  brouard
                    225:   (Module): Now imach stops if date of birth, at least year of birth, is not given. Some cleaning of the code.
                    226: 
1.134     brouard   227:   Revision 1.133  2009/07/06 10:21:25  brouard
                    228:   just nforces
                    229: 
1.133     brouard   230:   Revision 1.132  2009/07/06 08:22:05  brouard
                    231:   Many tings
                    232: 
1.132     brouard   233:   Revision 1.131  2009/06/20 16:22:47  brouard
                    234:   Some dimensions resccaled
                    235: 
1.131     brouard   236:   Revision 1.130  2009/05/26 06:44:34  brouard
                    237:   (Module): Max Covariate is now set to 20 instead of 8. A
                    238:   lot of cleaning with variables initialized to 0. Trying to make
                    239:   V2+V3*age+V1+V4 strb=V3*age+V1+V4 working better.
                    240: 
1.130     brouard   241:   Revision 1.129  2007/08/31 13:49:27  lievre
                    242:   Modification of the way of exiting when the covariate is not binary in order to see on the window the error message before exiting
                    243: 
1.129     lievre    244:   Revision 1.128  2006/06/30 13:02:05  brouard
                    245:   (Module): Clarifications on computing e.j
                    246: 
1.128     brouard   247:   Revision 1.127  2006/04/28 18:11:50  brouard
                    248:   (Module): Yes the sum of survivors was wrong since
                    249:   imach-114 because nhstepm was no more computed in the age
                    250:   loop. Now we define nhstepma in the age loop.
                    251:   (Module): In order to speed up (in case of numerous covariates) we
                    252:   compute health expectancies (without variances) in a first step
                    253:   and then all the health expectancies with variances or standard
                    254:   deviation (needs data from the Hessian matrices) which slows the
                    255:   computation.
                    256:   In the future we should be able to stop the program is only health
                    257:   expectancies and graph are needed without standard deviations.
                    258: 
1.127     brouard   259:   Revision 1.126  2006/04/28 17:23:28  brouard
                    260:   (Module): Yes the sum of survivors was wrong since
                    261:   imach-114 because nhstepm was no more computed in the age
                    262:   loop. Now we define nhstepma in the age loop.
                    263:   Version 0.98h
                    264: 
1.126     brouard   265:   Revision 1.125  2006/04/04 15:20:31  lievre
                    266:   Errors in calculation of health expectancies. Age was not initialized.
                    267:   Forecasting file added.
                    268: 
                    269:   Revision 1.124  2006/03/22 17:13:53  lievre
                    270:   Parameters are printed with %lf instead of %f (more numbers after the comma).
                    271:   The log-likelihood is printed in the log file
                    272: 
                    273:   Revision 1.123  2006/03/20 10:52:43  brouard
                    274:   * imach.c (Module): <title> changed, corresponds to .htm file
                    275:   name. <head> headers where missing.
                    276: 
                    277:   * imach.c (Module): Weights can have a decimal point as for
                    278:   English (a comma might work with a correct LC_NUMERIC environment,
                    279:   otherwise the weight is truncated).
                    280:   Modification of warning when the covariates values are not 0 or
                    281:   1.
                    282:   Version 0.98g
                    283: 
                    284:   Revision 1.122  2006/03/20 09:45:41  brouard
                    285:   (Module): Weights can have a decimal point as for
                    286:   English (a comma might work with a correct LC_NUMERIC environment,
                    287:   otherwise the weight is truncated).
                    288:   Modification of warning when the covariates values are not 0 or
                    289:   1.
                    290:   Version 0.98g
                    291: 
                    292:   Revision 1.121  2006/03/16 17:45:01  lievre
                    293:   * imach.c (Module): Comments concerning covariates added
                    294: 
                    295:   * imach.c (Module): refinements in the computation of lli if
                    296:   status=-2 in order to have more reliable computation if stepm is
                    297:   not 1 month. Version 0.98f
                    298: 
                    299:   Revision 1.120  2006/03/16 15:10:38  lievre
                    300:   (Module): refinements in the computation of lli if
                    301:   status=-2 in order to have more reliable computation if stepm is
                    302:   not 1 month. Version 0.98f
                    303: 
                    304:   Revision 1.119  2006/03/15 17:42:26  brouard
                    305:   (Module): Bug if status = -2, the loglikelihood was
                    306:   computed as likelihood omitting the logarithm. Version O.98e
                    307: 
                    308:   Revision 1.118  2006/03/14 18:20:07  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.117  2006/03/14 17:16:22  brouard
                    316:   (Module): varevsij Comments added explaining the second
                    317:   table of variances if popbased=1 .
                    318:   (Module): Covariances of eij, ekl added, graphs fixed, new html link.
                    319:   (Module): Function pstamp added
                    320:   (Module): Version 0.98d
                    321: 
                    322:   Revision 1.116  2006/03/06 10:29:27  brouard
                    323:   (Module): Variance-covariance wrong links and
                    324:   varian-covariance of ej. is needed (Saito).
                    325: 
                    326:   Revision 1.115  2006/02/27 12:17:45  brouard
                    327:   (Module): One freematrix added in mlikeli! 0.98c
                    328: 
                    329:   Revision 1.114  2006/02/26 12:57:58  brouard
                    330:   (Module): Some improvements in processing parameter
                    331:   filename with strsep.
                    332: 
                    333:   Revision 1.113  2006/02/24 14:20:24  brouard
                    334:   (Module): Memory leaks checks with valgrind and:
                    335:   datafile was not closed, some imatrix were not freed and on matrix
                    336:   allocation too.
                    337: 
                    338:   Revision 1.112  2006/01/30 09:55:26  brouard
                    339:   (Module): Back to gnuplot.exe instead of wgnuplot.exe
                    340: 
                    341:   Revision 1.111  2006/01/25 20:38:18  brouard
                    342:   (Module): Lots of cleaning and bugs added (Gompertz)
                    343:   (Module): Comments can be added in data file. Missing date values
                    344:   can be a simple dot '.'.
                    345: 
                    346:   Revision 1.110  2006/01/25 00:51:50  brouard
                    347:   (Module): Lots of cleaning and bugs added (Gompertz)
                    348: 
                    349:   Revision 1.109  2006/01/24 19:37:15  brouard
                    350:   (Module): Comments (lines starting with a #) are allowed in data.
                    351: 
                    352:   Revision 1.108  2006/01/19 18:05:42  lievre
                    353:   Gnuplot problem appeared...
                    354:   To be fixed
                    355: 
                    356:   Revision 1.107  2006/01/19 16:20:37  brouard
                    357:   Test existence of gnuplot in imach path
                    358: 
                    359:   Revision 1.106  2006/01/19 13:24:36  brouard
                    360:   Some cleaning and links added in html output
                    361: 
                    362:   Revision 1.105  2006/01/05 20:23:19  lievre
                    363:   *** empty log message ***
                    364: 
                    365:   Revision 1.104  2005/09/30 16:11:43  lievre
                    366:   (Module): sump fixed, loop imx fixed, and simplifications.
                    367:   (Module): If the status is missing at the last wave but we know
                    368:   that the person is alive, then we can code his/her status as -2
                    369:   (instead of missing=-1 in earlier versions) and his/her
                    370:   contributions to the likelihood is 1 - Prob of dying from last
                    371:   health status (= 1-p13= p11+p12 in the easiest case of somebody in
                    372:   the healthy state at last known wave). Version is 0.98
                    373: 
                    374:   Revision 1.103  2005/09/30 15:54:49  lievre
                    375:   (Module): sump fixed, loop imx fixed, and simplifications.
                    376: 
                    377:   Revision 1.102  2004/09/15 17:31:30  brouard
                    378:   Add the possibility to read data file including tab characters.
                    379: 
                    380:   Revision 1.101  2004/09/15 10:38:38  brouard
                    381:   Fix on curr_time
                    382: 
                    383:   Revision 1.100  2004/07/12 18:29:06  brouard
                    384:   Add version for Mac OS X. Just define UNIX in Makefile
                    385: 
                    386:   Revision 1.99  2004/06/05 08:57:40  brouard
                    387:   *** empty log message ***
                    388: 
                    389:   Revision 1.98  2004/05/16 15:05:56  brouard
                    390:   New version 0.97 . First attempt to estimate force of mortality
                    391:   directly from the data i.e. without the need of knowing the health
                    392:   state at each age, but using a Gompertz model: log u =a + b*age .
                    393:   This is the basic analysis of mortality and should be done before any
                    394:   other analysis, in order to test if the mortality estimated from the
                    395:   cross-longitudinal survey is different from the mortality estimated
                    396:   from other sources like vital statistic data.
                    397: 
                    398:   The same imach parameter file can be used but the option for mle should be -3.
                    399: 
1.133     brouard   400:   Agnès, who wrote this part of the code, tried to keep most of the
1.126     brouard   401:   former routines in order to include the new code within the former code.
                    402: 
                    403:   The output is very simple: only an estimate of the intercept and of
                    404:   the slope with 95% confident intervals.
                    405: 
                    406:   Current limitations:
                    407:   A) Even if you enter covariates, i.e. with the
                    408:   model= V1+V2 equation for example, the programm does only estimate a unique global model without covariates.
                    409:   B) There is no computation of Life Expectancy nor Life Table.
                    410: 
                    411:   Revision 1.97  2004/02/20 13:25:42  lievre
                    412:   Version 0.96d. Population forecasting command line is (temporarily)
                    413:   suppressed.
                    414: 
                    415:   Revision 1.96  2003/07/15 15:38:55  brouard
                    416:   * imach.c (Repository): Errors in subdirf, 2, 3 while printing tmpout is
                    417:   rewritten within the same printf. Workaround: many printfs.
                    418: 
                    419:   Revision 1.95  2003/07/08 07:54:34  brouard
                    420:   * imach.c (Repository):
                    421:   (Repository): Using imachwizard code to output a more meaningful covariance
                    422:   matrix (cov(a12,c31) instead of numbers.
                    423: 
                    424:   Revision 1.94  2003/06/27 13:00:02  brouard
                    425:   Just cleaning
                    426: 
                    427:   Revision 1.93  2003/06/25 16:33:55  brouard
                    428:   (Module): On windows (cygwin) function asctime_r doesn't
                    429:   exist so I changed back to asctime which exists.
                    430:   (Module): Version 0.96b
                    431: 
                    432:   Revision 1.92  2003/06/25 16:30:45  brouard
                    433:   (Module): On windows (cygwin) function asctime_r doesn't
                    434:   exist so I changed back to asctime which exists.
                    435: 
                    436:   Revision 1.91  2003/06/25 15:30:29  brouard
                    437:   * imach.c (Repository): Duplicated warning errors corrected.
                    438:   (Repository): Elapsed time after each iteration is now output. It
                    439:   helps to forecast when convergence will be reached. Elapsed time
                    440:   is stamped in powell.  We created a new html file for the graphs
                    441:   concerning matrix of covariance. It has extension -cov.htm.
                    442: 
                    443:   Revision 1.90  2003/06/24 12:34:15  brouard
                    444:   (Module): Some bugs corrected for windows. Also, when
                    445:   mle=-1 a template is output in file "or"mypar.txt with the design
                    446:   of the covariance matrix to be input.
                    447: 
                    448:   Revision 1.89  2003/06/24 12:30:52  brouard
                    449:   (Module): Some bugs corrected for windows. Also, when
                    450:   mle=-1 a template is output in file "or"mypar.txt with the design
                    451:   of the covariance matrix to be input.
                    452: 
                    453:   Revision 1.88  2003/06/23 17:54:56  brouard
                    454:   * 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.
                    455: 
                    456:   Revision 1.87  2003/06/18 12:26:01  brouard
                    457:   Version 0.96
                    458: 
                    459:   Revision 1.86  2003/06/17 20:04:08  brouard
                    460:   (Module): Change position of html and gnuplot routines and added
                    461:   routine fileappend.
                    462: 
                    463:   Revision 1.85  2003/06/17 13:12:43  brouard
                    464:   * imach.c (Repository): Check when date of death was earlier that
                    465:   current date of interview. It may happen when the death was just
                    466:   prior to the death. In this case, dh was negative and likelihood
                    467:   was wrong (infinity). We still send an "Error" but patch by
                    468:   assuming that the date of death was just one stepm after the
                    469:   interview.
                    470:   (Repository): Because some people have very long ID (first column)
                    471:   we changed int to long in num[] and we added a new lvector for
                    472:   memory allocation. But we also truncated to 8 characters (left
                    473:   truncation)
                    474:   (Repository): No more line truncation errors.
                    475: 
                    476:   Revision 1.84  2003/06/13 21:44:43  brouard
                    477:   * imach.c (Repository): Replace "freqsummary" at a correct
                    478:   place. It differs from routine "prevalence" which may be called
                    479:   many times. Probs is memory consuming and must be used with
                    480:   parcimony.
                    481:   Version 0.95a3 (should output exactly the same maximization than 0.8a2)
                    482: 
                    483:   Revision 1.83  2003/06/10 13:39:11  lievre
                    484:   *** empty log message ***
                    485: 
                    486:   Revision 1.82  2003/06/05 15:57:20  brouard
                    487:   Add log in  imach.c and  fullversion number is now printed.
                    488: 
                    489: */
                    490: /*
                    491:    Interpolated Markov Chain
                    492: 
                    493:   Short summary of the programme:
                    494:   
                    495:   This program computes Healthy Life Expectancies from
                    496:   cross-longitudinal data. Cross-longitudinal data consist in: -1- a
                    497:   first survey ("cross") where individuals from different ages are
                    498:   interviewed on their health status or degree of disability (in the
                    499:   case of a health survey which is our main interest) -2- at least a
                    500:   second wave of interviews ("longitudinal") which measure each change
                    501:   (if any) in individual health status.  Health expectancies are
                    502:   computed from the time spent in each health state according to a
                    503:   model. More health states you consider, more time is necessary to reach the
                    504:   Maximum Likelihood of the parameters involved in the model.  The
                    505:   simplest model is the multinomial logistic model where pij is the
                    506:   probability to be observed in state j at the second wave
                    507:   conditional to be observed in state i at the first wave. Therefore
                    508:   the model is: log(pij/pii)= aij + bij*age+ cij*sex + etc , where
                    509:   'age' is age and 'sex' is a covariate. If you want to have a more
                    510:   complex model than "constant and age", you should modify the program
                    511:   where the markup *Covariates have to be included here again* invites
                    512:   you to do it.  More covariates you add, slower the
                    513:   convergence.
                    514: 
                    515:   The advantage of this computer programme, compared to a simple
                    516:   multinomial logistic model, is clear when the delay between waves is not
                    517:   identical for each individual. Also, if a individual missed an
                    518:   intermediate interview, the information is lost, but taken into
                    519:   account using an interpolation or extrapolation.  
                    520: 
                    521:   hPijx is the probability to be observed in state i at age x+h
                    522:   conditional to the observed state i at age x. The delay 'h' can be
                    523:   split into an exact number (nh*stepm) of unobserved intermediate
                    524:   states. This elementary transition (by month, quarter,
                    525:   semester or year) is modelled as a multinomial logistic.  The hPx
                    526:   matrix is simply the matrix product of nh*stepm elementary matrices
                    527:   and the contribution of each individual to the likelihood is simply
                    528:   hPijx.
                    529: 
                    530:   Also this programme outputs the covariance matrix of the parameters but also
                    531:   of the life expectancies. It also computes the period (stable) prevalence. 
                    532:   
1.133     brouard   533:   Authors: Nicolas Brouard (brouard@ined.fr) and Agnès Lièvre (lievre@ined.fr).
                    534:            Institut national d'études démographiques, Paris.
1.126     brouard   535:   This software have been partly granted by Euro-REVES, a concerted action
                    536:   from the European Union.
                    537:   It is copyrighted identically to a GNU software product, ie programme and
                    538:   software can be distributed freely for non commercial use. Latest version
                    539:   can be accessed at http://euroreves.ined.fr/imach .
                    540: 
                    541:   Help to debug: LD_PRELOAD=/usr/local/lib/libnjamd.so ./imach foo.imach
                    542:   or better on gdb : set env LD_PRELOAD=/usr/local/lib/libnjamd.so
                    543:   
                    544:   **********************************************************************/
                    545: /*
                    546:   main
                    547:   read parameterfile
                    548:   read datafile
                    549:   concatwav
                    550:   freqsummary
                    551:   if (mle >= 1)
                    552:     mlikeli
                    553:   print results files
                    554:   if mle==1 
                    555:      computes hessian
                    556:   read end of parameter file: agemin, agemax, bage, fage, estepm
                    557:       begin-prev-date,...
                    558:   open gnuplot file
                    559:   open html file
1.145     brouard   560:   period (stable) prevalence      | pl_nom    1-1 2-2 etc by covariate
                    561:    for age prevalim()             | #****** V1=0  V2=1  V3=1  V4=0 ******
                    562:                                   | 65 1 0 2 1 3 1 4 0  0.96326 0.03674
                    563:     freexexit2 possible for memory heap.
                    564: 
                    565:   h Pij x                         | pij_nom  ficrestpij
                    566:    # Cov Agex agex+h hpijx with i,j= 1-1 1-2     1-3     2-1     2-2     2-3
                    567:        1  85   85    1.00000             0.00000 0.00000 0.00000 1.00000 0.00000
                    568:        1  85   86    0.68299             0.22291 0.09410 0.71093 0.00000 0.28907
                    569: 
                    570:        1  65   99    0.00364             0.00322 0.99314 0.00350 0.00310 0.99340
                    571:        1  65  100    0.00214             0.00204 0.99581 0.00206 0.00196 0.99597
                    572:   variance of p one-step probabilities varprob  | prob_nom   ficresprob #One-step probabilities and stand. devi in ()
                    573:    Standard deviation of one-step probabilities | probcor_nom   ficresprobcor #One-step probabilities and correlation matrix
                    574:    Matrix of variance covariance of one-step probabilities |  probcov_nom ficresprobcov #One-step probabilities and covariance matrix
                    575: 
1.126     brouard   576:   forecasting if prevfcast==1 prevforecast call prevalence()
                    577:   health expectancies
                    578:   Variance-covariance of DFLE
                    579:   prevalence()
                    580:    movingaverage()
                    581:   varevsij() 
                    582:   if popbased==1 varevsij(,popbased)
                    583:   total life expectancies
                    584:   Variance of period (stable) prevalence
                    585:  end
                    586: */
                    587: 
1.187   ! brouard   588: /* #define DEBUG */
        !           589: /* #define DEBUGBRENT */
1.165     brouard   590: #define POWELL /* Instead of NLOPT */
1.186     brouard   591: /* #define POWELLORIGINAL /\* Don't use Directest to decide new direction but original Powell test *\/ */
                    592: /* #define MNBRAKORIGINAL /\* Don't use mnbrak fix *\/ */
1.126     brouard   593: 
                    594: #include <math.h>
                    595: #include <stdio.h>
                    596: #include <stdlib.h>
                    597: #include <string.h>
1.159     brouard   598: 
                    599: #ifdef _WIN32
                    600: #include <io.h>
1.172     brouard   601: #include <windows.h>
                    602: #include <tchar.h>
1.159     brouard   603: #else
1.126     brouard   604: #include <unistd.h>
1.159     brouard   605: #endif
1.126     brouard   606: 
                    607: #include <limits.h>
                    608: #include <sys/types.h>
1.171     brouard   609: 
                    610: #if defined(__GNUC__)
                    611: #include <sys/utsname.h> /* Doesn't work on Windows */
                    612: #endif
                    613: 
1.126     brouard   614: #include <sys/stat.h>
                    615: #include <errno.h>
1.159     brouard   616: /* extern int errno; */
1.126     brouard   617: 
1.157     brouard   618: /* #ifdef LINUX */
                    619: /* #include <time.h> */
                    620: /* #include "timeval.h" */
                    621: /* #else */
                    622: /* #include <sys/time.h> */
                    623: /* #endif */
                    624: 
1.126     brouard   625: #include <time.h>
                    626: 
1.136     brouard   627: #ifdef GSL
                    628: #include <gsl/gsl_errno.h>
                    629: #include <gsl/gsl_multimin.h>
                    630: #endif
                    631: 
1.167     brouard   632: 
1.162     brouard   633: #ifdef NLOPT
                    634: #include <nlopt.h>
                    635: typedef struct {
                    636:   double (* function)(double [] );
                    637: } myfunc_data ;
                    638: #endif
                    639: 
1.126     brouard   640: /* #include <libintl.h> */
                    641: /* #define _(String) gettext (String) */
                    642: 
1.141     brouard   643: #define MAXLINE 1024 /* Was 256. Overflow with 312 with 2 states and 4 covariates. Should be ok */
1.126     brouard   644: 
                    645: #define GNUPLOTPROGRAM "gnuplot"
                    646: /*#define GNUPLOTPROGRAM "..\\gp37mgw\\wgnuplot"*/
                    647: #define FILENAMELENGTH 132
                    648: 
                    649: #define        GLOCK_ERROR_NOPATH              -1      /* empty path */
                    650: #define        GLOCK_ERROR_GETCWD              -2      /* cannot get cwd */
                    651: 
1.144     brouard   652: #define MAXPARM 128 /**< Maximum number of parameters for the optimization */
                    653: #define NPARMAX 64 /**< (nlstate+ndeath-1)*nlstate*ncovmodel */
1.126     brouard   654: 
                    655: #define NINTERVMAX 8
1.144     brouard   656: #define NLSTATEMAX 8 /**< Maximum number of live states (for func) */
                    657: #define NDEATHMAX 8 /**< Maximum number of dead states (for func) */
                    658: #define NCOVMAX 20 /**< Maximum number of covariates, including generated covariates V1*V2 */
1.145     brouard   659: #define codtabm(h,k)  1 & (h-1) >> (k-1) ;
1.126     brouard   660: #define MAXN 20000
1.144     brouard   661: #define YEARM 12. /**< Number of months per year */
1.126     brouard   662: #define AGESUP 130
                    663: #define AGEBASE 40
1.164     brouard   664: #define AGEGOMP 10 /**< Minimal age for Gompertz adjustment */
1.157     brouard   665: #ifdef _WIN32
                    666: #define DIRSEPARATOR '\\'
                    667: #define CHARSEPARATOR "\\"
                    668: #define ODIRSEPARATOR '/'
                    669: #else
1.126     brouard   670: #define DIRSEPARATOR '/'
                    671: #define CHARSEPARATOR "/"
                    672: #define ODIRSEPARATOR '\\'
                    673: #endif
                    674: 
1.187   ! brouard   675: /* $Id: imach.c,v 1.186 2015/04/23 12:01:52 brouard Exp $ */
1.126     brouard   676: /* $State: Exp $ */
                    677: 
1.186     brouard   678: char version[]="Imach version 0.98q1, April 2015,INED-EUROREVES-Institut de longevite-Japan Society for the Promotion of Science (Grant-in-Aid for Scientific Research 25293121), Intel Software 2015";
1.187   ! brouard   679: char fullversion[]="$Revision: 1.186 $ $Date: 2015/04/23 12:01:52 $"; 
1.126     brouard   680: char strstart[80];
                    681: char optionfilext[10], optionfilefiname[FILENAMELENGTH];
1.130     brouard   682: int erreur=0, nberr=0, nbwarn=0; /* Error number, number of errors number of warnings  */
1.187   ! brouard   683: int nagesqr=0, nforce=0; /* nagesqr=1 if model is including age*age, number of forces */
1.145     brouard   684: /* Number of covariates model=V2+V1+ V3*age+V2*V4 */
                    685: int cptcovn=0; /**< cptcovn number of covariates added in the model (excepting constant and age and age*product) */
                    686: int cptcovt=0; /**< cptcovt number of covariates added in the model (excepting constant and age) */
                    687: int cptcovs=0; /**< cptcovs number of simple covariates V2+V1 =2 */
                    688: int cptcovage=0; /**< Number of covariates with age: V3*age only =1 */
                    689: int cptcovprodnoage=0; /**< Number of covariate products without age */   
                    690: int cptcoveff=0; /* Total number of covariates to vary for printing results */
                    691: int cptcov=0; /* Working variable */
1.126     brouard   692: int npar=NPARMAX;
                    693: int nlstate=2; /* Number of live states */
                    694: int ndeath=1; /* Number of dead states */
1.130     brouard   695: int ncovmodel=0, ncovcol=0;     /* Total number of covariables including constant a12*1 +b12*x ncovmodel=2 */
1.126     brouard   696: int popbased=0;
                    697: 
                    698: int *wav; /* Number of waves for this individuual 0 is possible */
1.130     brouard   699: int maxwav=0; /* Maxim number of waves */
                    700: int jmin=0, jmax=0; /* min, max spacing between 2 waves */
                    701: int ijmin=0, ijmax=0; /* Individuals having jmin and jmax */ 
                    702: int gipmx=0, gsw=0; /* Global variables on the number of contributions 
1.126     brouard   703:                   to the likelihood and the sum of weights (done by funcone)*/
1.130     brouard   704: int mle=1, weightopt=0;
1.126     brouard   705: int **mw; /* mw[mi][i] is number of the mi wave for this individual */
                    706: int **dh; /* dh[mi][i] is number of steps between mi,mi+1 for this individual */
                    707: int **bh; /* bh[mi][i] is the bias (+ or -) for this individual if the delay between
                    708:           * wave mi and wave mi+1 is not an exact multiple of stepm. */
1.162     brouard   709: int countcallfunc=0;  /* Count the number of calls to func */
1.130     brouard   710: double jmean=1; /* Mean space between 2 waves */
1.145     brouard   711: double **matprod2(); /* test */
1.126     brouard   712: double **oldm, **newm, **savm; /* Working pointers to matrices */
                    713: double **oldms, **newms, **savms; /* Fixed working pointers to matrices */
1.136     brouard   714: /*FILE *fic ; */ /* Used in readdata only */
                    715: FILE *ficpar, *ficparo,*ficres, *ficresp, *ficrespl, *ficrespij, *ficrest,*ficresf,*ficrespop;
1.126     brouard   716: FILE *ficlog, *ficrespow;
1.130     brouard   717: int globpr=0; /* Global variable for printing or not */
1.126     brouard   718: double fretone; /* Only one call to likelihood */
1.130     brouard   719: long ipmx=0; /* Number of contributions */
1.126     brouard   720: double sw; /* Sum of weights */
                    721: char filerespow[FILENAMELENGTH];
                    722: char fileresilk[FILENAMELENGTH]; /* File of individual contributions to the likelihood */
                    723: FILE *ficresilk;
                    724: FILE *ficgp,*ficresprob,*ficpop, *ficresprobcov, *ficresprobcor;
                    725: FILE *ficresprobmorprev;
                    726: FILE *fichtm, *fichtmcov; /* Html File */
                    727: FILE *ficreseij;
                    728: char filerese[FILENAMELENGTH];
                    729: FILE *ficresstdeij;
                    730: char fileresstde[FILENAMELENGTH];
                    731: FILE *ficrescveij;
                    732: char filerescve[FILENAMELENGTH];
                    733: FILE  *ficresvij;
                    734: char fileresv[FILENAMELENGTH];
                    735: FILE  *ficresvpl;
                    736: char fileresvpl[FILENAMELENGTH];
                    737: char title[MAXLINE];
                    738: char optionfile[FILENAMELENGTH], datafile[FILENAMELENGTH],  filerespl[FILENAMELENGTH];
                    739: char plotcmd[FILENAMELENGTH], pplotcmd[FILENAMELENGTH];
                    740: char tmpout[FILENAMELENGTH],  tmpout2[FILENAMELENGTH]; 
                    741: char command[FILENAMELENGTH];
                    742: int  outcmd=0;
                    743: 
                    744: char fileres[FILENAMELENGTH], filerespij[FILENAMELENGTH], filereso[FILENAMELENGTH], rfileres[FILENAMELENGTH];
                    745: 
                    746: char filelog[FILENAMELENGTH]; /* Log file */
                    747: char filerest[FILENAMELENGTH];
                    748: char fileregp[FILENAMELENGTH];
                    749: char popfile[FILENAMELENGTH];
                    750: 
                    751: char optionfilegnuplot[FILENAMELENGTH], optionfilehtm[FILENAMELENGTH], optionfilehtmcov[FILENAMELENGTH] ;
                    752: 
1.157     brouard   753: /* struct timeval start_time, end_time, curr_time, last_time, forecast_time; */
                    754: /* struct timezone tzp; */
                    755: /* extern int gettimeofday(); */
                    756: struct tm tml, *gmtime(), *localtime();
                    757: 
                    758: extern time_t time();
                    759: 
                    760: struct tm start_time, end_time, curr_time, last_time, forecast_time;
                    761: time_t  rstart_time, rend_time, rcurr_time, rlast_time, rforecast_time; /* raw time */
                    762: struct tm tm;
                    763: 
1.126     brouard   764: char strcurr[80], strfor[80];
                    765: 
                    766: char *endptr;
                    767: long lval;
                    768: double dval;
                    769: 
                    770: #define NR_END 1
                    771: #define FREE_ARG char*
                    772: #define FTOL 1.0e-10
                    773: 
                    774: #define NRANSI 
                    775: #define ITMAX 200 
                    776: 
                    777: #define TOL 2.0e-4 
                    778: 
                    779: #define CGOLD 0.3819660 
                    780: #define ZEPS 1.0e-10 
                    781: #define SHFT(a,b,c,d) (a)=(b);(b)=(c);(c)=(d); 
                    782: 
                    783: #define GOLD 1.618034 
                    784: #define GLIMIT 100.0 
                    785: #define TINY 1.0e-20 
                    786: 
                    787: static double maxarg1,maxarg2;
                    788: #define FMAX(a,b) (maxarg1=(a),maxarg2=(b),(maxarg1)>(maxarg2)? (maxarg1):(maxarg2))
                    789: #define FMIN(a,b) (maxarg1=(a),maxarg2=(b),(maxarg1)<(maxarg2)? (maxarg1):(maxarg2))
                    790:   
                    791: #define SIGN(a,b) ((b)>0.0 ? fabs(a) : -fabs(a))
                    792: #define rint(a) floor(a+0.5)
1.166     brouard   793: /* http://www.thphys.uni-heidelberg.de/~robbers/cmbeasy/doc/html/myutils_8h-source.html */
1.183     brouard   794: #define mytinydouble 1.0e-16
1.166     brouard   795: /* #define DEQUAL(a,b) (fabs((a)-(b))<mytinydouble) */
                    796: /* http://www.thphys.uni-heidelberg.de/~robbers/cmbeasy/doc/html/mynrutils_8h-source.html */
                    797: /* static double dsqrarg; */
                    798: /* #define DSQR(a) (DEQUAL((dsqrarg=(a)),0.0) ? 0.0 : dsqrarg*dsqrarg) */
1.126     brouard   799: static double sqrarg;
                    800: #define SQR(a) ((sqrarg=(a)) == 0.0 ? 0.0 :sqrarg*sqrarg)
                    801: #define SWAP(a,b) {temp=(a);(a)=(b);(b)=temp;} 
                    802: int agegomp= AGEGOMP;
                    803: 
                    804: int imx; 
                    805: int stepm=1;
                    806: /* Stepm, step in month: minimum step interpolation*/
                    807: 
                    808: int estepm;
                    809: /* Estepm, step in month to interpolate survival function in order to approximate Life Expectancy*/
                    810: 
                    811: int m,nb;
                    812: long *num;
                    813: int firstpass=0, lastpass=4,*cod, *ncodemax, *Tage,*cens;
                    814: double **agev,*moisnais, *annais, *moisdc, *andc,**mint, **anint;
                    815: double **pmmij, ***probs;
                    816: double *ageexmed,*agecens;
                    817: double dateintmean=0;
                    818: 
                    819: double *weight;
                    820: int **s; /* Status */
1.141     brouard   821: double *agedc;
1.145     brouard   822: double  **covar; /**< covar[j,i], value of jth covariate for individual i,
1.141     brouard   823:                  * covar=matrix(0,NCOVMAX,1,n); 
1.187   ! brouard   824:                  * cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*age; */
1.141     brouard   825: double  idx; 
                    826: int **nbcode, *Tvar; /**< model=V2 => Tvar[1]= 2 */
1.145     brouard   827: int *Ndum; /** Freq of modality (tricode */
1.141     brouard   828: int **codtab; /**< codtab=imatrix(1,100,1,10); */
                    829: int **Tvard, *Tprod, cptcovprod, *Tvaraff;
1.126     brouard   830: double *lsurv, *lpop, *tpop;
                    831: 
1.143     brouard   832: double ftol=FTOL; /**< Tolerance for computing Max Likelihood */
                    833: double ftolhess; /**< Tolerance for computing hessian */
1.126     brouard   834: 
                    835: /**************** split *************************/
                    836: static int split( char *path, char *dirc, char *name, char *ext, char *finame )
                    837: {
                    838:   /* From a file name with (full) path (either Unix or Windows) we extract the directory (dirc)
                    839:      the name of the file (name), its extension only (ext) and its first part of the name (finame)
                    840:   */ 
                    841:   char *ss;                            /* pointer */
1.186     brouard   842:   int  l1=0, l2=0;                             /* length counters */
1.126     brouard   843: 
                    844:   l1 = strlen(path );                  /* length of path */
                    845:   if ( l1 == 0 ) return( GLOCK_ERROR_NOPATH );
                    846:   ss= strrchr( path, DIRSEPARATOR );           /* find last / */
                    847:   if ( ss == NULL ) {                  /* no directory, so determine current directory */
                    848:     strcpy( name, path );              /* we got the fullname name because no directory */
                    849:     /*if(strrchr(path, ODIRSEPARATOR )==NULL)
                    850:       printf("Warning you should use %s as a separator\n",DIRSEPARATOR);*/
                    851:     /* get current working directory */
                    852:     /*    extern  char* getcwd ( char *buf , int len);*/
1.184     brouard   853: #ifdef WIN32
                    854:     if (_getcwd( dirc, FILENAME_MAX ) == NULL ) {
                    855: #else
                    856:        if (getcwd(dirc, FILENAME_MAX) == NULL) {
                    857: #endif
1.126     brouard   858:       return( GLOCK_ERROR_GETCWD );
                    859:     }
                    860:     /* got dirc from getcwd*/
                    861:     printf(" DIRC = %s \n",dirc);
                    862:   } else {                             /* strip direcotry from path */
                    863:     ss++;                              /* after this, the filename */
                    864:     l2 = strlen( ss );                 /* length of filename */
                    865:     if ( l2 == 0 ) return( GLOCK_ERROR_NOPATH );
                    866:     strcpy( name, ss );                /* save file name */
                    867:     strncpy( dirc, path, l1 - l2 );    /* now the directory */
1.186     brouard   868:     dirc[l1-l2] = '\0';                        /* add zero */
1.126     brouard   869:     printf(" DIRC2 = %s \n",dirc);
                    870:   }
                    871:   /* We add a separator at the end of dirc if not exists */
                    872:   l1 = strlen( dirc );                 /* length of directory */
                    873:   if( dirc[l1-1] != DIRSEPARATOR ){
                    874:     dirc[l1] =  DIRSEPARATOR;
                    875:     dirc[l1+1] = 0; 
                    876:     printf(" DIRC3 = %s \n",dirc);
                    877:   }
                    878:   ss = strrchr( name, '.' );           /* find last / */
                    879:   if (ss >0){
                    880:     ss++;
                    881:     strcpy(ext,ss);                    /* save extension */
                    882:     l1= strlen( name);
                    883:     l2= strlen(ss)+1;
                    884:     strncpy( finame, name, l1-l2);
                    885:     finame[l1-l2]= 0;
                    886:   }
                    887: 
                    888:   return( 0 );                         /* we're done */
                    889: }
                    890: 
                    891: 
                    892: /******************************************/
                    893: 
                    894: void replace_back_to_slash(char *s, char*t)
                    895: {
                    896:   int i;
                    897:   int lg=0;
                    898:   i=0;
                    899:   lg=strlen(t);
                    900:   for(i=0; i<= lg; i++) {
                    901:     (s[i] = t[i]);
                    902:     if (t[i]== '\\') s[i]='/';
                    903:   }
                    904: }
                    905: 
1.132     brouard   906: char *trimbb(char *out, char *in)
1.137     brouard   907: { /* Trim multiple blanks in line but keeps first blanks if line starts with blanks */
1.132     brouard   908:   char *s;
                    909:   s=out;
                    910:   while (*in != '\0'){
1.137     brouard   911:     while( *in == ' ' && *(in+1) == ' '){ /* && *(in+1) != '\0'){*/
1.132     brouard   912:       in++;
                    913:     }
                    914:     *out++ = *in++;
                    915:   }
                    916:   *out='\0';
                    917:   return s;
                    918: }
                    919: 
1.187   ! brouard   920: /* char *substrchaine(char *out, char *in, char *chain) */
        !           921: /* { */
        !           922: /*   /\* Substract chain 'chain' from 'in', return and output 'out' *\/ */
        !           923: /*   char *s, *t; */
        !           924: /*   t=in;s=out; */
        !           925: /*   while ((*in != *chain) && (*in != '\0')){ */
        !           926: /*     *out++ = *in++; */
        !           927: /*   } */
        !           928: 
        !           929: /*   /\* *in matches *chain *\/ */
        !           930: /*   while ((*in++ == *chain++) && (*in != '\0')){ */
        !           931: /*     printf("*in = %c, *out= %c *chain= %c \n", *in, *out, *chain);  */
        !           932: /*   } */
        !           933: /*   in--; chain--; */
        !           934: /*   while ( (*in != '\0')){ */
        !           935: /*     printf("Bef *in = %c, *out= %c *chain= %c \n", *in, *out, *chain);  */
        !           936: /*     *out++ = *in++; */
        !           937: /*     printf("Aft *in = %c, *out= %c *chain= %c \n", *in, *out, *chain);  */
        !           938: /*   } */
        !           939: /*   *out='\0'; */
        !           940: /*   out=s; */
        !           941: /*   return out; */
        !           942: /* } */
        !           943: char *substrchaine(char *out, char *in, char *chain)
        !           944: {
        !           945:   /* Substract chain 'chain' from 'in', return and output 'out' */
        !           946:   /* in="V1+V1*age+age*age+V2", chain="age*age" */
        !           947: 
        !           948:   char *strloc;
        !           949: 
        !           950:   strcpy (out, in); 
        !           951:   strloc = strstr(out, chain); /* strloc points to out at age*age+V2 */
        !           952:   printf("Bef strloc=%s chain=%s out=%s \n", strloc, chain, out);
        !           953:   if(strloc != NULL){ 
        !           954:     /* will affect out */ /* strloc+strlenc(chain)=+V2 */ /* Will also work in Unicode */
        !           955:     memmove(strloc,strloc+strlen(chain), strlen(strloc+strlen(chain))+1);
        !           956:     /* strcpy (strloc, strloc +strlen(chain));*/
        !           957:   }
        !           958:   printf("Aft strloc=%s chain=%s in=%s out=%s \n", strloc, chain, in, out);
        !           959:   return out;
        !           960: }
        !           961: 
        !           962: 
1.145     brouard   963: char *cutl(char *blocc, char *alocc, char *in, char occ)
                    964: {
1.187   ! brouard   965:   /* cuts string in into blocc and alocc where blocc ends before FIRST occurence of char 'occ' 
1.145     brouard   966:      and alocc starts after first occurence of char 'occ' : ex cutv(blocc,alocc,"abcdef2ghi2j",'2')
1.187   ! brouard   967:      gives blocc="abcdef" and alocc="ghi2j".
1.145     brouard   968:      If occ is not found blocc is null and alocc is equal to in. Returns blocc
                    969:   */
1.160     brouard   970:   char *s, *t;
1.145     brouard   971:   t=in;s=in;
                    972:   while ((*in != occ) && (*in != '\0')){
                    973:     *alocc++ = *in++;
                    974:   }
                    975:   if( *in == occ){
                    976:     *(alocc)='\0';
                    977:     s=++in;
                    978:   }
                    979:  
                    980:   if (s == t) {/* occ not found */
                    981:     *(alocc-(in-s))='\0';
                    982:     in=s;
                    983:   }
                    984:   while ( *in != '\0'){
                    985:     *blocc++ = *in++;
                    986:   }
                    987: 
                    988:   *blocc='\0';
                    989:   return t;
                    990: }
1.137     brouard   991: char *cutv(char *blocc, char *alocc, char *in, char occ)
                    992: {
1.187   ! brouard   993:   /* cuts string in into blocc and alocc where blocc ends before LAST occurence of char 'occ' 
1.137     brouard   994:      and alocc starts after last occurence of char 'occ' : ex cutv(blocc,alocc,"abcdef2ghi2j",'2')
                    995:      gives blocc="abcdef2ghi" and alocc="j".
                    996:      If occ is not found blocc is null and alocc is equal to in. Returns alocc
                    997:   */
                    998:   char *s, *t;
                    999:   t=in;s=in;
                   1000:   while (*in != '\0'){
                   1001:     while( *in == occ){
                   1002:       *blocc++ = *in++;
                   1003:       s=in;
                   1004:     }
                   1005:     *blocc++ = *in++;
                   1006:   }
                   1007:   if (s == t) /* occ not found */
                   1008:     *(blocc-(in-s))='\0';
                   1009:   else
                   1010:     *(blocc-(in-s)-1)='\0';
                   1011:   in=s;
                   1012:   while ( *in != '\0'){
                   1013:     *alocc++ = *in++;
                   1014:   }
                   1015: 
                   1016:   *alocc='\0';
                   1017:   return s;
                   1018: }
                   1019: 
1.126     brouard  1020: int nbocc(char *s, char occ)
                   1021: {
                   1022:   int i,j=0;
                   1023:   int lg=20;
                   1024:   i=0;
                   1025:   lg=strlen(s);
                   1026:   for(i=0; i<= lg; i++) {
                   1027:   if  (s[i] == occ ) j++;
                   1028:   }
                   1029:   return j;
                   1030: }
                   1031: 
1.137     brouard  1032: /* void cutv(char *u,char *v, char*t, char occ) */
                   1033: /* { */
                   1034: /*   /\* cuts string t into u and v where u ends before last occurence of char 'occ'  */
                   1035: /*      and v starts after last occurence of char 'occ' : ex cutv(u,v,"abcdef2ghi2j",'2') */
                   1036: /*      gives u="abcdef2ghi" and v="j" *\/ */
                   1037: /*   int i,lg,j,p=0; */
                   1038: /*   i=0; */
                   1039: /*   lg=strlen(t); */
                   1040: /*   for(j=0; j<=lg-1; j++) { */
                   1041: /*     if((t[j]!= occ) && (t[j+1]== occ)) p=j+1; */
                   1042: /*   } */
1.126     brouard  1043: 
1.137     brouard  1044: /*   for(j=0; j<p; j++) { */
                   1045: /*     (u[j] = t[j]); */
                   1046: /*   } */
                   1047: /*      u[p]='\0'; */
1.126     brouard  1048: 
1.137     brouard  1049: /*    for(j=0; j<= lg; j++) { */
                   1050: /*     if (j>=(p+1))(v[j-p-1] = t[j]); */
                   1051: /*   } */
                   1052: /* } */
1.126     brouard  1053: 
1.160     brouard  1054: #ifdef _WIN32
                   1055: char * strsep(char **pp, const char *delim)
                   1056: {
                   1057:   char *p, *q;
                   1058:          
                   1059:   if ((p = *pp) == NULL)
                   1060:     return 0;
                   1061:   if ((q = strpbrk (p, delim)) != NULL)
                   1062:   {
                   1063:     *pp = q + 1;
                   1064:     *q = '\0';
                   1065:   }
                   1066:   else
                   1067:     *pp = 0;
                   1068:   return p;
                   1069: }
                   1070: #endif
                   1071: 
1.126     brouard  1072: /********************** nrerror ********************/
                   1073: 
                   1074: void nrerror(char error_text[])
                   1075: {
                   1076:   fprintf(stderr,"ERREUR ...\n");
                   1077:   fprintf(stderr,"%s\n",error_text);
                   1078:   exit(EXIT_FAILURE);
                   1079: }
                   1080: /*********************** vector *******************/
                   1081: double *vector(int nl, int nh)
                   1082: {
                   1083:   double *v;
                   1084:   v=(double *) malloc((size_t)((nh-nl+1+NR_END)*sizeof(double)));
                   1085:   if (!v) nrerror("allocation failure in vector");
                   1086:   return v-nl+NR_END;
                   1087: }
                   1088: 
                   1089: /************************ free vector ******************/
                   1090: void free_vector(double*v, int nl, int nh)
                   1091: {
                   1092:   free((FREE_ARG)(v+nl-NR_END));
                   1093: }
                   1094: 
                   1095: /************************ivector *******************************/
                   1096: int *ivector(long nl,long nh)
                   1097: {
                   1098:   int *v;
                   1099:   v=(int *) malloc((size_t)((nh-nl+1+NR_END)*sizeof(int)));
                   1100:   if (!v) nrerror("allocation failure in ivector");
                   1101:   return v-nl+NR_END;
                   1102: }
                   1103: 
                   1104: /******************free ivector **************************/
                   1105: void free_ivector(int *v, long nl, long nh)
                   1106: {
                   1107:   free((FREE_ARG)(v+nl-NR_END));
                   1108: }
                   1109: 
                   1110: /************************lvector *******************************/
                   1111: long *lvector(long nl,long nh)
                   1112: {
                   1113:   long *v;
                   1114:   v=(long *) malloc((size_t)((nh-nl+1+NR_END)*sizeof(long)));
                   1115:   if (!v) nrerror("allocation failure in ivector");
                   1116:   return v-nl+NR_END;
                   1117: }
                   1118: 
                   1119: /******************free lvector **************************/
                   1120: void free_lvector(long *v, long nl, long nh)
                   1121: {
                   1122:   free((FREE_ARG)(v+nl-NR_END));
                   1123: }
                   1124: 
                   1125: /******************* imatrix *******************************/
                   1126: int **imatrix(long nrl, long nrh, long ncl, long nch) 
                   1127:      /* allocate a int matrix with subscript range m[nrl..nrh][ncl..nch] */ 
                   1128: { 
                   1129:   long i, nrow=nrh-nrl+1,ncol=nch-ncl+1; 
                   1130:   int **m; 
                   1131:   
                   1132:   /* allocate pointers to rows */ 
                   1133:   m=(int **) malloc((size_t)((nrow+NR_END)*sizeof(int*))); 
                   1134:   if (!m) nrerror("allocation failure 1 in matrix()"); 
                   1135:   m += NR_END; 
                   1136:   m -= nrl; 
                   1137:   
                   1138:   
                   1139:   /* allocate rows and set pointers to them */ 
                   1140:   m[nrl]=(int *) malloc((size_t)((nrow*ncol+NR_END)*sizeof(int))); 
                   1141:   if (!m[nrl]) nrerror("allocation failure 2 in matrix()"); 
                   1142:   m[nrl] += NR_END; 
                   1143:   m[nrl] -= ncl; 
                   1144:   
                   1145:   for(i=nrl+1;i<=nrh;i++) m[i]=m[i-1]+ncol; 
                   1146:   
                   1147:   /* return pointer to array of pointers to rows */ 
                   1148:   return m; 
                   1149: } 
                   1150: 
                   1151: /****************** free_imatrix *************************/
                   1152: void free_imatrix(m,nrl,nrh,ncl,nch)
                   1153:       int **m;
                   1154:       long nch,ncl,nrh,nrl; 
                   1155:      /* free an int matrix allocated by imatrix() */ 
                   1156: { 
                   1157:   free((FREE_ARG) (m[nrl]+ncl-NR_END)); 
                   1158:   free((FREE_ARG) (m+nrl-NR_END)); 
                   1159: } 
                   1160: 
                   1161: /******************* matrix *******************************/
                   1162: double **matrix(long nrl, long nrh, long ncl, long nch)
                   1163: {
                   1164:   long i, nrow=nrh-nrl+1, ncol=nch-ncl+1;
                   1165:   double **m;
                   1166: 
                   1167:   m=(double **) malloc((size_t)((nrow+NR_END)*sizeof(double*)));
                   1168:   if (!m) nrerror("allocation failure 1 in matrix()");
                   1169:   m += NR_END;
                   1170:   m -= nrl;
                   1171: 
                   1172:   m[nrl]=(double *) malloc((size_t)((nrow*ncol+NR_END)*sizeof(double)));
                   1173:   if (!m[nrl]) nrerror("allocation failure 2 in matrix()");
                   1174:   m[nrl] += NR_END;
                   1175:   m[nrl] -= ncl;
                   1176: 
                   1177:   for (i=nrl+1; i<=nrh; i++) m[i]=m[i-1]+ncol;
                   1178:   return m;
1.145     brouard  1179:   /* print *(*(m+1)+70) or print m[1][70]; print m+1 or print &(m[1]) or &(m[1][0])
                   1180: m[i] = address of ith row of the table. &(m[i]) is its value which is another adress
                   1181: that of m[i][0]. In order to get the value p m[i][0] but it is unitialized.
1.126     brouard  1182:    */
                   1183: }
                   1184: 
                   1185: /*************************free matrix ************************/
                   1186: void free_matrix(double **m, long nrl, long nrh, long ncl, long nch)
                   1187: {
                   1188:   free((FREE_ARG)(m[nrl]+ncl-NR_END));
                   1189:   free((FREE_ARG)(m+nrl-NR_END));
                   1190: }
                   1191: 
                   1192: /******************* ma3x *******************************/
                   1193: double ***ma3x(long nrl, long nrh, long ncl, long nch, long nll, long nlh)
                   1194: {
                   1195:   long i, j, nrow=nrh-nrl+1, ncol=nch-ncl+1, nlay=nlh-nll+1;
                   1196:   double ***m;
                   1197: 
                   1198:   m=(double ***) malloc((size_t)((nrow+NR_END)*sizeof(double*)));
                   1199:   if (!m) nrerror("allocation failure 1 in matrix()");
                   1200:   m += NR_END;
                   1201:   m -= nrl;
                   1202: 
                   1203:   m[nrl]=(double **) malloc((size_t)((nrow*ncol+NR_END)*sizeof(double)));
                   1204:   if (!m[nrl]) nrerror("allocation failure 2 in matrix()");
                   1205:   m[nrl] += NR_END;
                   1206:   m[nrl] -= ncl;
                   1207: 
                   1208:   for (i=nrl+1; i<=nrh; i++) m[i]=m[i-1]+ncol;
                   1209: 
                   1210:   m[nrl][ncl]=(double *) malloc((size_t)((nrow*ncol*nlay+NR_END)*sizeof(double)));
                   1211:   if (!m[nrl][ncl]) nrerror("allocation failure 3 in matrix()");
                   1212:   m[nrl][ncl] += NR_END;
                   1213:   m[nrl][ncl] -= nll;
                   1214:   for (j=ncl+1; j<=nch; j++) 
                   1215:     m[nrl][j]=m[nrl][j-1]+nlay;
                   1216:   
                   1217:   for (i=nrl+1; i<=nrh; i++) {
                   1218:     m[i][ncl]=m[i-1l][ncl]+ncol*nlay;
                   1219:     for (j=ncl+1; j<=nch; j++) 
                   1220:       m[i][j]=m[i][j-1]+nlay;
                   1221:   }
                   1222:   return m; 
                   1223:   /*  gdb: p *(m+1) <=> p m[1] and p (m+1) <=> p (m+1) <=> p &(m[1])
                   1224:            &(m[i][j][k]) <=> *((*(m+i) + j)+k)
                   1225:   */
                   1226: }
                   1227: 
                   1228: /*************************free ma3x ************************/
                   1229: void free_ma3x(double ***m, long nrl, long nrh, long ncl, long nch,long nll, long nlh)
                   1230: {
                   1231:   free((FREE_ARG)(m[nrl][ncl]+ nll-NR_END));
                   1232:   free((FREE_ARG)(m[nrl]+ncl-NR_END));
                   1233:   free((FREE_ARG)(m+nrl-NR_END));
                   1234: }
                   1235: 
                   1236: /*************** function subdirf ***********/
                   1237: char *subdirf(char fileres[])
                   1238: {
                   1239:   /* Caution optionfilefiname is hidden */
                   1240:   strcpy(tmpout,optionfilefiname);
                   1241:   strcat(tmpout,"/"); /* Add to the right */
                   1242:   strcat(tmpout,fileres);
                   1243:   return tmpout;
                   1244: }
                   1245: 
                   1246: /*************** function subdirf2 ***********/
                   1247: char *subdirf2(char fileres[], char *preop)
                   1248: {
                   1249:   
                   1250:   /* Caution optionfilefiname is hidden */
                   1251:   strcpy(tmpout,optionfilefiname);
                   1252:   strcat(tmpout,"/");
                   1253:   strcat(tmpout,preop);
                   1254:   strcat(tmpout,fileres);
                   1255:   return tmpout;
                   1256: }
                   1257: 
                   1258: /*************** function subdirf3 ***********/
                   1259: char *subdirf3(char fileres[], char *preop, char *preop2)
                   1260: {
                   1261:   
                   1262:   /* Caution optionfilefiname is hidden */
                   1263:   strcpy(tmpout,optionfilefiname);
                   1264:   strcat(tmpout,"/");
                   1265:   strcat(tmpout,preop);
                   1266:   strcat(tmpout,preop2);
                   1267:   strcat(tmpout,fileres);
                   1268:   return tmpout;
                   1269: }
                   1270: 
1.162     brouard  1271: char *asc_diff_time(long time_sec, char ascdiff[])
                   1272: {
                   1273:   long sec_left, days, hours, minutes;
                   1274:   days = (time_sec) / (60*60*24);
                   1275:   sec_left = (time_sec) % (60*60*24);
                   1276:   hours = (sec_left) / (60*60) ;
                   1277:   sec_left = (sec_left) %(60*60);
                   1278:   minutes = (sec_left) /60;
                   1279:   sec_left = (sec_left) % (60);
                   1280:   sprintf(ascdiff,"%ld day(s) %ld hour(s) %ld minute(s) %ld second(s)",days, hours, minutes, sec_left);  
                   1281:   return ascdiff;
                   1282: }
                   1283: 
1.126     brouard  1284: /***************** f1dim *************************/
                   1285: extern int ncom; 
                   1286: extern double *pcom,*xicom;
                   1287: extern double (*nrfunc)(double []); 
                   1288:  
                   1289: double f1dim(double x) 
                   1290: { 
                   1291:   int j; 
                   1292:   double f;
                   1293:   double *xt; 
                   1294:  
                   1295:   xt=vector(1,ncom); 
                   1296:   for (j=1;j<=ncom;j++) xt[j]=pcom[j]+x*xicom[j]; 
                   1297:   f=(*nrfunc)(xt); 
                   1298:   free_vector(xt,1,ncom); 
                   1299:   return f; 
                   1300: } 
                   1301: 
                   1302: /*****************brent *************************/
                   1303: double brent(double ax, double bx, double cx, double (*f)(double), double tol,         double *xmin) 
1.187   ! brouard  1304: {
        !          1305:   /* Given a function f, and given a bracketing triplet of abscissas ax, bx, cx (such that bx is
        !          1306:    * between ax and cx, and f(bx) is less than both f(ax) and f(cx) ), this routine isolates
        !          1307:    * the minimum to a fractional precision of about tol using Brent’s method. The abscissa of
        !          1308:    * the minimum is returned as xmin, and the minimum function value is returned as brent , the
        !          1309:    * returned function value. 
        !          1310:   */
1.126     brouard  1311:   int iter; 
                   1312:   double a,b,d,etemp;
1.159     brouard  1313:   double fu=0,fv,fw,fx;
1.164     brouard  1314:   double ftemp=0.;
1.126     brouard  1315:   double p,q,r,tol1,tol2,u,v,w,x,xm; 
                   1316:   double e=0.0; 
                   1317:  
                   1318:   a=(ax < cx ? ax : cx); 
                   1319:   b=(ax > cx ? ax : cx); 
                   1320:   x=w=v=bx; 
                   1321:   fw=fv=fx=(*f)(x); 
                   1322:   for (iter=1;iter<=ITMAX;iter++) { 
                   1323:     xm=0.5*(a+b); 
                   1324:     tol2=2.0*(tol1=tol*fabs(x)+ZEPS); 
                   1325:     /*         if (2.0*fabs(fp-(*fret)) <= ftol*(fabs(fp)+fabs(*fret)))*/
                   1326:     printf(".");fflush(stdout);
                   1327:     fprintf(ficlog,".");fflush(ficlog);
1.162     brouard  1328: #ifdef DEBUGBRENT
1.126     brouard  1329:     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);
                   1330:     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);
                   1331:     /*         if ((fabs(x-xm) <= (tol2-0.5*(b-a)))||(2.0*fabs(fu-ftemp) <= ftol*1.e-2*(fabs(fu)+fabs(ftemp)))) { */
                   1332: #endif
                   1333:     if (fabs(x-xm) <= (tol2-0.5*(b-a))){ 
                   1334:       *xmin=x; 
                   1335:       return fx; 
                   1336:     } 
                   1337:     ftemp=fu;
                   1338:     if (fabs(e) > tol1) { 
                   1339:       r=(x-w)*(fx-fv); 
                   1340:       q=(x-v)*(fx-fw); 
                   1341:       p=(x-v)*q-(x-w)*r; 
                   1342:       q=2.0*(q-r); 
                   1343:       if (q > 0.0) p = -p; 
                   1344:       q=fabs(q); 
                   1345:       etemp=e; 
                   1346:       e=d; 
                   1347:       if (fabs(p) >= fabs(0.5*q*etemp) || p <= q*(a-x) || p >= q*(b-x)) 
                   1348:        d=CGOLD*(e=(x >= xm ? a-x : b-x)); 
                   1349:       else { 
                   1350:        d=p/q; 
                   1351:        u=x+d; 
                   1352:        if (u-a < tol2 || b-u < tol2) 
                   1353:          d=SIGN(tol1,xm-x); 
                   1354:       } 
                   1355:     } else { 
                   1356:       d=CGOLD*(e=(x >= xm ? a-x : b-x)); 
                   1357:     } 
                   1358:     u=(fabs(d) >= tol1 ? x+d : x+SIGN(tol1,d)); 
                   1359:     fu=(*f)(u); 
                   1360:     if (fu <= fx) { 
                   1361:       if (u >= x) a=x; else b=x; 
                   1362:       SHFT(v,w,x,u) 
1.183     brouard  1363:       SHFT(fv,fw,fx,fu) 
                   1364:     } else { 
                   1365:       if (u < x) a=u; else b=u; 
                   1366:       if (fu <= fw || w == x) { 
                   1367:        v=w; 
                   1368:        w=u; 
                   1369:        fv=fw; 
                   1370:        fw=fu; 
                   1371:       } else if (fu <= fv || v == x || v == w) { 
                   1372:        v=u; 
                   1373:        fv=fu; 
                   1374:       } 
                   1375:     } 
1.126     brouard  1376:   } 
                   1377:   nrerror("Too many iterations in brent"); 
                   1378:   *xmin=x; 
                   1379:   return fx; 
                   1380: } 
                   1381: 
                   1382: /****************** mnbrak ***********************/
                   1383: 
                   1384: void mnbrak(double *ax, double *bx, double *cx, double *fa, double *fb, double *fc, 
                   1385:            double (*func)(double)) 
1.183     brouard  1386: { /* Given a function func , and given distinct initial points ax and bx , this routine searches in
                   1387: the downhill direction (defined by the function as evaluated at the initial points) and returns
                   1388: new points ax , bx , cx that bracket a minimum of the function. Also returned are the function
                   1389: values at the three points, fa, fb , and fc such that fa > fb and fb < fc.
                   1390:    */
1.126     brouard  1391:   double ulim,u,r,q, dum;
                   1392:   double fu; 
1.187   ! brouard  1393: 
        !          1394:   double scale=10.;
        !          1395:   int iterscale=0;
        !          1396: 
        !          1397:   *fa=(*func)(*ax); /*  xta[j]=pcom[j]+(*ax)*xicom[j]; fa=f(xta[j])*/
        !          1398:   *fb=(*func)(*bx); /*  xtb[j]=pcom[j]+(*bx)*xicom[j]; fb=f(xtb[j]) */
        !          1399: 
        !          1400: 
        !          1401:   /* while(*fb != *fb){ /\* *ax should be ok, reducing distance to *ax *\/ */
        !          1402:   /*   printf("Warning mnbrak *fb = %lf, *bx=%lf *ax=%lf *fa==%lf iter=%d\n",*fb, *bx, *ax, *fa, iterscale++); */
        !          1403:   /*   *bx = *ax - (*ax - *bx)/scale; */
        !          1404:   /*   *fb=(*func)(*bx);  /\*  xtb[j]=pcom[j]+(*bx)*xicom[j]; fb=f(xtb[j]) *\/ */
        !          1405:   /* } */
        !          1406: 
1.126     brouard  1407:   if (*fb > *fa) { 
                   1408:     SHFT(dum,*ax,*bx,dum) 
1.183     brouard  1409:     SHFT(dum,*fb,*fa,dum) 
                   1410:   } 
1.126     brouard  1411:   *cx=(*bx)+GOLD*(*bx-*ax); 
                   1412:   *fc=(*func)(*cx); 
1.183     brouard  1413: #ifdef DEBUG
                   1414:   printf("mnbrak0 *fb=%.12e *fc=%.12e\n",*fb,*fc);
                   1415:   fprintf(ficlog,"mnbrak0 *fb=%.12e *fc=%.12e\n",*fb,*fc);
                   1416: #endif
                   1417:   while (*fb > *fc) { /* Declining a,b,c with fa> fb > fc */
1.126     brouard  1418:     r=(*bx-*ax)*(*fb-*fc); 
                   1419:     q=(*bx-*cx)*(*fb-*fa); 
                   1420:     u=(*bx)-((*bx-*cx)*q-(*bx-*ax)*r)/ 
1.183     brouard  1421:       (2.0*SIGN(FMAX(fabs(q-r),TINY),q-r)); /* Minimum abscissa of a parabolic estimated from (a,fa), (b,fb) and (c,fc). */
                   1422:     ulim=(*bx)+GLIMIT*(*cx-*bx); /* Maximum abscissa where function should be evaluated */
                   1423:     if ((*bx-u)*(u-*cx) > 0.0) { /* if u_p is between b and c */
1.126     brouard  1424:       fu=(*func)(u); 
1.163     brouard  1425: #ifdef DEBUG
                   1426:       /* f(x)=A(x-u)**2+f(u) */
                   1427:       double A, fparabu; 
                   1428:       A= (*fb - *fa)/(*bx-*ax)/(*bx+*ax-2*u);
                   1429:       fparabu= *fa - A*(*ax-u)*(*ax-u);
                   1430:       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);
                   1431:       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  1432:       /* And thus,it can be that fu > *fc even if fparabu < *fc */
                   1433:       /* mnbrak (*ax=7.666299858533, *fa=299039.693133272231), (*bx=8.595447774979, *fb=298976.598289369489),
                   1434:         (*cx=10.098840694817, *fc=298946.631474258087),  (*u=9.852501168332, fu=298948.773013752128, fparabu=298945.434711494134) */
                   1435:       /* In that case, there is no bracket in the output! Routine is wrong with many consequences.*/
1.163     brouard  1436: #endif 
1.184     brouard  1437: #ifdef MNBRAKORIGINAL
1.183     brouard  1438: #else
                   1439:       if (fu > *fc) {
                   1440: #ifdef DEBUG
                   1441:       printf("mnbrak4  fu > fc \n");
                   1442:       fprintf(ficlog, "mnbrak4 fu > fc\n");
                   1443: #endif
                   1444:        /* 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 *\/  */
                   1445:        /* SHFT(*fa,*fc,fu,*fc) /\* (b, u, c) is a bracket while test fb > fc will be fu > fc  will exit *\/ */
                   1446:        dum=u; /* Shifting c and u */
                   1447:        u = *cx;
                   1448:        *cx = dum;
                   1449:        dum = fu;
                   1450:        fu = *fc;
                   1451:        *fc =dum;
                   1452:       } else { /* end */
                   1453: #ifdef DEBUG
                   1454:       printf("mnbrak3  fu < fc \n");
                   1455:       fprintf(ficlog, "mnbrak3 fu < fc\n");
                   1456: #endif
                   1457:        dum=u; /* Shifting c and u */
                   1458:        u = *cx;
                   1459:        *cx = dum;
                   1460:        dum = fu;
                   1461:        fu = *fc;
                   1462:        *fc =dum;
                   1463:       }
                   1464: #endif
1.162     brouard  1465:     } else if ((*cx-u)*(u-ulim) > 0.0) { /* u is after c but before ulim */
1.183     brouard  1466: #ifdef DEBUG
                   1467:       printf("mnbrak2  u after c but before ulim\n");
                   1468:       fprintf(ficlog, "mnbrak2 u after c but before ulim\n");
                   1469: #endif
1.126     brouard  1470:       fu=(*func)(u); 
                   1471:       if (fu < *fc) { 
1.183     brouard  1472: #ifdef DEBUG
                   1473:       printf("mnbrak2  u after c but before ulim AND fu < fc\n");
                   1474:       fprintf(ficlog, "mnbrak2 u after c but before ulim AND fu <fc \n");
                   1475: #endif
1.126     brouard  1476:        SHFT(*bx,*cx,u,*cx+GOLD*(*cx-*bx)) 
1.183     brouard  1477:        SHFT(*fb,*fc,fu,(*func)(u)) 
                   1478:       } 
1.162     brouard  1479:     } else if ((u-ulim)*(ulim-*cx) >= 0.0) { /* u outside ulim (verifying that ulim is beyond c) */
1.183     brouard  1480: #ifdef DEBUG
                   1481:       printf("mnbrak2  u outside ulim (verifying that ulim is beyond c)\n");
                   1482:       fprintf(ficlog, "mnbrak2 u outside ulim (verifying that ulim is beyond c)\n");
                   1483: #endif
1.126     brouard  1484:       u=ulim; 
                   1485:       fu=(*func)(u); 
1.183     brouard  1486:     } else { /* u could be left to b (if r > q parabola has a maximum) */
                   1487: #ifdef DEBUG
                   1488:       printf("mnbrak2  u could be left to b (if r > q parabola has a maximum)\n");
                   1489:       fprintf(ficlog, "mnbrak2  u could be left to b (if r > q parabola has a maximum)\n");
                   1490: #endif
1.126     brouard  1491:       u=(*cx)+GOLD*(*cx-*bx); 
                   1492:       fu=(*func)(u); 
1.183     brouard  1493:     } /* end tests */
1.126     brouard  1494:     SHFT(*ax,*bx,*cx,u) 
1.183     brouard  1495:     SHFT(*fa,*fb,*fc,fu) 
                   1496: #ifdef DEBUG
                   1497:       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);
                   1498:       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);
                   1499: #endif
                   1500:   } /* 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  1501: } 
                   1502: 
                   1503: /*************** linmin ************************/
1.162     brouard  1504: /* Given an n -dimensional point p[1..n] and an n -dimensional direction xi[1..n] , moves and
                   1505: resets p to where the function func(p) takes on a minimum along the direction xi from p ,
                   1506: and replaces xi by the actual vector displacement that p was moved. Also returns as fret
                   1507: the value of func at the returned location p . This is actually all accomplished by calling the
                   1508: routines mnbrak and brent .*/
1.126     brouard  1509: int ncom; 
                   1510: double *pcom,*xicom;
                   1511: double (*nrfunc)(double []); 
                   1512:  
                   1513: void linmin(double p[], double xi[], int n, double *fret,double (*func)(double [])) 
                   1514: { 
                   1515:   double brent(double ax, double bx, double cx, 
                   1516:               double (*f)(double), double tol, double *xmin); 
                   1517:   double f1dim(double x); 
                   1518:   void mnbrak(double *ax, double *bx, double *cx, double *fa, double *fb, 
                   1519:              double *fc, double (*func)(double)); 
                   1520:   int j; 
                   1521:   double xx,xmin,bx,ax; 
                   1522:   double fx,fb,fa;
1.187   ! brouard  1523: 
        !          1524:   double scale=10., axs, xxs, xxss; /* Scale added for infinity */
1.126     brouard  1525:  
                   1526:   ncom=n; 
                   1527:   pcom=vector(1,n); 
                   1528:   xicom=vector(1,n); 
                   1529:   nrfunc=func; 
                   1530:   for (j=1;j<=n;j++) { 
                   1531:     pcom[j]=p[j]; 
                   1532:     xicom[j]=xi[j]; 
                   1533:   } 
1.187   ! brouard  1534: 
        !          1535:   axs=0.0;
        !          1536:   xxss=1; /* 1 and using scale */
        !          1537:   xxs=1;
        !          1538:   do{
        !          1539:     ax=0.;
        !          1540:     xx= xxs;
        !          1541:     mnbrak(&ax,&xx,&bx,&fa,&fx,&fb,f1dim);  /* Outputs: xtx[j]=pcom[j]+(*xx)*xicom[j]; fx=f(xtx[j]) */
        !          1542:     /* brackets with inputs ax=0 and xx=1, but points, pcom=p, and directions values, xicom=xi, are sent via f1dim(x) */
        !          1543:     /* xt[x,j]=pcom[j]+x*xicom[j]  f(ax) = f(xt(a,j=1,n)) = f(p(j) + 0 * xi(j)) and  f(xx) = f(xt(x, j=1,n)) = f(p(j) + 1 * xi(j))   */
        !          1544:     /* Outputs: fa=f(p(j)) and fx=f(p(j) + xxs * xi(j) ) and f(bx)= f(p(j)+ bx* xi(j)) */
        !          1545:     /* Given input ax=axs and xx=xxs, xx might be too far from ax to get a finite f(xx) */
        !          1546:     /* Searches on line, outputs (ax, xx, bx) such that fx < min(fa and fb) */
        !          1547:     /* Find a bracket a,x,b in direction n=xi ie xicom, order may change. Scale is [0:xxs*xi[j]] et non plus  [0:xi[j]]*/
        !          1548:     if (fx != fx){
        !          1549:        xxs=xxs/scale; /* Trying a smaller xx, closer to initial ax=0 */
        !          1550:        printf("\nLinmin NAN : input [axs=%lf:xxs=%lf], mnbrak outputs fx=%lf <(fb=%lf and fa=%lf) with xx=%lf in [ax=%lf:bx=%lf] \n",  axs, xxs, fx,fb, fa, xx, ax, bx);
        !          1551:     }
        !          1552:   }while(fx != fx);
        !          1553: 
        !          1554:   *fret=brent(ax,xx,bx,f1dim,TOL,&xmin); /* Giving a bracketting triplet (ax, xx, bx), find a minimum, xmin, according to f1dim, *fret(xmin),*/
        !          1555:   /* fa = f(p[j] + ax * xi[j]), fx = f(p[j] + xx * xi[j]), fb = f(p[j] + bx * xi[j]) */
        !          1556:   /* fmin = f(p[j] + xmin * xi[j]) */
        !          1557:   /* P+lambda n in that direction (lambdamin), with TOL between abscisses */
        !          1558:   /* f1dim(xmin): for (j=1;j<=ncom;j++) xt[j]=pcom[j]+xmin*xicom[j]; */
1.126     brouard  1559: #ifdef DEBUG
                   1560:   printf("retour brent fret=%.12e xmin=%.12e\n",*fret,xmin);
                   1561:   fprintf(ficlog,"retour brent fret=%.12e xmin=%.12e\n",*fret,xmin);
                   1562: #endif
1.187   ! brouard  1563:   printf("linmin end ");
1.126     brouard  1564:   for (j=1;j<=n;j++) { 
1.187   ! brouard  1565:     printf(" before xi[%d]=%12.8f", j,xi[j]);
        !          1566:     xi[j] *= xmin; /* xi rescaled by xmin: if xmin=-1.237 and xi=(1,0,...,0) xi=(-1.237,0,...,0) */
        !          1567:     if(xxs <1.0)
        !          1568:       printf(" after xi[%d]=%12.8f, xmin=%12.8f, ax=%12.8f, xx=%12.8f, bx=%12.8f, xxs=%12.8f", j,xi[j], xmin, ax, xx, bx,xxs );
        !          1569:     p[j] += xi[j]; /* Parameters values are updated accordingly */
1.126     brouard  1570:   } 
1.187   ! brouard  1571:   printf("\n");
1.126     brouard  1572:   free_vector(xicom,1,n); 
                   1573:   free_vector(pcom,1,n); 
                   1574: } 
                   1575: 
                   1576: 
                   1577: /*************** powell ************************/
1.162     brouard  1578: /*
                   1579: Minimization of a function func of n variables. Input consists of an initial starting point
                   1580: p[1..n] ; an initial matrix xi[1..n][1..n] , whose columns contain the initial set of di-
                   1581: rections (usually the n unit vectors); and ftol , the fractional tolerance in the function value
                   1582: such that failure to decrease by more than this amount on one iteration signals doneness. On
                   1583: output, p is set to the best point found, xi is the then-current direction set, fret is the returned
                   1584: function value at p , and iter is the number of iterations taken. The routine linmin is used.
                   1585:  */
1.126     brouard  1586: void powell(double p[], double **xi, int n, double ftol, int *iter, double *fret, 
                   1587:            double (*func)(double [])) 
                   1588: { 
                   1589:   void linmin(double p[], double xi[], int n, double *fret, 
                   1590:              double (*func)(double [])); 
                   1591:   int i,ibig,j; 
                   1592:   double del,t,*pt,*ptt,*xit;
1.181     brouard  1593:   double directest;
1.126     brouard  1594:   double fp,fptt;
                   1595:   double *xits;
                   1596:   int niterf, itmp;
                   1597: 
                   1598:   pt=vector(1,n); 
                   1599:   ptt=vector(1,n); 
                   1600:   xit=vector(1,n); 
                   1601:   xits=vector(1,n); 
                   1602:   *fret=(*func)(p); 
                   1603:   for (j=1;j<=n;j++) pt[j]=p[j]; 
1.157     brouard  1604:     rcurr_time = time(NULL);  
1.126     brouard  1605:   for (*iter=1;;++(*iter)) { 
1.187   ! brouard  1606:     fp=(*fret); /* From former iteration or initial value */
1.126     brouard  1607:     ibig=0; 
                   1608:     del=0.0; 
1.157     brouard  1609:     rlast_time=rcurr_time;
                   1610:     /* (void) gettimeofday(&curr_time,&tzp); */
                   1611:     rcurr_time = time(NULL);  
                   1612:     curr_time = *localtime(&rcurr_time);
                   1613:     printf("\nPowell iter=%d -2*LL=%.12f %ld sec. %ld sec.",*iter,*fret, rcurr_time-rlast_time, rcurr_time-rstart_time);fflush(stdout);
                   1614:     fprintf(ficlog,"\nPowell iter=%d -2*LL=%.12f %ld sec. %ld sec.",*iter,*fret,rcurr_time-rlast_time, rcurr_time-rstart_time); fflush(ficlog);
                   1615: /*     fprintf(ficrespow,"%d %.12f %ld",*iter,*fret,curr_time.tm_sec-start_time.tm_sec); */
1.126     brouard  1616:    for (i=1;i<=n;i++) {
                   1617:       printf(" %d %.12f",i, p[i]);
                   1618:       fprintf(ficlog," %d %.12lf",i, p[i]);
                   1619:       fprintf(ficrespow," %.12lf", p[i]);
                   1620:     }
                   1621:     printf("\n");
                   1622:     fprintf(ficlog,"\n");
                   1623:     fprintf(ficrespow,"\n");fflush(ficrespow);
                   1624:     if(*iter <=3){
1.157     brouard  1625:       tml = *localtime(&rcurr_time);
                   1626:       strcpy(strcurr,asctime(&tml));
                   1627:       rforecast_time=rcurr_time; 
1.126     brouard  1628:       itmp = strlen(strcurr);
                   1629:       if(strcurr[itmp-1]=='\n')  /* Windows outputs with a new line */
                   1630:        strcurr[itmp-1]='\0';
1.162     brouard  1631:       printf("\nConsidering the time needed for the last iteration #%d: %ld seconds,\n",*iter,rcurr_time-rlast_time);
1.157     brouard  1632:       fprintf(ficlog,"\nConsidering the time needed for this last iteration #%d: %ld seconds,\n",*iter,rcurr_time-rlast_time);
1.126     brouard  1633:       for(niterf=10;niterf<=30;niterf+=10){
1.157     brouard  1634:        rforecast_time=rcurr_time+(niterf-*iter)*(rcurr_time-rlast_time);
                   1635:        forecast_time = *localtime(&rforecast_time);
                   1636:        strcpy(strfor,asctime(&forecast_time));
1.126     brouard  1637:        itmp = strlen(strfor);
                   1638:        if(strfor[itmp-1]=='\n')
                   1639:        strfor[itmp-1]='\0';
1.157     brouard  1640:        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);
                   1641:        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  1642:       }
                   1643:     }
1.187   ! brouard  1644:     for (i=1;i<=n;i++) { /* For each direction i */
        !          1645:       for (j=1;j<=n;j++) xit[j]=xi[j][i]; /* Directions stored from previous iteration with previous scales */
1.126     brouard  1646:       fptt=(*fret); 
                   1647: #ifdef DEBUG
1.164     brouard  1648:          printf("fret=%lf, %lf, %lf \n", *fret, *fret, *fret);
                   1649:          fprintf(ficlog, "fret=%lf, %lf, %lf \n", *fret, *fret, *fret);
1.126     brouard  1650: #endif
1.187   ! brouard  1651:          printf("%d",i);fflush(stdout); /* print direction (parameter) i */
1.126     brouard  1652:       fprintf(ficlog,"%d",i);fflush(ficlog);
1.187   ! brouard  1653:       linmin(p,xit,n,fret,func); /* Point p[n]. xit[n] has been loaded for direction i as input. Outputs are fret(new point p) p is updated and xit rescaled */
1.181     brouard  1654:       if (fabs(fptt-(*fret)) > del) { /* We are keeping the max gain on each of the n directions 
                   1655:                                       because that direction will be replaced unless the gain del is small
                   1656:                                      in comparison with the 'probable' gain, mu^2, with the last average direction.
                   1657:                                      Unless the n directions are conjugate some gain in the determinant may be obtained
                   1658:                                      with the new direction.
                   1659:                                      */
1.126     brouard  1660:        del=fabs(fptt-(*fret)); 
                   1661:        ibig=i; 
                   1662:       } 
                   1663: #ifdef DEBUG
                   1664:       printf("%d %.12e",i,(*fret));
                   1665:       fprintf(ficlog,"%d %.12e",i,(*fret));
                   1666:       for (j=1;j<=n;j++) {
                   1667:        xits[j]=FMAX(fabs(p[j]-pt[j]),1.e-5);
                   1668:        printf(" x(%d)=%.12e",j,xit[j]);
                   1669:        fprintf(ficlog," x(%d)=%.12e",j,xit[j]);
                   1670:       }
                   1671:       for(j=1;j<=n;j++) {
1.162     brouard  1672:        printf(" p(%d)=%.12e",j,p[j]);
                   1673:        fprintf(ficlog," p(%d)=%.12e",j,p[j]);
1.126     brouard  1674:       }
                   1675:       printf("\n");
                   1676:       fprintf(ficlog,"\n");
                   1677: #endif
1.187   ! brouard  1678:     } /* end loop on each direction i */
        !          1679:     /* Convergence test will use last linmin estimation (fret) and compare former iteration (fp) */ 
        !          1680:     /* But p and xit have been updated at the end of linmin and do not produce *fret any more! */
        !          1681:     /* New value of last point Pn is not computed, P(n-1) */
1.182     brouard  1682:     if (2.0*fabs(fp-(*fret)) <= ftol*(fabs(fp)+fabs(*fret))) { /* Did we reach enough precision? */
1.126     brouard  1683: #ifdef DEBUG
                   1684:       int k[2],l;
                   1685:       k[0]=1;
                   1686:       k[1]=-1;
                   1687:       printf("Max: %.12e",(*func)(p));
                   1688:       fprintf(ficlog,"Max: %.12e",(*func)(p));
                   1689:       for (j=1;j<=n;j++) {
                   1690:        printf(" %.12e",p[j]);
                   1691:        fprintf(ficlog," %.12e",p[j]);
                   1692:       }
                   1693:       printf("\n");
                   1694:       fprintf(ficlog,"\n");
                   1695:       for(l=0;l<=1;l++) {
                   1696:        for (j=1;j<=n;j++) {
                   1697:          ptt[j]=p[j]+(p[j]-pt[j])*k[l];
                   1698:          printf("l=%d j=%d ptt=%.12e, xits=%.12e, p=%.12e, xit=%.12e", l,j,ptt[j],xits[j],p[j],xit[j]);
                   1699:          fprintf(ficlog,"l=%d j=%d ptt=%.12e, xits=%.12e, p=%.12e, xit=%.12e", l,j,ptt[j],xits[j],p[j],xit[j]);
                   1700:        }
                   1701:        printf("func(ptt)=%.12e, deriv=%.12e\n",(*func)(ptt),(ptt[j]-p[j])/((*func)(ptt)-(*func)(p)));
                   1702:        fprintf(ficlog,"func(ptt)=%.12e, deriv=%.12e\n",(*func)(ptt),(ptt[j]-p[j])/((*func)(ptt)-(*func)(p)));
                   1703:       }
                   1704: #endif
                   1705: 
                   1706: 
                   1707:       free_vector(xit,1,n); 
                   1708:       free_vector(xits,1,n); 
                   1709:       free_vector(ptt,1,n); 
                   1710:       free_vector(pt,1,n); 
                   1711:       return; 
                   1712:     } 
                   1713:     if (*iter == ITMAX) nrerror("powell exceeding maximum iterations."); 
1.181     brouard  1714:     for (j=1;j<=n;j++) { /* Computes the extrapolated point P_0 + 2 (P_n-P_0) */
1.126     brouard  1715:       ptt[j]=2.0*p[j]-pt[j]; 
                   1716:       xit[j]=p[j]-pt[j]; 
                   1717:       pt[j]=p[j]; 
                   1718:     } 
1.181     brouard  1719:     fptt=(*func)(ptt); /* f_3 */
1.161     brouard  1720:     if (fptt < fp) { /* If extrapolated point is better, decide if we keep that new direction or not */
1.162     brouard  1721:       /* (x1 f1=fp), (x2 f2=*fret), (x3 f3=fptt), (xm fm) */
1.161     brouard  1722:       /* From x1 (P0) distance of x2 is at h and x3 is 2h */
1.162     brouard  1723:       /* Let f"(x2) be the 2nd derivative equal everywhere.  */
                   1724:       /* Then the parabolic through (x1,f1), (x2,f2) and (x3,f3) */
                   1725:       /* will reach at f3 = fm + h^2/2 f"m  ; f" = (f1 -2f2 +f3 ) / h**2 */
1.181     brouard  1726:       /* Conditional for using this new direction is that mu^2 = (f1-2f2+f3)^2 /2 < del */
1.161     brouard  1727:       /* t=2.0*(fp-2.0*(*fret)+fptt)*SQR(fp-(*fret)-del)-del*SQR(fp-fptt); */
1.183     brouard  1728: #ifdef NRCORIGINAL
                   1729:       t=2.0*(fp-2.0*(*fret)+fptt)*SQR(fp-(*fret)-del)- del*SQR(fp-fptt); /* Original Numerical Recipes in C*/
                   1730: #else
                   1731:       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  1732:       t= t- del*SQR(fp-fptt);
1.183     brouard  1733: #endif
1.182     brouard  1734:       directest = fp-2.0*(*fret)+fptt - 2.0 * del; /* If del was big enough we change it for a new direction */
1.161     brouard  1735: #ifdef DEBUG
1.181     brouard  1736:       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);
                   1737:       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  1738:       printf("t3= %.12lf, t4= %.12lf, t3*= %.12lf, t4*= %.12lf\n",SQR(fp-(*fret)-del),SQR(fp-fptt),
                   1739:             (fp-(*fret)-del)*(fp-(*fret)-del),(fp-fptt)*(fp-fptt));
                   1740:       fprintf(ficlog,"t3= %.12lf, t4= %.12lf, t3*= %.12lf, t4*= %.12lf\n",SQR(fp-(*fret)-del),SQR(fp-fptt),
                   1741:             (fp-(*fret)-del)*(fp-(*fret)-del),(fp-fptt)*(fp-fptt));
                   1742:       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);
                   1743:       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);
                   1744: #endif
1.183     brouard  1745: #ifdef POWELLORIGINAL
                   1746:       if (t < 0.0) { /* Then we use it for new direction */
                   1747: #else
1.182     brouard  1748:       if (directest*t < 0.0) { /* Contradiction between both tests */
1.184     brouard  1749:       printf("directest= %.12lf, t= %.12lf, f1= %.12lf,f2= %.12lf,f3= %.12lf, del= %.12lf\n",directest, t, fp,(*fret),fptt,del);
1.182     brouard  1750:       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  1751:       fprintf(ficlog,"directest= %.12lf, t= %.12lf, f1= %.12lf,f2= %.12lf,f3= %.12lf, del= %.12lf\n",directest, t, fp,(*fret),fptt, del);
1.182     brouard  1752:       fprintf(ficlog,"f1-2f2+f3= %.12lf, f1-f2-del= %.12lf, f1-f3= %.12lf\n",fp-2.0*(*fret)+fptt, fp -(*fret) -del, fp-fptt);
                   1753:     } 
1.181     brouard  1754:       if (directest < 0.0) { /* Then we use it for new direction */
                   1755: #endif
1.187   ! brouard  1756:        linmin(p,xit,n,fret,func); /* computes minimum on the extrapolated direction: changes p and rescales xit.*/
1.126     brouard  1757:        for (j=1;j<=n;j++) { 
1.181     brouard  1758:          xi[j][ibig]=xi[j][n]; /* Replace direction with biggest decrease by last direction n */
                   1759:          xi[j][n]=xit[j];      /* and this nth direction by the by the average p_0 p_n */
1.126     brouard  1760:        }
1.181     brouard  1761:        printf("Gaining to use new average direction of P0 P%d instead of biggest increase direction %d :\n",n,ibig);
                   1762:        fprintf(ficlog,"Gaining to use new average direction of P0 P%d instead of biggest increase direction %d :\n",n,ibig);
1.161     brouard  1763: 
1.126     brouard  1764: #ifdef DEBUG
1.164     brouard  1765:        printf("Direction changed  last moved %d in place of ibig=%d, new last is the average:\n",n,ibig);
                   1766:        fprintf(ficlog,"Direction changed  last moved %d in place of ibig=%d, new last is the average:\n",n,ibig);
1.126     brouard  1767:        for(j=1;j<=n;j++){
                   1768:          printf(" %.12e",xit[j]);
                   1769:          fprintf(ficlog," %.12e",xit[j]);
                   1770:        }
                   1771:        printf("\n");
                   1772:        fprintf(ficlog,"\n");
                   1773: #endif
1.162     brouard  1774:       } /* end of t negative */
                   1775:     } /* end if (fptt < fp)  */
1.126     brouard  1776:   } 
                   1777: } 
                   1778: 
                   1779: /**** Prevalence limit (stable or period prevalence)  ****************/
                   1780: 
                   1781: double **prevalim(double **prlim, int nlstate, double x[], double age, double **oldm, double **savm, double ftolpl, int ij)
                   1782: {
                   1783:   /* Computes the prevalence limit in each live state at age x by left multiplying the unit
                   1784:      matrix by transitions matrix until convergence is reached */
1.169     brouard  1785:   
1.126     brouard  1786:   int i, ii,j,k;
                   1787:   double min, max, maxmin, maxmax,sumnew=0.;
1.145     brouard  1788:   /* double **matprod2(); */ /* test */
1.131     brouard  1789:   double **out, cov[NCOVMAX+1], **pmij();
1.126     brouard  1790:   double **newm;
                   1791:   double agefin, delaymax=50 ; /* Max number of years to converge */
1.169     brouard  1792:   
1.126     brouard  1793:   for (ii=1;ii<=nlstate+ndeath;ii++)
                   1794:     for (j=1;j<=nlstate+ndeath;j++){
                   1795:       oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   1796:     }
1.169     brouard  1797:   
                   1798:   cov[1]=1.;
                   1799:   
                   1800:   /* Even if hstepm = 1, at least one multiplication by the unit matrix */
1.126     brouard  1801:   for(agefin=age-stepm/YEARM; agefin>=age-delaymax; agefin=agefin-stepm/YEARM){
                   1802:     newm=savm;
                   1803:     /* Covariates have to be included here again */
1.138     brouard  1804:     cov[2]=agefin;
1.187   ! brouard  1805:     if(nagesqr==1)
        !          1806:       cov[3]= agefin*agefin;;
1.138     brouard  1807:     for (k=1; k<=cptcovn;k++) {
1.187   ! brouard  1808:       cov[2+nagesqr+k]=nbcode[Tvar[k]][codtab[ij][Tvar[k]]];
1.145     brouard  1809:       /*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  1810:     }
1.186     brouard  1811:     /*wrong? for (k=1; k<=cptcovage;k++) cov[2+Tage[k]]=cov[2+Tage[k]]*cov[2]; */
1.187   ! brouard  1812:     for (k=1; k<=cptcovage;k++) cov[2+nagesqr+Tage[k]]=nbcode[Tvar[k]][codtab[ij][Tvar[k]]]*cov[2];
1.186     brouard  1813:     for (k=1; k<=cptcovprod;k++) /* Useless */
1.187   ! brouard  1814:       cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtab[ij][Tvard[k][1]]] * nbcode[Tvard[k][2]][codtab[ij][Tvard[k][2]]];
1.138     brouard  1815:     
                   1816:     /*printf("ij=%d cptcovprod=%d tvar=%d ", ij, cptcovprod, Tvar[1]);*/
                   1817:     /*printf("ij=%d cov[3]=%lf cov[4]=%lf \n",ij, cov[3],cov[4]);*/
                   1818:     /*printf("ij=%d cov[3]=%lf \n",ij, cov[3]);*/
1.145     brouard  1819:     /* savm=pmij(pmmij,cov,ncovmodel,x,nlstate); */
                   1820:     /* out=matprod2(newm, pmij(pmmij,cov,ncovmodel,x,nlstate),1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, oldm); /\* Bug Valgrind *\/ */
1.142     brouard  1821:     out=matprod2(newm, pmij(pmmij,cov,ncovmodel,x,nlstate),1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, oldm); /* Bug Valgrind */
1.138     brouard  1822:     
1.126     brouard  1823:     savm=oldm;
                   1824:     oldm=newm;
                   1825:     maxmax=0.;
                   1826:     for(j=1;j<=nlstate;j++){
                   1827:       min=1.;
                   1828:       max=0.;
                   1829:       for(i=1; i<=nlstate; i++) {
                   1830:        sumnew=0;
                   1831:        for(k=1; k<=ndeath; k++) sumnew+=newm[i][nlstate+k];
                   1832:        prlim[i][j]= newm[i][j]/(1-sumnew);
1.145     brouard  1833:         /*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  1834:        max=FMAX(max,prlim[i][j]);
                   1835:        min=FMIN(min,prlim[i][j]);
                   1836:       }
                   1837:       maxmin=max-min;
                   1838:       maxmax=FMAX(maxmax,maxmin);
1.169     brouard  1839:     } /* j loop */
1.126     brouard  1840:     if(maxmax < ftolpl){
                   1841:       return prlim;
                   1842:     }
1.169     brouard  1843:   } /* age loop */
                   1844:   return prlim; /* should not reach here */
1.126     brouard  1845: }
                   1846: 
                   1847: /*************** transition probabilities ***************/ 
                   1848: 
                   1849: double **pmij(double **ps, double *cov, int ncovmodel, double *x, int nlstate )
                   1850: {
1.138     brouard  1851:   /* According to parameters values stored in x and the covariate's values stored in cov,
                   1852:      computes the probability to be observed in state j being in state i by appying the
                   1853:      model to the ncovmodel covariates (including constant and age).
                   1854:      lnpijopii=ln(pij/pii)= aij+bij*age+cij*v1+dij*v2+... = sum_nc=1^ncovmodel xij(nc)*cov[nc]
                   1855:      and, according on how parameters are entered, the position of the coefficient xij(nc) of the
                   1856:      ncth covariate in the global vector x is given by the formula:
                   1857:      j<i nc+((i-1)*(nlstate+ndeath-1)+j-1)*ncovmodel
                   1858:      j>=i nc + ((i-1)*(nlstate+ndeath-1)+(j-2))*ncovmodel
                   1859:      Computes ln(pij/pii) (lnpijopii), deduces pij/pii by exponentiation,
                   1860:      sums on j different of i to get 1-pii/pii, deduces pii, and then all pij.
                   1861:      Outputs ps[i][j] the probability to be observed in j being in j according to
                   1862:      the values of the covariates cov[nc] and corresponding parameter values x[nc+shiftij]
                   1863:   */
                   1864:   double s1, lnpijopii;
1.126     brouard  1865:   /*double t34;*/
1.164     brouard  1866:   int i,j, nc, ii, jj;
1.126     brouard  1867: 
                   1868:     for(i=1; i<= nlstate; i++){
                   1869:       for(j=1; j<i;j++){
1.138     brouard  1870:        for (nc=1, lnpijopii=0.;nc <=ncovmodel; nc++){
                   1871:          /*lnpijopii += param[i][j][nc]*cov[nc];*/
                   1872:          lnpijopii += x[nc+((i-1)*(nlstate+ndeath-1)+j-1)*ncovmodel]*cov[nc];
                   1873: /*      printf("Int j<i s1=%.17e, lnpijopii=%.17e\n",s1,lnpijopii); */
1.126     brouard  1874:        }
1.138     brouard  1875:        ps[i][j]=lnpijopii; /* In fact ln(pij/pii) */
                   1876: /*     printf("s1=%.17e, lnpijopii=%.17e\n",s1,lnpijopii); */
1.126     brouard  1877:       }
                   1878:       for(j=i+1; j<=nlstate+ndeath;j++){
1.138     brouard  1879:        for (nc=1, lnpijopii=0.;nc <=ncovmodel; nc++){
                   1880:          /*lnpijopii += x[(i-1)*nlstate*ncovmodel+(j-2)*ncovmodel+nc+(i-1)*(ndeath-1)*ncovmodel]*cov[nc];*/
                   1881:          lnpijopii += x[nc + ((i-1)*(nlstate+ndeath-1)+(j-2))*ncovmodel]*cov[nc];
                   1882: /*       printf("Int j>i s1=%.17e, lnpijopii=%.17e %lx %lx\n",s1,lnpijopii,s1,lnpijopii); */
1.126     brouard  1883:        }
1.138     brouard  1884:        ps[i][j]=lnpijopii; /* In fact ln(pij/pii) */
1.126     brouard  1885:       }
                   1886:     }
                   1887:     
                   1888:     for(i=1; i<= nlstate; i++){
                   1889:       s1=0;
1.131     brouard  1890:       for(j=1; j<i; j++){
1.138     brouard  1891:        s1+=exp(ps[i][j]); /* In fact sums pij/pii */
1.131     brouard  1892:        /*printf("debug1 %d %d ps=%lf exp(ps)=%lf s1+=%lf\n",i,j,ps[i][j],exp(ps[i][j]),s1); */
                   1893:       }
                   1894:       for(j=i+1; j<=nlstate+ndeath; j++){
1.138     brouard  1895:        s1+=exp(ps[i][j]); /* In fact sums pij/pii */
1.131     brouard  1896:        /*printf("debug2 %d %d ps=%lf exp(ps)=%lf s1+=%lf\n",i,j,ps[i][j],exp(ps[i][j]),s1); */
                   1897:       }
1.138     brouard  1898:       /* s1= sum_{j<>i} pij/pii=(1-pii)/pii and thus pii is known from s1 */
1.126     brouard  1899:       ps[i][i]=1./(s1+1.);
1.138     brouard  1900:       /* Computing other pijs */
1.126     brouard  1901:       for(j=1; j<i; j++)
                   1902:        ps[i][j]= exp(ps[i][j])*ps[i][i];
                   1903:       for(j=i+1; j<=nlstate+ndeath; j++)
                   1904:        ps[i][j]= exp(ps[i][j])*ps[i][i];
                   1905:       /* ps[i][nlstate+1]=1.-s1- ps[i][i];*/ /* Sum should be 1 */
                   1906:     } /* end i */
                   1907:     
                   1908:     for(ii=nlstate+1; ii<= nlstate+ndeath; ii++){
                   1909:       for(jj=1; jj<= nlstate+ndeath; jj++){
                   1910:        ps[ii][jj]=0;
                   1911:        ps[ii][ii]=1;
                   1912:       }
                   1913:     }
                   1914:     
1.145     brouard  1915:     
                   1916:     /* for(ii=1; ii<= nlstate+ndeath; ii++){ */
                   1917:     /*   for(jj=1; jj<= nlstate+ndeath; jj++){ */
                   1918:     /*         printf(" pmij  ps[%d][%d]=%lf ",ii,jj,ps[ii][jj]); */
                   1919:     /*   } */
                   1920:     /*   printf("\n "); */
                   1921:     /* } */
                   1922:     /* printf("\n ");printf("%lf ",cov[2]);*/
                   1923:     /*
1.126     brouard  1924:       for(i=1; i<= npar; i++) printf("%f ",x[i]);
                   1925:       goto end;*/
                   1926:     return ps;
                   1927: }
                   1928: 
                   1929: /**************** Product of 2 matrices ******************/
                   1930: 
1.145     brouard  1931: double **matprod2(double **out, double **in,int nrl, int nrh, int ncl, int nch, int ncolol, int ncoloh, double **b)
1.126     brouard  1932: {
                   1933:   /* Computes the matrix product of in(1,nrh-nrl+1)(1,nch-ncl+1) times
                   1934:      b(1,nch-ncl+1)(1,ncoloh-ncolol+1) into out(...) */
                   1935:   /* in, b, out are matrice of pointers which should have been initialized 
                   1936:      before: only the contents of out is modified. The function returns
                   1937:      a pointer to pointers identical to out */
1.145     brouard  1938:   int i, j, k;
1.126     brouard  1939:   for(i=nrl; i<= nrh; i++)
1.145     brouard  1940:     for(k=ncolol; k<=ncoloh; k++){
                   1941:       out[i][k]=0.;
                   1942:       for(j=ncl; j<=nch; j++)
                   1943:        out[i][k] +=in[i][j]*b[j][k];
                   1944:     }
1.126     brouard  1945:   return out;
                   1946: }
                   1947: 
                   1948: 
                   1949: /************* Higher Matrix Product ***************/
                   1950: 
                   1951: double ***hpxij(double ***po, int nhstepm, double age, int hstepm, double *x, int nlstate, int stepm, double **oldm, double **savm, int ij )
                   1952: {
                   1953:   /* Computes the transition matrix starting at age 'age' over 
                   1954:      'nhstepm*hstepm*stepm' months (i.e. until
                   1955:      age (in years)  age+nhstepm*hstepm*stepm/12) by multiplying 
                   1956:      nhstepm*hstepm matrices. 
                   1957:      Output is stored in matrix po[i][j][h] for h every 'hstepm' step 
                   1958:      (typically every 2 years instead of every month which is too big 
                   1959:      for the memory).
                   1960:      Model is determined by parameters x and covariates have to be 
                   1961:      included manually here. 
                   1962: 
                   1963:      */
                   1964: 
                   1965:   int i, j, d, h, k;
1.131     brouard  1966:   double **out, cov[NCOVMAX+1];
1.126     brouard  1967:   double **newm;
1.187   ! brouard  1968:   double agexact;
1.126     brouard  1969: 
                   1970:   /* Hstepm could be zero and should return the unit matrix */
                   1971:   for (i=1;i<=nlstate+ndeath;i++)
                   1972:     for (j=1;j<=nlstate+ndeath;j++){
                   1973:       oldm[i][j]=(i==j ? 1.0 : 0.0);
                   1974:       po[i][j][0]=(i==j ? 1.0 : 0.0);
                   1975:     }
                   1976:   /* Even if hstepm = 1, at least one multiplication by the unit matrix */
                   1977:   for(h=1; h <=nhstepm; h++){
                   1978:     for(d=1; d <=hstepm; d++){
                   1979:       newm=savm;
                   1980:       /* Covariates have to be included here again */
                   1981:       cov[1]=1.;
1.187   ! brouard  1982:       agexact=age+((h-1)*hstepm + (d-1))*stepm/YEARM;
        !          1983:       cov[2]=agexact;
        !          1984:       if(nagesqr==1)
        !          1985:        cov[3]= agexact*agexact;
1.131     brouard  1986:       for (k=1; k<=cptcovn;k++) 
1.187   ! brouard  1987:        cov[2+nagesqr+k]=nbcode[Tvar[k]][codtab[ij][Tvar[k]]];
1.186     brouard  1988:       for (k=1; k<=cptcovage;k++) /* Should start at cptcovn+1 */
                   1989:        /* cov[2+Tage[k]]=cov[2+Tage[k]]*cov[2]; */
1.187   ! brouard  1990:        cov[2+nagesqr+Tage[k]]=nbcode[Tvar[Tage[k]]][codtab[ij][Tvar[Tage[k]]]]*cov[2];
1.145     brouard  1991:       for (k=1; k<=cptcovprod;k++) /* Useless because included in cptcovn */
1.187   ! brouard  1992:        cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtab[ij][Tvard[k][1]]]*nbcode[Tvard[k][2]][codtab[ij][Tvard[k][2]]];
1.126     brouard  1993: 
                   1994: 
                   1995:       /*printf("hxi cptcov=%d cptcode=%d\n",cptcov,cptcode);*/
                   1996:       /*printf("h=%d d=%d age=%f cov=%f\n",h,d,age,cov[2]);*/
                   1997:       out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, 
                   1998:                   pmij(pmmij,cov,ncovmodel,x,nlstate));
                   1999:       savm=oldm;
                   2000:       oldm=newm;
                   2001:     }
                   2002:     for(i=1; i<=nlstate+ndeath; i++)
                   2003:       for(j=1;j<=nlstate+ndeath;j++) {
                   2004:        po[i][j][h]=newm[i][j];
1.128     brouard  2005:        /*if(h==nhstepm) printf("po[%d][%d][%d]=%f ",i,j,h,po[i][j][h]);*/
1.126     brouard  2006:       }
1.128     brouard  2007:     /*printf("h=%d ",h);*/
1.126     brouard  2008:   } /* end h */
1.128     brouard  2009: /*     printf("\n H=%d \n",h); */
1.126     brouard  2010:   return po;
                   2011: }
                   2012: 
1.162     brouard  2013: #ifdef NLOPT
                   2014:   double  myfunc(unsigned n, const double *p1, double *grad, void *pd){
                   2015:   double fret;
                   2016:   double *xt;
                   2017:   int j;
                   2018:   myfunc_data *d2 = (myfunc_data *) pd;
                   2019: /* xt = (p1-1); */
                   2020:   xt=vector(1,n); 
                   2021:   for (j=1;j<=n;j++)   xt[j]=p1[j-1]; /* xt[1]=p1[0] */
                   2022: 
                   2023:   fret=(d2->function)(xt); /*  p xt[1]@8 is fine */
                   2024:   /* fret=(*func)(xt); /\*  p xt[1]@8 is fine *\/ */
                   2025:   printf("Function = %.12lf ",fret);
                   2026:   for (j=1;j<=n;j++) printf(" %d %.8lf", j, xt[j]); 
                   2027:   printf("\n");
                   2028:  free_vector(xt,1,n);
                   2029:   return fret;
                   2030: }
                   2031: #endif
1.126     brouard  2032: 
                   2033: /*************** log-likelihood *************/
                   2034: double func( double *x)
                   2035: {
                   2036:   int i, ii, j, k, mi, d, kk;
1.131     brouard  2037:   double l, ll[NLSTATEMAX+1], cov[NCOVMAX+1];
1.126     brouard  2038:   double **out;
                   2039:   double sw; /* Sum of weights */
                   2040:   double lli; /* Individual log likelihood */
                   2041:   int s1, s2;
                   2042:   double bbh, survp;
                   2043:   long ipmx;
1.187   ! brouard  2044:   double agexact;
1.126     brouard  2045:   /*extern weight */
                   2046:   /* We are differentiating ll according to initial status */
                   2047:   /*  for (i=1;i<=npar;i++) printf("%f ", x[i]);*/
                   2048:   /*for(i=1;i<imx;i++) 
                   2049:     printf(" %d\n",s[4][i]);
                   2050:   */
1.162     brouard  2051: 
                   2052:   ++countcallfunc;
                   2053: 
1.126     brouard  2054:   cov[1]=1.;
                   2055: 
                   2056:   for(k=1; k<=nlstate; k++) ll[k]=0.;
                   2057: 
                   2058:   if(mle==1){
                   2059:     for (i=1,ipmx=0, sw=0.; i<=imx; i++){
1.138     brouard  2060:       /* Computes the values of the ncovmodel covariates of the model
                   2061:         depending if the covariates are fixed or variying (age dependent) and stores them in cov[]
                   2062:         Then computes with function pmij which return a matrix p[i][j] giving the elementary probability
                   2063:         to be observed in j being in i according to the model.
                   2064:        */
1.145     brouard  2065:       for (k=1; k<=cptcovn;k++){ /* Simple and product covariates without age* products */
1.187   ! brouard  2066:          cov[2+nagesqr+k]=covar[Tvar[k]][i];
1.145     brouard  2067:       }
1.137     brouard  2068:       /* In model V2+V1*V4+age*V3+V3*V2 Tvar[1] is V2, Tvar[2=V1*V4] 
1.138     brouard  2069:         is 6, Tvar[3=age*V3] should not be computed because of age Tvar[4=V3*V2] 
1.137     brouard  2070:         has been calculated etc */
1.126     brouard  2071:       for(mi=1; mi<= wav[i]-1; mi++){
                   2072:        for (ii=1;ii<=nlstate+ndeath;ii++)
                   2073:          for (j=1;j<=nlstate+ndeath;j++){
                   2074:            oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   2075:            savm[ii][j]=(ii==j ? 1.0 : 0.0);
                   2076:          }
                   2077:        for(d=0; d<dh[mi][i]; d++){
                   2078:          newm=savm;
1.187   ! brouard  2079:          agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;
        !          2080:          cov[2]=agexact;
        !          2081:          if(nagesqr==1)
        !          2082:            cov[3]= agexact*agexact;
1.126     brouard  2083:          for (kk=1; kk<=cptcovage;kk++) {
1.187   ! brouard  2084:            cov[Tage[kk]+2+nagesqr]=covar[Tvar[Tage[kk]]][i]*agexact; /* Tage[kk] gives the data-covariate associated with age */
1.126     brouard  2085:          }
                   2086:          out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
                   2087:                       1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
                   2088:          savm=oldm;
                   2089:          oldm=newm;
                   2090:        } /* end mult */
                   2091:       
                   2092:        /*lli=log(out[s[mw[mi][i]][i]][s[mw[mi+1][i]][i]]);*/ /* Original formula */
                   2093:        /* But now since version 0.9 we anticipate for bias at large stepm.
                   2094:         * If stepm is larger than one month (smallest stepm) and if the exact delay 
                   2095:         * (in months) between two waves is not a multiple of stepm, we rounded to 
                   2096:         * the nearest (and in case of equal distance, to the lowest) interval but now
                   2097:         * we keep into memory the bias bh[mi][i] and also the previous matrix product
                   2098:         * (i.e to dh[mi][i]-1) saved in 'savm'. Then we inter(extra)polate the
                   2099:         * probability in order to take into account the bias as a fraction of the way
                   2100:         * from savm to out if bh is negative or even beyond if bh is positive. bh varies
                   2101:         * -stepm/2 to stepm/2 .
                   2102:         * For stepm=1 the results are the same as for previous versions of Imach.
                   2103:         * For stepm > 1 the results are less biased than in previous versions. 
                   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:        /* bias bh is positive if real duration
                   2109:         * is higher than the multiple of stepm and negative otherwise.
                   2110:         */
                   2111:        /* lli= (savm[s1][s2]>1.e-8 ?(1.+bbh)*log(out[s1][s2])- bbh*log(savm[s1][s2]):log((1.+bbh)*out[s1][s2]));*/
                   2112:        if( s2 > nlstate){ 
                   2113:          /* i.e. if s2 is a death state and if the date of death is known 
                   2114:             then the contribution to the likelihood is the probability to 
                   2115:             die between last step unit time and current  step unit time, 
                   2116:             which is also equal to probability to die before dh 
                   2117:             minus probability to die before dh-stepm . 
                   2118:             In version up to 0.92 likelihood was computed
                   2119:        as if date of death was unknown. Death was treated as any other
                   2120:        health state: the date of the interview describes the actual state
                   2121:        and not the date of a change in health state. The former idea was
                   2122:        to consider that at each interview the state was recorded
                   2123:        (healthy, disable or death) and IMaCh was corrected; but when we
                   2124:        introduced the exact date of death then we should have modified
                   2125:        the contribution of an exact death to the likelihood. This new
                   2126:        contribution is smaller and very dependent of the step unit
                   2127:        stepm. It is no more the probability to die between last interview
                   2128:        and month of death but the probability to survive from last
                   2129:        interview up to one month before death multiplied by the
                   2130:        probability to die within a month. Thanks to Chris
                   2131:        Jackson for correcting this bug.  Former versions increased
                   2132:        mortality artificially. The bad side is that we add another loop
                   2133:        which slows down the processing. The difference can be up to 10%
                   2134:        lower mortality.
                   2135:          */
1.183     brouard  2136:        /* If, at the beginning of the maximization mostly, the
                   2137:           cumulative probability or probability to be dead is
                   2138:           constant (ie = 1) over time d, the difference is equal to
                   2139:           0.  out[s1][3] = savm[s1][3]: probability, being at state
                   2140:           s1 at precedent wave, to be dead a month before current
                   2141:           wave is equal to probability, being at state s1 at
                   2142:           precedent wave, to be dead at mont of the current
                   2143:           wave. Then the observed probability (that this person died)
                   2144:           is null according to current estimated parameter. In fact,
                   2145:           it should be very low but not zero otherwise the log go to
                   2146:           infinity.
                   2147:        */
                   2148: /* #ifdef INFINITYORIGINAL */
                   2149: /*         lli=log(out[s1][s2] - savm[s1][s2]); */
                   2150: /* #else */
                   2151: /*       if ((out[s1][s2] - savm[s1][s2]) < mytinydouble)  */
                   2152: /*         lli=log(mytinydouble); */
                   2153: /*       else */
                   2154: /*         lli=log(out[s1][s2] - savm[s1][s2]); */
                   2155: /* #endif */
                   2156:            lli=log(out[s1][s2] - savm[s1][s2]);
1.126     brouard  2157: 
                   2158:        } else if  (s2==-2) {
                   2159:          for (j=1,survp=0. ; j<=nlstate; j++) 
                   2160:            survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j];
                   2161:          /*survp += out[s1][j]; */
                   2162:          lli= log(survp);
                   2163:        }
                   2164:        
                   2165:        else if  (s2==-4) { 
                   2166:          for (j=3,survp=0. ; j<=nlstate; j++)  
                   2167:            survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j];
                   2168:          lli= log(survp); 
                   2169:        } 
                   2170: 
                   2171:        else if  (s2==-5) { 
                   2172:          for (j=1,survp=0. ; j<=2; j++)  
                   2173:            survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j];
                   2174:          lli= log(survp); 
                   2175:        } 
                   2176:        
                   2177:        else{
                   2178:          lli= log((1.+bbh)*out[s1][s2]- bbh*savm[s1][s2]); /* linear interpolation */
                   2179:          /*  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 */
                   2180:        } 
                   2181:        /*lli=(1.+bbh)*log(out[s1][s2])- bbh*log(savm[s1][s2]);*/
                   2182:        /*if(lli ==000.0)*/
                   2183:        /*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); */
                   2184:        ipmx +=1;
                   2185:        sw += weight[i];
                   2186:        ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
1.183     brouard  2187:        /* if (lli < log(mytinydouble)){ */
                   2188:        /*   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); */
                   2189:        /*   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]); */
                   2190:        /* } */
1.126     brouard  2191:       } /* end of wave */
                   2192:     } /* end of individual */
                   2193:   }  else if(mle==2){
                   2194:     for (i=1,ipmx=0, sw=0.; i<=imx; i++){
1.187   ! brouard  2195:       for (k=1; k<=cptcovn;k++) cov[2+nagesqr+k]=covar[Tvar[k]][i];
1.126     brouard  2196:       for(mi=1; mi<= wav[i]-1; mi++){
                   2197:        for (ii=1;ii<=nlstate+ndeath;ii++)
                   2198:          for (j=1;j<=nlstate+ndeath;j++){
                   2199:            oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   2200:            savm[ii][j]=(ii==j ? 1.0 : 0.0);
                   2201:          }
                   2202:        for(d=0; d<=dh[mi][i]; d++){
                   2203:          newm=savm;
1.187   ! brouard  2204:          agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;
        !          2205:          cov[2]=agexact;
        !          2206:          if(nagesqr==1)
        !          2207:            cov[3]= agexact*agexact;
1.126     brouard  2208:          for (kk=1; kk<=cptcovage;kk++) {
1.187   ! brouard  2209:            cov[Tage[kk]+2+nagesqr]=covar[Tvar[Tage[kk]]][i]*agexact;
1.126     brouard  2210:          }
                   2211:          out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
                   2212:                       1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
                   2213:          savm=oldm;
                   2214:          oldm=newm;
                   2215:        } /* end mult */
                   2216:       
                   2217:        s1=s[mw[mi][i]][i];
                   2218:        s2=s[mw[mi+1][i]][i];
                   2219:        bbh=(double)bh[mi][i]/(double)stepm; 
                   2220:        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 */
                   2221:        ipmx +=1;
                   2222:        sw += weight[i];
                   2223:        ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
                   2224:       } /* end of wave */
                   2225:     } /* end of individual */
                   2226:   }  else if(mle==3){  /* exponential inter-extrapolation */
                   2227:     for (i=1,ipmx=0, sw=0.; i<=imx; i++){
1.187   ! brouard  2228:       for (k=1; k<=cptcovn;k++) cov[2+nagesqr+k]=covar[Tvar[k]][i];
1.126     brouard  2229:       for(mi=1; mi<= wav[i]-1; mi++){
                   2230:        for (ii=1;ii<=nlstate+ndeath;ii++)
                   2231:          for (j=1;j<=nlstate+ndeath;j++){
                   2232:            oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   2233:            savm[ii][j]=(ii==j ? 1.0 : 0.0);
                   2234:          }
                   2235:        for(d=0; d<dh[mi][i]; d++){
                   2236:          newm=savm;
1.187   ! brouard  2237:          agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;
        !          2238:          cov[2]=agexact;
        !          2239:          if(nagesqr==1)
        !          2240:            cov[3]= agexact*agexact;
1.126     brouard  2241:          for (kk=1; kk<=cptcovage;kk++) {
1.187   ! brouard  2242:            cov[Tage[kk]+2+nagesqr]=covar[Tvar[Tage[kk]]][i]*agexact;
1.126     brouard  2243:          }
                   2244:          out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
                   2245:                       1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
                   2246:          savm=oldm;
                   2247:          oldm=newm;
                   2248:        } /* end mult */
                   2249:       
                   2250:        s1=s[mw[mi][i]][i];
                   2251:        s2=s[mw[mi+1][i]][i];
                   2252:        bbh=(double)bh[mi][i]/(double)stepm; 
                   2253:        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 */
                   2254:        ipmx +=1;
                   2255:        sw += weight[i];
                   2256:        ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
                   2257:       } /* end of wave */
                   2258:     } /* end of individual */
                   2259:   }else if (mle==4){  /* ml=4 no inter-extrapolation */
                   2260:     for (i=1,ipmx=0, sw=0.; i<=imx; i++){
1.187   ! brouard  2261:       for (k=1; k<=cptcovn;k++) cov[2+nagesqr+k]=covar[Tvar[k]][i];
1.126     brouard  2262:       for(mi=1; mi<= wav[i]-1; mi++){
                   2263:        for (ii=1;ii<=nlstate+ndeath;ii++)
                   2264:          for (j=1;j<=nlstate+ndeath;j++){
                   2265:            oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   2266:            savm[ii][j]=(ii==j ? 1.0 : 0.0);
                   2267:          }
                   2268:        for(d=0; d<dh[mi][i]; d++){
                   2269:          newm=savm;
1.187   ! brouard  2270:          agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;
        !          2271:          cov[2]=agexact;
        !          2272:          if(nagesqr==1)
        !          2273:            cov[3]= agexact*agexact;
1.126     brouard  2274:          for (kk=1; kk<=cptcovage;kk++) {
1.187   ! brouard  2275:            cov[Tage[kk]+2+nagesqr]=covar[Tvar[Tage[kk]]][i]*agexact;
1.126     brouard  2276:          }
                   2277:        
                   2278:          out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
                   2279:                       1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
                   2280:          savm=oldm;
                   2281:          oldm=newm;
                   2282:        } /* end mult */
                   2283:       
                   2284:        s1=s[mw[mi][i]][i];
                   2285:        s2=s[mw[mi+1][i]][i];
                   2286:        if( s2 > nlstate){ 
                   2287:          lli=log(out[s1][s2] - savm[s1][s2]);
                   2288:        }else{
                   2289:          lli=log(out[s[mw[mi][i]][i]][s[mw[mi+1][i]][i]]); /* Original formula */
                   2290:        }
                   2291:        ipmx +=1;
                   2292:        sw += weight[i];
                   2293:        ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
                   2294: /*     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]); */
                   2295:       } /* end of wave */
                   2296:     } /* end of individual */
                   2297:   }else{  /* ml=5 no inter-extrapolation no jackson =0.8a */
                   2298:     for (i=1,ipmx=0, sw=0.; i<=imx; i++){
1.187   ! brouard  2299:       for (k=1; k<=cptcovn;k++) cov[2+nagesqr+k]=covar[Tvar[k]][i];
1.126     brouard  2300:       for(mi=1; mi<= wav[i]-1; mi++){
                   2301:        for (ii=1;ii<=nlstate+ndeath;ii++)
                   2302:          for (j=1;j<=nlstate+ndeath;j++){
                   2303:            oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   2304:            savm[ii][j]=(ii==j ? 1.0 : 0.0);
                   2305:          }
                   2306:        for(d=0; d<dh[mi][i]; d++){
                   2307:          newm=savm;
1.187   ! brouard  2308:          agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;
        !          2309:          cov[2]=agexact;
        !          2310:          if(nagesqr==1)
        !          2311:            cov[3]= agexact*agexact;
1.126     brouard  2312:          for (kk=1; kk<=cptcovage;kk++) {
1.187   ! brouard  2313:            cov[Tage[kk]+2+nagesqr]=covar[Tvar[Tage[kk]]][i]*agexact;
1.126     brouard  2314:          }
                   2315:        
                   2316:          out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
                   2317:                       1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
                   2318:          savm=oldm;
                   2319:          oldm=newm;
                   2320:        } /* end mult */
                   2321:       
                   2322:        s1=s[mw[mi][i]][i];
                   2323:        s2=s[mw[mi+1][i]][i];
                   2324:        lli=log(out[s[mw[mi][i]][i]][s[mw[mi+1][i]][i]]); /* Original formula */
                   2325:        ipmx +=1;
                   2326:        sw += weight[i];
                   2327:        ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
                   2328:        /*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]);*/
                   2329:       } /* end of wave */
                   2330:     } /* end of individual */
                   2331:   } /* End of if */
                   2332:   for(k=1,l=0.; k<=nlstate; k++) l += ll[k];
                   2333:   /* printf("l1=%f l2=%f ",ll[1],ll[2]); */
                   2334:   l= l*ipmx/sw; /* To get the same order of magnitude as if weight=1 for every body */
                   2335:   return -l;
                   2336: }
                   2337: 
                   2338: /*************** log-likelihood *************/
                   2339: double funcone( double *x)
                   2340: {
                   2341:   /* Same as likeli but slower because of a lot of printf and if */
                   2342:   int i, ii, j, k, mi, d, kk;
1.131     brouard  2343:   double l, ll[NLSTATEMAX+1], cov[NCOVMAX+1];
1.126     brouard  2344:   double **out;
                   2345:   double lli; /* Individual log likelihood */
                   2346:   double llt;
                   2347:   int s1, s2;
                   2348:   double bbh, survp;
1.187   ! brouard  2349:   double agexact;
1.126     brouard  2350:   /*extern weight */
                   2351:   /* We are differentiating ll according to initial status */
                   2352:   /*  for (i=1;i<=npar;i++) printf("%f ", x[i]);*/
                   2353:   /*for(i=1;i<imx;i++) 
                   2354:     printf(" %d\n",s[4][i]);
                   2355:   */
                   2356:   cov[1]=1.;
                   2357: 
                   2358:   for(k=1; k<=nlstate; k++) ll[k]=0.;
                   2359: 
                   2360:   for (i=1,ipmx=0, sw=0.; i<=imx; i++){
1.187   ! brouard  2361:     for (k=1; k<=cptcovn;k++) cov[2+nagesqr+k]=covar[Tvar[k]][i];
1.126     brouard  2362:     for(mi=1; mi<= wav[i]-1; mi++){
                   2363:       for (ii=1;ii<=nlstate+ndeath;ii++)
                   2364:        for (j=1;j<=nlstate+ndeath;j++){
                   2365:          oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   2366:          savm[ii][j]=(ii==j ? 1.0 : 0.0);
                   2367:        }
                   2368:       for(d=0; d<dh[mi][i]; d++){
                   2369:        newm=savm;
1.187   ! brouard  2370:        agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;
        !          2371:        cov[2]=agexact;
        !          2372:        if(nagesqr==1)
        !          2373:          cov[3]= agexact*agexact;
1.126     brouard  2374:        for (kk=1; kk<=cptcovage;kk++) {
1.187   ! brouard  2375:          cov[Tage[kk]+2+nagesqr]=covar[Tvar[Tage[kk]]][i]*agexact;
1.126     brouard  2376:        }
1.187   ! brouard  2377: 
1.145     brouard  2378:        /* savm=pmij(pmmij,cov,ncovmodel,x,nlstate); */
1.126     brouard  2379:        out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
                   2380:                     1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
1.145     brouard  2381:        /* out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath, */
                   2382:        /*           1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate)); */
1.126     brouard  2383:        savm=oldm;
                   2384:        oldm=newm;
                   2385:       } /* end mult */
                   2386:       
                   2387:       s1=s[mw[mi][i]][i];
                   2388:       s2=s[mw[mi+1][i]][i];
                   2389:       bbh=(double)bh[mi][i]/(double)stepm; 
                   2390:       /* bias is positive if real duration
                   2391:        * is higher than the multiple of stepm and negative otherwise.
                   2392:        */
                   2393:       if( s2 > nlstate && (mle <5) ){  /* Jackson */
                   2394:        lli=log(out[s1][s2] - savm[s1][s2]);
                   2395:       } else if  (s2==-2) {
                   2396:        for (j=1,survp=0. ; j<=nlstate; j++) 
                   2397:          survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j];
                   2398:        lli= log(survp);
                   2399:       }else if (mle==1){
                   2400:        lli= log((1.+bbh)*out[s1][s2]- bbh*savm[s1][s2]); /* linear interpolation */
                   2401:       } else if(mle==2){
                   2402:        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 */
                   2403:       } else if(mle==3){  /* exponential inter-extrapolation */
                   2404:        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 */
                   2405:       } else if (mle==4){  /* mle=4 no inter-extrapolation */
                   2406:        lli=log(out[s1][s2]); /* Original formula */
1.136     brouard  2407:       } else{  /* mle=0 back to 1 */
                   2408:        lli= log((1.+bbh)*out[s1][s2]- bbh*savm[s1][s2]); /* linear interpolation */
                   2409:        /*lli=log(out[s1][s2]); */ /* Original formula */
1.126     brouard  2410:       } /* End of if */
                   2411:       ipmx +=1;
                   2412:       sw += weight[i];
                   2413:       ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
1.132     brouard  2414:       /*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  2415:       if(globpr){
1.141     brouard  2416:        fprintf(ficresilk,"%9ld %6d %2d %2d %1d %1d %3d %11.6f %8.4f\
1.126     brouard  2417:  %11.6f %11.6f %11.6f ", \
                   2418:                num[i],i,s1,s2,mi,mw[mi][i],dh[mi][i],exp(lli),weight[i],
                   2419:                2*weight[i]*lli,out[s1][s2],savm[s1][s2]);
                   2420:        for(k=1,llt=0.,l=0.; k<=nlstate; k++){
                   2421:          llt +=ll[k]*gipmx/gsw;
                   2422:          fprintf(ficresilk," %10.6f",-ll[k]*gipmx/gsw);
                   2423:        }
                   2424:        fprintf(ficresilk," %10.6f\n", -llt);
                   2425:       }
                   2426:     } /* end of wave */
                   2427:   } /* end of individual */
                   2428:   for(k=1,l=0.; k<=nlstate; k++) l += ll[k];
                   2429:   /* printf("l1=%f l2=%f ",ll[1],ll[2]); */
                   2430:   l= l*ipmx/sw; /* To get the same order of magnitude as if weight=1 for every body */
                   2431:   if(globpr==0){ /* First time we count the contributions and weights */
                   2432:     gipmx=ipmx;
                   2433:     gsw=sw;
                   2434:   }
                   2435:   return -l;
                   2436: }
                   2437: 
                   2438: 
                   2439: /*************** function likelione ***********/
                   2440: void likelione(FILE *ficres,double p[], int npar, int nlstate, int *globpri, long *ipmx, double *sw, double *fretone, double (*funcone)(double []))
                   2441: {
                   2442:   /* This routine should help understanding what is done with 
                   2443:      the selection of individuals/waves and
                   2444:      to check the exact contribution to the likelihood.
                   2445:      Plotting could be done.
                   2446:    */
                   2447:   int k;
                   2448: 
                   2449:   if(*globpri !=0){ /* Just counts and sums, no printings */
                   2450:     strcpy(fileresilk,"ilk"); 
                   2451:     strcat(fileresilk,fileres);
                   2452:     if((ficresilk=fopen(fileresilk,"w"))==NULL) {
                   2453:       printf("Problem with resultfile: %s\n", fileresilk);
                   2454:       fprintf(ficlog,"Problem with resultfile: %s\n", fileresilk);
                   2455:     }
                   2456:     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");
                   2457:     fprintf(ficresilk, "#num_i i s1 s2 mi mw dh likeli weight 2wlli out sav ");
                   2458:     /*         i,s1,s2,mi,mw[mi][i],dh[mi][i],exp(lli),weight[i],2*weight[i]*lli,out[s1][s2],savm[s1][s2]); */
                   2459:     for(k=1; k<=nlstate; k++) 
                   2460:       fprintf(ficresilk," -2*gipw/gsw*weight*ll[%d]++",k);
                   2461:     fprintf(ficresilk," -2*gipw/gsw*weight*ll(total)\n");
                   2462:   }
                   2463: 
                   2464:   *fretone=(*funcone)(p);
                   2465:   if(*globpri !=0){
                   2466:     fclose(ficresilk);
                   2467:     fprintf(fichtm,"\n<br>File of contributions to the likelihood: <a href=\"%s\">%s</a><br>\n",subdirf(fileresilk),subdirf(fileresilk));
                   2468:     fflush(fichtm); 
                   2469:   } 
                   2470:   return;
                   2471: }
                   2472: 
                   2473: 
                   2474: /*********** Maximum Likelihood Estimation ***************/
                   2475: 
                   2476: void mlikeli(FILE *ficres,double p[], int npar, int ncovmodel, int nlstate, double ftol, double (*func)(double []))
                   2477: {
1.165     brouard  2478:   int i,j, iter=0;
1.126     brouard  2479:   double **xi;
                   2480:   double fret;
                   2481:   double fretone; /* Only one call to likelihood */
                   2482:   /*  char filerespow[FILENAMELENGTH];*/
1.162     brouard  2483: 
                   2484: #ifdef NLOPT
                   2485:   int creturn;
                   2486:   nlopt_opt opt;
                   2487:   /* double lb[9] = { -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL }; /\* lower bounds *\/ */
                   2488:   double *lb;
                   2489:   double minf; /* the minimum objective value, upon return */
                   2490:   double * p1; /* Shifted parameters from 0 instead of 1 */
                   2491:   myfunc_data dinst, *d = &dinst;
                   2492: #endif
                   2493: 
                   2494: 
1.126     brouard  2495:   xi=matrix(1,npar,1,npar);
                   2496:   for (i=1;i<=npar;i++)
                   2497:     for (j=1;j<=npar;j++)
                   2498:       xi[i][j]=(i==j ? 1.0 : 0.0);
                   2499:   printf("Powell\n");  fprintf(ficlog,"Powell\n");
                   2500:   strcpy(filerespow,"pow"); 
                   2501:   strcat(filerespow,fileres);
                   2502:   if((ficrespow=fopen(filerespow,"w"))==NULL) {
                   2503:     printf("Problem with resultfile: %s\n", filerespow);
                   2504:     fprintf(ficlog,"Problem with resultfile: %s\n", filerespow);
                   2505:   }
                   2506:   fprintf(ficrespow,"# Powell\n# iter -2*LL");
                   2507:   for (i=1;i<=nlstate;i++)
                   2508:     for(j=1;j<=nlstate+ndeath;j++)
                   2509:       if(j!=i)fprintf(ficrespow," p%1d%1d",i,j);
                   2510:   fprintf(ficrespow,"\n");
1.162     brouard  2511: #ifdef POWELL
1.126     brouard  2512:   powell(p,xi,npar,ftol,&iter,&fret,func);
1.162     brouard  2513: #endif
1.126     brouard  2514: 
1.162     brouard  2515: #ifdef NLOPT
                   2516: #ifdef NEWUOA
                   2517:   opt = nlopt_create(NLOPT_LN_NEWUOA,npar);
                   2518: #else
                   2519:   opt = nlopt_create(NLOPT_LN_BOBYQA,npar);
                   2520: #endif
                   2521:   lb=vector(0,npar-1);
                   2522:   for (i=0;i<npar;i++) lb[i]= -HUGE_VAL;
                   2523:   nlopt_set_lower_bounds(opt, lb);
                   2524:   nlopt_set_initial_step1(opt, 0.1);
                   2525:   
                   2526:   p1= (p+1); /*  p *(p+1)@8 and p *(p1)@8 are equal p1[0]=p[1] */
                   2527:   d->function = func;
                   2528:   printf(" Func %.12lf \n",myfunc(npar,p1,NULL,d));
                   2529:   nlopt_set_min_objective(opt, myfunc, d);
                   2530:   nlopt_set_xtol_rel(opt, ftol);
                   2531:   if ((creturn=nlopt_optimize(opt, p1, &minf)) < 0) {
                   2532:     printf("nlopt failed! %d\n",creturn); 
                   2533:   }
                   2534:   else {
                   2535:     printf("found minimum after %d evaluations (NLOPT=%d)\n", countcallfunc ,NLOPT);
                   2536:     printf("found minimum at f(%g,%g) = %0.10g\n", p[0], p[1], minf);
                   2537:     iter=1; /* not equal */
                   2538:   }
                   2539:   nlopt_destroy(opt);
                   2540: #endif
1.126     brouard  2541:   free_matrix(xi,1,npar,1,npar);
                   2542:   fclose(ficrespow);
1.180     brouard  2543:   printf("#Number of iterations & function calls = %d & %d, -2 Log likelihood = %.12f\n",iter, countcallfunc,func(p));
                   2544:   fprintf(ficlog,"#Number of iterations & function calls = %d & %d, -2 Log likelihood = %.12f\n",iter, countcallfunc,func(p));
                   2545:   fprintf(ficres,"#Number of iterations & function calls = %d & %d, -2 Log likelihood = %.12f\n",iter, countcallfunc,func(p));
1.126     brouard  2546: 
                   2547: }
                   2548: 
                   2549: /**** Computes Hessian and covariance matrix ***/
                   2550: void hesscov(double **matcov, double p[], int npar, double delti[], double ftolhess, double (*func)(double []))
                   2551: {
                   2552:   double  **a,**y,*x,pd;
                   2553:   double **hess;
1.164     brouard  2554:   int i, j;
1.126     brouard  2555:   int *indx;
                   2556: 
                   2557:   double hessii(double p[], double delta, int theta, double delti[],double (*func)(double []),int npar);
                   2558:   double hessij(double p[], double delti[], int i, int j,double (*func)(double []),int npar);
                   2559:   void lubksb(double **a, int npar, int *indx, double b[]) ;
                   2560:   void ludcmp(double **a, int npar, int *indx, double *d) ;
                   2561:   double gompertz(double p[]);
                   2562:   hess=matrix(1,npar,1,npar);
                   2563: 
                   2564:   printf("\nCalculation of the hessian matrix. Wait...\n");
                   2565:   fprintf(ficlog,"\nCalculation of the hessian matrix. Wait...\n");
                   2566:   for (i=1;i<=npar;i++){
                   2567:     printf("%d",i);fflush(stdout);
                   2568:     fprintf(ficlog,"%d",i);fflush(ficlog);
                   2569:    
                   2570:      hess[i][i]=hessii(p,ftolhess,i,delti,func,npar);
                   2571:     
                   2572:     /*  printf(" %f ",p[i]);
                   2573:        printf(" %lf %lf %lf",hess[i][i],ftolhess,delti[i]);*/
                   2574:   }
                   2575:   
                   2576:   for (i=1;i<=npar;i++) {
                   2577:     for (j=1;j<=npar;j++)  {
                   2578:       if (j>i) { 
                   2579:        printf(".%d%d",i,j);fflush(stdout);
                   2580:        fprintf(ficlog,".%d%d",i,j);fflush(ficlog);
                   2581:        hess[i][j]=hessij(p,delti,i,j,func,npar);
                   2582:        
                   2583:        hess[j][i]=hess[i][j];    
                   2584:        /*printf(" %lf ",hess[i][j]);*/
                   2585:       }
                   2586:     }
                   2587:   }
                   2588:   printf("\n");
                   2589:   fprintf(ficlog,"\n");
                   2590: 
                   2591:   printf("\nInverting the hessian to get the covariance matrix. Wait...\n");
                   2592:   fprintf(ficlog,"\nInverting the hessian to get the covariance matrix. Wait...\n");
                   2593:   
                   2594:   a=matrix(1,npar,1,npar);
                   2595:   y=matrix(1,npar,1,npar);
                   2596:   x=vector(1,npar);
                   2597:   indx=ivector(1,npar);
                   2598:   for (i=1;i<=npar;i++)
                   2599:     for (j=1;j<=npar;j++) a[i][j]=hess[i][j];
                   2600:   ludcmp(a,npar,indx,&pd);
                   2601: 
                   2602:   for (j=1;j<=npar;j++) {
                   2603:     for (i=1;i<=npar;i++) x[i]=0;
                   2604:     x[j]=1;
                   2605:     lubksb(a,npar,indx,x);
                   2606:     for (i=1;i<=npar;i++){ 
                   2607:       matcov[i][j]=x[i];
                   2608:     }
                   2609:   }
                   2610: 
                   2611:   printf("\n#Hessian matrix#\n");
                   2612:   fprintf(ficlog,"\n#Hessian matrix#\n");
                   2613:   for (i=1;i<=npar;i++) { 
                   2614:     for (j=1;j<=npar;j++) { 
                   2615:       printf("%.3e ",hess[i][j]);
                   2616:       fprintf(ficlog,"%.3e ",hess[i][j]);
                   2617:     }
                   2618:     printf("\n");
                   2619:     fprintf(ficlog,"\n");
                   2620:   }
                   2621: 
                   2622:   /* Recompute Inverse */
                   2623:   for (i=1;i<=npar;i++)
                   2624:     for (j=1;j<=npar;j++) a[i][j]=matcov[i][j];
                   2625:   ludcmp(a,npar,indx,&pd);
                   2626: 
                   2627:   /*  printf("\n#Hessian matrix recomputed#\n");
                   2628: 
                   2629:   for (j=1;j<=npar;j++) {
                   2630:     for (i=1;i<=npar;i++) x[i]=0;
                   2631:     x[j]=1;
                   2632:     lubksb(a,npar,indx,x);
                   2633:     for (i=1;i<=npar;i++){ 
                   2634:       y[i][j]=x[i];
                   2635:       printf("%.3e ",y[i][j]);
                   2636:       fprintf(ficlog,"%.3e ",y[i][j]);
                   2637:     }
                   2638:     printf("\n");
                   2639:     fprintf(ficlog,"\n");
                   2640:   }
                   2641:   */
                   2642: 
                   2643:   free_matrix(a,1,npar,1,npar);
                   2644:   free_matrix(y,1,npar,1,npar);
                   2645:   free_vector(x,1,npar);
                   2646:   free_ivector(indx,1,npar);
                   2647:   free_matrix(hess,1,npar,1,npar);
                   2648: 
                   2649: 
                   2650: }
                   2651: 
                   2652: /*************** hessian matrix ****************/
                   2653: double hessii(double x[], double delta, int theta, double delti[], double (*func)(double []), int npar)
                   2654: {
                   2655:   int i;
                   2656:   int l=1, lmax=20;
                   2657:   double k1,k2;
1.132     brouard  2658:   double p2[MAXPARM+1]; /* identical to x */
1.126     brouard  2659:   double res;
                   2660:   double delt=0.0001, delts, nkhi=10.,nkhif=1., khi=1.e-4;
                   2661:   double fx;
                   2662:   int k=0,kmax=10;
                   2663:   double l1;
                   2664: 
                   2665:   fx=func(x);
                   2666:   for (i=1;i<=npar;i++) p2[i]=x[i];
1.145     brouard  2667:   for(l=0 ; l <=lmax; l++){  /* Enlarging the zone around the Maximum */
1.126     brouard  2668:     l1=pow(10,l);
                   2669:     delts=delt;
                   2670:     for(k=1 ; k <kmax; k=k+1){
                   2671:       delt = delta*(l1*k);
                   2672:       p2[theta]=x[theta] +delt;
1.145     brouard  2673:       k1=func(p2)-fx;   /* Might be negative if too close to the theoretical maximum */
1.126     brouard  2674:       p2[theta]=x[theta]-delt;
                   2675:       k2=func(p2)-fx;
                   2676:       /*res= (k1-2.0*fx+k2)/delt/delt; */
                   2677:       res= (k1+k2)/delt/delt/2.; /* Divided by because L and not 2*L */
                   2678:       
1.132     brouard  2679: #ifdef DEBUGHESS
1.126     brouard  2680:       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);
                   2681:       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);
                   2682: #endif
                   2683:       /*if(fabs(k1-2.0*fx+k2) <1.e-13){ */
                   2684:       if((k1 <khi/nkhi/2.) || (k2 <khi/nkhi/2.)){
                   2685:        k=kmax;
                   2686:       }
                   2687:       else if((k1 >khi/nkhif) || (k2 >khi/nkhif)){ /* Keeps lastvalue before 3.84/2 KHI2 5% 1d.f. */
1.164     brouard  2688:        k=kmax; l=lmax*10;
1.126     brouard  2689:       }
                   2690:       else if((k1 >khi/nkhi) || (k2 >khi/nkhi)){ 
                   2691:        delts=delt;
                   2692:       }
                   2693:     }
                   2694:   }
                   2695:   delti[theta]=delts;
                   2696:   return res; 
                   2697:   
                   2698: }
                   2699: 
                   2700: double hessij( double x[], double delti[], int thetai,int thetaj,double (*func)(double []),int npar)
                   2701: {
                   2702:   int i;
1.164     brouard  2703:   int l=1, lmax=20;
1.126     brouard  2704:   double k1,k2,k3,k4,res,fx;
1.132     brouard  2705:   double p2[MAXPARM+1];
1.126     brouard  2706:   int k;
                   2707: 
                   2708:   fx=func(x);
                   2709:   for (k=1; k<=2; k++) {
                   2710:     for (i=1;i<=npar;i++) p2[i]=x[i];
                   2711:     p2[thetai]=x[thetai]+delti[thetai]/k;
                   2712:     p2[thetaj]=x[thetaj]+delti[thetaj]/k;
                   2713:     k1=func(p2)-fx;
                   2714:   
                   2715:     p2[thetai]=x[thetai]+delti[thetai]/k;
                   2716:     p2[thetaj]=x[thetaj]-delti[thetaj]/k;
                   2717:     k2=func(p2)-fx;
                   2718:   
                   2719:     p2[thetai]=x[thetai]-delti[thetai]/k;
                   2720:     p2[thetaj]=x[thetaj]+delti[thetaj]/k;
                   2721:     k3=func(p2)-fx;
                   2722:   
                   2723:     p2[thetai]=x[thetai]-delti[thetai]/k;
                   2724:     p2[thetaj]=x[thetaj]-delti[thetaj]/k;
                   2725:     k4=func(p2)-fx;
                   2726:     res=(k1-k2-k3+k4)/4.0/delti[thetai]*k/delti[thetaj]*k/2.; /* Because of L not 2*L */
                   2727: #ifdef DEBUG
                   2728:     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);
                   2729:     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);
                   2730: #endif
                   2731:   }
                   2732:   return res;
                   2733: }
                   2734: 
                   2735: /************** Inverse of matrix **************/
                   2736: void ludcmp(double **a, int n, int *indx, double *d) 
                   2737: { 
                   2738:   int i,imax,j,k; 
                   2739:   double big,dum,sum,temp; 
                   2740:   double *vv; 
                   2741:  
                   2742:   vv=vector(1,n); 
                   2743:   *d=1.0; 
                   2744:   for (i=1;i<=n;i++) { 
                   2745:     big=0.0; 
                   2746:     for (j=1;j<=n;j++) 
                   2747:       if ((temp=fabs(a[i][j])) > big) big=temp; 
                   2748:     if (big == 0.0) nrerror("Singular matrix in routine ludcmp"); 
                   2749:     vv[i]=1.0/big; 
                   2750:   } 
                   2751:   for (j=1;j<=n;j++) { 
                   2752:     for (i=1;i<j;i++) { 
                   2753:       sum=a[i][j]; 
                   2754:       for (k=1;k<i;k++) sum -= a[i][k]*a[k][j]; 
                   2755:       a[i][j]=sum; 
                   2756:     } 
                   2757:     big=0.0; 
                   2758:     for (i=j;i<=n;i++) { 
                   2759:       sum=a[i][j]; 
                   2760:       for (k=1;k<j;k++) 
                   2761:        sum -= a[i][k]*a[k][j]; 
                   2762:       a[i][j]=sum; 
                   2763:       if ( (dum=vv[i]*fabs(sum)) >= big) { 
                   2764:        big=dum; 
                   2765:        imax=i; 
                   2766:       } 
                   2767:     } 
                   2768:     if (j != imax) { 
                   2769:       for (k=1;k<=n;k++) { 
                   2770:        dum=a[imax][k]; 
                   2771:        a[imax][k]=a[j][k]; 
                   2772:        a[j][k]=dum; 
                   2773:       } 
                   2774:       *d = -(*d); 
                   2775:       vv[imax]=vv[j]; 
                   2776:     } 
                   2777:     indx[j]=imax; 
                   2778:     if (a[j][j] == 0.0) a[j][j]=TINY; 
                   2779:     if (j != n) { 
                   2780:       dum=1.0/(a[j][j]); 
                   2781:       for (i=j+1;i<=n;i++) a[i][j] *= dum; 
                   2782:     } 
                   2783:   } 
                   2784:   free_vector(vv,1,n);  /* Doesn't work */
                   2785: ;
                   2786: } 
                   2787: 
                   2788: void lubksb(double **a, int n, int *indx, double b[]) 
                   2789: { 
                   2790:   int i,ii=0,ip,j; 
                   2791:   double sum; 
                   2792:  
                   2793:   for (i=1;i<=n;i++) { 
                   2794:     ip=indx[i]; 
                   2795:     sum=b[ip]; 
                   2796:     b[ip]=b[i]; 
                   2797:     if (ii) 
                   2798:       for (j=ii;j<=i-1;j++) sum -= a[i][j]*b[j]; 
                   2799:     else if (sum) ii=i; 
                   2800:     b[i]=sum; 
                   2801:   } 
                   2802:   for (i=n;i>=1;i--) { 
                   2803:     sum=b[i]; 
                   2804:     for (j=i+1;j<=n;j++) sum -= a[i][j]*b[j]; 
                   2805:     b[i]=sum/a[i][i]; 
                   2806:   } 
                   2807: } 
                   2808: 
                   2809: void pstamp(FILE *fichier)
                   2810: {
                   2811:   fprintf(fichier,"# %s.%s\n#%s\n#%s\n# %s", optionfilefiname,optionfilext,version,fullversion,strstart);
                   2812: }
                   2813: 
                   2814: /************ Frequencies ********************/
                   2815: 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[])
                   2816: {  /* Some frequencies */
                   2817:   
1.164     brouard  2818:   int i, m, jk, j1, bool, z1,j;
1.126     brouard  2819:   int first;
                   2820:   double ***freq; /* Frequencies */
                   2821:   double *pp, **prop;
                   2822:   double pos,posprop, k2, dateintsum=0,k2cpt=0;
                   2823:   char fileresp[FILENAMELENGTH];
                   2824:   
                   2825:   pp=vector(1,nlstate);
                   2826:   prop=matrix(1,nlstate,iagemin,iagemax+3);
                   2827:   strcpy(fileresp,"p");
                   2828:   strcat(fileresp,fileres);
                   2829:   if((ficresp=fopen(fileresp,"w"))==NULL) {
                   2830:     printf("Problem with prevalence resultfile: %s\n", fileresp);
                   2831:     fprintf(ficlog,"Problem with prevalence resultfile: %s\n", fileresp);
                   2832:     exit(0);
                   2833:   }
                   2834:   freq= ma3x(-5,nlstate+ndeath,-5,nlstate+ndeath,iagemin,iagemax+3);
                   2835:   j1=0;
                   2836:   
                   2837:   j=cptcoveff;
                   2838:   if (cptcovn<1) {j=1;ncodemax[1]=1;}
                   2839: 
                   2840:   first=1;
                   2841: 
1.169     brouard  2842:   /* for(k1=1; k1<=j ; k1++){ */  /* Loop on covariates */
                   2843:   /*  for(i1=1; i1<=ncodemax[k1];i1++){ */ /* Now it is 2 */
                   2844:   /*    j1++; */
1.145     brouard  2845:   for (j1 = 1; j1 <= (int) pow(2,cptcoveff); j1++){
1.126     brouard  2846:       /*printf("cptcoveff=%d Tvaraff=%d", cptcoveff,Tvaraff[1]);
                   2847:        scanf("%d", i);*/
                   2848:       for (i=-5; i<=nlstate+ndeath; i++)  
                   2849:        for (jk=-5; jk<=nlstate+ndeath; jk++)  
                   2850:          for(m=iagemin; m <= iagemax+3; m++)
                   2851:            freq[i][jk][m]=0;
1.143     brouard  2852:       
                   2853:       for (i=1; i<=nlstate; i++)  
                   2854:        for(m=iagemin; m <= iagemax+3; m++)
                   2855:          prop[i][m]=0;
1.126     brouard  2856:       
                   2857:       dateintsum=0;
                   2858:       k2cpt=0;
                   2859:       for (i=1; i<=imx; i++) {
                   2860:        bool=1;
1.144     brouard  2861:        if  (cptcovn>0) { /* Filter is here: Must be looked at for model=V1+V2+V3+V4 */
                   2862:          for (z1=1; z1<=cptcoveff; z1++)       
                   2863:             if (covar[Tvaraff[z1]][i]!= nbcode[Tvaraff[z1]][codtab[j1][z1]]){
1.145     brouard  2864:                 /* Tests if the value of each of the covariates of i is equal to filter j1 */
1.144     brouard  2865:               bool=0;
1.145     brouard  2866:               /* 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", 
                   2867:                 bool,i,z1, z1, Tvaraff[z1],i,covar[Tvaraff[z1]][i],j1,z1,codtab[j1][z1],
                   2868:                 j1,z1,nbcode[Tvaraff[z1]][codtab[j1][z1]],j1);*/
1.144     brouard  2869:               /* For j1=7 in V1+V2+V3+V4 = 0 1 1 0 and codtab[7][3]=1 and nbcde[3][?]=1*/
                   2870:             } 
1.126     brouard  2871:        }
1.144     brouard  2872:  
1.126     brouard  2873:        if (bool==1){
                   2874:          for(m=firstpass; m<=lastpass; m++){
                   2875:            k2=anint[m][i]+(mint[m][i]/12.);
                   2876:            /*if ((k2>=dateprev1) && (k2<=dateprev2)) {*/
                   2877:              if(agev[m][i]==0) agev[m][i]=iagemax+1;
                   2878:              if(agev[m][i]==1) agev[m][i]=iagemax+2;
                   2879:              if (s[m][i]>0 && s[m][i]<=nlstate) prop[s[m][i]][(int)agev[m][i]] += weight[i];
                   2880:              if (m<lastpass) {
                   2881:                freq[s[m][i]][s[m+1][i]][(int)agev[m][i]] += weight[i];
                   2882:                freq[s[m][i]][s[m+1][i]][iagemax+3] += weight[i];
                   2883:              }
                   2884:              
                   2885:              if ((agev[m][i]>1) && (agev[m][i]< (iagemax+3))) {
                   2886:                dateintsum=dateintsum+k2;
                   2887:                k2cpt++;
                   2888:              }
                   2889:              /*}*/
                   2890:          }
                   2891:        }
1.145     brouard  2892:       } /* end i */
1.126     brouard  2893:        
                   2894:       /*      fprintf(ficresp, "#Count between %.lf/%.lf/%.lf and %.lf/%.lf/%.lf\n",jprev1, mprev1,anprev1,jprev2, mprev2,anprev2);*/
                   2895:       pstamp(ficresp);
                   2896:       if  (cptcovn>0) {
                   2897:        fprintf(ficresp, "\n#********** Variable "); 
                   2898:        for (z1=1; z1<=cptcoveff; z1++) fprintf(ficresp, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtab[j1][z1]]);
                   2899:        fprintf(ficresp, "**********\n#");
1.143     brouard  2900:        fprintf(ficlog, "\n#********** Variable "); 
                   2901:        for (z1=1; z1<=cptcoveff; z1++) fprintf(ficlog, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtab[j1][z1]]);
                   2902:        fprintf(ficlog, "**********\n#");
1.126     brouard  2903:       }
                   2904:       for(i=1; i<=nlstate;i++) 
                   2905:        fprintf(ficresp, " Age Prev(%d) N(%d) N",i,i);
                   2906:       fprintf(ficresp, "\n");
                   2907:       
                   2908:       for(i=iagemin; i <= iagemax+3; i++){
                   2909:        if(i==iagemax+3){
                   2910:          fprintf(ficlog,"Total");
                   2911:        }else{
                   2912:          if(first==1){
                   2913:            first=0;
                   2914:            printf("See log file for details...\n");
                   2915:          }
                   2916:          fprintf(ficlog,"Age %d", i);
                   2917:        }
                   2918:        for(jk=1; jk <=nlstate ; jk++){
                   2919:          for(m=-1, pp[jk]=0; m <=nlstate+ndeath ; m++)
                   2920:            pp[jk] += freq[jk][m][i]; 
                   2921:        }
                   2922:        for(jk=1; jk <=nlstate ; jk++){
                   2923:          for(m=-1, pos=0; m <=0 ; m++)
                   2924:            pos += freq[jk][m][i];
                   2925:          if(pp[jk]>=1.e-10){
                   2926:            if(first==1){
1.132     brouard  2927:              printf(" %d.=%.0f loss[%d]=%.1f%%",jk,pp[jk],jk,100*pos/pp[jk]);
1.126     brouard  2928:            }
                   2929:            fprintf(ficlog," %d.=%.0f loss[%d]=%.1f%%",jk,pp[jk],jk,100*pos/pp[jk]);
                   2930:          }else{
                   2931:            if(first==1)
                   2932:              printf(" %d.=%.0f loss[%d]=NaNQ%%",jk,pp[jk],jk);
                   2933:            fprintf(ficlog," %d.=%.0f loss[%d]=NaNQ%%",jk,pp[jk],jk);
                   2934:          }
                   2935:        }
                   2936: 
                   2937:        for(jk=1; jk <=nlstate ; jk++){
                   2938:          for(m=0, pp[jk]=0; m <=nlstate+ndeath; m++)
                   2939:            pp[jk] += freq[jk][m][i];
                   2940:        }       
                   2941:        for(jk=1,pos=0,posprop=0; jk <=nlstate ; jk++){
                   2942:          pos += pp[jk];
                   2943:          posprop += prop[jk][i];
                   2944:        }
                   2945:        for(jk=1; jk <=nlstate ; jk++){
                   2946:          if(pos>=1.e-5){
                   2947:            if(first==1)
                   2948:              printf(" %d.=%.0f prev[%d]=%.1f%%",jk,pp[jk],jk,100*pp[jk]/pos);
                   2949:            fprintf(ficlog," %d.=%.0f prev[%d]=%.1f%%",jk,pp[jk],jk,100*pp[jk]/pos);
                   2950:          }else{
                   2951:            if(first==1)
                   2952:              printf(" %d.=%.0f prev[%d]=NaNQ%%",jk,pp[jk],jk);
                   2953:            fprintf(ficlog," %d.=%.0f prev[%d]=NaNQ%%",jk,pp[jk],jk);
                   2954:          }
                   2955:          if( i <= iagemax){
                   2956:            if(pos>=1.e-5){
                   2957:              fprintf(ficresp," %d %.5f %.0f %.0f",i,prop[jk][i]/posprop, prop[jk][i],posprop);
                   2958:              /*probs[i][jk][j1]= pp[jk]/pos;*/
                   2959:              /*printf("\ni=%d jk=%d j1=%d %.5f %.0f %.0f %f",i,jk,j1,pp[jk]/pos, pp[jk],pos,probs[i][jk][j1]);*/
                   2960:            }
                   2961:            else
                   2962:              fprintf(ficresp," %d NaNq %.0f %.0f",i,prop[jk][i],posprop);
                   2963:          }
                   2964:        }
                   2965:        
                   2966:        for(jk=-1; jk <=nlstate+ndeath; jk++)
                   2967:          for(m=-1; m <=nlstate+ndeath; m++)
                   2968:            if(freq[jk][m][i] !=0 ) {
                   2969:            if(first==1)
                   2970:              printf(" %d%d=%.0f",jk,m,freq[jk][m][i]);
                   2971:              fprintf(ficlog," %d%d=%.0f",jk,m,freq[jk][m][i]);
                   2972:            }
                   2973:        if(i <= iagemax)
                   2974:          fprintf(ficresp,"\n");
                   2975:        if(first==1)
                   2976:          printf("Others in log...\n");
                   2977:        fprintf(ficlog,"\n");
                   2978:       }
1.145     brouard  2979:       /*}*/
1.126     brouard  2980:   }
                   2981:   dateintmean=dateintsum/k2cpt; 
                   2982:  
                   2983:   fclose(ficresp);
                   2984:   free_ma3x(freq,-5,nlstate+ndeath,-5,nlstate+ndeath, iagemin, iagemax+3);
                   2985:   free_vector(pp,1,nlstate);
                   2986:   free_matrix(prop,1,nlstate,iagemin, iagemax+3);
                   2987:   /* End of Freq */
                   2988: }
                   2989: 
                   2990: /************ Prevalence ********************/
                   2991: 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)
                   2992: {  
                   2993:   /* Compute observed prevalence between dateprev1 and dateprev2 by counting the number of people
                   2994:      in each health status at the date of interview (if between dateprev1 and dateprev2).
                   2995:      We still use firstpass and lastpass as another selection.
                   2996:   */
                   2997:  
1.164     brouard  2998:   int i, m, jk, j1, bool, z1,j;
                   2999: 
                   3000:   double **prop;
                   3001:   double posprop; 
1.126     brouard  3002:   double  y2; /* in fractional years */
                   3003:   int iagemin, iagemax;
1.145     brouard  3004:   int first; /** to stop verbosity which is redirected to log file */
1.126     brouard  3005: 
                   3006:   iagemin= (int) agemin;
                   3007:   iagemax= (int) agemax;
                   3008:   /*pp=vector(1,nlstate);*/
                   3009:   prop=matrix(1,nlstate,iagemin,iagemax+3); 
                   3010:   /*  freq=ma3x(-1,nlstate+ndeath,-1,nlstate+ndeath,iagemin,iagemax+3);*/
                   3011:   j1=0;
                   3012:   
1.145     brouard  3013:   /*j=cptcoveff;*/
1.126     brouard  3014:   if (cptcovn<1) {j=1;ncodemax[1]=1;}
                   3015:   
1.145     brouard  3016:   first=1;
                   3017:   for(j1=1; j1<= (int) pow(2,cptcoveff);j1++){
                   3018:     /*for(i1=1; i1<=ncodemax[k1];i1++){
                   3019:       j1++;*/
1.126     brouard  3020:       
                   3021:       for (i=1; i<=nlstate; i++)  
                   3022:        for(m=iagemin; m <= iagemax+3; m++)
                   3023:          prop[i][m]=0.0;
                   3024:      
                   3025:       for (i=1; i<=imx; i++) { /* Each individual */
                   3026:        bool=1;
                   3027:        if  (cptcovn>0) {
                   3028:          for (z1=1; z1<=cptcoveff; z1++) 
                   3029:            if (covar[Tvaraff[z1]][i]!= nbcode[Tvaraff[z1]][codtab[j1][z1]]) 
                   3030:              bool=0;
                   3031:        } 
                   3032:        if (bool==1) { 
                   3033:          for(m=firstpass; m<=lastpass; m++){/* Other selection (we can limit to certain interviews*/
                   3034:            y2=anint[m][i]+(mint[m][i]/12.); /* Fractional date in year */
                   3035:            if ((y2>=dateprev1) && (y2<=dateprev2)) { /* Here is the main selection (fractional years) */
                   3036:              if(agev[m][i]==0) agev[m][i]=iagemax+1;
                   3037:              if(agev[m][i]==1) agev[m][i]=iagemax+2;
                   3038:              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); 
                   3039:              if (s[m][i]>0 && s[m][i]<=nlstate) { 
                   3040:                /*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]]);*/
                   3041:                prop[s[m][i]][(int)agev[m][i]] += weight[i];
                   3042:                prop[s[m][i]][iagemax+3] += weight[i]; 
                   3043:              } 
                   3044:            }
                   3045:          } /* end selection of waves */
                   3046:        }
                   3047:       }
                   3048:       for(i=iagemin; i <= iagemax+3; i++){  
                   3049:        for(jk=1,posprop=0; jk <=nlstate ; jk++) { 
                   3050:          posprop += prop[jk][i]; 
                   3051:        } 
1.145     brouard  3052:        
1.126     brouard  3053:        for(jk=1; jk <=nlstate ; jk++){     
                   3054:          if( i <=  iagemax){ 
                   3055:            if(posprop>=1.e-5){ 
                   3056:              probs[i][jk][j1]= prop[jk][i]/posprop;
1.145     brouard  3057:            } else{
                   3058:              if(first==1){
                   3059:                first=0;
                   3060:                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]);
                   3061:              }
                   3062:            }
1.126     brouard  3063:          } 
                   3064:        }/* end jk */ 
                   3065:       }/* end i */ 
1.145     brouard  3066:     /*} *//* end i1 */
                   3067:   } /* end j1 */
1.126     brouard  3068:   
                   3069:   /*  free_ma3x(freq,-1,nlstate+ndeath,-1,nlstate+ndeath, iagemin, iagemax+3);*/
                   3070:   /*free_vector(pp,1,nlstate);*/
                   3071:   free_matrix(prop,1,nlstate, iagemin,iagemax+3);
                   3072: }  /* End of prevalence */
                   3073: 
                   3074: /************* Waves Concatenation ***************/
                   3075: 
                   3076: 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)
                   3077: {
                   3078:   /* Concatenates waves: wav[i] is the number of effective (useful waves) of individual i.
                   3079:      Death is a valid wave (if date is known).
                   3080:      mw[mi][i] is the mi (mi=1 to wav[i])  effective wave of individual i
                   3081:      dh[m][i] or dh[mw[mi][i]][i] is the delay between two effective waves m=mw[mi][i]
                   3082:      and mw[mi+1][i]. dh depends on stepm.
                   3083:      */
                   3084: 
                   3085:   int i, mi, m;
                   3086:   /* int j, k=0,jk, ju, jl,jmin=1e+5, jmax=-1;
                   3087:      double sum=0., jmean=0.;*/
                   3088:   int first;
                   3089:   int j, k=0,jk, ju, jl;
                   3090:   double sum=0.;
                   3091:   first=0;
1.164     brouard  3092:   jmin=100000;
1.126     brouard  3093:   jmax=-1;
                   3094:   jmean=0.;
                   3095:   for(i=1; i<=imx; i++){
                   3096:     mi=0;
                   3097:     m=firstpass;
                   3098:     while(s[m][i] <= nlstate){
                   3099:       if(s[m][i]>=1 || s[m][i]==-2 || s[m][i]==-4 || s[m][i]==-5)
                   3100:        mw[++mi][i]=m;
                   3101:       if(m >=lastpass)
                   3102:        break;
                   3103:       else
                   3104:        m++;
                   3105:     }/* end while */
                   3106:     if (s[m][i] > nlstate){
                   3107:       mi++;    /* Death is another wave */
                   3108:       /* if(mi==0)  never been interviewed correctly before death */
                   3109:         /* Only death is a correct wave */
                   3110:       mw[mi][i]=m;
                   3111:     }
                   3112: 
                   3113:     wav[i]=mi;
                   3114:     if(mi==0){
                   3115:       nbwarn++;
                   3116:       if(first==0){
                   3117:        printf("Warning! No valid information for individual %ld line=%d (skipped) and may be others, see log file\n",num[i],i);
                   3118:        first=1;
                   3119:       }
                   3120:       if(first==1){
                   3121:        fprintf(ficlog,"Warning! No valid information for individual %ld line=%d (skipped)\n",num[i],i);
                   3122:       }
                   3123:     } /* end mi==0 */
                   3124:   } /* End individuals */
                   3125: 
                   3126:   for(i=1; i<=imx; i++){
                   3127:     for(mi=1; mi<wav[i];mi++){
                   3128:       if (stepm <=0)
                   3129:        dh[mi][i]=1;
                   3130:       else{
                   3131:        if (s[mw[mi+1][i]][i] > nlstate) { /* A death */
                   3132:          if (agedc[i] < 2*AGESUP) {
                   3133:            j= rint(agedc[i]*12-agev[mw[mi][i]][i]*12); 
                   3134:            if(j==0) j=1;  /* Survives at least one month after exam */
                   3135:            else if(j<0){
                   3136:              nberr++;
                   3137:              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]);
                   3138:              j=1; /* Temporary Dangerous patch */
                   3139:              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);
                   3140:              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]);
                   3141:              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);
                   3142:            }
                   3143:            k=k+1;
                   3144:            if (j >= jmax){
                   3145:              jmax=j;
                   3146:              ijmax=i;
                   3147:            }
                   3148:            if (j <= jmin){
                   3149:              jmin=j;
                   3150:              ijmin=i;
                   3151:            }
                   3152:            sum=sum+j;
                   3153:            /*if (j<0) printf("j=%d num=%d \n",j,i);*/
                   3154:            /*    printf("%d %d %d %d\n", s[mw[mi][i]][i] ,s[mw[mi+1][i]][i],j,i);*/
                   3155:          }
                   3156:        }
                   3157:        else{
                   3158:          j= rint( (agev[mw[mi+1][i]][i]*12 - agev[mw[mi][i]][i]*12));
                   3159: /*       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]); */
                   3160: 
                   3161:          k=k+1;
                   3162:          if (j >= jmax) {
                   3163:            jmax=j;
                   3164:            ijmax=i;
                   3165:          }
                   3166:          else if (j <= jmin){
                   3167:            jmin=j;
                   3168:            ijmin=i;
                   3169:          }
                   3170:          /*        if (j<10) printf("j=%d jmin=%d num=%d ",j,jmin,i); */
                   3171:          /*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]);*/
                   3172:          if(j<0){
                   3173:            nberr++;
                   3174:            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]);
                   3175:            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]);
                   3176:          }
                   3177:          sum=sum+j;
                   3178:        }
                   3179:        jk= j/stepm;
                   3180:        jl= j -jk*stepm;
                   3181:        ju= j -(jk+1)*stepm;
                   3182:        if(mle <=1){ /* only if we use a the linear-interpoloation pseudo-likelihood */
                   3183:          if(jl==0){
                   3184:            dh[mi][i]=jk;
                   3185:            bh[mi][i]=0;
                   3186:          }else{ /* We want a negative bias in order to only have interpolation ie
1.136     brouard  3187:                  * to avoid the price of an extra matrix product in likelihood */
1.126     brouard  3188:            dh[mi][i]=jk+1;
                   3189:            bh[mi][i]=ju;
                   3190:          }
                   3191:        }else{
                   3192:          if(jl <= -ju){
                   3193:            dh[mi][i]=jk;
                   3194:            bh[mi][i]=jl;       /* bias is positive if real duration
                   3195:                                 * is higher than the multiple of stepm and negative otherwise.
                   3196:                                 */
                   3197:          }
                   3198:          else{
                   3199:            dh[mi][i]=jk+1;
                   3200:            bh[mi][i]=ju;
                   3201:          }
                   3202:          if(dh[mi][i]==0){
                   3203:            dh[mi][i]=1; /* At least one step */
                   3204:            bh[mi][i]=ju; /* At least one step */
                   3205:            /*  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);*/
                   3206:          }
                   3207:        } /* end if mle */
                   3208:       }
                   3209:     } /* end wave */
                   3210:   }
                   3211:   jmean=sum/k;
                   3212:   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  3213:   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  3214:  }
                   3215: 
                   3216: /*********** Tricode ****************************/
1.145     brouard  3217: void tricode(int *Tvar, int **nbcode, int imx, int *Ndum)
1.126     brouard  3218: {
1.144     brouard  3219:   /**< Uses cptcovn+2*cptcovprod as the number of covariates */
                   3220:   /*     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  3221:    * Boring subroutine which should only output nbcode[Tvar[j]][k]
1.145     brouard  3222:    * Tvar[5] in V2+V1+V3*age+V2*V4 is 2 (V2)
1.169     brouard  3223:    * nbcode[Tvar[j]][1]= 
1.144     brouard  3224:   */
1.130     brouard  3225: 
1.145     brouard  3226:   int ij=1, k=0, j=0, i=0, maxncov=NCOVMAX;
1.136     brouard  3227:   int modmaxcovj=0; /* Modality max of covariates j */
1.145     brouard  3228:   int cptcode=0; /* Modality max of covariates j */
                   3229:   int modmincovj=0; /* Modality min of covariates j */
                   3230: 
                   3231: 
1.126     brouard  3232:   cptcoveff=0; 
                   3233:  
1.145     brouard  3234:   for (k=-1; k < maxncov; k++) Ndum[k]=0;
1.144     brouard  3235:   for (k=1; k <= maxncov; k++) ncodemax[k]=0; /* Horrible constant again replaced by NCOVMAX */
1.126     brouard  3236: 
1.145     brouard  3237:   /* Loop on covariates without age and products */
1.186     brouard  3238:   for (j=1; j<=(cptcovs); j++) { /* From model V1 + V2*age+ V3 + V3*V4 keeps V1 + V3 = 2 only */
                   3239:     for (i=1; i<=imx; i++) { /* Loop on individuals: reads the data file to get the maximum value of the 
1.136     brouard  3240:                               modality of this covariate Vj*/ 
1.145     brouard  3241:       ij=(int)(covar[Tvar[j]][i]); /* ij=0 or 1 or -1. Value of the covariate Tvar[j] for individual i
                   3242:                                    * If product of Vn*Vm, still boolean *:
                   3243:                                    * If it was coded 1, 2, 3, 4 should be splitted into 3 boolean variables
                   3244:                                    * 1 => 0 0 0, 2 => 0 0 1, 3 => 0 1 1, 4=1 0 0   */
                   3245:       /* Finds for covariate j, n=Tvar[j] of Vn . ij is the
1.136     brouard  3246:                                      modality of the nth covariate of individual i. */
1.145     brouard  3247:       if (ij > modmaxcovj)
                   3248:         modmaxcovj=ij; 
                   3249:       else if (ij < modmincovj) 
                   3250:        modmincovj=ij; 
                   3251:       if ((ij < -1) && (ij > NCOVMAX)){
                   3252:        printf( "Error: minimal is less than -1 or maximal is bigger than %d. Exiting. \n", NCOVMAX );
                   3253:        exit(1);
                   3254:       }else
1.136     brouard  3255:       Ndum[ij]++; /*counts and stores the occurence of this modality 0, 1, -1*/
1.145     brouard  3256:       /*  If coded 1, 2, 3 , counts the number of 1 Ndum[1], number of 2, Ndum[2], etc */
1.126     brouard  3257:       /*printf("i=%d ij=%d Ndum[ij]=%d imx=%d",i,ij,Ndum[ij],imx);*/
1.136     brouard  3258:       /* getting the maximum value of the modality of the covariate
                   3259:         (should be 0 or 1 now) Tvar[j]. If V=sex and male is coded 0 and
                   3260:         female is 1, then modmaxcovj=1.*/
1.187   ! brouard  3261:     } /* end for loop on individuals */
1.145     brouard  3262:     printf(" Minimal and maximal values of %d th covariate V%d: min=%d max=%d \n", j, Tvar[j], modmincovj, modmaxcovj);
                   3263:     cptcode=modmaxcovj;
1.137     brouard  3264:     /* Ndum[0] = frequency of 0 for model-covariate j, Ndum[1] frequency of 1 etc. */
1.145     brouard  3265:    /*for (i=0; i<=cptcode; i++) {*/
                   3266:     for (i=modmincovj;  i<=modmaxcovj; i++) { /* i=-1 ? 0 and 1*//* For each value of the modality of model-cov j */
1.187   ! brouard  3267:       printf("Frequencies of covariates %d ie V%d with value %d: %d\n", j, Tvar[j], i, Ndum[i]);
1.145     brouard  3268:       if( Ndum[i] != 0 ){ /* Counts if nobody answered, empty modality */
                   3269:        ncodemax[j]++;  /* ncodemax[j]= Number of non-null modalities of the j th covariate. */
                   3270:       }
                   3271:       /* In fact  ncodemax[j]=2 (dichotom. variables only) but it could be more for
                   3272:         historical reasons: 3 if coded 1, 2, 3 and 4 and Ndum[2]=0 */
1.131     brouard  3273:     } /* Ndum[-1] number of undefined modalities */
1.126     brouard  3274: 
1.136     brouard  3275:     /* j is a covariate, n=Tvar[j] of Vn; Fills nbcode */
1.186     brouard  3276:     /* For covariate j, modalities could be 1, 2, 3, 4, 5, 6, 7. 
                   3277:        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  3278:        modmincovj=3; modmaxcovj = 7;
1.186     brouard  3279:        There are only 3 modalities non empty 3, 6, 7 (or 2 if 27 is too few) : ncodemax[j]=3;
                   3280:        which will be coded 0, 1, 2 which in binary on 2=3-1 digits are 0=00 1=01, 2=10;
                   3281:        defining two dummy variables: variables V1_1 and V1_2.
1.145     brouard  3282:        nbcode[Tvar[j]][ij]=k;
                   3283:        nbcode[Tvar[j]][1]=0;
                   3284:        nbcode[Tvar[j]][2]=1;
                   3285:        nbcode[Tvar[j]][3]=2;
                   3286:     */
                   3287:     ij=1; /* ij is similar to i but can jumps over null modalities */
                   3288:     for (i=modmincovj; i<=modmaxcovj; i++) { /* i= 1 to 2 for dichotomous, or from 1 to 3 */
                   3289:       for (k=0; k<= cptcode; k++) { /* k=-1 ? k=0 to 1 *//* Could be 1 to 4 */
                   3290:        /*recode from 0 */
1.131     brouard  3291:        if (Ndum[k] != 0) { /* If at least one individual responded to this modality k */
1.186     brouard  3292:          nbcode[Tvar[j]][ij]=k;  /* stores the modality k in an array nbcode. 
1.131     brouard  3293:                                     k is a modality. If we have model=V1+V1*sex 
                   3294:                                     then: nbcode[1][1]=0 ; nbcode[1][2]=1; nbcode[2][1]=0 ; nbcode[2][2]=1; */
1.126     brouard  3295:          ij++;
                   3296:        }
                   3297:        if (ij > ncodemax[j]) break; 
1.137     brouard  3298:       }  /* end of loop on */
                   3299:     } /* end of loop on modality */ 
                   3300:   } /* end of loop on model-covariate j. nbcode[Tvarj][1]=0 and nbcode[Tvarj][2]=1 sets the value of covariate j*/  
                   3301:   
1.145     brouard  3302:  for (k=-1; k< maxncov; k++) Ndum[k]=0; 
1.137     brouard  3303:   
1.187   ! brouard  3304:   for (i=1; i<=ncovmodel-2-nagesqr; i++) { /* -2, cste and age and eventually age*age */ 
1.145     brouard  3305:    /* Listing of all covariables in statement model to see if some covariates appear twice. For example, V1 appears twice in V1+V1*V2.*/ 
                   3306:    ij=Tvar[i]; /* Tvar might be -1 if status was unknown */ 
1.187   ! brouard  3307:    Ndum[ij]++; /* Might be supersed V1 + V1*age */
1.145     brouard  3308:  } 
1.126     brouard  3309: 
                   3310:  ij=1;
1.145     brouard  3311:  for (i=0; i<=  maxncov-1; i++) { /* modmaxcovj is unknown here. Only Ndum[2(V2),3(age*V3), 5(V3*V2) 6(V1*V4) */
                   3312:    /*printf("Ndum[%d]=%d\n",i, Ndum[i]);*/
1.126     brouard  3313:    if((Ndum[i]!=0) && (i<=ncovcol)){
1.145     brouard  3314:      /*printf("diff Ndum[%d]=%d\n",i, Ndum[i]);*/
                   3315:      Tvaraff[ij]=i; /*For printing (unclear) */
1.126     brouard  3316:      ij++;
1.145     brouard  3317:    }else
                   3318:        Tvaraff[ij]=0;
1.126     brouard  3319:  }
1.131     brouard  3320:  ij--;
1.144     brouard  3321:  cptcoveff=ij; /*Number of total covariates*/
1.145     brouard  3322: 
1.126     brouard  3323: }
                   3324: 
1.145     brouard  3325: 
1.126     brouard  3326: /*********** Health Expectancies ****************/
                   3327: 
1.127     brouard  3328: 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  3329: 
                   3330: {
                   3331:   /* Health expectancies, no variances */
1.164     brouard  3332:   int i, j, nhstepm, hstepm, h, nstepm;
1.126     brouard  3333:   int nhstepma, nstepma; /* Decreasing with age */
                   3334:   double age, agelim, hf;
                   3335:   double ***p3mat;
                   3336:   double eip;
                   3337: 
                   3338:   pstamp(ficreseij);
                   3339:   fprintf(ficreseij,"# (a) Life expectancies by health status at initial age and (b) health expectancies by health status at initial age\n");
                   3340:   fprintf(ficreseij,"# Age");
                   3341:   for(i=1; i<=nlstate;i++){
                   3342:     for(j=1; j<=nlstate;j++){
                   3343:       fprintf(ficreseij," e%1d%1d ",i,j);
                   3344:     }
                   3345:     fprintf(ficreseij," e%1d. ",i);
                   3346:   }
                   3347:   fprintf(ficreseij,"\n");
                   3348: 
                   3349:   
                   3350:   if(estepm < stepm){
                   3351:     printf ("Problem %d lower than %d\n",estepm, stepm);
                   3352:   }
                   3353:   else  hstepm=estepm;   
                   3354:   /* We compute the life expectancy from trapezoids spaced every estepm months
                   3355:    * This is mainly to measure the difference between two models: for example
                   3356:    * if stepm=24 months pijx are given only every 2 years and by summing them
                   3357:    * we are calculating an estimate of the Life Expectancy assuming a linear 
                   3358:    * progression in between and thus overestimating or underestimating according
                   3359:    * to the curvature of the survival function. If, for the same date, we 
                   3360:    * estimate the model with stepm=1 month, we can keep estepm to 24 months
                   3361:    * to compare the new estimate of Life expectancy with the same linear 
                   3362:    * hypothesis. A more precise result, taking into account a more precise
                   3363:    * curvature will be obtained if estepm is as small as stepm. */
                   3364: 
                   3365:   /* For example we decided to compute the life expectancy with the smallest unit */
                   3366:   /* hstepm beeing the number of stepms, if hstepm=1 the length of hstepm is stepm. 
                   3367:      nhstepm is the number of hstepm from age to agelim 
                   3368:      nstepm is the number of stepm from age to agelin. 
                   3369:      Look at hpijx to understand the reason of that which relies in memory size
                   3370:      and note for a fixed period like estepm months */
                   3371:   /* We decided (b) to get a life expectancy respecting the most precise curvature of the
                   3372:      survival function given by stepm (the optimization length). Unfortunately it
                   3373:      means that if the survival funtion is printed only each two years of age and if
                   3374:      you sum them up and add 1 year (area under the trapezoids) you won't get the same 
                   3375:      results. So we changed our mind and took the option of the best precision.
                   3376:   */
                   3377:   hstepm=hstepm/stepm; /* Typically in stepm units, if stepm=6 & estepm=24 , = 24/6 months = 4 */ 
                   3378: 
                   3379:   agelim=AGESUP;
                   3380:   /* If stepm=6 months */
                   3381:     /* Computed by stepm unit matrices, product of hstepm matrices, stored
                   3382:        in an array of nhstepm length: nhstepm=10, hstepm=4, stepm=6 months */
                   3383:     
                   3384: /* nhstepm age range expressed in number of stepm */
                   3385:   nstepm=(int) rint((agelim-bage)*YEARM/stepm); /* Biggest nstepm */
                   3386:   /* Typically if 20 years nstepm = 20*12/6=40 stepm */ 
                   3387:   /* if (stepm >= YEARM) hstepm=1;*/
                   3388:   nhstepm = nstepm/hstepm;/* Expressed in hstepm, typically nhstepm=40/4=10 */
                   3389:   p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   3390: 
                   3391:   for (age=bage; age<=fage; age ++){ 
                   3392:     nstepma=(int) rint((agelim-bage)*YEARM/stepm); /* Biggest nstepm */
                   3393:     /* Typically if 20 years nstepm = 20*12/6=40 stepm */ 
                   3394:     /* if (stepm >= YEARM) hstepm=1;*/
                   3395:     nhstepma = nstepma/hstepm;/* Expressed in hstepm, typically nhstepma=40/4=10 */
                   3396: 
                   3397:     /* If stepm=6 months */
                   3398:     /* Computed by stepm unit matrices, product of hstepma matrices, stored
                   3399:        in an array of nhstepma length: nhstepma=10, hstepm=4, stepm=6 months */
                   3400:     
                   3401:     hpxij(p3mat,nhstepma,age,hstepm,x,nlstate,stepm,oldm, savm, cij);  
                   3402:     
                   3403:     hf=hstepm*stepm/YEARM;  /* Duration of hstepm expressed in year unit. */
                   3404:     
                   3405:     printf("%d|",(int)age);fflush(stdout);
                   3406:     fprintf(ficlog,"%d|",(int)age);fflush(ficlog);
                   3407:     
                   3408:     /* Computing expectancies */
                   3409:     for(i=1; i<=nlstate;i++)
                   3410:       for(j=1; j<=nlstate;j++)
                   3411:        for (h=0, eij[i][j][(int)age]=0; h<=nhstepm-1; h++){
                   3412:          eij[i][j][(int)age] += (p3mat[i][j][h]+p3mat[i][j][h+1])/2.0*hf;
                   3413:          
                   3414:          /* 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]);*/
                   3415: 
                   3416:        }
                   3417: 
                   3418:     fprintf(ficreseij,"%3.0f",age );
                   3419:     for(i=1; i<=nlstate;i++){
                   3420:       eip=0;
                   3421:       for(j=1; j<=nlstate;j++){
                   3422:        eip +=eij[i][j][(int)age];
                   3423:        fprintf(ficreseij,"%9.4f", eij[i][j][(int)age] );
                   3424:       }
                   3425:       fprintf(ficreseij,"%9.4f", eip );
                   3426:     }
                   3427:     fprintf(ficreseij,"\n");
                   3428:     
                   3429:   }
                   3430:   free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   3431:   printf("\n");
                   3432:   fprintf(ficlog,"\n");
                   3433:   
                   3434: }
                   3435: 
1.127     brouard  3436: 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  3437: 
                   3438: {
                   3439:   /* Covariances of health expectancies eij and of total life expectancies according
                   3440:    to initial status i, ei. .
                   3441:   */
                   3442:   int i, j, nhstepm, hstepm, h, nstepm, k, cptj, cptj2, i2, j2, ij, ji;
                   3443:   int nhstepma, nstepma; /* Decreasing with age */
                   3444:   double age, agelim, hf;
                   3445:   double ***p3matp, ***p3matm, ***varhe;
                   3446:   double **dnewm,**doldm;
                   3447:   double *xp, *xm;
                   3448:   double **gp, **gm;
                   3449:   double ***gradg, ***trgradg;
                   3450:   int theta;
                   3451: 
                   3452:   double eip, vip;
                   3453: 
                   3454:   varhe=ma3x(1,nlstate*nlstate,1,nlstate*nlstate,(int) bage, (int) fage);
                   3455:   xp=vector(1,npar);
                   3456:   xm=vector(1,npar);
                   3457:   dnewm=matrix(1,nlstate*nlstate,1,npar);
                   3458:   doldm=matrix(1,nlstate*nlstate,1,nlstate*nlstate);
                   3459:   
                   3460:   pstamp(ficresstdeij);
                   3461:   fprintf(ficresstdeij,"# Health expectancies with standard errors\n");
                   3462:   fprintf(ficresstdeij,"# Age");
                   3463:   for(i=1; i<=nlstate;i++){
                   3464:     for(j=1; j<=nlstate;j++)
                   3465:       fprintf(ficresstdeij," e%1d%1d (SE)",i,j);
                   3466:     fprintf(ficresstdeij," e%1d. ",i);
                   3467:   }
                   3468:   fprintf(ficresstdeij,"\n");
                   3469: 
                   3470:   pstamp(ficrescveij);
                   3471:   fprintf(ficrescveij,"# Subdiagonal matrix of covariances of health expectancies by age: cov(eij,ekl)\n");
                   3472:   fprintf(ficrescveij,"# Age");
                   3473:   for(i=1; i<=nlstate;i++)
                   3474:     for(j=1; j<=nlstate;j++){
                   3475:       cptj= (j-1)*nlstate+i;
                   3476:       for(i2=1; i2<=nlstate;i2++)
                   3477:        for(j2=1; j2<=nlstate;j2++){
                   3478:          cptj2= (j2-1)*nlstate+i2;
                   3479:          if(cptj2 <= cptj)
                   3480:            fprintf(ficrescveij,"  %1d%1d,%1d%1d",i,j,i2,j2);
                   3481:        }
                   3482:     }
                   3483:   fprintf(ficrescveij,"\n");
                   3484:   
                   3485:   if(estepm < stepm){
                   3486:     printf ("Problem %d lower than %d\n",estepm, stepm);
                   3487:   }
                   3488:   else  hstepm=estepm;   
                   3489:   /* We compute the life expectancy from trapezoids spaced every estepm months
                   3490:    * This is mainly to measure the difference between two models: for example
                   3491:    * if stepm=24 months pijx are given only every 2 years and by summing them
                   3492:    * we are calculating an estimate of the Life Expectancy assuming a linear 
                   3493:    * progression in between and thus overestimating or underestimating according
                   3494:    * to the curvature of the survival function. If, for the same date, we 
                   3495:    * estimate the model with stepm=1 month, we can keep estepm to 24 months
                   3496:    * to compare the new estimate of Life expectancy with the same linear 
                   3497:    * hypothesis. A more precise result, taking into account a more precise
                   3498:    * curvature will be obtained if estepm is as small as stepm. */
                   3499: 
                   3500:   /* For example we decided to compute the life expectancy with the smallest unit */
                   3501:   /* hstepm beeing the number of stepms, if hstepm=1 the length of hstepm is stepm. 
                   3502:      nhstepm is the number of hstepm from age to agelim 
                   3503:      nstepm is the number of stepm from age to agelin. 
                   3504:      Look at hpijx to understand the reason of that which relies in memory size
                   3505:      and note for a fixed period like estepm months */
                   3506:   /* We decided (b) to get a life expectancy respecting the most precise curvature of the
                   3507:      survival function given by stepm (the optimization length). Unfortunately it
                   3508:      means that if the survival funtion is printed only each two years of age and if
                   3509:      you sum them up and add 1 year (area under the trapezoids) you won't get the same 
                   3510:      results. So we changed our mind and took the option of the best precision.
                   3511:   */
                   3512:   hstepm=hstepm/stepm; /* Typically in stepm units, if stepm=6 & estepm=24 , = 24/6 months = 4 */ 
                   3513: 
                   3514:   /* If stepm=6 months */
                   3515:   /* nhstepm age range expressed in number of stepm */
                   3516:   agelim=AGESUP;
                   3517:   nstepm=(int) rint((agelim-bage)*YEARM/stepm); 
                   3518:   /* Typically if 20 years nstepm = 20*12/6=40 stepm */ 
                   3519:   /* if (stepm >= YEARM) hstepm=1;*/
                   3520:   nhstepm = nstepm/hstepm;/* Expressed in hstepm, typically nhstepm=40/4=10 */
                   3521:   
                   3522:   p3matp=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   3523:   p3matm=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   3524:   gradg=ma3x(0,nhstepm,1,npar,1,nlstate*nlstate);
                   3525:   trgradg =ma3x(0,nhstepm,1,nlstate*nlstate,1,npar);
                   3526:   gp=matrix(0,nhstepm,1,nlstate*nlstate);
                   3527:   gm=matrix(0,nhstepm,1,nlstate*nlstate);
                   3528: 
                   3529:   for (age=bage; age<=fage; age ++){ 
                   3530:     nstepma=(int) rint((agelim-bage)*YEARM/stepm); /* Biggest nstepm */
                   3531:     /* Typically if 20 years nstepm = 20*12/6=40 stepm */ 
                   3532:     /* if (stepm >= YEARM) hstepm=1;*/
                   3533:     nhstepma = nstepma/hstepm;/* Expressed in hstepm, typically nhstepma=40/4=10 */
                   3534: 
                   3535:     /* If stepm=6 months */
                   3536:     /* Computed by stepm unit matrices, product of hstepma matrices, stored
                   3537:        in an array of nhstepma length: nhstepma=10, hstepm=4, stepm=6 months */
                   3538:     
                   3539:     hf=hstepm*stepm/YEARM;  /* Duration of hstepm expressed in year unit. */
                   3540: 
                   3541:     /* Computing  Variances of health expectancies */
                   3542:     /* Gradient is computed with plus gp and minus gm. Code is duplicated in order to
                   3543:        decrease memory allocation */
                   3544:     for(theta=1; theta <=npar; theta++){
                   3545:       for(i=1; i<=npar; i++){ 
                   3546:        xp[i] = x[i] + (i==theta ?delti[theta]:0);
                   3547:        xm[i] = x[i] - (i==theta ?delti[theta]:0);
                   3548:       }
                   3549:       hpxij(p3matp,nhstepm,age,hstepm,xp,nlstate,stepm,oldm,savm, cij);  
                   3550:       hpxij(p3matm,nhstepm,age,hstepm,xm,nlstate,stepm,oldm,savm, cij);  
                   3551:   
                   3552:       for(j=1; j<= nlstate; j++){
                   3553:        for(i=1; i<=nlstate; i++){
                   3554:          for(h=0; h<=nhstepm-1; h++){
                   3555:            gp[h][(j-1)*nlstate + i] = (p3matp[i][j][h]+p3matp[i][j][h+1])/2.;
                   3556:            gm[h][(j-1)*nlstate + i] = (p3matm[i][j][h]+p3matm[i][j][h+1])/2.;
                   3557:          }
                   3558:        }
                   3559:       }
                   3560:      
                   3561:       for(ij=1; ij<= nlstate*nlstate; ij++)
                   3562:        for(h=0; h<=nhstepm-1; h++){
                   3563:          gradg[h][theta][ij]= (gp[h][ij]-gm[h][ij])/2./delti[theta];
                   3564:        }
                   3565:     }/* End theta */
                   3566:     
                   3567:     
                   3568:     for(h=0; h<=nhstepm-1; h++)
                   3569:       for(j=1; j<=nlstate*nlstate;j++)
                   3570:        for(theta=1; theta <=npar; theta++)
                   3571:          trgradg[h][j][theta]=gradg[h][theta][j];
                   3572:     
                   3573: 
                   3574:      for(ij=1;ij<=nlstate*nlstate;ij++)
                   3575:       for(ji=1;ji<=nlstate*nlstate;ji++)
                   3576:        varhe[ij][ji][(int)age] =0.;
                   3577: 
                   3578:      printf("%d|",(int)age);fflush(stdout);
                   3579:      fprintf(ficlog,"%d|",(int)age);fflush(ficlog);
                   3580:      for(h=0;h<=nhstepm-1;h++){
                   3581:       for(k=0;k<=nhstepm-1;k++){
                   3582:        matprod2(dnewm,trgradg[h],1,nlstate*nlstate,1,npar,1,npar,matcov);
                   3583:        matprod2(doldm,dnewm,1,nlstate*nlstate,1,npar,1,nlstate*nlstate,gradg[k]);
                   3584:        for(ij=1;ij<=nlstate*nlstate;ij++)
                   3585:          for(ji=1;ji<=nlstate*nlstate;ji++)
                   3586:            varhe[ij][ji][(int)age] += doldm[ij][ji]*hf*hf;
                   3587:       }
                   3588:     }
                   3589: 
                   3590:     /* Computing expectancies */
                   3591:     hpxij(p3matm,nhstepm,age,hstepm,x,nlstate,stepm,oldm, savm, cij);  
                   3592:     for(i=1; i<=nlstate;i++)
                   3593:       for(j=1; j<=nlstate;j++)
                   3594:        for (h=0, eij[i][j][(int)age]=0; h<=nhstepm-1; h++){
                   3595:          eij[i][j][(int)age] += (p3matm[i][j][h]+p3matm[i][j][h+1])/2.0*hf;
                   3596:          
                   3597:          /* 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]);*/
                   3598: 
                   3599:        }
                   3600: 
                   3601:     fprintf(ficresstdeij,"%3.0f",age );
                   3602:     for(i=1; i<=nlstate;i++){
                   3603:       eip=0.;
                   3604:       vip=0.;
                   3605:       for(j=1; j<=nlstate;j++){
                   3606:        eip += eij[i][j][(int)age];
                   3607:        for(k=1; k<=nlstate;k++) /* Sum on j and k of cov(eij,eik) */
                   3608:          vip += varhe[(j-1)*nlstate+i][(k-1)*nlstate+i][(int)age];
                   3609:        fprintf(ficresstdeij," %9.4f (%.4f)", eij[i][j][(int)age], sqrt(varhe[(j-1)*nlstate+i][(j-1)*nlstate+i][(int)age]) );
                   3610:       }
                   3611:       fprintf(ficresstdeij," %9.4f (%.4f)", eip, sqrt(vip));
                   3612:     }
                   3613:     fprintf(ficresstdeij,"\n");
                   3614: 
                   3615:     fprintf(ficrescveij,"%3.0f",age );
                   3616:     for(i=1; i<=nlstate;i++)
                   3617:       for(j=1; j<=nlstate;j++){
                   3618:        cptj= (j-1)*nlstate+i;
                   3619:        for(i2=1; i2<=nlstate;i2++)
                   3620:          for(j2=1; j2<=nlstate;j2++){
                   3621:            cptj2= (j2-1)*nlstate+i2;
                   3622:            if(cptj2 <= cptj)
                   3623:              fprintf(ficrescveij," %.4f", varhe[cptj][cptj2][(int)age]);
                   3624:          }
                   3625:       }
                   3626:     fprintf(ficrescveij,"\n");
                   3627:    
                   3628:   }
                   3629:   free_matrix(gm,0,nhstepm,1,nlstate*nlstate);
                   3630:   free_matrix(gp,0,nhstepm,1,nlstate*nlstate);
                   3631:   free_ma3x(gradg,0,nhstepm,1,npar,1,nlstate*nlstate);
                   3632:   free_ma3x(trgradg,0,nhstepm,1,nlstate*nlstate,1,npar);
                   3633:   free_ma3x(p3matm,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   3634:   free_ma3x(p3matp,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   3635:   printf("\n");
                   3636:   fprintf(ficlog,"\n");
                   3637: 
                   3638:   free_vector(xm,1,npar);
                   3639:   free_vector(xp,1,npar);
                   3640:   free_matrix(dnewm,1,nlstate*nlstate,1,npar);
                   3641:   free_matrix(doldm,1,nlstate*nlstate,1,nlstate*nlstate);
                   3642:   free_ma3x(varhe,1,nlstate*nlstate,1,nlstate*nlstate,(int) bage, (int)fage);
                   3643: }
                   3644: 
                   3645: /************ Variance ******************/
                   3646: 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[])
                   3647: {
                   3648:   /* Variance of health expectancies */
                   3649:   /*  double **prevalim(double **prlim, int nlstate, double *xp, double age, double **oldm, double ** savm,double ftolpl);*/
                   3650:   /* double **newm;*/
1.169     brouard  3651:   /* int movingaverage(double ***probs, double bage,double fage, double ***mobaverage, int mobilav)*/
                   3652:   
                   3653:   int movingaverage();
1.126     brouard  3654:   double **dnewm,**doldm;
                   3655:   double **dnewmp,**doldmp;
                   3656:   int i, j, nhstepm, hstepm, h, nstepm ;
1.164     brouard  3657:   int k;
1.126     brouard  3658:   double *xp;
                   3659:   double **gp, **gm;  /* for var eij */
                   3660:   double ***gradg, ***trgradg; /*for var eij */
                   3661:   double **gradgp, **trgradgp; /* for var p point j */
                   3662:   double *gpp, *gmp; /* for var p point j */
                   3663:   double **varppt; /* for var p point j nlstate to nlstate+ndeath */
                   3664:   double ***p3mat;
                   3665:   double age,agelim, hf;
                   3666:   double ***mobaverage;
                   3667:   int theta;
                   3668:   char digit[4];
                   3669:   char digitp[25];
                   3670: 
                   3671:   char fileresprobmorprev[FILENAMELENGTH];
                   3672: 
                   3673:   if(popbased==1){
                   3674:     if(mobilav!=0)
                   3675:       strcpy(digitp,"-populbased-mobilav-");
                   3676:     else strcpy(digitp,"-populbased-nomobil-");
                   3677:   }
                   3678:   else 
                   3679:     strcpy(digitp,"-stablbased-");
                   3680: 
                   3681:   if (mobilav!=0) {
                   3682:     mobaverage= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
                   3683:     if (movingaverage(probs, bage, fage, mobaverage,mobilav)!=0){
                   3684:       fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav);
                   3685:       printf(" Error in movingaverage mobilav=%d\n",mobilav);
                   3686:     }
                   3687:   }
                   3688: 
                   3689:   strcpy(fileresprobmorprev,"prmorprev"); 
                   3690:   sprintf(digit,"%-d",ij);
                   3691:   /*printf("DIGIT=%s, ij=%d ijr=%-d|\n",digit, ij,ij);*/
                   3692:   strcat(fileresprobmorprev,digit); /* Tvar to be done */
                   3693:   strcat(fileresprobmorprev,digitp); /* Popbased or not, mobilav or not */
                   3694:   strcat(fileresprobmorprev,fileres);
                   3695:   if((ficresprobmorprev=fopen(fileresprobmorprev,"w"))==NULL) {
                   3696:     printf("Problem with resultfile: %s\n", fileresprobmorprev);
                   3697:     fprintf(ficlog,"Problem with resultfile: %s\n", fileresprobmorprev);
                   3698:   }
                   3699:   printf("Computing total mortality p.j=w1*p1j+w2*p2j+..: result on file '%s' \n",fileresprobmorprev);
                   3700:  
                   3701:   fprintf(ficlog,"Computing total mortality p.j=w1*p1j+w2*p2j+..: result on file '%s' \n",fileresprobmorprev);
                   3702:   pstamp(ficresprobmorprev);
                   3703:   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);
                   3704:   fprintf(ficresprobmorprev,"# Age cov=%-d",ij);
                   3705:   for(j=nlstate+1; j<=(nlstate+ndeath);j++){
                   3706:     fprintf(ficresprobmorprev," p.%-d SE",j);
                   3707:     for(i=1; i<=nlstate;i++)
                   3708:       fprintf(ficresprobmorprev," w%1d p%-d%-d",i,i,j);
                   3709:   }  
                   3710:   fprintf(ficresprobmorprev,"\n");
                   3711:   fprintf(ficgp,"\n# Routine varevsij");
                   3712:   /* fprintf(fichtm, "#Local time at start: %s", strstart);*/
                   3713:   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");
                   3714:   fprintf(fichtm,"\n<br>%s  <br>\n",digitp);
                   3715: /*   } */
                   3716:   varppt = matrix(nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);
                   3717:   pstamp(ficresvij);
                   3718:   fprintf(ficresvij,"# Variance and covariance of health expectancies e.j \n#  (weighted average of eij where weights are ");
                   3719:   if(popbased==1)
1.128     brouard  3720:     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  3721:   else
                   3722:     fprintf(ficresvij,"the age specific period (stable) prevalences in each health state \n");
                   3723:   fprintf(ficresvij,"# Age");
                   3724:   for(i=1; i<=nlstate;i++)
                   3725:     for(j=1; j<=nlstate;j++)
                   3726:       fprintf(ficresvij," Cov(e.%1d, e.%1d)",i,j);
                   3727:   fprintf(ficresvij,"\n");
                   3728: 
                   3729:   xp=vector(1,npar);
                   3730:   dnewm=matrix(1,nlstate,1,npar);
                   3731:   doldm=matrix(1,nlstate,1,nlstate);
                   3732:   dnewmp= matrix(nlstate+1,nlstate+ndeath,1,npar);
                   3733:   doldmp= matrix(nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);
                   3734: 
                   3735:   gradgp=matrix(1,npar,nlstate+1,nlstate+ndeath);
                   3736:   gpp=vector(nlstate+1,nlstate+ndeath);
                   3737:   gmp=vector(nlstate+1,nlstate+ndeath);
                   3738:   trgradgp =matrix(nlstate+1,nlstate+ndeath,1,npar); /* mu or p point j*/
                   3739:   
                   3740:   if(estepm < stepm){
                   3741:     printf ("Problem %d lower than %d\n",estepm, stepm);
                   3742:   }
                   3743:   else  hstepm=estepm;   
                   3744:   /* For example we decided to compute the life expectancy with the smallest unit */
                   3745:   /* hstepm beeing the number of stepms, if hstepm=1 the length of hstepm is stepm. 
                   3746:      nhstepm is the number of hstepm from age to agelim 
                   3747:      nstepm is the number of stepm from age to agelin. 
1.128     brouard  3748:      Look at function hpijx to understand why (it is linked to memory size questions) */
1.126     brouard  3749:   /* We decided (b) to get a life expectancy respecting the most precise curvature of the
                   3750:      survival function given by stepm (the optimization length). Unfortunately it
                   3751:      means that if the survival funtion is printed every two years of age and if
                   3752:      you sum them up and add 1 year (area under the trapezoids) you won't get the same 
                   3753:      results. So we changed our mind and took the option of the best precision.
                   3754:   */
                   3755:   hstepm=hstepm/stepm; /* Typically in stepm units, if stepm=6 & estepm=24 , = 24/6 months = 4 */ 
                   3756:   agelim = AGESUP;
                   3757:   for (age=bage; age<=fage; age ++){ /* If stepm=6 months */
                   3758:     nstepm=(int) rint((agelim-age)*YEARM/stepm); /* Typically 20 years = 20*12/6=40 */ 
                   3759:     nhstepm = nstepm/hstepm;/* Expressed in hstepm, typically nhstepm=40/4=10 */
                   3760:     p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   3761:     gradg=ma3x(0,nhstepm,1,npar,1,nlstate);
                   3762:     gp=matrix(0,nhstepm,1,nlstate);
                   3763:     gm=matrix(0,nhstepm,1,nlstate);
                   3764: 
                   3765: 
                   3766:     for(theta=1; theta <=npar; theta++){
                   3767:       for(i=1; i<=npar; i++){ /* Computes gradient x + delta*/
                   3768:        xp[i] = x[i] + (i==theta ?delti[theta]:0);
                   3769:       }
                   3770:       hpxij(p3mat,nhstepm,age,hstepm,xp,nlstate,stepm,oldm,savm, ij);  
                   3771:       prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ij);
                   3772: 
                   3773:       if (popbased==1) {
                   3774:        if(mobilav ==0){
                   3775:          for(i=1; i<=nlstate;i++)
                   3776:            prlim[i][i]=probs[(int)age][i][ij];
                   3777:        }else{ /* mobilav */ 
                   3778:          for(i=1; i<=nlstate;i++)
                   3779:            prlim[i][i]=mobaverage[(int)age][i][ij];
                   3780:        }
                   3781:       }
                   3782:   
                   3783:       for(j=1; j<= nlstate; j++){
                   3784:        for(h=0; h<=nhstepm; h++){
                   3785:          for(i=1, gp[h][j]=0.;i<=nlstate;i++)
                   3786:            gp[h][j] += prlim[i][i]*p3mat[i][j][h];
                   3787:        }
                   3788:       }
                   3789:       /* This for computing probability of death (h=1 means
                   3790:          computed over hstepm matrices product = hstepm*stepm months) 
                   3791:          as a weighted average of prlim.
                   3792:       */
                   3793:       for(j=nlstate+1;j<=nlstate+ndeath;j++){
                   3794:        for(i=1,gpp[j]=0.; i<= nlstate; i++)
                   3795:          gpp[j] += prlim[i][i]*p3mat[i][j][1];
                   3796:       }    
                   3797:       /* end probability of death */
                   3798: 
                   3799:       for(i=1; i<=npar; i++) /* Computes gradient x - delta */
                   3800:        xp[i] = x[i] - (i==theta ?delti[theta]:0);
                   3801:       hpxij(p3mat,nhstepm,age,hstepm,xp,nlstate,stepm,oldm,savm, ij);  
                   3802:       prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ij);
                   3803:  
                   3804:       if (popbased==1) {
                   3805:        if(mobilav ==0){
                   3806:          for(i=1; i<=nlstate;i++)
                   3807:            prlim[i][i]=probs[(int)age][i][ij];
                   3808:        }else{ /* mobilav */ 
                   3809:          for(i=1; i<=nlstate;i++)
                   3810:            prlim[i][i]=mobaverage[(int)age][i][ij];
                   3811:        }
                   3812:       }
                   3813: 
1.128     brouard  3814:       for(j=1; j<= nlstate; j++){  /* Sum of wi * eij = e.j */
1.126     brouard  3815:        for(h=0; h<=nhstepm; h++){
                   3816:          for(i=1, gm[h][j]=0.;i<=nlstate;i++)
                   3817:            gm[h][j] += prlim[i][i]*p3mat[i][j][h];
                   3818:        }
                   3819:       }
                   3820:       /* This for computing probability of death (h=1 means
                   3821:          computed over hstepm matrices product = hstepm*stepm months) 
                   3822:          as a weighted average of prlim.
                   3823:       */
                   3824:       for(j=nlstate+1;j<=nlstate+ndeath;j++){
                   3825:        for(i=1,gmp[j]=0.; i<= nlstate; i++)
                   3826:          gmp[j] += prlim[i][i]*p3mat[i][j][1];
                   3827:       }    
                   3828:       /* end probability of death */
                   3829: 
                   3830:       for(j=1; j<= nlstate; j++) /* vareij */
                   3831:        for(h=0; h<=nhstepm; h++){
                   3832:          gradg[h][theta][j]= (gp[h][j]-gm[h][j])/2./delti[theta];
                   3833:        }
                   3834: 
                   3835:       for(j=nlstate+1; j<= nlstate+ndeath; j++){ /* var mu */
                   3836:        gradgp[theta][j]= (gpp[j]-gmp[j])/2./delti[theta];
                   3837:       }
                   3838: 
                   3839:     } /* End theta */
                   3840: 
                   3841:     trgradg =ma3x(0,nhstepm,1,nlstate,1,npar); /* veij */
                   3842: 
                   3843:     for(h=0; h<=nhstepm; h++) /* veij */
                   3844:       for(j=1; j<=nlstate;j++)
                   3845:        for(theta=1; theta <=npar; theta++)
                   3846:          trgradg[h][j][theta]=gradg[h][theta][j];
                   3847: 
                   3848:     for(j=nlstate+1; j<=nlstate+ndeath;j++) /* mu */
                   3849:       for(theta=1; theta <=npar; theta++)
                   3850:        trgradgp[j][theta]=gradgp[theta][j];
                   3851:   
                   3852: 
                   3853:     hf=hstepm*stepm/YEARM;  /* Duration of hstepm expressed in year unit. */
                   3854:     for(i=1;i<=nlstate;i++)
                   3855:       for(j=1;j<=nlstate;j++)
                   3856:        vareij[i][j][(int)age] =0.;
                   3857: 
                   3858:     for(h=0;h<=nhstepm;h++){
                   3859:       for(k=0;k<=nhstepm;k++){
                   3860:        matprod2(dnewm,trgradg[h],1,nlstate,1,npar,1,npar,matcov);
                   3861:        matprod2(doldm,dnewm,1,nlstate,1,npar,1,nlstate,gradg[k]);
                   3862:        for(i=1;i<=nlstate;i++)
                   3863:          for(j=1;j<=nlstate;j++)
                   3864:            vareij[i][j][(int)age] += doldm[i][j]*hf*hf;
                   3865:       }
                   3866:     }
                   3867:   
                   3868:     /* pptj */
                   3869:     matprod2(dnewmp,trgradgp,nlstate+1,nlstate+ndeath,1,npar,1,npar,matcov);
                   3870:     matprod2(doldmp,dnewmp,nlstate+1,nlstate+ndeath,1,npar,nlstate+1,nlstate+ndeath,gradgp);
                   3871:     for(j=nlstate+1;j<=nlstate+ndeath;j++)
                   3872:       for(i=nlstate+1;i<=nlstate+ndeath;i++)
                   3873:        varppt[j][i]=doldmp[j][i];
                   3874:     /* end ppptj */
                   3875:     /*  x centered again */
                   3876:     hpxij(p3mat,nhstepm,age,hstepm,x,nlstate,stepm,oldm,savm, ij);  
                   3877:     prevalim(prlim,nlstate,x,age,oldm,savm,ftolpl,ij);
                   3878:  
                   3879:     if (popbased==1) {
                   3880:       if(mobilav ==0){
                   3881:        for(i=1; i<=nlstate;i++)
                   3882:          prlim[i][i]=probs[(int)age][i][ij];
                   3883:       }else{ /* mobilav */ 
                   3884:        for(i=1; i<=nlstate;i++)
                   3885:          prlim[i][i]=mobaverage[(int)age][i][ij];
                   3886:       }
                   3887:     }
                   3888:              
                   3889:     /* This for computing probability of death (h=1 means
                   3890:        computed over hstepm (estepm) matrices product = hstepm*stepm months) 
                   3891:        as a weighted average of prlim.
                   3892:     */
                   3893:     for(j=nlstate+1;j<=nlstate+ndeath;j++){
                   3894:       for(i=1,gmp[j]=0.;i<= nlstate; i++) 
                   3895:        gmp[j] += prlim[i][i]*p3mat[i][j][1]; 
                   3896:     }    
                   3897:     /* end probability of death */
                   3898: 
                   3899:     fprintf(ficresprobmorprev,"%3d %d ",(int) age, ij);
                   3900:     for(j=nlstate+1; j<=(nlstate+ndeath);j++){
                   3901:       fprintf(ficresprobmorprev," %11.3e %11.3e",gmp[j], sqrt(varppt[j][j]));
                   3902:       for(i=1; i<=nlstate;i++){
                   3903:        fprintf(ficresprobmorprev," %11.3e %11.3e ",prlim[i][i],p3mat[i][j][1]);
                   3904:       }
                   3905:     } 
                   3906:     fprintf(ficresprobmorprev,"\n");
                   3907: 
                   3908:     fprintf(ficresvij,"%.0f ",age );
                   3909:     for(i=1; i<=nlstate;i++)
                   3910:       for(j=1; j<=nlstate;j++){
                   3911:        fprintf(ficresvij," %.4f", vareij[i][j][(int)age]);
                   3912:       }
                   3913:     fprintf(ficresvij,"\n");
                   3914:     free_matrix(gp,0,nhstepm,1,nlstate);
                   3915:     free_matrix(gm,0,nhstepm,1,nlstate);
                   3916:     free_ma3x(gradg,0,nhstepm,1,npar,1,nlstate);
                   3917:     free_ma3x(trgradg,0,nhstepm,1,nlstate,1,npar);
                   3918:     free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   3919:   } /* End age */
                   3920:   free_vector(gpp,nlstate+1,nlstate+ndeath);
                   3921:   free_vector(gmp,nlstate+1,nlstate+ndeath);
                   3922:   free_matrix(gradgp,1,npar,nlstate+1,nlstate+ndeath);
                   3923:   free_matrix(trgradgp,nlstate+1,nlstate+ndeath,1,npar); /* mu or p point j*/
1.145     brouard  3924:   fprintf(ficgp,"\nunset parametric;unset label; set ter png small size 320, 240");
1.126     brouard  3925:   /* for(j=nlstate+1; j<= nlstate+ndeath; j++){ *//* Only the first actually */
1.131     brouard  3926:   fprintf(ficgp,"\n set log y; unset log x;set xlabel \"Age\"; set ylabel \"Force of mortality (year-1)\";");
1.126     brouard  3927: /*   fprintf(ficgp,"\n plot \"%s\"  u 1:($3*%6.3f) not w l 1 ",fileresprobmorprev,YEARM/estepm); */
                   3928: /*   fprintf(ficgp,"\n replot \"%s\"  u 1:(($3+1.96*$4)*%6.3f) t \"95\%% interval\" w l 2 ",fileresprobmorprev,YEARM/estepm); */
                   3929: /*   fprintf(ficgp,"\n replot \"%s\"  u 1:(($3-1.96*$4)*%6.3f) not w l 2 ",fileresprobmorprev,YEARM/estepm); */
1.145     brouard  3930:   fprintf(ficgp,"\n plot \"%s\"  u 1:($3) not w l lt 1 ",subdirf(fileresprobmorprev));
1.170     brouard  3931:   fprintf(ficgp,"\n replot \"%s\"  u 1:(($3+1.96*$4)) t \"95%% interval\" w l lt 2 ",subdirf(fileresprobmorprev));
1.145     brouard  3932:   fprintf(ficgp,"\n replot \"%s\"  u 1:(($3-1.96*$4)) not w l lt 2 ",subdirf(fileresprobmorprev));
1.126     brouard  3933:   fprintf(fichtm,"\n<br> File (multiple files are possible if covariates are present): <A href=\"%s\">%s</a>\n",subdirf(fileresprobmorprev),subdirf(fileresprobmorprev));
                   3934:   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);
                   3935:   /*  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);
                   3936: */
                   3937: /*   fprintf(ficgp,"\nset out \"varmuptjgr%s%s%s.png\";replot;",digitp,optionfilefiname,digit); */
                   3938:   fprintf(ficgp,"\nset out \"%s%s.png\";replot;\n",subdirf3(optionfilefiname,"varmuptjgr",digitp),digit);
                   3939: 
                   3940:   free_vector(xp,1,npar);
                   3941:   free_matrix(doldm,1,nlstate,1,nlstate);
                   3942:   free_matrix(dnewm,1,nlstate,1,npar);
                   3943:   free_matrix(doldmp,nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);
                   3944:   free_matrix(dnewmp,nlstate+1,nlstate+ndeath,1,npar);
                   3945:   free_matrix(varppt,nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);
                   3946:   if (mobilav!=0) free_ma3x(mobaverage,1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
                   3947:   fclose(ficresprobmorprev);
                   3948:   fflush(ficgp);
                   3949:   fflush(fichtm); 
                   3950: }  /* end varevsij */
                   3951: 
                   3952: /************ Variance of prevlim ******************/
                   3953: 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[])
                   3954: {
                   3955:   /* Variance of prevalence limit */
                   3956:   /*  double **prevalim(double **prlim, int nlstate, double *xp, double age, double **oldm, double **savm,double ftolpl);*/
1.164     brouard  3957: 
1.126     brouard  3958:   double **dnewm,**doldm;
                   3959:   int i, j, nhstepm, hstepm;
                   3960:   double *xp;
                   3961:   double *gp, *gm;
                   3962:   double **gradg, **trgradg;
                   3963:   double age,agelim;
                   3964:   int theta;
                   3965:   
                   3966:   pstamp(ficresvpl);
                   3967:   fprintf(ficresvpl,"# Standard deviation of period (stable) prevalences \n");
                   3968:   fprintf(ficresvpl,"# Age");
                   3969:   for(i=1; i<=nlstate;i++)
                   3970:       fprintf(ficresvpl," %1d-%1d",i,i);
                   3971:   fprintf(ficresvpl,"\n");
                   3972: 
                   3973:   xp=vector(1,npar);
                   3974:   dnewm=matrix(1,nlstate,1,npar);
                   3975:   doldm=matrix(1,nlstate,1,nlstate);
                   3976:   
                   3977:   hstepm=1*YEARM; /* Every year of age */
                   3978:   hstepm=hstepm/stepm; /* Typically in stepm units, if j= 2 years, = 2/6 months = 4 */ 
                   3979:   agelim = AGESUP;
                   3980:   for (age=bage; age<=fage; age ++){ /* If stepm=6 months */
                   3981:     nhstepm=(int) rint((agelim-age)*YEARM/stepm); /* Typically 20 years = 20*12/6=40 */ 
                   3982:     if (stepm >= YEARM) hstepm=1;
                   3983:     nhstepm = nhstepm/hstepm; /* Typically 40/4=10 */
                   3984:     gradg=matrix(1,npar,1,nlstate);
                   3985:     gp=vector(1,nlstate);
                   3986:     gm=vector(1,nlstate);
                   3987: 
                   3988:     for(theta=1; theta <=npar; theta++){
                   3989:       for(i=1; i<=npar; i++){ /* Computes gradient */
                   3990:        xp[i] = x[i] + (i==theta ?delti[theta]:0);
                   3991:       }
                   3992:       prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ij);
                   3993:       for(i=1;i<=nlstate;i++)
                   3994:        gp[i] = prlim[i][i];
                   3995:     
                   3996:       for(i=1; i<=npar; i++) /* Computes gradient */
                   3997:        xp[i] = x[i] - (i==theta ?delti[theta]:0);
                   3998:       prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ij);
                   3999:       for(i=1;i<=nlstate;i++)
                   4000:        gm[i] = prlim[i][i];
                   4001: 
                   4002:       for(i=1;i<=nlstate;i++)
                   4003:        gradg[theta][i]= (gp[i]-gm[i])/2./delti[theta];
                   4004:     } /* End theta */
                   4005: 
                   4006:     trgradg =matrix(1,nlstate,1,npar);
                   4007: 
                   4008:     for(j=1; j<=nlstate;j++)
                   4009:       for(theta=1; theta <=npar; theta++)
                   4010:        trgradg[j][theta]=gradg[theta][j];
                   4011: 
                   4012:     for(i=1;i<=nlstate;i++)
                   4013:       varpl[i][(int)age] =0.;
                   4014:     matprod2(dnewm,trgradg,1,nlstate,1,npar,1,npar,matcov);
                   4015:     matprod2(doldm,dnewm,1,nlstate,1,npar,1,nlstate,gradg);
                   4016:     for(i=1;i<=nlstate;i++)
                   4017:       varpl[i][(int)age] = doldm[i][i]; /* Covariances are useless */
                   4018: 
                   4019:     fprintf(ficresvpl,"%.0f ",age );
                   4020:     for(i=1; i<=nlstate;i++)
                   4021:       fprintf(ficresvpl," %.5f (%.5f)",prlim[i][i],sqrt(varpl[i][(int)age]));
                   4022:     fprintf(ficresvpl,"\n");
                   4023:     free_vector(gp,1,nlstate);
                   4024:     free_vector(gm,1,nlstate);
                   4025:     free_matrix(gradg,1,npar,1,nlstate);
                   4026:     free_matrix(trgradg,1,nlstate,1,npar);
                   4027:   } /* End age */
                   4028: 
                   4029:   free_vector(xp,1,npar);
                   4030:   free_matrix(doldm,1,nlstate,1,npar);
                   4031:   free_matrix(dnewm,1,nlstate,1,nlstate);
                   4032: 
                   4033: }
                   4034: 
                   4035: /************ Variance of one-step probabilities  ******************/
                   4036: 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[])
                   4037: {
1.164     brouard  4038:   int i, j=0,  k1, l1, tj;
1.126     brouard  4039:   int k2, l2, j1,  z1;
1.164     brouard  4040:   int k=0, l;
1.145     brouard  4041:   int first=1, first1, first2;
1.126     brouard  4042:   double cv12, mu1, mu2, lc1, lc2, v12, v21, v11, v22,v1,v2, c12, tnalp;
                   4043:   double **dnewm,**doldm;
                   4044:   double *xp;
                   4045:   double *gp, *gm;
                   4046:   double **gradg, **trgradg;
                   4047:   double **mu;
1.164     brouard  4048:   double age, cov[NCOVMAX+1];
1.126     brouard  4049:   double std=2.0; /* Number of standard deviation wide of confidence ellipsoids */
                   4050:   int theta;
                   4051:   char fileresprob[FILENAMELENGTH];
                   4052:   char fileresprobcov[FILENAMELENGTH];
                   4053:   char fileresprobcor[FILENAMELENGTH];
                   4054:   double ***varpij;
                   4055: 
                   4056:   strcpy(fileresprob,"prob"); 
                   4057:   strcat(fileresprob,fileres);
                   4058:   if((ficresprob=fopen(fileresprob,"w"))==NULL) {
                   4059:     printf("Problem with resultfile: %s\n", fileresprob);
                   4060:     fprintf(ficlog,"Problem with resultfile: %s\n", fileresprob);
                   4061:   }
                   4062:   strcpy(fileresprobcov,"probcov"); 
                   4063:   strcat(fileresprobcov,fileres);
                   4064:   if((ficresprobcov=fopen(fileresprobcov,"w"))==NULL) {
                   4065:     printf("Problem with resultfile: %s\n", fileresprobcov);
                   4066:     fprintf(ficlog,"Problem with resultfile: %s\n", fileresprobcov);
                   4067:   }
                   4068:   strcpy(fileresprobcor,"probcor"); 
                   4069:   strcat(fileresprobcor,fileres);
                   4070:   if((ficresprobcor=fopen(fileresprobcor,"w"))==NULL) {
                   4071:     printf("Problem with resultfile: %s\n", fileresprobcor);
                   4072:     fprintf(ficlog,"Problem with resultfile: %s\n", fileresprobcor);
                   4073:   }
                   4074:   printf("Computing standard deviation of one-step probabilities: result on file '%s' \n",fileresprob);
                   4075:   fprintf(ficlog,"Computing standard deviation of one-step probabilities: result on file '%s' \n",fileresprob);
                   4076:   printf("Computing matrix of variance covariance of one-step probabilities: result on file '%s' \n",fileresprobcov);
                   4077:   fprintf(ficlog,"Computing matrix of variance covariance of one-step probabilities: result on file '%s' \n",fileresprobcov);
                   4078:   printf("and correlation matrix of one-step probabilities: result on file '%s' \n",fileresprobcor);
                   4079:   fprintf(ficlog,"and correlation matrix of one-step probabilities: result on file '%s' \n",fileresprobcor);
                   4080:   pstamp(ficresprob);
                   4081:   fprintf(ficresprob,"#One-step probabilities and stand. devi in ()\n");
                   4082:   fprintf(ficresprob,"# Age");
                   4083:   pstamp(ficresprobcov);
                   4084:   fprintf(ficresprobcov,"#One-step probabilities and covariance matrix\n");
                   4085:   fprintf(ficresprobcov,"# Age");
                   4086:   pstamp(ficresprobcor);
                   4087:   fprintf(ficresprobcor,"#One-step probabilities and correlation matrix\n");
                   4088:   fprintf(ficresprobcor,"# Age");
                   4089: 
                   4090: 
                   4091:   for(i=1; i<=nlstate;i++)
                   4092:     for(j=1; j<=(nlstate+ndeath);j++){
                   4093:       fprintf(ficresprob," p%1d-%1d (SE)",i,j);
                   4094:       fprintf(ficresprobcov," p%1d-%1d ",i,j);
                   4095:       fprintf(ficresprobcor," p%1d-%1d ",i,j);
                   4096:     }  
                   4097:  /* fprintf(ficresprob,"\n");
                   4098:   fprintf(ficresprobcov,"\n");
                   4099:   fprintf(ficresprobcor,"\n");
                   4100:  */
1.131     brouard  4101:   xp=vector(1,npar);
1.126     brouard  4102:   dnewm=matrix(1,(nlstate)*(nlstate+ndeath),1,npar);
                   4103:   doldm=matrix(1,(nlstate)*(nlstate+ndeath),1,(nlstate)*(nlstate+ndeath));
                   4104:   mu=matrix(1,(nlstate)*(nlstate+ndeath), (int) bage, (int)fage);
                   4105:   varpij=ma3x(1,nlstate*(nlstate+ndeath),1,nlstate*(nlstate+ndeath),(int) bage, (int) fage);
                   4106:   first=1;
                   4107:   fprintf(ficgp,"\n# Routine varprob");
                   4108:   fprintf(fichtm,"\n<li><h4> Computing and drawing one step probabilities with their confidence intervals</h4></li>\n");
                   4109:   fprintf(fichtm,"\n");
                   4110: 
                   4111:   fprintf(fichtm,"\n<li><h4> <a href=\"%s\">Matrix of variance-covariance of pairs of step probabilities (drawings)</a></h4></li>\n",optionfilehtmcov);
                   4112:   fprintf(fichtmcov,"\n<h4>Matrix of variance-covariance of pairs of step probabilities</h4>\n\
                   4113:   file %s<br>\n",optionfilehtmcov);
                   4114:   fprintf(fichtmcov,"\nEllipsoids of confidence centered on point (p<inf>ij</inf>, p<inf>kl</inf>) are estimated\
                   4115: and drawn. It helps understanding how is the covariance between two incidences.\
                   4116:  They are expressed in year<sup>-1</sup> in order to be less dependent of stepm.<br>\n");
                   4117:   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. \
                   4118: It can be understood this way: if pij and pkl where uncorrelated the (2x2) matrix of covariance \
                   4119: would have been (1/(var pij), 0 , 0, 1/(var pkl)), and the confidence interval would be 2 \
                   4120: standard deviations wide on each axis. <br>\
                   4121:  Now, if both incidences are correlated (usual case) we diagonalised the inverse of the covariance matrix\
                   4122:  and made the appropriate rotation to look at the uncorrelated principal directions.<br>\
                   4123: To be simple, these graphs help to understand the significativity of each parameter in relation to a second other one.<br> \n");
                   4124: 
                   4125:   cov[1]=1;
1.145     brouard  4126:   /* tj=cptcoveff; */
                   4127:   tj = (int) pow(2,cptcoveff);
1.126     brouard  4128:   if (cptcovn<1) {tj=1;ncodemax[1]=1;}
                   4129:   j1=0;
1.145     brouard  4130:   for(j1=1; j1<=tj;j1++){
                   4131:     /*for(i1=1; i1<=ncodemax[t];i1++){ */
                   4132:     /*j1++;*/
1.126     brouard  4133:       if  (cptcovn>0) {
                   4134:        fprintf(ficresprob, "\n#********** Variable "); 
                   4135:        for (z1=1; z1<=cptcoveff; z1++) fprintf(ficresprob, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtab[j1][z1]]);
                   4136:        fprintf(ficresprob, "**********\n#\n");
                   4137:        fprintf(ficresprobcov, "\n#********** Variable "); 
                   4138:        for (z1=1; z1<=cptcoveff; z1++) fprintf(ficresprobcov, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtab[j1][z1]]);
                   4139:        fprintf(ficresprobcov, "**********\n#\n");
                   4140:        
                   4141:        fprintf(ficgp, "\n#********** Variable "); 
                   4142:        for (z1=1; z1<=cptcoveff; z1++) fprintf(ficgp, " V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtab[j1][z1]]);
                   4143:        fprintf(ficgp, "**********\n#\n");
                   4144:        
                   4145:        
                   4146:        fprintf(fichtmcov, "\n<hr  size=\"2\" color=\"#EC5E5E\">********** Variable "); 
                   4147:        for (z1=1; z1<=cptcoveff; z1++) fprintf(fichtm, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtab[j1][z1]]);
                   4148:        fprintf(fichtmcov, "**********\n<hr size=\"2\" color=\"#EC5E5E\">");
                   4149:        
                   4150:        fprintf(ficresprobcor, "\n#********** Variable ");    
                   4151:        for (z1=1; z1<=cptcoveff; z1++) fprintf(ficresprobcor, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtab[j1][z1]]);
                   4152:        fprintf(ficresprobcor, "**********\n#");    
                   4153:       }
                   4154:       
1.145     brouard  4155:       gradg=matrix(1,npar,1,(nlstate)*(nlstate+ndeath));
                   4156:       trgradg=matrix(1,(nlstate)*(nlstate+ndeath),1,npar);
                   4157:       gp=vector(1,(nlstate)*(nlstate+ndeath));
                   4158:       gm=vector(1,(nlstate)*(nlstate+ndeath));
1.126     brouard  4159:       for (age=bage; age<=fage; age ++){ 
                   4160:        cov[2]=age;
1.187   ! brouard  4161:        if(nagesqr==1)
        !          4162:          cov[3]= age*age;
1.126     brouard  4163:        for (k=1; k<=cptcovn;k++) {
1.187   ! brouard  4164:          cov[2+nagesqr+k]=nbcode[Tvar[k]][codtab[j1][Tvar[k]]];/* j1 1 2 3 4
1.145     brouard  4165:                                                         * 1  1 1 1 1
                   4166:                                                         * 2  2 1 1 1
                   4167:                                                         * 3  1 2 1 1
                   4168:                                                         */
                   4169:          /* nbcode[1][1]=0 nbcode[1][2]=1;*/
1.126     brouard  4170:        }
1.186     brouard  4171:        /* for (k=1; k<=cptcovage;k++) cov[2+Tage[k]]=cov[2+Tage[k]]*cov[2]; */
                   4172:        for (k=1; k<=cptcovage;k++) cov[2+Tage[k]]=nbcode[Tvar[Tage[k]]][codtab[ij][Tvar[Tage[k]]]]*cov[2];
1.126     brouard  4173:        for (k=1; k<=cptcovprod;k++)
1.187   ! brouard  4174:          cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtab[ij][Tvard[k][1]]]*nbcode[Tvard[k][2]][codtab[ij][Tvard[k][2]]];
1.126     brouard  4175:        
                   4176:     
                   4177:        for(theta=1; theta <=npar; theta++){
                   4178:          for(i=1; i<=npar; i++)
                   4179:            xp[i] = x[i] + (i==theta ?delti[theta]:(double)0);
                   4180:          
                   4181:          pmij(pmmij,cov,ncovmodel,xp,nlstate);
                   4182:          
                   4183:          k=0;
                   4184:          for(i=1; i<= (nlstate); i++){
                   4185:            for(j=1; j<=(nlstate+ndeath);j++){
                   4186:              k=k+1;
                   4187:              gp[k]=pmmij[i][j];
                   4188:            }
                   4189:          }
                   4190:          
                   4191:          for(i=1; i<=npar; i++)
                   4192:            xp[i] = x[i] - (i==theta ?delti[theta]:(double)0);
                   4193:     
                   4194:          pmij(pmmij,cov,ncovmodel,xp,nlstate);
                   4195:          k=0;
                   4196:          for(i=1; i<=(nlstate); i++){
                   4197:            for(j=1; j<=(nlstate+ndeath);j++){
                   4198:              k=k+1;
                   4199:              gm[k]=pmmij[i][j];
                   4200:            }
                   4201:          }
                   4202:      
                   4203:          for(i=1; i<= (nlstate)*(nlstate+ndeath); i++) 
                   4204:            gradg[theta][i]=(gp[i]-gm[i])/(double)2./delti[theta];  
                   4205:        }
                   4206: 
                   4207:        for(j=1; j<=(nlstate)*(nlstate+ndeath);j++)
                   4208:          for(theta=1; theta <=npar; theta++)
                   4209:            trgradg[j][theta]=gradg[theta][j];
                   4210:        
                   4211:        matprod2(dnewm,trgradg,1,(nlstate)*(nlstate+ndeath),1,npar,1,npar,matcov); 
                   4212:        matprod2(doldm,dnewm,1,(nlstate)*(nlstate+ndeath),1,npar,1,(nlstate)*(nlstate+ndeath),gradg);
                   4213: 
                   4214:        pmij(pmmij,cov,ncovmodel,x,nlstate);
                   4215:        
                   4216:        k=0;
                   4217:        for(i=1; i<=(nlstate); i++){
                   4218:          for(j=1; j<=(nlstate+ndeath);j++){
                   4219:            k=k+1;
                   4220:            mu[k][(int) age]=pmmij[i][j];
                   4221:          }
                   4222:        }
                   4223:        for(i=1;i<=(nlstate)*(nlstate+ndeath);i++)
                   4224:          for(j=1;j<=(nlstate)*(nlstate+ndeath);j++)
                   4225:            varpij[i][j][(int)age] = doldm[i][j];
                   4226: 
                   4227:        /*printf("\n%d ",(int)age);
                   4228:          for (i=1; i<=(nlstate)*(nlstate+ndeath);i++){
                   4229:          printf("%e [%e ;%e] ",gm[i],gm[i]-2*sqrt(doldm[i][i]),gm[i]+2*sqrt(doldm[i][i]));
                   4230:          fprintf(ficlog,"%e [%e ;%e] ",gm[i],gm[i]-2*sqrt(doldm[i][i]),gm[i]+2*sqrt(doldm[i][i]));
                   4231:          }*/
                   4232: 
                   4233:        fprintf(ficresprob,"\n%d ",(int)age);
                   4234:        fprintf(ficresprobcov,"\n%d ",(int)age);
                   4235:        fprintf(ficresprobcor,"\n%d ",(int)age);
                   4236: 
                   4237:        for (i=1; i<=(nlstate)*(nlstate+ndeath);i++)
                   4238:          fprintf(ficresprob,"%11.3e (%11.3e) ",mu[i][(int) age],sqrt(varpij[i][i][(int)age]));
                   4239:        for (i=1; i<=(nlstate)*(nlstate+ndeath);i++){
                   4240:          fprintf(ficresprobcov,"%11.3e ",mu[i][(int) age]);
                   4241:          fprintf(ficresprobcor,"%11.3e ",mu[i][(int) age]);
                   4242:        }
                   4243:        i=0;
                   4244:        for (k=1; k<=(nlstate);k++){
                   4245:          for (l=1; l<=(nlstate+ndeath);l++){ 
1.145     brouard  4246:            i++;
1.126     brouard  4247:            fprintf(ficresprobcov,"\n%d %d-%d",(int)age,k,l);
                   4248:            fprintf(ficresprobcor,"\n%d %d-%d",(int)age,k,l);
                   4249:            for (j=1; j<=i;j++){
1.145     brouard  4250:              /* printf(" k=%d l=%d i=%d j=%d\n",k,l,i,j);fflush(stdout); */
1.126     brouard  4251:              fprintf(ficresprobcov," %11.3e",varpij[i][j][(int)age]);
                   4252:              fprintf(ficresprobcor," %11.3e",varpij[i][j][(int) age]/sqrt(varpij[i][i][(int) age])/sqrt(varpij[j][j][(int)age]));
                   4253:            }
                   4254:          }
                   4255:        }/* end of loop for state */
                   4256:       } /* end of loop for age */
1.145     brouard  4257:       free_vector(gp,1,(nlstate+ndeath)*(nlstate+ndeath));
                   4258:       free_vector(gm,1,(nlstate+ndeath)*(nlstate+ndeath));
                   4259:       free_matrix(trgradg,1,(nlstate+ndeath)*(nlstate+ndeath),1,npar);
                   4260:       free_matrix(gradg,1,(nlstate+ndeath)*(nlstate+ndeath),1,npar);
                   4261:       
1.126     brouard  4262:       /* Confidence intervalle of pij  */
                   4263:       /*
1.131     brouard  4264:        fprintf(ficgp,"\nunset parametric;unset label");
1.126     brouard  4265:        fprintf(ficgp,"\nset log y;unset log x; set xlabel \"Age\";set ylabel \"probability (year-1)\"");
                   4266:        fprintf(ficgp,"\nset ter png small\nset size 0.65,0.65");
                   4267:        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);
                   4268:        fprintf(fichtm,"\n<br><img src=\"pijgr%s.png\"> ",optionfilefiname);
                   4269:        fprintf(ficgp,"\nset out \"pijgr%s.png\"",optionfilefiname);
                   4270:        fprintf(ficgp,"\nplot \"%s\" every :::%d::%d u 1:2 \"\%%lf",k1,k2,xfilevarprob);
                   4271:       */
                   4272: 
                   4273:       /* Drawing ellipsoids of confidence of two variables p(k1-l1,k2-l2)*/
1.145     brouard  4274:       first1=1;first2=2;
1.126     brouard  4275:       for (k2=1; k2<=(nlstate);k2++){
                   4276:        for (l2=1; l2<=(nlstate+ndeath);l2++){ 
                   4277:          if(l2==k2) continue;
                   4278:          j=(k2-1)*(nlstate+ndeath)+l2;
                   4279:          for (k1=1; k1<=(nlstate);k1++){
                   4280:            for (l1=1; l1<=(nlstate+ndeath);l1++){ 
                   4281:              if(l1==k1) continue;
                   4282:              i=(k1-1)*(nlstate+ndeath)+l1;
                   4283:              if(i<=j) continue;
                   4284:              for (age=bage; age<=fage; age ++){ 
                   4285:                if ((int)age %5==0){
                   4286:                  v1=varpij[i][i][(int)age]/stepm*YEARM/stepm*YEARM;
                   4287:                  v2=varpij[j][j][(int)age]/stepm*YEARM/stepm*YEARM;
                   4288:                  cv12=varpij[i][j][(int)age]/stepm*YEARM/stepm*YEARM;
                   4289:                  mu1=mu[i][(int) age]/stepm*YEARM ;
                   4290:                  mu2=mu[j][(int) age]/stepm*YEARM;
                   4291:                  c12=cv12/sqrt(v1*v2);
                   4292:                  /* Computing eigen value of matrix of covariance */
                   4293:                  lc1=((v1+v2)+sqrt((v1+v2)*(v1+v2) - 4*(v1*v2-cv12*cv12)))/2.;
                   4294:                  lc2=((v1+v2)-sqrt((v1+v2)*(v1+v2) - 4*(v1*v2-cv12*cv12)))/2.;
1.135     brouard  4295:                  if ((lc2 <0) || (lc1 <0) ){
1.145     brouard  4296:                    if(first2==1){
                   4297:                      first1=0;
                   4298:                    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);
                   4299:                    }
                   4300:                    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);
                   4301:                    /* lc1=fabs(lc1); */ /* If we want to have them positive */
                   4302:                    /* lc2=fabs(lc2); */
1.135     brouard  4303:                  }
                   4304: 
1.126     brouard  4305:                  /* Eigen vectors */
                   4306:                  v11=(1./sqrt(1+(v1-lc1)*(v1-lc1)/cv12/cv12));
                   4307:                  /*v21=sqrt(1.-v11*v11); *//* error */
                   4308:                  v21=(lc1-v1)/cv12*v11;
                   4309:                  v12=-v21;
                   4310:                  v22=v11;
                   4311:                  tnalp=v21/v11;
                   4312:                  if(first1==1){
                   4313:                    first1=0;
                   4314:                    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);
                   4315:                  }
                   4316:                  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);
                   4317:                  /*printf(fignu*/
                   4318:                  /* mu1+ v11*lc1*cost + v12*lc2*sin(t) */
                   4319:                  /* mu2+ v21*lc1*cost + v22*lc2*sin(t) */
                   4320:                  if(first==1){
                   4321:                    first=0;
                   4322:                    fprintf(ficgp,"\nset parametric;unset label");
                   4323:                    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  4324:                    fprintf(ficgp,"\nset ter png small size 320, 240");
1.126     brouard  4325:                    fprintf(fichtmcov,"\n<br>Ellipsoids of confidence cov(p%1d%1d,p%1d%1d) expressed in year<sup>-1</sup>\
                   4326:  :<a href=\"%s%d%1d%1d-%1d%1d.png\">\
                   4327: %s%d%1d%1d-%1d%1d.png</A>, ",k1,l1,k2,l2,\
                   4328:                            subdirf2(optionfilefiname,"varpijgr"), j1,k1,l1,k2,l2,\
                   4329:                            subdirf2(optionfilefiname,"varpijgr"), j1,k1,l1,k2,l2);
                   4330:                    fprintf(fichtmcov,"\n<br><img src=\"%s%d%1d%1d-%1d%1d.png\"> ",subdirf2(optionfilefiname,"varpijgr"), j1,k1,l1,k2,l2);
                   4331:                    fprintf(fichtmcov,"\n<br> Correlation at age %d (%.3f),",(int) age, c12);
                   4332:                    fprintf(ficgp,"\nset out \"%s%d%1d%1d-%1d%1d.png\"",subdirf2(optionfilefiname,"varpijgr"), j1,k1,l1,k2,l2);
                   4333:                    fprintf(ficgp,"\nset label \"%d\" at %11.3e,%11.3e center",(int) age, mu1,mu2);
                   4334:                    fprintf(ficgp,"\n# Age %d, p%1d%1d - p%1d%1d",(int) age, k1,l1,k2,l2);
                   4335:                    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",\
                   4336:                            mu1,std,v11,sqrt(lc1),v12,sqrt(lc2),\
                   4337:                            mu2,std,v21,sqrt(lc1),v22,sqrt(lc2));
                   4338:                  }else{
                   4339:                    first=0;
                   4340:                    fprintf(fichtmcov," %d (%.3f),",(int) age, c12);
                   4341:                    fprintf(ficgp,"\n# Age %d, p%1d%1d - p%1d%1d",(int) age, k1,l1,k2,l2);
                   4342:                    fprintf(ficgp,"\nset label \"%d\" at %11.3e,%11.3e center",(int) age, mu1,mu2);
                   4343:                    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",\
                   4344:                            mu1,std,v11,sqrt(lc1),v12,sqrt(lc2),\
                   4345:                            mu2,std,v21,sqrt(lc1),v22,sqrt(lc2));
                   4346:                  }/* if first */
                   4347:                } /* age mod 5 */
                   4348:              } /* end loop age */
                   4349:              fprintf(ficgp,"\nset out \"%s%d%1d%1d-%1d%1d.png\";replot;",subdirf2(optionfilefiname,"varpijgr"), j1,k1,l1,k2,l2);
                   4350:              first=1;
                   4351:            } /*l12 */
                   4352:          } /* k12 */
                   4353:        } /*l1 */
                   4354:       }/* k1 */
1.169     brouard  4355:       /* } */ /* loop covariates */
1.126     brouard  4356:   }
                   4357:   free_ma3x(varpij,1,nlstate,1,nlstate+ndeath,(int) bage, (int)fage);
                   4358:   free_matrix(mu,1,(nlstate+ndeath)*(nlstate+ndeath),(int) bage, (int)fage);
                   4359:   free_matrix(doldm,1,(nlstate)*(nlstate+ndeath),1,(nlstate)*(nlstate+ndeath));
                   4360:   free_matrix(dnewm,1,(nlstate)*(nlstate+ndeath),1,npar);
                   4361:   free_vector(xp,1,npar);
                   4362:   fclose(ficresprob);
                   4363:   fclose(ficresprobcov);
                   4364:   fclose(ficresprobcor);
                   4365:   fflush(ficgp);
                   4366:   fflush(fichtmcov);
                   4367: }
                   4368: 
                   4369: 
                   4370: /******************* Printing html file ***********/
                   4371: void printinghtml(char fileres[], char title[], char datafile[], int firstpass, \
                   4372:                  int lastpass, int stepm, int weightopt, char model[],\
                   4373:                  int imx,int jmin, int jmax, double jmeanint,char rfileres[],\
                   4374:                  int popforecast, int estepm ,\
                   4375:                  double jprev1, double mprev1,double anprev1, \
                   4376:                  double jprev2, double mprev2,double anprev2){
                   4377:   int jj1, k1, i1, cpt;
                   4378: 
                   4379:    fprintf(fichtm,"<ul><li><a href='#firstorder'>Result files (first order: no variance)</a>\n \
                   4380:    <li><a href='#secondorder'>Result files (second order (variance)</a>\n \
                   4381: </ul>");
                   4382:    fprintf(fichtm,"<ul><li><h4><a name='firstorder'>Result files (first order: no variance)</a></h4>\n \
                   4383:  - Observed prevalence in each state (during the period defined between %.lf/%.lf/%.lf and %.lf/%.lf/%.lf): <a href=\"%s\">%s</a> <br>\n ",
                   4384:           jprev1, mprev1,anprev1,jprev2, mprev2,anprev2,subdirf2(fileres,"p"),subdirf2(fileres,"p"));
                   4385:    fprintf(fichtm,"\
                   4386:  - Estimated transition probabilities over %d (stepm) months: <a href=\"%s\">%s</a><br>\n ",
                   4387:           stepm,subdirf2(fileres,"pij"),subdirf2(fileres,"pij"));
                   4388:    fprintf(fichtm,"\
                   4389:  - Period (stable) prevalence in each health state: <a href=\"%s\">%s</a> <br>\n",
                   4390:           subdirf2(fileres,"pl"),subdirf2(fileres,"pl"));
                   4391:    fprintf(fichtm,"\
1.128     brouard  4392:  - (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  4393:    <a href=\"%s\">%s</a> <br>\n",
                   4394:           estepm,subdirf2(fileres,"e"),subdirf2(fileres,"e"));
                   4395:    fprintf(fichtm,"\
                   4396:  - Population projections by age and states: \
                   4397:    <a href=\"%s\">%s</a> <br>\n</li>", subdirf2(fileres,"f"),subdirf2(fileres,"f"));
                   4398: 
                   4399: fprintf(fichtm," \n<ul><li><b>Graphs</b></li><p>");
                   4400: 
1.145     brouard  4401:  m=pow(2,cptcoveff);
1.126     brouard  4402:  if (cptcovn < 1) {m=1;ncodemax[1]=1;}
                   4403: 
                   4404:  jj1=0;
                   4405:  for(k1=1; k1<=m;k1++){
                   4406:    for(i1=1; i1<=ncodemax[k1];i1++){
                   4407:      jj1++;
                   4408:      if (cptcovn > 0) {
                   4409:        fprintf(fichtm,"<hr  size=\"2\" color=\"#EC5E5E\">************ Results for covariates");
                   4410:        for (cpt=1; cpt<=cptcoveff;cpt++) 
                   4411:         fprintf(fichtm," V%d=%d ",Tvaraff[cpt],nbcode[Tvaraff[cpt]][codtab[jj1][cpt]]);
                   4412:        fprintf(fichtm," ************\n<hr size=\"2\" color=\"#EC5E5E\">");
                   4413:      }
                   4414:      /* Pij */
1.145     brouard  4415:      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> \
                   4416: <img src=\"%s%d_1.png\">",stepm,subdirf2(optionfilefiname,"pe"),jj1,subdirf2(optionfilefiname,"pe"),jj1,subdirf2(optionfilefiname,"pe"),jj1);     
1.126     brouard  4417:      /* Quasi-incidences */
                   4418:      fprintf(fichtm,"<br>- Pij or Conditional probabilities to be observed in state j being in state i %d (stepm) months\
1.145     brouard  4419:  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> \
                   4420: <img src=\"%s%d_2.png\">",stepm,subdirf2(optionfilefiname,"pe"),jj1,subdirf2(optionfilefiname,"pe"),jj1,subdirf2(optionfilefiname,"pe"),jj1); 
1.126     brouard  4421:        /* Period (stable) prevalence in each health state */
1.154     brouard  4422:        for(cpt=1; cpt<=nlstate;cpt++){
1.166     brouard  4423:         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> \
                   4424: <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  4425:        }
                   4426:      for(cpt=1; cpt<=nlstate;cpt++) {
1.154     brouard  4427:         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> \
                   4428: <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  4429:      }
                   4430:    } /* end i1 */
                   4431:  }/* End k1 */
                   4432:  fprintf(fichtm,"</ul>");
                   4433: 
                   4434: 
                   4435:  fprintf(fichtm,"\
                   4436: \n<br><li><h4> <a name='secondorder'>Result files (second order: variances)</a></h4>\n\
                   4437:  - Parameter file with estimated parameters and covariance matrix: <a href=\"%s\">%s</a> <br>\n", rfileres,rfileres);
                   4438: 
                   4439:  fprintf(fichtm," - Variance of one-step probabilities: <a href=\"%s\">%s</a> <br>\n",
                   4440:         subdirf2(fileres,"prob"),subdirf2(fileres,"prob"));
                   4441:  fprintf(fichtm,"\
                   4442:  - Variance-covariance of one-step probabilities: <a href=\"%s\">%s</a> <br>\n",
                   4443:         subdirf2(fileres,"probcov"),subdirf2(fileres,"probcov"));
                   4444: 
                   4445:  fprintf(fichtm,"\
                   4446:  - Correlation matrix of one-step probabilities: <a href=\"%s\">%s</a> <br>\n",
                   4447:         subdirf2(fileres,"probcor"),subdirf2(fileres,"probcor"));
                   4448:  fprintf(fichtm,"\
                   4449:  - 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): \
                   4450:    <a href=\"%s\">%s</a> <br>\n</li>",
                   4451:           estepm,subdirf2(fileres,"cve"),subdirf2(fileres,"cve"));
                   4452:  fprintf(fichtm,"\
                   4453:  - (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): \
                   4454:    <a href=\"%s\">%s</a> <br>\n</li>",
                   4455:           estepm,subdirf2(fileres,"stde"),subdirf2(fileres,"stde"));
                   4456:  fprintf(fichtm,"\
1.128     brouard  4457:  - 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  4458:         estepm, subdirf2(fileres,"v"),subdirf2(fileres,"v"));
                   4459:  fprintf(fichtm,"\
1.128     brouard  4460:  - 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",
                   4461:         estepm, subdirf2(fileres,"t"),subdirf2(fileres,"t"));
1.126     brouard  4462:  fprintf(fichtm,"\
                   4463:  - Standard deviation of period (stable) prevalences: <a href=\"%s\">%s</a> <br>\n",\
                   4464:         subdirf2(fileres,"vpl"),subdirf2(fileres,"vpl"));
                   4465: 
                   4466: /*  if(popforecast==1) fprintf(fichtm,"\n */
                   4467: /*  - Prevalences forecasting: <a href=\"f%s\">f%s</a> <br>\n */
                   4468: /*  - Population forecasting (if popforecast=1): <a href=\"pop%s\">pop%s</a> <br>\n */
                   4469: /*     <br>",fileres,fileres,fileres,fileres); */
                   4470: /*  else  */
                   4471: /*    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); */
                   4472:  fflush(fichtm);
                   4473:  fprintf(fichtm," <ul><li><b>Graphs</b></li><p>");
                   4474: 
1.145     brouard  4475:  m=pow(2,cptcoveff);
1.126     brouard  4476:  if (cptcovn < 1) {m=1;ncodemax[1]=1;}
                   4477: 
                   4478:  jj1=0;
                   4479:  for(k1=1; k1<=m;k1++){
                   4480:    for(i1=1; i1<=ncodemax[k1];i1++){
                   4481:      jj1++;
                   4482:      if (cptcovn > 0) {
                   4483:        fprintf(fichtm,"<hr  size=\"2\" color=\"#EC5E5E\">************ Results for covariates");
                   4484:        for (cpt=1; cpt<=cptcoveff;cpt++) 
                   4485:         fprintf(fichtm," V%d=%d ",Tvaraff[cpt],nbcode[Tvaraff[cpt]][codtab[jj1][cpt]]);
                   4486:        fprintf(fichtm," ************\n<hr size=\"2\" color=\"#EC5E5E\">");
                   4487:      }
                   4488:      for(cpt=1; cpt<=nlstate;cpt++) {
                   4489:        fprintf(fichtm,"<br>- Observed (cross-sectional) and period (incidence based) \
1.145     brouard  4490: prevalence (with 95%% confidence interval) in state (%d): %s%d_%d.png <br>\
                   4491: <img src=\"%s%d_%d.png\">",cpt,subdirf2(optionfilefiname,"v"),cpt,jj1,subdirf2(optionfilefiname,"v"),cpt,jj1);  
1.126     brouard  4492:      }
                   4493:      fprintf(fichtm,"\n<br>- Total life expectancy by age and \
1.128     brouard  4494: health expectancies in states (1) and (2). If popbased=1 the smooth (due to the model) \
                   4495: true period expectancies (those weighted with period prevalences are also\
                   4496:  drawn in addition to the population based expectancies computed using\
                   4497:  observed and cahotic prevalences: %s%d.png<br>\
1.126     brouard  4498: <img src=\"%s%d.png\">",subdirf2(optionfilefiname,"e"),jj1,subdirf2(optionfilefiname,"e"),jj1);
                   4499:    } /* end i1 */
                   4500:  }/* End k1 */
                   4501:  fprintf(fichtm,"</ul>");
                   4502:  fflush(fichtm);
                   4503: }
                   4504: 
                   4505: /******************* Gnuplot file **************/
                   4506: void printinggnuplot(char fileres[], char optionfilefiname[], double ageminpar, double agemaxpar, double fage , char pathc[], double p[]){
                   4507: 
                   4508:   char dirfileres[132],optfileres[132];
1.164     brouard  4509:   int cpt=0,k1=0,i=0,k=0,j=0,jk=0,k2=0,k3=0,ij=0,l=0;
1.130     brouard  4510:   int ng=0;
1.126     brouard  4511: /*   if((ficgp=fopen(optionfilegnuplot,"a"))==NULL) { */
                   4512: /*     printf("Problem with file %s",optionfilegnuplot); */
                   4513: /*     fprintf(ficlog,"Problem with file %s",optionfilegnuplot); */
                   4514: /*   } */
                   4515: 
                   4516:   /*#ifdef windows */
                   4517:   fprintf(ficgp,"cd \"%s\" \n",pathc);
                   4518:     /*#endif */
                   4519:   m=pow(2,cptcoveff);
                   4520: 
                   4521:   strcpy(dirfileres,optionfilefiname);
                   4522:   strcpy(optfileres,"vpl");
                   4523:  /* 1eme*/
1.153     brouard  4524:   fprintf(ficgp,"\n# 1st: Period (stable) prevalence with CI: 'vpl' files\n");
1.126     brouard  4525:   for (cpt=1; cpt<= nlstate ; cpt ++) {
1.145     brouard  4526:     for (k1=1; k1<= m ; k1 ++) { /* plot [100000000000000000000:-100000000000000000000] "mysbiaspar/vplrmysbiaspar.txt to check */
                   4527:      fprintf(ficgp,"\nset out \"%s%d_%d.png\" \n",subdirf2(optionfilefiname,"v"),cpt,k1);
                   4528:      fprintf(ficgp,"\n#set out \"v%s%d_%d.png\" \n",optionfilefiname,cpt,k1);
1.126     brouard  4529:      fprintf(ficgp,"set xlabel \"Age\" \n\
                   4530: set ylabel \"Probability\" \n\
1.145     brouard  4531: set ter png small size 320, 240\n\
1.170     brouard  4532: plot [%.f:%.f] \"%s\" every :::%d::%d u 1:2 \"%%lf",ageminpar,fage,subdirf2(fileres,"vpl"),k1-1,k1-1);
1.126     brouard  4533: 
                   4534:      for (i=1; i<= nlstate ; i ++) {
1.170     brouard  4535:        if (i==cpt) fprintf(ficgp," %%lf (%%lf)");
                   4536:        else        fprintf(ficgp," %%*lf (%%*lf)");
1.126     brouard  4537:      }
1.170     brouard  4538:      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  4539:      for (i=1; i<= nlstate ; i ++) {
1.170     brouard  4540:        if (i==cpt) fprintf(ficgp," %%lf (%%lf)");
                   4541:        else fprintf(ficgp," %%*lf (%%*lf)");
1.126     brouard  4542:      } 
1.170     brouard  4543:      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  4544:      for (i=1; i<= nlstate ; i ++) {
1.170     brouard  4545:        if (i==cpt) fprintf(ficgp," %%lf (%%lf)");
                   4546:        else fprintf(ficgp," %%*lf (%%*lf)");
1.126     brouard  4547:      }  
1.145     brouard  4548:      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  4549:    }
                   4550:   }
                   4551:   /*2 eme*/
1.153     brouard  4552:   fprintf(ficgp,"\n# 2nd: Total life expectancy with CI: 't' files\n");
1.126     brouard  4553:   for (k1=1; k1<= m ; k1 ++) { 
                   4554:     fprintf(ficgp,"\nset out \"%s%d.png\" \n",subdirf2(optionfilefiname,"e"),k1);
1.145     brouard  4555:     fprintf(ficgp,"set ylabel \"Years\" \nset ter png small size 320, 240\nplot [%.f:%.f] ",ageminpar,fage);
1.126     brouard  4556:     
                   4557:     for (i=1; i<= nlstate+1 ; i ++) {
                   4558:       k=2*i;
1.170     brouard  4559:       fprintf(ficgp,"\"%s\" every :::%d::%d u 1:2 \"%%lf",subdirf2(fileres,"t"),k1-1,k1-1);
1.126     brouard  4560:       for (j=1; j<= nlstate+1 ; j ++) {
1.170     brouard  4561:        if (j==i) fprintf(ficgp," %%lf (%%lf)");
                   4562:        else fprintf(ficgp," %%*lf (%%*lf)");
1.126     brouard  4563:       }   
                   4564:       if (i== 1) fprintf(ficgp,"\" t\"TLE\" w l ,");
                   4565:       else fprintf(ficgp,"\" t\"LE in state (%d)\" w l ,",i-1);
1.170     brouard  4566:       fprintf(ficgp,"\"%s\" every :::%d::%d u 1:($2-$3*2) \"%%lf",subdirf2(fileres,"t"),k1-1,k1-1);
1.126     brouard  4567:       for (j=1; j<= nlstate+1 ; j ++) {
1.170     brouard  4568:        if (j==i) fprintf(ficgp," %%lf (%%lf)");
                   4569:        else fprintf(ficgp," %%*lf (%%*lf)");
1.126     brouard  4570:       }   
1.145     brouard  4571:       fprintf(ficgp,"\" t\"\" w l lt 0,");
1.170     brouard  4572:       fprintf(ficgp,"\"%s\" every :::%d::%d u 1:($2+$3*2) \"%%lf",subdirf2(fileres,"t"),k1-1,k1-1);
1.126     brouard  4573:       for (j=1; j<= nlstate+1 ; j ++) {
1.170     brouard  4574:        if (j==i) fprintf(ficgp," %%lf (%%lf)");
                   4575:        else fprintf(ficgp," %%*lf (%%*lf)");
1.126     brouard  4576:       }   
1.145     brouard  4577:       if (i== (nlstate+1)) fprintf(ficgp,"\" t\"\" w l lt 0");
                   4578:       else fprintf(ficgp,"\" t\"\" w l lt 0,");
1.126     brouard  4579:     }
                   4580:   }
                   4581:   
                   4582:   /*3eme*/
                   4583:   
                   4584:   for (k1=1; k1<= m ; k1 ++) { 
                   4585:     for (cpt=1; cpt<= nlstate ; cpt ++) {
                   4586:       /*       k=2+nlstate*(2*cpt-2); */
                   4587:       k=2+(nlstate+1)*(cpt-1);
                   4588:       fprintf(ficgp,"\nset out \"%s%d%d.png\" \n",subdirf2(optionfilefiname,"exp"),cpt,k1);
1.145     brouard  4589:       fprintf(ficgp,"set ter png small size 320, 240\n\
1.126     brouard  4590: 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);
                   4591:       /*fprintf(ficgp,",\"e%s\" every :::%d::%d u 1:($%d-2*$%d) \"\%%lf ",fileres,k1-1,k1-1,k,k+1);
                   4592:        for (i=1; i<= nlstate*2 ; i ++) fprintf(ficgp,"\%%lf (\%%lf) ");
                   4593:        fprintf(ficgp,"\" t \"e%d1\" w l",cpt);
                   4594:        fprintf(ficgp,",\"e%s\" every :::%d::%d u 1:($%d+2*$%d) \"\%%lf ",fileres,k1-1,k1-1,k,k+1);
                   4595:        for (i=1; i<= nlstate*2 ; i ++) fprintf(ficgp,"\%%lf (\%%lf) ");
                   4596:        fprintf(ficgp,"\" t \"e%d1\" w l",cpt);
                   4597:        
                   4598:       */
                   4599:       for (i=1; i< nlstate ; i ++) {
                   4600:        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);
                   4601:        /*      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);*/
                   4602:        
                   4603:       } 
                   4604:       fprintf(ficgp," ,\"%s\" every :::%d::%d u 1:%d t \"e%d.\" w l",subdirf2(fileres,"e"),k1-1,k1-1,k+nlstate,cpt);
                   4605:     }
                   4606:   }
                   4607:   
                   4608:   /* CV preval stable (period) */
1.153     brouard  4609:   for (k1=1; k1<= m ; k1 ++) { /* For each multivariate if any */
                   4610:     for (cpt=1; cpt<=nlstate ; cpt ++) { /* For each life state */
1.126     brouard  4611:       k=3;
1.153     brouard  4612:       fprintf(ficgp,"\n#\n#\n#CV preval stable (period): 'pij' files, cov=%d state=%d",k1, cpt);
1.145     brouard  4613:       fprintf(ficgp,"\nset out \"%s%d_%d.png\" \n",subdirf2(optionfilefiname,"p"),cpt,k1);
1.126     brouard  4614:       fprintf(ficgp,"set xlabel \"Age\" \nset ylabel \"Probability\" \n\
1.145     brouard  4615: set ter png small size 320, 240\n\
1.126     brouard  4616: unset log y\n\
1.153     brouard  4617: plot [%.f:%.f]  ", ageminpar, agemaxpar);
                   4618:       for (i=1; i<= nlstate ; i ++){
                   4619:        if(i==1)
                   4620:          fprintf(ficgp,"\"%s\"",subdirf2(fileres,"pij"));
                   4621:        else
                   4622:          fprintf(ficgp,", '' ");
1.154     brouard  4623:        l=(nlstate+ndeath)*(i-1)+1;
                   4624:        fprintf(ficgp," u ($1==%d ? ($3):1/0):($%d/($%d",k1,k+l+(cpt-1),k+l);
1.153     brouard  4625:        for (j=1; j<= (nlstate-1) ; j ++)
                   4626:          fprintf(ficgp,"+$%d",k+l+j);
                   4627:        fprintf(ficgp,")) t \"prev(%d,%d)\" w l",i,cpt);
                   4628:       } /* nlstate */
                   4629:       fprintf(ficgp,"\n");
                   4630:     } /* end cpt state*/ 
                   4631:   } /* end covariate */  
1.126     brouard  4632:   
                   4633:   /* proba elementaires */
1.187   ! brouard  4634:   fprintf(ficgp,"\n##############\n#MLE estimated parameters\n#############\n");
1.126     brouard  4635:   for(i=1,jk=1; i <=nlstate; i++){
1.187   ! brouard  4636:     fprintf(ficgp,"# initial state %d\n",i);
1.126     brouard  4637:     for(k=1; k <=(nlstate+ndeath); k++){
                   4638:       if (k != i) {
1.187   ! brouard  4639:        fprintf(ficgp,"#   current state %d\n",k);
1.126     brouard  4640:        for(j=1; j <=ncovmodel; j++){
1.187   ! brouard  4641:          fprintf(ficgp,"p%d=%f; ",jk,p[jk]);
1.126     brouard  4642:          jk++; 
                   4643:        }
1.187   ! brouard  4644:        fprintf(ficgp,"\n");
1.126     brouard  4645:       }
                   4646:     }
                   4647:    }
1.187   ! brouard  4648:   fprintf(ficgp,"##############\n#\n");
        !          4649: 
1.145     brouard  4650:   /*goto avoid;*/
1.187   ! brouard  4651:   fprintf(ficgp,"\n##############\n#Graphics of of probabilities or incidences\n#############\n");
        !          4652:   fprintf(ficgp,"# logi(p12/p11)=a12+b12*age+c12age*age+d12*V1+e12*V1*age\n");
        !          4653:   fprintf(ficgp,"# logi(p12/p11)=p1 +p2*age +p3*age*age+ p4*V1+ p5*V1*age\n");
        !          4654:   fprintf(ficgp,"# logi(p13/p11)=a13+b13*age+c13age*age+d13*V1+e13*V1*age\n");
        !          4655:   fprintf(ficgp,"# logi(p13/p11)=p6 +p7*age +p8*age*age+ p9*V1+ p10*V1*age\n");
        !          4656:   fprintf(ficgp,"# p12+p13+p14+p11=1=p11(1+exp(a12+b12*age+c12age*age+d12*V1+e12*V1*age)\n");
        !          4657:   fprintf(ficgp,"#                      +exp(a13+b13*age+c13age*age+d13*V1+e13*V1*age)+...)\n");
        !          4658:   fprintf(ficgp,"# p11=1/(1+exp(a12+b12*age+c12age*age+d12*V1+e12*V1*age)\n");
        !          4659:   fprintf(ficgp,"#                      +exp(a13+b13*age+c13age*age+d13*V1+e13*V1*age)+...)\n");
        !          4660:   fprintf(ficgp,"# p12=exp(a12+b12*age+c12age*age+d12*V1+e12*V1*age)/\n");
        !          4661:   fprintf(ficgp,"#     (1+exp(a12+b12*age+c12age*age+d12*V1+e12*V1*age)\n");
        !          4662:   fprintf(ficgp,"#       +exp(a13+b13*age+c13age*age+d13*V1+e13*V1*age))\n");
        !          4663:   fprintf(ficgp,"#       +exp(a14+b14*age+c14age*age+d14*V1+e14*V1*age)+...)\n");
        !          4664:   fprintf(ficgp,"#\n");
1.126     brouard  4665:    for(ng=1; ng<=2;ng++){ /* Number of graphics: first is probabilities second is incidence per year*/
1.187   ! brouard  4666:      fprintf(ficgp,"# ng=%d\n",ng);
        !          4667:      fprintf(ficgp,"#   jk=1 to 2^%d=%d\n",cptcoveff,m);
1.126     brouard  4668:      for(jk=1; jk <=m; jk++) {
1.187   ! brouard  4669:        fprintf(ficgp,"#    jk=%d\n",jk);
1.145     brouard  4670:        fprintf(ficgp,"\nset out \"%s%d_%d.png\" \n",subdirf2(optionfilefiname,"pe"),jk,ng); 
1.126     brouard  4671:        if (ng==2)
                   4672:         fprintf(ficgp,"\nset ylabel \"Quasi-incidence per year\"\n");
                   4673:        else
                   4674:         fprintf(ficgp,"\nset title \"Probability\"\n");
1.145     brouard  4675:        fprintf(ficgp,"\nset ter png small size 320, 240\nset log y\nplot  [%.f:%.f] ",ageminpar,agemaxpar);
1.126     brouard  4676:        i=1;
                   4677:        for(k2=1; k2<=nlstate; k2++) {
                   4678:         k3=i;
                   4679:         for(k=1; k<=(nlstate+ndeath); k++) {
                   4680:           if (k != k2){
                   4681:             if(ng==2)
1.187   ! brouard  4682:               if(nagesqr==0)
        !          4683:                 fprintf(ficgp," %f*exp(p%d+p%d*x",YEARM/stepm,i,i+1);
        !          4684:               else /* nagesqr =1 */
        !          4685:                 fprintf(ficgp," %f*exp(p%d+p%d*x+p%d*x*x",YEARM/stepm,i,i+1,i+1+nagesqr);
1.126     brouard  4686:             else
1.187   ! brouard  4687:               if(nagesqr==0)
        !          4688:                 fprintf(ficgp," exp(p%d+p%d*x",i,i+1);
        !          4689:               else /* nagesqr =1 */
        !          4690:                 fprintf(ficgp," exp(p%d+p%d*x+p%d*x*x",i,i+1,i+1+nagesqr);
1.141     brouard  4691:             ij=1;/* To be checked else nbcode[0][0] wrong */
1.187   ! brouard  4692:             for(j=3; j <=ncovmodel-nagesqr; j++) {
1.186     brouard  4693:               if(((j-2)==Tage[ij]) &&(ij <=cptcovage)) { /* Bug valgrind */
1.187   ! brouard  4694:                 fprintf(ficgp,"+p%d*%d*x",i+j+nagesqr-1,nbcode[Tvar[j-2]][codtab[jk][Tvar[j-2]]]);
1.186     brouard  4695:                 ij++;
                   4696:               }
                   4697:               else
1.187   ! brouard  4698:                 fprintf(ficgp,"+p%d*%d",i+j+nagesqr-1,nbcode[Tvar[j-2]][codtab[jk][j-2]]);
1.126     brouard  4699:             }
                   4700:             fprintf(ficgp,")/(1");
                   4701:             
1.187   ! brouard  4702:             for(k1=1; k1 <=nlstate; k1++){ 
        !          4703:               if(nagesqr==0)
        !          4704:                 fprintf(ficgp,"+exp(p%d+p%d*x",k3+(k1-1)*ncovmodel,k3+(k1-1)*ncovmodel+1);
        !          4705:               else /* nagesqr =1 */
        !          4706:                 fprintf(ficgp,"+exp(p%d+p%d*x+p%d*x*x",k3+(k1-1)*ncovmodel,k3+(k1-1)*ncovmodel+1,k3+(k1-1)*ncovmodel+1+nagesqr);
        !          4707:   
1.126     brouard  4708:               ij=1;
1.187   ! brouard  4709:               for(j=3; j <=ncovmodel-nagesqr; j++){
1.186     brouard  4710:                 if(((j-2)==Tage[ij]) &&(ij <=cptcovage)) {
1.187   ! brouard  4711:                   fprintf(ficgp,"+p%d*%d*x",k3+(k1-1)*ncovmodel+1+j-2+nagesqr,nbcode[Tvar[j-2]][codtab[jk][Tvar[j-2]]]);
1.186     brouard  4712:                   ij++;
                   4713:                 }
                   4714:                 else
1.187   ! brouard  4715:                   fprintf(ficgp,"+p%d*%d",k3+(k1-1)*ncovmodel+1+j-2+nagesqr,nbcode[Tvar[j-2]][codtab[jk][j-2]]);
1.126     brouard  4716:               }
                   4717:               fprintf(ficgp,")");
                   4718:             }
                   4719:             fprintf(ficgp,") t \"p%d%d\" ", k2,k);
                   4720:             if ((k+k2)!= (nlstate*2+ndeath)) fprintf(ficgp,",");
                   4721:             i=i+ncovmodel;
                   4722:           }
                   4723:         } /* end k */
                   4724:        } /* end k2 */
                   4725:      } /* end jk */
                   4726:    } /* end ng */
1.164     brouard  4727:  /* avoid: */
1.126     brouard  4728:    fflush(ficgp); 
                   4729: }  /* end gnuplot */
                   4730: 
                   4731: 
                   4732: /*************** Moving average **************/
                   4733: int movingaverage(double ***probs, double bage,double fage, double ***mobaverage, int mobilav){
                   4734: 
                   4735:   int i, cpt, cptcod;
                   4736:   int modcovmax =1;
                   4737:   int mobilavrange, mob;
                   4738:   double age;
                   4739: 
                   4740:   modcovmax=2*cptcoveff;/* Max number of modalities. We suppose 
                   4741:                           a covariate has 2 modalities */
                   4742:   if (cptcovn<1) modcovmax=1; /* At least 1 pass */
                   4743: 
                   4744:   if(mobilav==1||mobilav ==3 ||mobilav==5 ||mobilav== 7){
                   4745:     if(mobilav==1) mobilavrange=5; /* default */
                   4746:     else mobilavrange=mobilav;
                   4747:     for (age=bage; age<=fage; age++)
                   4748:       for (i=1; i<=nlstate;i++)
                   4749:        for (cptcod=1;cptcod<=modcovmax;cptcod++)
                   4750:          mobaverage[(int)age][i][cptcod]=probs[(int)age][i][cptcod];
                   4751:     /* We keep the original values on the extreme ages bage, fage and for 
                   4752:        fage+1 and bage-1 we use a 3 terms moving average; for fage+2 bage+2
                   4753:        we use a 5 terms etc. until the borders are no more concerned. 
                   4754:     */ 
                   4755:     for (mob=3;mob <=mobilavrange;mob=mob+2){
                   4756:       for (age=bage+(mob-1)/2; age<=fage-(mob-1)/2; age++){
                   4757:        for (i=1; i<=nlstate;i++){
                   4758:          for (cptcod=1;cptcod<=modcovmax;cptcod++){
                   4759:            mobaverage[(int)age][i][cptcod] =probs[(int)age][i][cptcod];
                   4760:              for (cpt=1;cpt<=(mob-1)/2;cpt++){
                   4761:                mobaverage[(int)age][i][cptcod] +=probs[(int)age-cpt][i][cptcod];
                   4762:                mobaverage[(int)age][i][cptcod] +=probs[(int)age+cpt][i][cptcod];
                   4763:              }
                   4764:            mobaverage[(int)age][i][cptcod]=mobaverage[(int)age][i][cptcod]/mob;
                   4765:          }
                   4766:        }
                   4767:       }/* end age */
                   4768:     }/* end mob */
                   4769:   }else return -1;
                   4770:   return 0;
                   4771: }/* End movingaverage */
                   4772: 
                   4773: 
                   4774: /************** Forecasting ******************/
1.169     brouard  4775: 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  4776:   /* proj1, year, month, day of starting projection 
                   4777:      agemin, agemax range of age
                   4778:      dateprev1 dateprev2 range of dates during which prevalence is computed
                   4779:      anproj2 year of en of projection (same day and month as proj1).
                   4780:   */
1.164     brouard  4781:   int yearp, stepsize, hstepm, nhstepm, j, k, cptcod, i, h, i1;
1.126     brouard  4782:   double agec; /* generic age */
                   4783:   double agelim, ppij, yp,yp1,yp2,jprojmean,mprojmean,anprojmean;
                   4784:   double *popeffectif,*popcount;
                   4785:   double ***p3mat;
                   4786:   double ***mobaverage;
                   4787:   char fileresf[FILENAMELENGTH];
                   4788: 
                   4789:   agelim=AGESUP;
                   4790:   prevalence(probs, ageminpar, agemax, s, agev, nlstate, imx, Tvar, nbcode, ncodemax, mint, anint, dateprev1, dateprev2, firstpass, lastpass);
                   4791:  
                   4792:   strcpy(fileresf,"f"); 
                   4793:   strcat(fileresf,fileres);
                   4794:   if((ficresf=fopen(fileresf,"w"))==NULL) {
                   4795:     printf("Problem with forecast resultfile: %s\n", fileresf);
                   4796:     fprintf(ficlog,"Problem with forecast resultfile: %s\n", fileresf);
                   4797:   }
                   4798:   printf("Computing forecasting: result on file '%s' \n", fileresf);
                   4799:   fprintf(ficlog,"Computing forecasting: result on file '%s' \n", fileresf);
                   4800: 
                   4801:   if (cptcoveff==0) ncodemax[cptcoveff]=1;
                   4802: 
                   4803:   if (mobilav!=0) {
                   4804:     mobaverage= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
                   4805:     if (movingaverage(probs, ageminpar, fage, mobaverage,mobilav)!=0){
                   4806:       fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav);
                   4807:       printf(" Error in movingaverage mobilav=%d\n",mobilav);
                   4808:     }
                   4809:   }
                   4810: 
                   4811:   stepsize=(int) (stepm+YEARM-1)/YEARM;
                   4812:   if (stepm<=12) stepsize=1;
                   4813:   if(estepm < stepm){
                   4814:     printf ("Problem %d lower than %d\n",estepm, stepm);
                   4815:   }
                   4816:   else  hstepm=estepm;   
                   4817: 
                   4818:   hstepm=hstepm/stepm; 
                   4819:   yp1=modf(dateintmean,&yp);/* extracts integral of datemean in yp  and
                   4820:                                fractional in yp1 */
                   4821:   anprojmean=yp;
                   4822:   yp2=modf((yp1*12),&yp);
                   4823:   mprojmean=yp;
                   4824:   yp1=modf((yp2*30.5),&yp);
                   4825:   jprojmean=yp;
                   4826:   if(jprojmean==0) jprojmean=1;
                   4827:   if(mprojmean==0) jprojmean=1;
                   4828: 
                   4829:   i1=cptcoveff;
                   4830:   if (cptcovn < 1){i1=1;}
                   4831:   
                   4832:   fprintf(ficresf,"# Mean day of interviews %.lf/%.lf/%.lf (%.2f) between %.2f and %.2f \n",jprojmean,mprojmean,anprojmean,dateintmean,dateprev1,dateprev2); 
                   4833:   
                   4834:   fprintf(ficresf,"#****** Routine prevforecast **\n");
                   4835: 
                   4836: /*           if (h==(int)(YEARM*yearp)){ */
                   4837:   for(cptcov=1, k=0;cptcov<=i1;cptcov++){
                   4838:     for(cptcod=1;cptcod<=ncodemax[cptcoveff];cptcod++){
                   4839:       k=k+1;
                   4840:       fprintf(ficresf,"\n#******");
                   4841:       for(j=1;j<=cptcoveff;j++) {
                   4842:        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]]);
                   4843:       }
                   4844:       fprintf(ficresf,"******\n");
                   4845:       fprintf(ficresf,"# Covariate valuofcovar yearproj age");
                   4846:       for(j=1; j<=nlstate+ndeath;j++){ 
                   4847:        for(i=1; i<=nlstate;i++)              
                   4848:           fprintf(ficresf," p%d%d",i,j);
                   4849:        fprintf(ficresf," p.%d",j);
                   4850:       }
                   4851:       for (yearp=0; yearp<=(anproj2-anproj1);yearp +=stepsize) { 
                   4852:        fprintf(ficresf,"\n");
                   4853:        fprintf(ficresf,"\n# Forecasting at date %.lf/%.lf/%.lf ",jproj1,mproj1,anproj1+yearp);   
                   4854: 
                   4855:        for (agec=fage; agec>=(ageminpar-1); agec--){ 
                   4856:          nhstepm=(int) rint((agelim-agec)*YEARM/stepm); 
                   4857:          nhstepm = nhstepm/hstepm; 
                   4858:          p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   4859:          oldm=oldms;savm=savms;
                   4860:          hpxij(p3mat,nhstepm,agec,hstepm,p,nlstate,stepm,oldm,savm, k);  
                   4861:        
                   4862:          for (h=0; h<=nhstepm; h++){
                   4863:            if (h*hstepm/YEARM*stepm ==yearp) {
                   4864:               fprintf(ficresf,"\n");
                   4865:               for(j=1;j<=cptcoveff;j++) 
                   4866:                 fprintf(ficresf,"%d %d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
                   4867:              fprintf(ficresf,"%.f %.f ",anproj1+yearp,agec+h*hstepm/YEARM*stepm);
                   4868:            } 
                   4869:            for(j=1; j<=nlstate+ndeath;j++) {
                   4870:              ppij=0.;
                   4871:              for(i=1; i<=nlstate;i++) {
                   4872:                if (mobilav==1) 
                   4873:                  ppij=ppij+p3mat[i][j][h]*mobaverage[(int)agec][i][cptcod];
                   4874:                else {
                   4875:                  ppij=ppij+p3mat[i][j][h]*probs[(int)(agec)][i][cptcod];
                   4876:                }
                   4877:                if (h*hstepm/YEARM*stepm== yearp) {
                   4878:                  fprintf(ficresf," %.3f", p3mat[i][j][h]);
                   4879:                }
                   4880:              } /* end i */
                   4881:              if (h*hstepm/YEARM*stepm==yearp) {
                   4882:                fprintf(ficresf," %.3f", ppij);
                   4883:              }
                   4884:            }/* end j */
                   4885:          } /* end h */
                   4886:          free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   4887:        } /* end agec */
                   4888:       } /* end yearp */
                   4889:     } /* end cptcod */
                   4890:   } /* end  cptcov */
                   4891:        
                   4892:   if (mobilav!=0) free_ma3x(mobaverage,1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
                   4893: 
                   4894:   fclose(ficresf);
                   4895: }
                   4896: 
                   4897: /************** Forecasting *****not tested NB*************/
1.169     brouard  4898: 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  4899:   
                   4900:   int cpt, stepsize, hstepm, nhstepm, j,k,c, cptcod, i,h;
                   4901:   int *popage;
                   4902:   double calagedatem, agelim, kk1, kk2;
                   4903:   double *popeffectif,*popcount;
                   4904:   double ***p3mat,***tabpop,***tabpopprev;
                   4905:   double ***mobaverage;
                   4906:   char filerespop[FILENAMELENGTH];
                   4907: 
                   4908:   tabpop= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
                   4909:   tabpopprev= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
                   4910:   agelim=AGESUP;
                   4911:   calagedatem=(anpyram+mpyram/12.+jpyram/365.-dateintmean)*YEARM;
                   4912:   
                   4913:   prevalence(probs, ageminpar, agemax, s, agev, nlstate, imx, Tvar, nbcode, ncodemax, mint, anint, dateprev1, dateprev2, firstpass, lastpass);
                   4914:   
                   4915:   
                   4916:   strcpy(filerespop,"pop"); 
                   4917:   strcat(filerespop,fileres);
                   4918:   if((ficrespop=fopen(filerespop,"w"))==NULL) {
                   4919:     printf("Problem with forecast resultfile: %s\n", filerespop);
                   4920:     fprintf(ficlog,"Problem with forecast resultfile: %s\n", filerespop);
                   4921:   }
                   4922:   printf("Computing forecasting: result on file '%s' \n", filerespop);
                   4923:   fprintf(ficlog,"Computing forecasting: result on file '%s' \n", filerespop);
                   4924: 
                   4925:   if (cptcoveff==0) ncodemax[cptcoveff]=1;
                   4926: 
                   4927:   if (mobilav!=0) {
                   4928:     mobaverage= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
                   4929:     if (movingaverage(probs, ageminpar, fage, mobaverage,mobilav)!=0){
                   4930:       fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav);
                   4931:       printf(" Error in movingaverage mobilav=%d\n",mobilav);
                   4932:     }
                   4933:   }
                   4934: 
                   4935:   stepsize=(int) (stepm+YEARM-1)/YEARM;
                   4936:   if (stepm<=12) stepsize=1;
                   4937:   
                   4938:   agelim=AGESUP;
                   4939:   
                   4940:   hstepm=1;
                   4941:   hstepm=hstepm/stepm; 
                   4942:   
                   4943:   if (popforecast==1) {
                   4944:     if((ficpop=fopen(popfile,"r"))==NULL) {
                   4945:       printf("Problem with population file : %s\n",popfile);exit(0);
                   4946:       fprintf(ficlog,"Problem with population file : %s\n",popfile);exit(0);
                   4947:     } 
                   4948:     popage=ivector(0,AGESUP);
                   4949:     popeffectif=vector(0,AGESUP);
                   4950:     popcount=vector(0,AGESUP);
                   4951:     
                   4952:     i=1;   
                   4953:     while ((c=fscanf(ficpop,"%d %lf\n",&popage[i],&popcount[i])) != EOF) i=i+1;
                   4954:    
                   4955:     imx=i;
                   4956:     for (i=1; i<imx;i++) popeffectif[popage[i]]=popcount[i];
                   4957:   }
                   4958: 
                   4959:   for(cptcov=1,k=0;cptcov<=i2;cptcov++){
                   4960:    for(cptcod=1;cptcod<=ncodemax[cptcoveff];cptcod++){
                   4961:       k=k+1;
                   4962:       fprintf(ficrespop,"\n#******");
                   4963:       for(j=1;j<=cptcoveff;j++) {
                   4964:        fprintf(ficrespop," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
                   4965:       }
                   4966:       fprintf(ficrespop,"******\n");
                   4967:       fprintf(ficrespop,"# Age");
                   4968:       for(j=1; j<=nlstate+ndeath;j++) fprintf(ficrespop," P.%d",j);
                   4969:       if (popforecast==1)  fprintf(ficrespop," [Population]");
                   4970:       
                   4971:       for (cpt=0; cpt<=0;cpt++) { 
                   4972:        fprintf(ficrespop,"\n\n# Forecasting at date %.lf/%.lf/%.lf ",jpyram,mpyram,anpyram+cpt);   
                   4973:        
                   4974:        for (agedeb=(fage-((int)calagedatem %12/12.)); agedeb>=(ageminpar-((int)calagedatem %12)/12.); agedeb--){ 
                   4975:          nhstepm=(int) rint((agelim-agedeb)*YEARM/stepm); 
                   4976:          nhstepm = nhstepm/hstepm; 
                   4977:          
                   4978:          p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   4979:          oldm=oldms;savm=savms;
                   4980:          hpxij(p3mat,nhstepm,agedeb,hstepm,p,nlstate,stepm,oldm,savm, k);  
                   4981:        
                   4982:          for (h=0; h<=nhstepm; h++){
                   4983:            if (h==(int) (calagedatem+YEARM*cpt)) {
                   4984:              fprintf(ficrespop,"\n %3.f ",agedeb+h*hstepm/YEARM*stepm);
                   4985:            } 
                   4986:            for(j=1; j<=nlstate+ndeath;j++) {
                   4987:              kk1=0.;kk2=0;
                   4988:              for(i=1; i<=nlstate;i++) {              
                   4989:                if (mobilav==1) 
                   4990:                  kk1=kk1+p3mat[i][j][h]*mobaverage[(int)agedeb+1][i][cptcod];
                   4991:                else {
                   4992:                  kk1=kk1+p3mat[i][j][h]*probs[(int)(agedeb+1)][i][cptcod];
                   4993:                }
                   4994:              }
                   4995:              if (h==(int)(calagedatem+12*cpt)){
                   4996:                tabpop[(int)(agedeb)][j][cptcod]=kk1;
                   4997:                  /*fprintf(ficrespop," %.3f", kk1);
                   4998:                    if (popforecast==1) fprintf(ficrespop," [%.f]", kk1*popeffectif[(int)agedeb+1]);*/
                   4999:              }
                   5000:            }
                   5001:            for(i=1; i<=nlstate;i++){
                   5002:              kk1=0.;
                   5003:                for(j=1; j<=nlstate;j++){
                   5004:                  kk1= kk1+tabpop[(int)(agedeb)][j][cptcod]; 
                   5005:                }
                   5006:                  tabpopprev[(int)(agedeb)][i][cptcod]=tabpop[(int)(agedeb)][i][cptcod]/kk1*popeffectif[(int)(agedeb+(calagedatem+12*cpt)*hstepm/YEARM*stepm-1)];
                   5007:            }
                   5008: 
                   5009:            if (h==(int)(calagedatem+12*cpt)) for(j=1; j<=nlstate;j++) 
                   5010:              fprintf(ficrespop," %15.2f",tabpopprev[(int)(agedeb+1)][j][cptcod]);
                   5011:          }
                   5012:          free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   5013:        }
                   5014:       }
                   5015:  
                   5016:   /******/
                   5017: 
                   5018:       for (cpt=1; cpt<=(anpyram1-anpyram);cpt++) { 
                   5019:        fprintf(ficrespop,"\n\n# Forecasting at date %.lf/%.lf/%.lf ",jpyram,mpyram,anpyram+cpt);   
                   5020:        for (agedeb=(fage-((int)calagedatem %12/12.)); agedeb>=(ageminpar-((int)calagedatem %12)/12.); agedeb--){ 
                   5021:          nhstepm=(int) rint((agelim-agedeb)*YEARM/stepm); 
                   5022:          nhstepm = nhstepm/hstepm; 
                   5023:          
                   5024:          p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   5025:          oldm=oldms;savm=savms;
                   5026:          hpxij(p3mat,nhstepm,agedeb,hstepm,p,nlstate,stepm,oldm,savm, k);  
                   5027:          for (h=0; h<=nhstepm; h++){
                   5028:            if (h==(int) (calagedatem+YEARM*cpt)) {
                   5029:              fprintf(ficresf,"\n %3.f ",agedeb+h*hstepm/YEARM*stepm);
                   5030:            } 
                   5031:            for(j=1; j<=nlstate+ndeath;j++) {
                   5032:              kk1=0.;kk2=0;
                   5033:              for(i=1; i<=nlstate;i++) {              
                   5034:                kk1=kk1+p3mat[i][j][h]*tabpopprev[(int)agedeb+1][i][cptcod];    
                   5035:              }
                   5036:              if (h==(int)(calagedatem+12*cpt)) fprintf(ficresf," %15.2f", kk1);        
                   5037:            }
                   5038:          }
                   5039:          free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   5040:        }
                   5041:       }
                   5042:    } 
                   5043:   }
                   5044:  
                   5045:   if (mobilav!=0) free_ma3x(mobaverage,1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
                   5046: 
                   5047:   if (popforecast==1) {
                   5048:     free_ivector(popage,0,AGESUP);
                   5049:     free_vector(popeffectif,0,AGESUP);
                   5050:     free_vector(popcount,0,AGESUP);
                   5051:   }
                   5052:   free_ma3x(tabpop,1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
                   5053:   free_ma3x(tabpopprev,1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
                   5054:   fclose(ficrespop);
                   5055: } /* End of popforecast */
                   5056: 
                   5057: int fileappend(FILE *fichier, char *optionfich)
                   5058: {
                   5059:   if((fichier=fopen(optionfich,"a"))==NULL) {
                   5060:     printf("Problem with file: %s\n", optionfich);
                   5061:     fprintf(ficlog,"Problem with file: %s\n", optionfich);
                   5062:     return (0);
                   5063:   }
                   5064:   fflush(fichier);
                   5065:   return (1);
                   5066: }
                   5067: 
                   5068: 
                   5069: /**************** function prwizard **********************/
                   5070: void prwizard(int ncovmodel, int nlstate, int ndeath,  char model[], FILE *ficparo)
                   5071: {
                   5072: 
                   5073:   /* Wizard to print covariance matrix template */
                   5074: 
1.164     brouard  5075:   char ca[32], cb[32];
                   5076:   int i,j, k, li, lj, lk, ll, jj, npar, itimes;
1.126     brouard  5077:   int numlinepar;
                   5078: 
                   5079:   printf("# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
                   5080:   fprintf(ficparo,"# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
                   5081:   for(i=1; i <=nlstate; i++){
                   5082:     jj=0;
                   5083:     for(j=1; j <=nlstate+ndeath; j++){
                   5084:       if(j==i) continue;
                   5085:       jj++;
                   5086:       /*ca[0]= k+'a'-1;ca[1]='\0';*/
                   5087:       printf("%1d%1d",i,j);
                   5088:       fprintf(ficparo,"%1d%1d",i,j);
                   5089:       for(k=1; k<=ncovmodel;k++){
                   5090:        /*        printf(" %lf",param[i][j][k]); */
                   5091:        /*        fprintf(ficparo," %lf",param[i][j][k]); */
                   5092:        printf(" 0.");
                   5093:        fprintf(ficparo," 0.");
                   5094:       }
                   5095:       printf("\n");
                   5096:       fprintf(ficparo,"\n");
                   5097:     }
                   5098:   }
                   5099:   printf("# Scales (for hessian or gradient estimation)\n");
                   5100:   fprintf(ficparo,"# Scales (for hessian or gradient estimation)\n");
                   5101:   npar= (nlstate+ndeath-1)*nlstate*ncovmodel; /* Number of parameters*/ 
                   5102:   for(i=1; i <=nlstate; i++){
                   5103:     jj=0;
                   5104:     for(j=1; j <=nlstate+ndeath; j++){
                   5105:       if(j==i) continue;
                   5106:       jj++;
                   5107:       fprintf(ficparo,"%1d%1d",i,j);
                   5108:       printf("%1d%1d",i,j);
                   5109:       fflush(stdout);
                   5110:       for(k=1; k<=ncovmodel;k++){
                   5111:        /*      printf(" %le",delti3[i][j][k]); */
                   5112:        /*      fprintf(ficparo," %le",delti3[i][j][k]); */
                   5113:        printf(" 0.");
                   5114:        fprintf(ficparo," 0.");
                   5115:       }
                   5116:       numlinepar++;
                   5117:       printf("\n");
                   5118:       fprintf(ficparo,"\n");
                   5119:     }
                   5120:   }
                   5121:   printf("# Covariance matrix\n");
                   5122: /* # 121 Var(a12)\n\ */
                   5123: /* # 122 Cov(b12,a12) Var(b12)\n\ */
                   5124: /* # 131 Cov(a13,a12) Cov(a13,b12, Var(a13)\n\ */
                   5125: /* # 132 Cov(b13,a12) Cov(b13,b12, Cov(b13,a13) Var(b13)\n\ */
                   5126: /* # 212 Cov(a21,a12) Cov(a21,b12, Cov(a21,a13) Cov(a21,b13) Var(a21)\n\ */
                   5127: /* # 212 Cov(b21,a12) Cov(b21,b12, Cov(b21,a13) Cov(b21,b13) Cov(b21,a21) Var(b21)\n\ */
                   5128: /* # 232 Cov(a23,a12) Cov(a23,b12, Cov(a23,a13) Cov(a23,b13) Cov(a23,a21) Cov(a23,b21) Var(a23)\n\ */
                   5129: /* # 232 Cov(b23,a12) Cov(b23,b12) ... Var (b23)\n" */
                   5130:   fflush(stdout);
                   5131:   fprintf(ficparo,"# Covariance matrix\n");
                   5132:   /* # 121 Var(a12)\n\ */
                   5133:   /* # 122 Cov(b12,a12) Var(b12)\n\ */
                   5134:   /* #   ...\n\ */
                   5135:   /* # 232 Cov(b23,a12)  Cov(b23,b12) ... Var (b23)\n" */
                   5136:   
                   5137:   for(itimes=1;itimes<=2;itimes++){
                   5138:     jj=0;
                   5139:     for(i=1; i <=nlstate; i++){
                   5140:       for(j=1; j <=nlstate+ndeath; j++){
                   5141:        if(j==i) continue;
                   5142:        for(k=1; k<=ncovmodel;k++){
                   5143:          jj++;
                   5144:          ca[0]= k+'a'-1;ca[1]='\0';
                   5145:          if(itimes==1){
                   5146:            printf("#%1d%1d%d",i,j,k);
                   5147:            fprintf(ficparo,"#%1d%1d%d",i,j,k);
                   5148:          }else{
                   5149:            printf("%1d%1d%d",i,j,k);
                   5150:            fprintf(ficparo,"%1d%1d%d",i,j,k);
                   5151:            /*  printf(" %.5le",matcov[i][j]); */
                   5152:          }
                   5153:          ll=0;
                   5154:          for(li=1;li <=nlstate; li++){
                   5155:            for(lj=1;lj <=nlstate+ndeath; lj++){
                   5156:              if(lj==li) continue;
                   5157:              for(lk=1;lk<=ncovmodel;lk++){
                   5158:                ll++;
                   5159:                if(ll<=jj){
                   5160:                  cb[0]= lk +'a'-1;cb[1]='\0';
                   5161:                  if(ll<jj){
                   5162:                    if(itimes==1){
                   5163:                      printf(" Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
                   5164:                      fprintf(ficparo," Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
                   5165:                    }else{
                   5166:                      printf(" 0.");
                   5167:                      fprintf(ficparo," 0.");
                   5168:                    }
                   5169:                  }else{
                   5170:                    if(itimes==1){
                   5171:                      printf(" Var(%s%1d%1d)",ca,i,j);
                   5172:                      fprintf(ficparo," Var(%s%1d%1d)",ca,i,j);
                   5173:                    }else{
                   5174:                      printf(" 0.");
                   5175:                      fprintf(ficparo," 0.");
                   5176:                    }
                   5177:                  }
                   5178:                }
                   5179:              } /* end lk */
                   5180:            } /* end lj */
                   5181:          } /* end li */
                   5182:          printf("\n");
                   5183:          fprintf(ficparo,"\n");
                   5184:          numlinepar++;
                   5185:        } /* end k*/
                   5186:       } /*end j */
                   5187:     } /* end i */
                   5188:   } /* end itimes */
                   5189: 
                   5190: } /* end of prwizard */
                   5191: /******************* Gompertz Likelihood ******************************/
                   5192: double gompertz(double x[])
                   5193: { 
                   5194:   double A,B,L=0.0,sump=0.,num=0.;
                   5195:   int i,n=0; /* n is the size of the sample */
                   5196: 
                   5197:   for (i=0;i<=imx-1 ; i++) {
                   5198:     sump=sump+weight[i];
                   5199:     /*    sump=sump+1;*/
                   5200:     num=num+1;
                   5201:   }
                   5202:  
                   5203:  
                   5204:   /* for (i=0; i<=imx; i++) 
                   5205:      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]);*/
                   5206: 
                   5207:   for (i=1;i<=imx ; i++)
                   5208:     {
                   5209:       if (cens[i] == 1 && wav[i]>1)
                   5210:        A=-x[1]/(x[2])*(exp(x[2]*(agecens[i]-agegomp))-exp(x[2]*(ageexmed[i]-agegomp)));
                   5211:       
                   5212:       if (cens[i] == 0 && wav[i]>1)
                   5213:        A=-x[1]/(x[2])*(exp(x[2]*(agedc[i]-agegomp))-exp(x[2]*(ageexmed[i]-agegomp)))
                   5214:             +log(x[1]/YEARM)+x[2]*(agedc[i]-agegomp)+log(YEARM);  
                   5215:       
                   5216:       /*if (wav[i] > 1 && agecens[i] > 15) {*/ /* ??? */
                   5217:       if (wav[i] > 1 ) { /* ??? */
                   5218:        L=L+A*weight[i];
                   5219:        /*      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]);*/
                   5220:       }
                   5221:     }
                   5222: 
                   5223:  /*printf("x1=%2.9f x2=%2.9f x3=%2.9f L=%f\n",x[1],x[2],x[3],L);*/
                   5224:  
                   5225:   return -2*L*num/sump;
                   5226: }
                   5227: 
1.136     brouard  5228: #ifdef GSL
                   5229: /******************* Gompertz_f Likelihood ******************************/
                   5230: double gompertz_f(const gsl_vector *v, void *params)
                   5231: { 
                   5232:   double A,B,LL=0.0,sump=0.,num=0.;
                   5233:   double *x= (double *) v->data;
                   5234:   int i,n=0; /* n is the size of the sample */
                   5235: 
                   5236:   for (i=0;i<=imx-1 ; i++) {
                   5237:     sump=sump+weight[i];
                   5238:     /*    sump=sump+1;*/
                   5239:     num=num+1;
                   5240:   }
                   5241:  
                   5242:  
                   5243:   /* for (i=0; i<=imx; i++) 
                   5244:      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]);*/
                   5245:   printf("x[0]=%lf x[1]=%lf\n",x[0],x[1]);
                   5246:   for (i=1;i<=imx ; i++)
                   5247:     {
                   5248:       if (cens[i] == 1 && wav[i]>1)
                   5249:        A=-x[0]/(x[1])*(exp(x[1]*(agecens[i]-agegomp))-exp(x[1]*(ageexmed[i]-agegomp)));
                   5250:       
                   5251:       if (cens[i] == 0 && wav[i]>1)
                   5252:        A=-x[0]/(x[1])*(exp(x[1]*(agedc[i]-agegomp))-exp(x[1]*(ageexmed[i]-agegomp)))
                   5253:             +log(x[0]/YEARM)+x[1]*(agedc[i]-agegomp)+log(YEARM);  
                   5254:       
                   5255:       /*if (wav[i] > 1 && agecens[i] > 15) {*/ /* ??? */
                   5256:       if (wav[i] > 1 ) { /* ??? */
                   5257:        LL=LL+A*weight[i];
                   5258:        /*      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]);*/
                   5259:       }
                   5260:     }
                   5261: 
                   5262:  /*printf("x1=%2.9f x2=%2.9f x3=%2.9f L=%f\n",x[1],x[2],x[3],L);*/
                   5263:   printf("x[0]=%lf x[1]=%lf -2*LL*num/sump=%lf\n",x[0],x[1],-2*LL*num/sump);
                   5264:  
                   5265:   return -2*LL*num/sump;
                   5266: }
                   5267: #endif
                   5268: 
1.126     brouard  5269: /******************* Printing html file ***********/
                   5270: void printinghtmlmort(char fileres[], char title[], char datafile[], int firstpass, \
                   5271:                  int lastpass, int stepm, int weightopt, char model[],\
                   5272:                  int imx,  double p[],double **matcov,double agemortsup){
                   5273:   int i,k;
                   5274: 
                   5275:   fprintf(fichtm,"<ul><li><h4>Result files </h4>\n Force of mortality. Parameters of the Gompertz fit (with confidence interval in brackets):<br>");
                   5276:   fprintf(fichtm,"  mu(age) =%lf*exp(%lf*(age-%d)) per year<br><br>",p[1],p[2],agegomp);
                   5277:   for (i=1;i<=2;i++) 
                   5278:     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]));
                   5279:   fprintf(fichtm,"<br><br><img src=\"graphmort.png\">");
                   5280:   fprintf(fichtm,"</ul>");
                   5281: 
                   5282: fprintf(fichtm,"<ul><li><h4>Life table</h4>\n <br>");
                   5283: 
                   5284:  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>");
                   5285: 
                   5286:  for (k=agegomp;k<(agemortsup-2);k++) 
                   5287:    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]);
                   5288: 
                   5289:  
                   5290:   fflush(fichtm);
                   5291: }
                   5292: 
                   5293: /******************* Gnuplot file **************/
                   5294: void printinggnuplotmort(char fileres[], char optionfilefiname[], double ageminpar, double agemaxpar, double fage , char pathc[], double p[]){
                   5295: 
                   5296:   char dirfileres[132],optfileres[132];
1.164     brouard  5297: 
1.126     brouard  5298:   int ng;
                   5299: 
                   5300: 
                   5301:   /*#ifdef windows */
                   5302:   fprintf(ficgp,"cd \"%s\" \n",pathc);
                   5303:     /*#endif */
                   5304: 
                   5305: 
                   5306:   strcpy(dirfileres,optionfilefiname);
                   5307:   strcpy(optfileres,"vpl");
                   5308:   fprintf(ficgp,"set out \"graphmort.png\"\n "); 
                   5309:   fprintf(ficgp,"set xlabel \"Age\"\n set ylabel \"Force of mortality (per year)\" \n "); 
1.145     brouard  5310:   fprintf(ficgp, "set ter png small size 320, 240\n set log y\n"); 
                   5311:   /* fprintf(ficgp, "set size 0.65,0.65\n"); */
1.126     brouard  5312:   fprintf(ficgp,"plot [%d:100] %lf*exp(%lf*(x-%d))",agegomp,p[1],p[2],agegomp);
                   5313: 
                   5314: } 
                   5315: 
1.136     brouard  5316: int readdata(char datafile[], int firstobs, int lastobs, int *imax)
                   5317: {
1.126     brouard  5318: 
1.136     brouard  5319:   /*-------- data file ----------*/
                   5320:   FILE *fic;
                   5321:   char dummy[]="                         ";
1.164     brouard  5322:   int i=0, j=0, n=0;
1.136     brouard  5323:   int linei, month, year,iout;
                   5324:   char line[MAXLINE], linetmp[MAXLINE];
1.164     brouard  5325:   char stra[MAXLINE], strb[MAXLINE];
1.136     brouard  5326:   char *stratrunc;
                   5327:   int lstra;
1.126     brouard  5328: 
                   5329: 
1.136     brouard  5330:   if((fic=fopen(datafile,"r"))==NULL)    {
                   5331:     printf("Problem while opening datafile: %s\n", datafile);return 1;
                   5332:     fprintf(ficlog,"Problem while opening datafile: %s\n", datafile);return 1;
                   5333:   }
1.126     brouard  5334: 
1.136     brouard  5335:   i=1;
                   5336:   linei=0;
                   5337:   while ((fgets(line, MAXLINE, fic) != NULL) &&((i >= firstobs) && (i <=lastobs))) {
                   5338:     linei=linei+1;
                   5339:     for(j=strlen(line); j>=0;j--){  /* Untabifies line */
                   5340:       if(line[j] == '\t')
                   5341:        line[j] = ' ';
                   5342:     }
                   5343:     for(j=strlen(line)-1; (line[j]==' ')||(line[j]==10)||(line[j]==13);j--){
                   5344:       ;
                   5345:     };
                   5346:     line[j+1]=0;  /* Trims blanks at end of line */
                   5347:     if(line[0]=='#'){
                   5348:       fprintf(ficlog,"Comment line\n%s\n",line);
                   5349:       printf("Comment line\n%s\n",line);
                   5350:       continue;
                   5351:     }
                   5352:     trimbb(linetmp,line); /* Trims multiple blanks in line */
1.164     brouard  5353:     strcpy(line, linetmp);
1.136     brouard  5354:   
1.126     brouard  5355: 
1.136     brouard  5356:     for (j=maxwav;j>=1;j--){
1.137     brouard  5357:       cutv(stra, strb, line, ' '); 
1.136     brouard  5358:       if(strb[0]=='.') { /* Missing status */
                   5359:        lval=-1;
                   5360:       }else{
                   5361:        errno=0;
                   5362:        lval=strtol(strb,&endptr,10); 
                   5363:       /*       if (errno == ERANGE && (lval == LONG_MAX || lval == LONG_MIN))*/
                   5364:        if( strb[0]=='\0' || (*endptr != '\0')){
1.141     brouard  5365:          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);
                   5366:          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  5367:          return 1;
                   5368:        }
                   5369:       }
                   5370:       s[j][i]=lval;
                   5371:       
                   5372:       strcpy(line,stra);
                   5373:       cutv(stra, strb,line,' ');
1.169     brouard  5374:       if( (iout=sscanf(strb,"%d/%d",&month, &year)) != 0){
1.136     brouard  5375:       }
1.169     brouard  5376:       else  if( (iout=sscanf(strb,"%s.",dummy)) != 0){
1.136     brouard  5377:        month=99;
                   5378:        year=9999;
                   5379:       }else{
1.141     brouard  5380:        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);
                   5381:        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  5382:        return 1;
                   5383:       }
                   5384:       anint[j][i]= (double) year; 
                   5385:       mint[j][i]= (double)month; 
                   5386:       strcpy(line,stra);
                   5387:     } /* ENd Waves */
                   5388:     
                   5389:     cutv(stra, strb,line,' '); 
1.169     brouard  5390:     if( (iout=sscanf(strb,"%d/%d",&month, &year)) != 0){
1.136     brouard  5391:     }
1.169     brouard  5392:     else  if( (iout=sscanf(strb,"%s.",dummy)) != 0){
1.136     brouard  5393:       month=99;
                   5394:       year=9999;
                   5395:     }else{
1.141     brouard  5396:       printf("Error reading data around '%s' at line number %d for individual %d, '%s'\nShould be a date of death (mm/yyyy or .).  Exiting.\n",strb, linei,i,line);
                   5397:        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  5398:        return 1;
                   5399:     }
                   5400:     andc[i]=(double) year; 
                   5401:     moisdc[i]=(double) month; 
                   5402:     strcpy(line,stra);
                   5403:     
                   5404:     cutv(stra, strb,line,' '); 
1.169     brouard  5405:     if( (iout=sscanf(strb,"%d/%d",&month, &year)) != 0){
1.136     brouard  5406:     }
1.169     brouard  5407:     else  if( (iout=sscanf(strb,"%s.", dummy)) != 0){
1.136     brouard  5408:       month=99;
                   5409:       year=9999;
                   5410:     }else{
1.141     brouard  5411:       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);
                   5412:       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  5413:        return 1;
                   5414:     }
                   5415:     if (year==9999) {
1.141     brouard  5416:       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);
                   5417:       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  5418:        return 1;
1.126     brouard  5419: 
1.136     brouard  5420:     }
                   5421:     annais[i]=(double)(year);
                   5422:     moisnais[i]=(double)(month); 
                   5423:     strcpy(line,stra);
                   5424:     
                   5425:     cutv(stra, strb,line,' '); 
                   5426:     errno=0;
                   5427:     dval=strtod(strb,&endptr); 
                   5428:     if( strb[0]=='\0' || (*endptr != '\0')){
1.141     brouard  5429:       printf("Error reading data around '%f' at line number %d, \"%s\" for individual %d\nShould be a weight.  Exiting.\n",dval, i,line,linei);
                   5430:       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  5431:       fflush(ficlog);
                   5432:       return 1;
                   5433:     }
                   5434:     weight[i]=dval; 
                   5435:     strcpy(line,stra);
                   5436:     
                   5437:     for (j=ncovcol;j>=1;j--){
                   5438:       cutv(stra, strb,line,' '); 
                   5439:       if(strb[0]=='.') { /* Missing status */
                   5440:        lval=-1;
                   5441:       }else{
                   5442:        errno=0;
                   5443:        lval=strtol(strb,&endptr,10); 
                   5444:        if( strb[0]=='\0' || (*endptr != '\0')){
1.141     brouard  5445:          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);
                   5446:          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  5447:          return 1;
                   5448:        }
                   5449:       }
                   5450:       if(lval <-1 || lval >1){
1.141     brouard  5451:        printf("Error reading data around '%ld' at line number %d for individual %d, '%s'\n \
1.136     brouard  5452:  Should be a value of %d(nth) covariate (0 should be the value for the reference and 1\n \
                   5453:  for the alternative. IMaCh does not build design variables automatically, do it yourself.\n \
                   5454:  For example, for multinomial values like 1, 2 and 3,\n \
                   5455:  build V1=0 V2=0 for the reference value (1),\n \
                   5456:         V1=1 V2=0 for (2) \n \
                   5457:  and V1=0 V2=1 for (3). V1=1 V2=1 should not exist and the corresponding\n \
                   5458:  output of IMaCh is often meaningless.\n \
                   5459:  Exiting.\n",lval,linei, i,line,j);
1.141     brouard  5460:        fprintf(ficlog,"Error reading data around '%ld' at line number %d for individual %d, '%s'\n \
1.136     brouard  5461:  Should be a value of %d(nth) covariate (0 should be the value for the reference and 1\n \
                   5462:  for the alternative. IMaCh does not build design variables automatically, do it yourself.\n \
                   5463:  For example, for multinomial values like 1, 2 and 3,\n \
                   5464:  build V1=0 V2=0 for the reference value (1),\n \
                   5465:         V1=1 V2=0 for (2) \n \
                   5466:  and V1=0 V2=1 for (3). V1=1 V2=1 should not exist and the corresponding\n \
                   5467:  output of IMaCh is often meaningless.\n \
                   5468:  Exiting.\n",lval,linei, i,line,j);fflush(ficlog);
                   5469:        return 1;
                   5470:       }
                   5471:       covar[j][i]=(double)(lval);
                   5472:       strcpy(line,stra);
                   5473:     }  
                   5474:     lstra=strlen(stra);
                   5475:      
                   5476:     if(lstra > 9){ /* More than 2**32 or max of what printf can write with %ld */
                   5477:       stratrunc = &(stra[lstra-9]);
                   5478:       num[i]=atol(stratrunc);
                   5479:     }
                   5480:     else
                   5481:       num[i]=atol(stra);
                   5482:     /*if((s[2][i]==2) && (s[3][i]==-1)&&(s[4][i]==9)){
                   5483:       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;}*/
                   5484:     
                   5485:     i=i+1;
                   5486:   } /* End loop reading  data */
1.126     brouard  5487: 
1.136     brouard  5488:   *imax=i-1; /* Number of individuals */
                   5489:   fclose(fic);
                   5490:  
                   5491:   return (0);
1.164     brouard  5492:   /* endread: */
1.136     brouard  5493:     printf("Exiting readdata: ");
                   5494:     fclose(fic);
                   5495:     return (1);
1.126     brouard  5496: 
                   5497: 
                   5498: 
1.136     brouard  5499: }
1.145     brouard  5500: void removespace(char *str) {
                   5501:   char *p1 = str, *p2 = str;
                   5502:   do
                   5503:     while (*p2 == ' ')
                   5504:       p2++;
1.169     brouard  5505:   while (*p1++ == *p2++);
1.145     brouard  5506: }
                   5507: 
                   5508: int decodemodel ( char model[], int lastobs) /**< This routine decode the model and returns:
1.187   ! brouard  5509:    * Model  V1+V2+V3+V8+V7*V8+V5*V6+V8*age+V3*age+age*age
        !          5510:    * - nagesqr = 1 if age*age in the model, otherwise 0.
        !          5511:    * - cptcovt total number of covariates of the model nbocc(+)+1 = 8 excepting constant and age and age*age
        !          5512:    * - cptcovn or number of covariates k of the models excluding age*products =6 and age*age
1.145     brouard  5513:    * - cptcovage number of covariates with age*products =2
                   5514:    * - cptcovs number of simple covariates
                   5515:    * - 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
                   5516:    *     which is a new column after the 9 (ncovcol) variables. 
                   5517:    * - if k is a product Vn*Vm covar[k][i] is filled with correct values for each individual
                   5518:    * - Tprod[l] gives the kth covariates of the product Vn*Vm l=1 to cptcovprod-cptcovage
                   5519:    *    Tprod[1]@2 {5, 6}: position of first product V7*V8 is 5, and second V5*V6 is 6.
                   5520:    * - Tvard[k]  p Tvard[1][1]@4 {7, 8, 5, 6} for V7*V8 and V5*V6 .
                   5521:  */
1.136     brouard  5522: {
1.145     brouard  5523:   int i, j, k, ks;
1.164     brouard  5524:   int  j1, k1, k2;
1.136     brouard  5525:   char modelsav[80];
1.145     brouard  5526:   char stra[80], strb[80], strc[80], strd[80],stre[80];
1.187   ! brouard  5527:   char *strpt;
1.136     brouard  5528: 
1.145     brouard  5529:   /*removespace(model);*/
1.136     brouard  5530:   if (strlen(model) >1){ /* If there is at least 1 covariate */
1.145     brouard  5531:     j=0, j1=0, k1=0, k2=-1, ks=0, cptcovn=0;
1.137     brouard  5532:     if (strstr(model,"AGE") !=0){
1.187   ! brouard  5533:       printf("Error. AGE must be in lower case 'age' model=1+age+%s ",model);
        !          5534:       fprintf(ficlog,"Error. AGE must be in lower case model=1+age+%s ",model);fflush(ficlog);
1.136     brouard  5535:       return 1;
                   5536:     }
1.141     brouard  5537:     if (strstr(model,"v") !=0){
                   5538:       printf("Error. 'v' must be in upper case 'V' model=%s ",model);
                   5539:       fprintf(ficlog,"Error. 'v' must be in upper case model=%s ",model);fflush(ficlog);
                   5540:       return 1;
                   5541:     }
1.187   ! brouard  5542:     strcpy(modelsav,model); 
        !          5543:     if ((strpt=strstr(model,"age*age")) !=0){
        !          5544:       printf(" strpt=%s, model=%s\n",strpt, model);
        !          5545:       if(strpt != model){
        !          5546:       printf("Error in model: 'model=%s'; 'age*age' should in first place before other covariates\n \
        !          5547:  'model=1+age+age*age+V1' or 'model=1+age+age*age+V1+V1*age', please swap as well as \n \
        !          5548:  corresponding column of parameters.\n",model);
        !          5549:       fprintf(ficlog,"Error in model: 'model=%s'; 'age*age' should in first place before other covariates\n \
        !          5550:  'model=1+age+age*age+V1' or 'model=1+age+age*age+V1+V1*age', please swap as well as \n \
        !          5551:  corresponding column of parameters.\n",model); fflush(ficlog);
        !          5552:       return 1;
        !          5553:     }
        !          5554: 
        !          5555:       nagesqr=1;
        !          5556:       if (strstr(model,"+age*age") !=0)
        !          5557:        substrchaine(modelsav, model, "+age*age");
        !          5558:       else if (strstr(model,"age*age+") !=0)
        !          5559:        substrchaine(modelsav, model, "age*age+");
        !          5560:       else 
        !          5561:        substrchaine(modelsav, model, "age*age");
        !          5562:     }else
        !          5563:       nagesqr=0;
        !          5564:     if (strlen(modelsav) >1){
        !          5565:       j=nbocc(modelsav,'+'); /**< j=Number of '+' */
        !          5566:       j1=nbocc(modelsav,'*'); /**< j1=Number of '*' */
        !          5567:       cptcovs=j+1-j1; /**<  Number of simple covariates V1+V1*age+V3 +V3*V4+age*age=> V1 + V3 =2  */
        !          5568:       cptcovt= j+1; /* Number of total covariates in the model, not including
        !          5569:                   * cst, age and age*age 
        !          5570:                   * V1+V1*age+ V3 + V3*V4+age*age=> 4*/
        !          5571:                   /* including age products which are counted in cptcovage.
        !          5572:                  * but the covariates which are products must be treated 
        !          5573:                  * separately: ncovn=4- 2=2 (V1+V3). */
        !          5574:       cptcovprod=j1; /**< Number of products  V1*V2 +v3*age = 2 */
        !          5575:       cptcovprodnoage=0; /**< Number of covariate products without age: V3*V4 =1  */
        !          5576: 
        !          5577:     
        !          5578:       /*   Design
        !          5579:        *  V1   V2   V3   V4  V5  V6  V7  V8  V9 Weight
        !          5580:        *  <          ncovcol=8                >
        !          5581:        * Model V2 + V1 + V3*age + V3 + V5*V6 + V7*V8 + V8*age + V8
        !          5582:        *   k=  1    2      3       4     5       6      7        8
        !          5583:        *  cptcovn number of covariates (not including constant and age ) = # of + plus 1 = 7+1=8
        !          5584:        *  covar[k,i], value of kth covariate if not including age for individual i:
        !          5585:        *       covar[1][i]= (V2), covar[4][i]=(V3), covar[8][i]=(V8)
        !          5586:        *  Tvar[k] # of the kth covariate:  Tvar[1]=2  Tvar[4]=3 Tvar[8]=8
        !          5587:        *       if multiplied by age: V3*age Tvar[3=V3*age]=3 (V3) Tvar[7]=8 and 
        !          5588:        *  Tage[++cptcovage]=k
        !          5589:        *       if products, new covar are created after ncovcol with k1
        !          5590:        *  Tvar[k]=ncovcol+k1; # of the kth covariate product:  Tvar[5]=ncovcol+1=10  Tvar[6]=ncovcol+1=11
        !          5591:        *  Tprod[k1]=k; Tprod[1]=5 Tprod[2]= 6; gives the position of the k1th product
        !          5592:        *  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
        !          5593:        *  Tvar[cptcovn+k2]=Tvard[k1][1];Tvar[cptcovn+k2+1]=Tvard[k1][2];
        !          5594:        *  Tvar[8+1]=5;Tvar[8+2]=6;Tvar[8+3]=7;Tvar[8+4]=8 inverted
        !          5595:        *  V1   V2   V3   V4  V5  V6  V7  V8  V9  V10  V11
        !          5596:        *  <          ncovcol=8                >
        !          5597:        *       Model V2 + V1 + V3*age + V3 + V5*V6 + V7*V8 + V8*age + V8    d1   d1   d2  d2
        !          5598:        *          k=  1    2      3       4     5       6      7        8    9   10   11  12
        !          5599:        *     Tvar[k]= 2    1      3       3    10      11      8        8    5    6    7   8
        !          5600:        * p Tvar[1]@12={2,   1,     3,      3,   11,     10,     8,       8,   7,   8,   5,  6}
        !          5601:        * p Tprod[1]@2={                         6, 5}
        !          5602:        *p Tvard[1][1]@4= {7, 8, 5, 6}
        !          5603:        * covar[k][i]= V2   V1      ?      V3    V5*V6?   V7*V8?  ?       V8   
        !          5604:        *  cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*cov[2];
        !          5605:        *How to reorganize?
        !          5606:        * Model V1 + V2 + V3 + V8 + V5*V6 + V7*V8 + V3*age + V8*age
        !          5607:        * Tvars {2,   1,     3,      3,   11,     10,     8,       8,   7,   8,   5,  6}
        !          5608:        *       {2,   1,     4,      8,    5,      6,     3,       7}
        !          5609:        * Struct []
        !          5610:        */
1.145     brouard  5611: 
1.187   ! brouard  5612:       /* This loop fills the array Tvar from the string 'model'.*/
        !          5613:       /* j is the number of + signs in the model V1+V2+V3 j=2 i=3 to 1 */
        !          5614:       /*   modelsav=V2+V1+V4+age*V3 strb=age*V3 stra=V2+V1+V4  */
        !          5615:       /*       k=4 (age*V3) Tvar[k=4]= 3 (from V3) Tage[cptcovage=1]=4 */
        !          5616:       /*       k=3 V4 Tvar[k=3]= 4 (from V4) */
        !          5617:       /*       k=2 V1 Tvar[k=2]= 1 (from V1) */
        !          5618:       /*       k=1 Tvar[1]=2 (from V2) */
        !          5619:       /*       k=5 Tvar[5] */
        !          5620:       /* for (k=1; k<=cptcovn;k++) { */
        !          5621:       /*       cov[2+k]=nbcode[Tvar[k]][codtab[ij][Tvar[k]]]; */
        !          5622:       /*       } */
        !          5623:       /* for (k=1; k<=cptcovage;k++) cov[2+Tage[k]]=nbcode[Tvar[Tage[k]]][codtab[ij][Tvar[Tage[k]]]]*cov[2]; */
        !          5624:       /*
        !          5625:        * Treating invertedly V2+V1+V3*age+V2*V4 is as if written V2*V4 +V3*age + V1 + V2 */
        !          5626:       for(k=cptcovt; k>=1;k--) /**< Number of covariates */
1.145     brouard  5627:         Tvar[k]=0;
1.187   ! brouard  5628:       cptcovage=0;
        !          5629:       for(k=1; k<=cptcovt;k++){ /* Loop on total covariates of the model */
        !          5630:        cutl(stra,strb,modelsav,'+'); /* keeps in strb after the first '+' 
        !          5631:                                         modelsav==V2+V1+V4+V3*age strb=V3*age stra=V2+V1+V4 */ 
        !          5632:        if (nbocc(modelsav,'+')==0) strcpy(strb,modelsav); /* and analyzes it */
        !          5633:        /*      printf("i=%d a=%s b=%s sav=%s\n",i, stra,strb,modelsav);*/
        !          5634:        /*scanf("%d",i);*/
        !          5635:        if (strchr(strb,'*')) {  /**< Model includes a product V2+V1+V4+V3*age strb=V3*age */
        !          5636:          cutl(strc,strd,strb,'*'); /**< strd*strc  Vm*Vn: strb=V3*age(input) strc=age strd=V3 ; V3*V2 strc=V2, strd=V3 */
        !          5637:          if (strcmp(strc,"age")==0) { /**< Model includes age: Vn*age */
        !          5638:            /* covar is not filled and then is empty */
        !          5639:            cptcovprod--;
        !          5640:            cutl(stre,strb,strd,'V'); /* strd=V3(input): stre="3" */
        !          5641:            Tvar[k]=atoi(stre);  /* V2+V1+V4+V3*age Tvar[4]=3 ; V1+V2*age Tvar[2]=2; V1+V1*age Tvar[2]=1 */
        !          5642:            cptcovage++; /* Sums the number of covariates which include age as a product */
        !          5643:            Tage[cptcovage]=k;  /* Tvar[4]=3, Tage[1] = 4 or V1+V1*age Tvar[2]=1, Tage[1]=2 */
        !          5644:            /*printf("stre=%s ", stre);*/
        !          5645:          } else if (strcmp(strd,"age")==0) { /* or age*Vn */
        !          5646:            cptcovprod--;
        !          5647:            cutl(stre,strb,strc,'V');
        !          5648:            Tvar[k]=atoi(stre);
        !          5649:            cptcovage++;
        !          5650:            Tage[cptcovage]=k;
        !          5651:          } else {  /* Age is not in the model product V2+V1+V1*V4+V3*age+V3*V2  strb=V3*V2*/
        !          5652:            /* loops on k1=1 (V3*V2) and k1=2 V4*V3 */
        !          5653:            cptcovn++;
        !          5654:            cptcovprodnoage++;k1++;
        !          5655:            cutl(stre,strb,strc,'V'); /* strc= Vn, stre is n; strb=V3*V2 stre=3 strc=*/
        !          5656:            Tvar[k]=ncovcol+k1; /* For model-covariate k tells which data-covariate to use but
        !          5657:                                   because this model-covariate is a construction we invent a new column
        !          5658:                                   ncovcol + k1
        !          5659:                                   If already ncovcol=4 and model=V2+V1+V1*V4+age*V3+V3*V2
        !          5660:                                   Tvar[3=V1*V4]=4+1 Tvar[5=V3*V2]=4 + 2= 6, etc */
        !          5661:            cutl(strc,strb,strd,'V'); /* strd was Vm, strc is m */
        !          5662:            Tprod[k1]=k;  /* Tprod[1]=3(=V1*V4) for V2+V1+V1*V4+age*V3+V3*V2  */
        !          5663:            Tvard[k1][1] =atoi(strc); /* m 1 for V1*/
        !          5664:            Tvard[k1][2] =atoi(stre); /* n 4 for V4*/
        !          5665:            k2=k2+2;
        !          5666:            Tvar[cptcovt+k2]=Tvard[k1][1]; /* Tvar[(cptcovt=4+k2=1)=5]= 1 (V1) */
        !          5667:            Tvar[cptcovt+k2+1]=Tvard[k1][2];  /* Tvar[(cptcovt=4+(k2=1)+1)=6]= 4 (V4) */
        !          5668:            for (i=1; i<=lastobs;i++){
        !          5669:              /* Computes the new covariate which is a product of
        !          5670:                 covar[n][i]* covar[m][i] and stores it at ncovol+k1 May not be defined */
        !          5671:              covar[ncovcol+k1][i]=covar[atoi(stre)][i]*covar[atoi(strc)][i];
        !          5672:            }
        !          5673:          } /* End age is not in the model */
        !          5674:        } /* End if model includes a product */
        !          5675:        else { /* no more sum */
        !          5676:          /*printf("d=%s c=%s b=%s\n", strd,strc,strb);*/
        !          5677:          /*  scanf("%d",i);*/
        !          5678:          cutl(strd,strc,strb,'V');
        !          5679:          ks++; /**< Number of simple covariates */
1.145     brouard  5680:          cptcovn++;
1.187   ! brouard  5681:          Tvar[k]=atoi(strd);
        !          5682:        }
        !          5683:        strcpy(modelsav,stra);  /* modelsav=V2+V1+V4 stra=V2+V1+V4 */ 
        !          5684:        /*printf("a=%s b=%s sav=%s\n", stra,strb,modelsav);
        !          5685:          scanf("%d",i);*/
        !          5686:       } /* end of loop + on total covariates */
        !          5687:     } /* end if strlen(modelsave == 0) age*age might exist */
        !          5688:   } /* end if strlen(model == 0) */
1.136     brouard  5689:   
                   5690:   /*The number n of Vn is stored in Tvar. cptcovage =number of age covariate. Tage gives the position of age. cptcovprod= number of products.
                   5691:     If model=V1+V1*age then Tvar[1]=1 Tvar[2]=1 cptcovage=1 Tage[1]=2 cptcovprod=0*/
                   5692: 
                   5693:   /* printf("tvar1=%d tvar2=%d tvar3=%d cptcovage=%d Tage=%d",Tvar[1],Tvar[2],Tvar[3],cptcovage,Tage[1]);
                   5694:   printf("cptcovprod=%d ", cptcovprod);
                   5695:   fprintf(ficlog,"cptcovprod=%d ", cptcovprod);
                   5696: 
                   5697:   scanf("%d ",i);*/
                   5698: 
                   5699: 
1.137     brouard  5700:   return (0); /* with covar[new additional covariate if product] and Tage if age */ 
1.164     brouard  5701:   /*endread:*/
1.136     brouard  5702:     printf("Exiting decodemodel: ");
                   5703:     return (1);
                   5704: }
                   5705: 
1.169     brouard  5706: int calandcheckages(int imx, int maxwav, double *agemin, double *agemax, int *nberr, int *nbwarn )
1.136     brouard  5707: {
                   5708:   int i, m;
                   5709: 
                   5710:   for (i=1; i<=imx; i++) {
                   5711:     for(m=2; (m<= maxwav); m++) {
                   5712:       if (((int)mint[m][i]== 99) && (s[m][i] <= nlstate)){
                   5713:        anint[m][i]=9999;
                   5714:        s[m][i]=-1;
                   5715:       }
                   5716:       if((int)moisdc[i]==99 && (int)andc[i]==9999 && s[m][i]>nlstate){
1.169     brouard  5717:        *nberr = *nberr + 1;
                   5718:        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);
                   5719:        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  5720:        s[m][i]=-1;
                   5721:       }
                   5722:       if((int)moisdc[i]==99 && (int)andc[i]!=9999 && s[m][i]>nlstate){
1.169     brouard  5723:        (*nberr)++;
1.136     brouard  5724:        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]); 
                   5725:        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]); 
                   5726:        s[m][i]=-1; /* We prefer to skip it (and to skip it in version 0.8a1 too */
                   5727:       }
                   5728:     }
                   5729:   }
                   5730: 
                   5731:   for (i=1; i<=imx; i++)  {
                   5732:     agedc[i]=(moisdc[i]/12.+andc[i])-(moisnais[i]/12.+annais[i]);
                   5733:     for(m=firstpass; (m<= lastpass); m++){
                   5734:       if(s[m][i] >0 || s[m][i]==-2 || s[m][i]==-4 || s[m][i]==-5){
                   5735:        if (s[m][i] >= nlstate+1) {
1.169     brouard  5736:          if(agedc[i]>0){
                   5737:            if((int)moisdc[i]!=99 && (int)andc[i]!=9999){
1.136     brouard  5738:              agev[m][i]=agedc[i];
                   5739:          /*if(moisdc[i]==99 && andc[i]==9999) s[m][i]=-1;*/
1.169     brouard  5740:            }else {
1.136     brouard  5741:              if ((int)andc[i]!=9999){
                   5742:                nbwarn++;
                   5743:                printf("Warning negative age at death: %ld line:%d\n",num[i],i);
                   5744:                fprintf(ficlog,"Warning negative age at death: %ld line:%d\n",num[i],i);
                   5745:                agev[m][i]=-1;
                   5746:              }
                   5747:            }
1.169     brouard  5748:          } /* agedc > 0 */
1.136     brouard  5749:        }
                   5750:        else if(s[m][i] !=9){ /* Standard case, age in fractional
                   5751:                                 years but with the precision of a month */
                   5752:          agev[m][i]=(mint[m][i]/12.+1./24.+anint[m][i])-(moisnais[i]/12.+1./24.+annais[i]);
                   5753:          if((int)mint[m][i]==99 || (int)anint[m][i]==9999)
                   5754:            agev[m][i]=1;
                   5755:          else if(agev[m][i] < *agemin){ 
                   5756:            *agemin=agev[m][i];
                   5757:            printf(" Min anint[%d][%d]=%.2f annais[%d]=%.2f, agemin=%.2f\n",m,i,anint[m][i], i,annais[i], *agemin);
                   5758:          }
                   5759:          else if(agev[m][i] >*agemax){
                   5760:            *agemax=agev[m][i];
1.156     brouard  5761:            /* printf(" Max anint[%d][%d]=%.0f annais[%d]=%.0f, agemax=%.2f\n",m,i,anint[m][i], i,annais[i], *agemax);*/
1.136     brouard  5762:          }
                   5763:          /*agev[m][i]=anint[m][i]-annais[i];*/
                   5764:          /*     agev[m][i] = age[i]+2*m;*/
                   5765:        }
                   5766:        else { /* =9 */
                   5767:          agev[m][i]=1;
                   5768:          s[m][i]=-1;
                   5769:        }
                   5770:       }
                   5771:       else /*= 0 Unknown */
                   5772:        agev[m][i]=1;
                   5773:     }
                   5774:     
                   5775:   }
                   5776:   for (i=1; i<=imx; i++)  {
                   5777:     for(m=firstpass; (m<=lastpass); m++){
                   5778:       if (s[m][i] > (nlstate+ndeath)) {
1.169     brouard  5779:        (*nberr)++;
1.136     brouard  5780:        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);     
                   5781:        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);     
                   5782:        return 1;
                   5783:       }
                   5784:     }
                   5785:   }
                   5786: 
                   5787:   /*for (i=1; i<=imx; i++){
                   5788:   for (m=firstpass; (m<lastpass); m++){
                   5789:      printf("%ld %d %.lf %d %d\n", num[i],(covar[1][i]),agev[m][i],s[m][i],s[m+1][i]);
                   5790: }
                   5791: 
                   5792: }*/
                   5793: 
                   5794: 
1.139     brouard  5795:   printf("Total number of individuals= %d, Agemin = %.2f, Agemax= %.2f\n\n", imx, *agemin, *agemax);
                   5796:   fprintf(ficlog,"Total number of individuals= %d, Agemin = %.2f, Agemax= %.2f\n\n", imx, *agemin, *agemax); 
1.136     brouard  5797: 
                   5798:   return (0);
1.164     brouard  5799:  /* endread:*/
1.136     brouard  5800:     printf("Exiting calandcheckages: ");
                   5801:     return (1);
                   5802: }
                   5803: 
1.172     brouard  5804: #if defined(_MSC_VER)
                   5805: /*printf("Visual C++ compiler: %s \n;", _MSC_FULL_VER);*/
                   5806: /*fprintf(ficlog, "Visual C++ compiler: %s \n;", _MSC_FULL_VER);*/
                   5807: //#include "stdafx.h"
                   5808: //#include <stdio.h>
                   5809: //#include <tchar.h>
                   5810: //#include <windows.h>
                   5811: //#include <iostream>
                   5812: typedef BOOL(WINAPI *LPFN_ISWOW64PROCESS) (HANDLE, PBOOL);
                   5813: 
                   5814: LPFN_ISWOW64PROCESS fnIsWow64Process;
                   5815: 
                   5816: BOOL IsWow64()
                   5817: {
                   5818:        BOOL bIsWow64 = FALSE;
                   5819: 
                   5820:        //typedef BOOL (APIENTRY *LPFN_ISWOW64PROCESS)
                   5821:        //  (HANDLE, PBOOL);
                   5822: 
                   5823:        //LPFN_ISWOW64PROCESS fnIsWow64Process;
                   5824: 
                   5825:        HMODULE module = GetModuleHandle(_T("kernel32"));
                   5826:        const char funcName[] = "IsWow64Process";
                   5827:        fnIsWow64Process = (LPFN_ISWOW64PROCESS)
                   5828:                GetProcAddress(module, funcName);
                   5829: 
                   5830:        if (NULL != fnIsWow64Process)
                   5831:        {
                   5832:                if (!fnIsWow64Process(GetCurrentProcess(),
                   5833:                        &bIsWow64))
                   5834:                        //throw std::exception("Unknown error");
                   5835:                        printf("Unknown error\n");
                   5836:        }
                   5837:        return bIsWow64 != FALSE;
                   5838: }
                   5839: #endif
1.177     brouard  5840: 
1.169     brouard  5841: void syscompilerinfo()
1.167     brouard  5842:  {
                   5843:    /* #include "syscompilerinfo.h"*/
1.185     brouard  5844:    /* command line Intel compiler 32bit windows, XP compatible:*/
                   5845:    /* /GS /W3 /Gy
                   5846:       /Zc:wchar_t /Zi /O2 /Fd"Release\vc120.pdb" /D "WIN32" /D "NDEBUG" /D
                   5847:       "_CONSOLE" /D "_LIB" /D "_USING_V110_SDK71_" /D "_UNICODE" /D
                   5848:       "UNICODE" /Qipo /Zc:forScope /Gd /Oi /MT /Fa"Release\" /EHsc /nologo
1.186     brouard  5849:       /Fo"Release\" /Qprof-dir "Release\" /Fp"Release\IMaCh.pch"
                   5850:    */ 
                   5851:    /* 64 bits */
1.185     brouard  5852:    /*
                   5853:      /GS /W3 /Gy
                   5854:      /Zc:wchar_t /Zi /O2 /Fd"x64\Release\vc120.pdb" /D "WIN32" /D "NDEBUG"
                   5855:      /D "_CONSOLE" /D "_LIB" /D "_UNICODE" /D "UNICODE" /Qipo /Zc:forScope
                   5856:      /Oi /MD /Fa"x64\Release\" /EHsc /nologo /Fo"x64\Release\" /Qprof-dir
                   5857:      "x64\Release\" /Fp"x64\Release\IMaCh.pch" */
                   5858:    /* Optimization are useless and O3 is slower than O2 */
                   5859:    /*
                   5860:      /GS /W3 /Gy /Zc:wchar_t /Zi /O3 /Fd"x64\Release\vc120.pdb" /D "WIN32" 
                   5861:      /D "NDEBUG" /D "_CONSOLE" /D "_LIB" /D "_UNICODE" /D "UNICODE" /Qipo 
                   5862:      /Zc:forScope /Oi /MD /Fa"x64\Release\" /EHsc /nologo /Qparallel 
                   5863:      /Fo"x64\Release\" /Qprof-dir "x64\Release\" /Fp"x64\Release\IMaCh.pch" 
                   5864:    */
1.186     brouard  5865:    /* Link is */ /* /OUT:"visual studio
1.185     brouard  5866:       2013\Projects\IMaCh\Release\IMaCh.exe" /MANIFEST /NXCOMPAT
                   5867:       /PDB:"visual studio
                   5868:       2013\Projects\IMaCh\Release\IMaCh.pdb" /DYNAMICBASE
                   5869:       "kernel32.lib" "user32.lib" "gdi32.lib" "winspool.lib"
                   5870:       "comdlg32.lib" "advapi32.lib" "shell32.lib" "ole32.lib"
                   5871:       "oleaut32.lib" "uuid.lib" "odbc32.lib" "odbccp32.lib"
                   5872:       /MACHINE:X86 /OPT:REF /SAFESEH /INCREMENTAL:NO
                   5873:       /SUBSYSTEM:CONSOLE",5.01" /MANIFESTUAC:"level='asInvoker'
                   5874:       uiAccess='false'"
                   5875:       /ManifestFile:"Release\IMaCh.exe.intermediate.manifest" /OPT:ICF
                   5876:       /NOLOGO /TLBID:1
                   5877:    */
1.177     brouard  5878: #if defined __INTEL_COMPILER
1.178     brouard  5879: #if defined(__GNUC__)
                   5880:        struct utsname sysInfo;  /* For Intel on Linux and OS/X */
                   5881: #endif
1.177     brouard  5882: #elif defined(__GNUC__) 
1.179     brouard  5883: #ifndef  __APPLE__
1.174     brouard  5884: #include <gnu/libc-version.h>  /* Only on gnu */
1.179     brouard  5885: #endif
1.177     brouard  5886:    struct utsname sysInfo;
1.178     brouard  5887:    int cross = CROSS;
                   5888:    if (cross){
                   5889:           printf("Cross-");
                   5890:           fprintf(ficlog, "Cross-");
                   5891:    }
1.174     brouard  5892: #endif
                   5893: 
1.171     brouard  5894: #include <stdint.h>
1.178     brouard  5895: 
1.169     brouard  5896:    printf("Compiled with:");fprintf(ficlog,"Compiled with:");
                   5897: #if defined(__clang__)
                   5898:    printf(" Clang/LLVM");fprintf(ficlog," Clang/LLVM");        /* Clang/LLVM. ---------------------------------------------- */
                   5899: #endif
                   5900: #if defined(__ICC) || defined(__INTEL_COMPILER)
                   5901:    printf(" Intel ICC/ICPC");fprintf(ficlog," Intel ICC/ICPC");/* Intel ICC/ICPC. ------------------------------------------ */
                   5902: #endif
                   5903: #if defined(__GNUC__) || defined(__GNUG__)
                   5904:    printf(" GNU GCC/G++");fprintf(ficlog," GNU GCC/G++");/* GNU GCC/G++. --------------------------------------------- */
                   5905: #endif
                   5906: #if defined(__HP_cc) || defined(__HP_aCC)
                   5907:    printf(" Hewlett-Packard C/aC++");fprintf(fcilog," Hewlett-Packard C/aC++"); /* Hewlett-Packard C/aC++. ---------------------------------- */
                   5908: #endif
                   5909: #if defined(__IBMC__) || defined(__IBMCPP__)
                   5910:    printf(" IBM XL C/C++"); fprintf(ficlog," IBM XL C/C++");/* IBM XL C/C++. -------------------------------------------- */
                   5911: #endif
                   5912: #if defined(_MSC_VER)
                   5913:    printf(" Microsoft Visual Studio");fprintf(ficlog," Microsoft Visual Studio");/* Microsoft Visual Studio. --------------------------------- */
                   5914: #endif
                   5915: #if defined(__PGI)
                   5916:    printf(" Portland Group PGCC/PGCPP");fprintf(ficlog," Portland Group PGCC/PGCPP");/* Portland Group PGCC/PGCPP. ------------------------------- */
                   5917: #endif
                   5918: #if defined(__SUNPRO_C) || defined(__SUNPRO_CC)
                   5919:    printf(" Oracle Solaris Studio");fprintf(ficlog," Oracle Solaris Studio\n");/* Oracle Solaris Studio. ----------------------------------- */
1.167     brouard  5920: #endif
1.174     brouard  5921:    printf(" for ");fprintf(ficlog," for ");
1.169     brouard  5922:    
1.167     brouard  5923: // http://stackoverflow.com/questions/4605842/how-to-identify-platform-compiler-from-preprocessor-macros
                   5924: #ifdef _WIN32 // note the underscore: without it, it's not msdn official!
                   5925:     // Windows (x64 and x86)
1.174     brouard  5926:    printf("Windows (x64 and x86) ");fprintf(ficlog,"Windows (x64 and x86) ");
1.167     brouard  5927: #elif __unix__ // all unices, not all compilers
                   5928:     // Unix
1.174     brouard  5929:    printf("Unix ");fprintf(ficlog,"Unix ");
1.167     brouard  5930: #elif __linux__
                   5931:     // linux
1.174     brouard  5932:    printf("linux ");fprintf(ficlog,"linux ");
1.167     brouard  5933: #elif __APPLE__
1.174     brouard  5934:     // Mac OS, not sure if this is covered by __posix__ and/or __unix__ though..
                   5935:    printf("Mac OS ");fprintf(ficlog,"Mac OS ");
1.167     brouard  5936: #endif
                   5937: 
                   5938: /*  __MINGW32__          */
                   5939: /*  __CYGWIN__  */
                   5940: /* __MINGW64__  */
                   5941: // http://msdn.microsoft.com/en-us/library/b0084kay.aspx
                   5942: /* _MSC_VER  //the Visual C++ compiler is 17.00.51106.1, the _MSC_VER macro evaluates to 1700. Type cl /?  */
                   5943: /* _MSC_FULL_VER //the Visual C++ compiler is 15.00.20706.01, the _MSC_FULL_VER macro evaluates to 150020706 */
                   5944: /* _WIN64  // Defined for applications for Win64. */
                   5945: /* _M_X64 // Defined for compilations that target x64 processors. */
                   5946: /* _DEBUG // Defined when you compile with /LDd, /MDd, and /MTd. */
1.171     brouard  5947: 
1.167     brouard  5948: #if UINTPTR_MAX == 0xffffffff
1.174     brouard  5949:    printf(" 32-bit"); fprintf(ficlog," 32-bit");/* 32-bit */
1.167     brouard  5950: #elif UINTPTR_MAX == 0xffffffffffffffff
1.174     brouard  5951:    printf(" 64-bit"); fprintf(ficlog," 64-bit");/* 64-bit */
1.167     brouard  5952: #else
1.174     brouard  5953:    printf(" wtf-bit"); fprintf(ficlog," wtf-bit");/* wtf */
1.167     brouard  5954: #endif
                   5955: 
1.169     brouard  5956: #if defined(__GNUC__)
                   5957: # if defined(__GNUC_PATCHLEVEL__)
                   5958: #  define __GNUC_VERSION__ (__GNUC__ * 10000 \
                   5959:                             + __GNUC_MINOR__ * 100 \
                   5960:                             + __GNUC_PATCHLEVEL__)
                   5961: # else
                   5962: #  define __GNUC_VERSION__ (__GNUC__ * 10000 \
                   5963:                             + __GNUC_MINOR__ * 100)
                   5964: # endif
1.174     brouard  5965:    printf(" using GNU C version %d.\n", __GNUC_VERSION__);
                   5966:    fprintf(ficlog, " using GNU C version %d.\n", __GNUC_VERSION__);
1.176     brouard  5967: 
                   5968:    if (uname(&sysInfo) != -1) {
                   5969:      printf("Running on: %s %s %s %s %s\n",sysInfo.sysname, sysInfo.nodename, sysInfo.release, sysInfo.version, sysInfo.machine);
                   5970:      fprintf(ficlog,"Running on: %s %s %s %s %s\n ",sysInfo.sysname, sysInfo.nodename, sysInfo.release, sysInfo.version, sysInfo.machine);
                   5971:    }
                   5972:    else
                   5973:       perror("uname() error");
1.179     brouard  5974:    //#ifndef __INTEL_COMPILER 
                   5975: #if !defined (__INTEL_COMPILER) && !defined(__APPLE__)
1.174     brouard  5976:    printf("GNU libc version: %s\n", gnu_get_libc_version()); 
1.179     brouard  5977:    fprintf(ficlog,"GNU libc version: %s\n", gnu_get_libc_version());
1.177     brouard  5978: #endif
1.169     brouard  5979: #endif
1.172     brouard  5980: 
                   5981:    //   void main()
                   5982:    //   {
1.169     brouard  5983: #if defined(_MSC_VER)
1.174     brouard  5984:    if (IsWow64()){
1.176     brouard  5985:           printf("The program (probably compiled for 32bit) is running under WOW64 (64bit) emulation.\n");
                   5986:           fprintf(ficlog, "The program (probably compiled for 32bit) is running under WOW64 (64bit) emulation.\n");
1.174     brouard  5987:    }
                   5988:    else{
1.176     brouard  5989:           printf("The process is not running under WOW64 (i.e probably on a 64bit Windows).\n");
1.178     brouard  5990:           fprintf(ficlog,"The programm is not running under WOW64 (i.e probably on a 64bit Windows).\n");
1.174     brouard  5991:    }
1.172     brouard  5992:    //     printf("\nPress Enter to continue...");
                   5993:    //     getchar();
                   5994:    //   }
                   5995: 
1.169     brouard  5996: #endif
                   5997:    
1.167     brouard  5998: 
                   5999:  }
1.136     brouard  6000: 
1.180     brouard  6001: int prevalence_limit(double *p, double **prlim, double ageminpar, double agemaxpar){
                   6002:   /*--------------- Prevalence limit  (period or stable prevalence) --------------*/
                   6003:   int i, j, k, i1 ;
                   6004:   double ftolpl = 1.e-10;
                   6005:   double age, agebase, agelim;
                   6006: 
                   6007:     strcpy(filerespl,"pl");
                   6008:     strcat(filerespl,fileres);
                   6009:     if((ficrespl=fopen(filerespl,"w"))==NULL) {
                   6010:       printf("Problem with period (stable) prevalence resultfile: %s\n", filerespl);return 1;
                   6011:       fprintf(ficlog,"Problem with period (stable) prevalence resultfile: %s\n", filerespl);return 1;
                   6012:     }
                   6013:     printf("Computing period (stable) prevalence: result on file '%s' \n", filerespl);
                   6014:     fprintf(ficlog,"Computing period (stable) prevalence: result on file '%s' \n", filerespl);
                   6015:     pstamp(ficrespl);
                   6016:     fprintf(ficrespl,"# Period (stable) prevalence \n");
                   6017:     fprintf(ficrespl,"#Age ");
                   6018:     for(i=1; i<=nlstate;i++) fprintf(ficrespl,"%d-%d ",i,i);
                   6019:     fprintf(ficrespl,"\n");
                   6020:   
                   6021:     /* prlim=matrix(1,nlstate,1,nlstate);*/ /* back in main */
                   6022: 
                   6023:     agebase=ageminpar;
                   6024:     agelim=agemaxpar;
                   6025: 
                   6026:     i1=pow(2,cptcoveff);
                   6027:     if (cptcovn < 1){i1=1;}
                   6028: 
                   6029:     for(cptcov=1,k=0;cptcov<=i1;cptcov++){
                   6030:     /* for(cptcov=1,k=0;cptcov<=1;cptcov++){ */
                   6031:       //for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){
                   6032:        k=k+1;
                   6033:        /* to clean */
                   6034:        //printf("cptcov=%d cptcod=%d codtab=%d\n",cptcov, cptcod,codtab[cptcod][cptcov]);
                   6035:        fprintf(ficrespl,"\n#******");
                   6036:        printf("\n#******");
                   6037:        fprintf(ficlog,"\n#******");
                   6038:        for(j=1;j<=cptcoveff;j++) {
                   6039:          fprintf(ficrespl," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
                   6040:          printf(" V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
                   6041:          fprintf(ficlog," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
                   6042:        }
                   6043:        fprintf(ficrespl,"******\n");
                   6044:        printf("******\n");
                   6045:        fprintf(ficlog,"******\n");
                   6046: 
                   6047:        fprintf(ficrespl,"#Age ");
                   6048:        for(j=1;j<=cptcoveff;j++) {
                   6049:          fprintf(ficrespl,"V%d %d",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
                   6050:        }
                   6051:        for(i=1; i<=nlstate;i++) fprintf(ficrespl,"%d-%d ",i,i);
                   6052:        fprintf(ficrespl,"\n");
                   6053:        
                   6054:        for (age=agebase; age<=agelim; age++){
                   6055:        /* for (age=agebase; age<=agebase; age++){ */
                   6056:          prevalim(prlim, nlstate, p, age, oldm, savm,ftolpl,k);
                   6057:          fprintf(ficrespl,"%.0f ",age );
                   6058:          for(j=1;j<=cptcoveff;j++)
                   6059:            fprintf(ficrespl,"%d %d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
                   6060:          for(i=1; i<=nlstate;i++)
                   6061:            fprintf(ficrespl," %.5f", prlim[i][i]);
                   6062:          fprintf(ficrespl,"\n");
                   6063:        } /* Age */
                   6064:        /* was end of cptcod */
                   6065:     } /* cptcov */
1.184     brouard  6066:        return 0;
1.180     brouard  6067: }
                   6068: 
                   6069: int hPijx(double *p, int bage, int fage){
                   6070:     /*------------- h Pij x at various ages ------------*/
                   6071: 
                   6072:   int stepsize;
                   6073:   int agelim;
                   6074:   int hstepm;
                   6075:   int nhstepm;
                   6076:   int h, i, i1, j, k;
                   6077: 
                   6078:   double agedeb;
                   6079:   double ***p3mat;
                   6080: 
                   6081:     strcpy(filerespij,"pij");  strcat(filerespij,fileres);
                   6082:     if((ficrespij=fopen(filerespij,"w"))==NULL) {
                   6083:       printf("Problem with Pij resultfile: %s\n", filerespij); return 1;
                   6084:       fprintf(ficlog,"Problem with Pij resultfile: %s\n", filerespij); return 1;
                   6085:     }
                   6086:     printf("Computing pij: result on file '%s' \n", filerespij);
                   6087:     fprintf(ficlog,"Computing pij: result on file '%s' \n", filerespij);
                   6088:   
                   6089:     stepsize=(int) (stepm+YEARM-1)/YEARM;
                   6090:     /*if (stepm<=24) stepsize=2;*/
                   6091: 
                   6092:     agelim=AGESUP;
                   6093:     hstepm=stepsize*YEARM; /* Every year of age */
                   6094:     hstepm=hstepm/stepm; /* Typically 2 years, = 2/6 months = 4 */ 
                   6095: 
                   6096:     /* hstepm=1;   aff par mois*/
                   6097:     pstamp(ficrespij);
                   6098:     fprintf(ficrespij,"#****** h Pij x Probability to be in state j at age x+h being in i at x ");
                   6099:     i1= pow(2,cptcoveff);
1.183     brouard  6100:    /* for(cptcov=1,k=0;cptcov<=i1;cptcov++){ */
                   6101:    /*    /\*for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){*\/ */
                   6102:    /*          k=k+1;  */
                   6103:     for (k=1; k <= (int) pow(2,cptcoveff); k++){
                   6104:       fprintf(ficrespij,"\n#****** ");
                   6105:       for(j=1;j<=cptcoveff;j++) 
                   6106:        fprintf(ficrespij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
                   6107:       fprintf(ficrespij,"******\n");
                   6108:       
                   6109:       for (agedeb=fage; agedeb>=bage; agedeb--){ /* If stepm=6 months */
                   6110:        nhstepm=(int) rint((agelim-agedeb)*YEARM/stepm); /* Typically 20 years = 20*12/6=40 */ 
                   6111:        nhstepm = nhstepm/hstepm; /* Typically 40/4=10 */
                   6112:        
                   6113:        /*        nhstepm=nhstepm*YEARM; aff par mois*/
1.180     brouard  6114:        
1.183     brouard  6115:        p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   6116:        oldm=oldms;savm=savms;
                   6117:        hpxij(p3mat,nhstepm,agedeb,hstepm,p,nlstate,stepm,oldm,savm, k);  
                   6118:        fprintf(ficrespij,"# Cov Agex agex+h hpijx with i,j=");
                   6119:        for(i=1; i<=nlstate;i++)
                   6120:          for(j=1; j<=nlstate+ndeath;j++)
                   6121:            fprintf(ficrespij," %1d-%1d",i,j);
                   6122:        fprintf(ficrespij,"\n");
                   6123:        for (h=0; h<=nhstepm; h++){
                   6124:          /*agedebphstep = agedeb + h*hstepm/YEARM*stepm;*/
                   6125:          fprintf(ficrespij,"%d %3.f %3.f",k, agedeb, agedeb + h*hstepm/YEARM*stepm );
1.180     brouard  6126:          for(i=1; i<=nlstate;i++)
                   6127:            for(j=1; j<=nlstate+ndeath;j++)
1.183     brouard  6128:              fprintf(ficrespij," %.5f", p3mat[i][j][h]);
1.180     brouard  6129:          fprintf(ficrespij,"\n");
                   6130:        }
1.183     brouard  6131:        free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   6132:        fprintf(ficrespij,"\n");
                   6133:       }
1.180     brouard  6134:       /*}*/
                   6135:     }
1.184     brouard  6136:        return 0;
1.180     brouard  6137: }
                   6138: 
                   6139: 
1.136     brouard  6140: /***********************************************/
                   6141: /**************** Main Program *****************/
                   6142: /***********************************************/
                   6143: 
                   6144: int main(int argc, char *argv[])
                   6145: {
                   6146: #ifdef GSL
                   6147:   const gsl_multimin_fminimizer_type *T;
                   6148:   size_t iteri = 0, it;
                   6149:   int rval = GSL_CONTINUE;
                   6150:   int status = GSL_SUCCESS;
                   6151:   double ssval;
                   6152: #endif
                   6153:   int movingaverage(double ***probs, double bage,double fage, double ***mobaverage, int mobilav);
1.164     brouard  6154:   int i,j, k, n=MAXN,iter=0,m,size=100, cptcod;
                   6155: 
                   6156:   int jj, ll, li, lj, lk;
1.136     brouard  6157:   int numlinepar=0; /* Current linenumber of parameter file */
                   6158:   int itimes;
                   6159:   int NDIM=2;
                   6160:   int vpopbased=0;
                   6161: 
1.164     brouard  6162:   char ca[32], cb[32];
1.136     brouard  6163:   /*  FILE *fichtm; *//* Html File */
                   6164:   /* FILE *ficgp;*/ /*Gnuplot File */
                   6165:   struct stat info;
1.164     brouard  6166:   double agedeb;
1.136     brouard  6167:   double ageminpar=1.e20,agemin=1.e20, agemaxpar=-1.e20, agemax=-1.e20;
                   6168: 
1.165     brouard  6169:   double fret;
1.136     brouard  6170:   double dum; /* Dummy variable */
                   6171:   double ***p3mat;
                   6172:   double ***mobaverage;
1.164     brouard  6173: 
                   6174:   char line[MAXLINE];
1.136     brouard  6175:   char path[MAXLINE],pathc[MAXLINE],pathcd[MAXLINE],pathtot[MAXLINE],model[MAXLINE];
                   6176:   char pathr[MAXLINE], pathimach[MAXLINE]; 
1.164     brouard  6177:   char *tok, *val; /* pathtot */
1.136     brouard  6178:   int firstobs=1, lastobs=10;
1.164     brouard  6179:   int c,  h , cpt;
                   6180:   int jl;
                   6181:   int i1, j1, jk, stepsize;
                   6182:   int *tab; 
1.136     brouard  6183:   int mobilavproj=0 , prevfcast=0 ; /* moving average of prev, If prevfcast=1 prevalence projection */
                   6184:   int mobilav=0,popforecast=0;
                   6185:   int hstepm, nhstepm;
                   6186:   int agemortsup;
                   6187:   float  sumlpop=0.;
                   6188:   double jprev1=1, mprev1=1,anprev1=2000,jprev2=1, mprev2=1,anprev2=2000;
                   6189:   double jpyram=1, mpyram=1,anpyram=2000,jpyram1=1, mpyram1=1,anpyram1=2000;
                   6190: 
1.164     brouard  6191:   double bage=0, fage=110, age, agelim, agebase;
1.136     brouard  6192:   double ftolpl=FTOL;
                   6193:   double **prlim;
                   6194:   double ***param; /* Matrix of parameters */
                   6195:   double  *p;
                   6196:   double **matcov; /* Matrix of covariance */
                   6197:   double ***delti3; /* Scale */
                   6198:   double *delti; /* Scale */
                   6199:   double ***eij, ***vareij;
                   6200:   double **varpl; /* Variances of prevalence limits by age */
                   6201:   double *epj, vepp;
1.164     brouard  6202: 
1.136     brouard  6203:   double dateprev1, dateprev2,jproj1=1,mproj1=1,anproj1=2000,jproj2=1,mproj2=1,anproj2=2000;
                   6204:   double **ximort;
1.145     brouard  6205:   char *alph[]={"a","a","b","c","d","e"}, str[4]="1234";
1.136     brouard  6206:   int *dcwave;
                   6207: 
1.164     brouard  6208:   char z[1]="c";
1.136     brouard  6209: 
                   6210:   /*char  *strt;*/
                   6211:   char strtend[80];
1.126     brouard  6212: 
1.164     brouard  6213: 
1.126     brouard  6214: /*   setlocale (LC_ALL, ""); */
                   6215: /*   bindtextdomain (PACKAGE, LOCALEDIR); */
                   6216: /*   textdomain (PACKAGE); */
                   6217: /*   setlocale (LC_CTYPE, ""); */
                   6218: /*   setlocale (LC_MESSAGES, ""); */
                   6219: 
                   6220:   /*   gettimeofday(&start_time, (struct timezone*)0); */ /* at first time */
1.157     brouard  6221:   rstart_time = time(NULL);  
                   6222:   /*  (void) gettimeofday(&start_time,&tzp);*/
                   6223:   start_time = *localtime(&rstart_time);
1.126     brouard  6224:   curr_time=start_time;
1.157     brouard  6225:   /*tml = *localtime(&start_time.tm_sec);*/
                   6226:   /* strcpy(strstart,asctime(&tml)); */
                   6227:   strcpy(strstart,asctime(&start_time));
1.126     brouard  6228: 
                   6229: /*  printf("Localtime (at start)=%s",strstart); */
1.157     brouard  6230: /*  tp.tm_sec = tp.tm_sec +86400; */
                   6231: /*  tm = *localtime(&start_time.tm_sec); */
1.126     brouard  6232: /*   tmg.tm_year=tmg.tm_year +dsign*dyear; */
                   6233: /*   tmg.tm_mon=tmg.tm_mon +dsign*dmonth; */
                   6234: /*   tmg.tm_hour=tmg.tm_hour + 1; */
1.157     brouard  6235: /*   tp.tm_sec = mktime(&tmg); */
1.126     brouard  6236: /*   strt=asctime(&tmg); */
                   6237: /*   printf("Time(after) =%s",strstart);  */
                   6238: /*  (void) time (&time_value);
                   6239: *  printf("time=%d,t-=%d\n",time_value,time_value-86400);
                   6240: *  tm = *localtime(&time_value);
                   6241: *  strstart=asctime(&tm);
                   6242: *  printf("tim_value=%d,asctime=%s\n",time_value,strstart); 
                   6243: */
                   6244: 
                   6245:   nberr=0; /* Number of errors and warnings */
                   6246:   nbwarn=0;
1.184     brouard  6247: #ifdef WIN32
                   6248:   _getcwd(pathcd, size);
                   6249: #else
1.126     brouard  6250:   getcwd(pathcd, size);
1.184     brouard  6251: #endif
1.126     brouard  6252: 
                   6253:   printf("\n%s\n%s",version,fullversion);
                   6254:   if(argc <=1){
                   6255:     printf("\nEnter the parameter file name: ");
                   6256:     fgets(pathr,FILENAMELENGTH,stdin);
                   6257:     i=strlen(pathr);
                   6258:     if(pathr[i-1]=='\n')
                   6259:       pathr[i-1]='\0';
1.156     brouard  6260:     i=strlen(pathr);
                   6261:     if(pathr[i-1]==' ') /* This may happen when dragging on oS/X! */
                   6262:       pathr[i-1]='\0';
1.126     brouard  6263:    for (tok = pathr; tok != NULL; ){
                   6264:       printf("Pathr |%s|\n",pathr);
                   6265:       while ((val = strsep(&tok, "\"" )) != NULL && *val == '\0');
                   6266:       printf("val= |%s| pathr=%s\n",val,pathr);
                   6267:       strcpy (pathtot, val);
                   6268:       if(pathr[0] == '\0') break; /* Dirty */
                   6269:     }
                   6270:   }
                   6271:   else{
                   6272:     strcpy(pathtot,argv[1]);
                   6273:   }
                   6274:   /*if(getcwd(pathcd, MAXLINE)!= NULL)printf ("Error pathcd\n");*/
                   6275:   /*cygwin_split_path(pathtot,path,optionfile);
                   6276:     printf("pathtot=%s, path=%s, optionfile=%s\n",pathtot,path,optionfile);*/
                   6277:   /* cutv(path,optionfile,pathtot,'\\');*/
                   6278: 
                   6279:   /* Split argv[0], imach program to get pathimach */
                   6280:   printf("\nargv[0]=%s argv[1]=%s, \n",argv[0],argv[1]);
                   6281:   split(argv[0],pathimach,optionfile,optionfilext,optionfilefiname);
                   6282:   printf("\nargv[0]=%s pathimach=%s, \noptionfile=%s \noptionfilext=%s \noptionfilefiname=%s\n",argv[0],pathimach,optionfile,optionfilext,optionfilefiname);
                   6283:  /*   strcpy(pathimach,argv[0]); */
                   6284:   /* Split argv[1]=pathtot, parameter file name to get path, optionfile, extension and name */
                   6285:   split(pathtot,path,optionfile,optionfilext,optionfilefiname);
                   6286:   printf("\npathtot=%s,\npath=%s,\noptionfile=%s \noptionfilext=%s \noptionfilefiname=%s\n",pathtot,path,optionfile,optionfilext,optionfilefiname);
1.184     brouard  6287: #ifdef WIN32
                   6288:   _chdir(path); /* Can be a relative path */
                   6289:   if(_getcwd(pathcd,MAXLINE) > 0) /* So pathcd is the full path */
                   6290: #else
1.126     brouard  6291:   chdir(path); /* Can be a relative path */
1.184     brouard  6292:   if (getcwd(pathcd, MAXLINE) > 0) /* So pathcd is the full path */
                   6293: #endif
                   6294:   printf("Current directory %s!\n",pathcd);
1.126     brouard  6295:   strcpy(command,"mkdir ");
                   6296:   strcat(command,optionfilefiname);
                   6297:   if((outcmd=system(command)) != 0){
1.169     brouard  6298:     printf("Directory already exists (or can't create it) %s%s, err=%d\n",path,optionfilefiname,outcmd);
1.126     brouard  6299:     /* fprintf(ficlog,"Problem creating directory %s%s\n",path,optionfilefiname); */
                   6300:     /* fclose(ficlog); */
                   6301: /*     exit(1); */
                   6302:   }
                   6303: /*   if((imk=mkdir(optionfilefiname))<0){ */
                   6304: /*     perror("mkdir"); */
                   6305: /*   } */
                   6306: 
                   6307:   /*-------- arguments in the command line --------*/
                   6308: 
1.186     brouard  6309:   /* Main Log file */
1.126     brouard  6310:   strcat(filelog, optionfilefiname);
                   6311:   strcat(filelog,".log");    /* */
                   6312:   if((ficlog=fopen(filelog,"w"))==NULL)    {
                   6313:     printf("Problem with logfile %s\n",filelog);
                   6314:     goto end;
                   6315:   }
                   6316:   fprintf(ficlog,"Log filename:%s\n",filelog);
                   6317:   fprintf(ficlog,"\n%s\n%s",version,fullversion);
                   6318:   fprintf(ficlog,"\nEnter the parameter file name: \n");
                   6319:   fprintf(ficlog,"pathimach=%s\npathtot=%s\n\
                   6320:  path=%s \n\
                   6321:  optionfile=%s\n\
                   6322:  optionfilext=%s\n\
1.156     brouard  6323:  optionfilefiname='%s'\n",pathimach,pathtot,path,optionfile,optionfilext,optionfilefiname);
1.126     brouard  6324: 
1.167     brouard  6325:   syscompilerinfo();
                   6326: 
1.126     brouard  6327:   printf("Local time (at start):%s",strstart);
                   6328:   fprintf(ficlog,"Local time (at start): %s",strstart);
                   6329:   fflush(ficlog);
                   6330: /*   (void) gettimeofday(&curr_time,&tzp); */
1.157     brouard  6331: /*   printf("Elapsed time %d\n", asc_diff_time(curr_time.tm_sec-start_time.tm_sec,tmpout)); */
1.126     brouard  6332: 
                   6333:   /* */
                   6334:   strcpy(fileres,"r");
                   6335:   strcat(fileres, optionfilefiname);
                   6336:   strcat(fileres,".txt");    /* Other files have txt extension */
                   6337: 
1.186     brouard  6338:   /* Main ---------arguments file --------*/
1.126     brouard  6339: 
                   6340:   if((ficpar=fopen(optionfile,"r"))==NULL)    {
1.155     brouard  6341:     printf("Problem with optionfile '%s' with errno='%s'\n",optionfile,strerror(errno));
                   6342:     fprintf(ficlog,"Problem with optionfile '%s' with errno='%s'\n",optionfile,strerror(errno));
1.126     brouard  6343:     fflush(ficlog);
1.149     brouard  6344:     /* goto end; */
                   6345:     exit(70); 
1.126     brouard  6346:   }
                   6347: 
                   6348: 
                   6349: 
                   6350:   strcpy(filereso,"o");
                   6351:   strcat(filereso,fileres);
                   6352:   if((ficparo=fopen(filereso,"w"))==NULL) { /* opened on subdirectory */
                   6353:     printf("Problem with Output resultfile: %s\n", filereso);
                   6354:     fprintf(ficlog,"Problem with Output resultfile: %s\n", filereso);
                   6355:     fflush(ficlog);
                   6356:     goto end;
                   6357:   }
                   6358: 
                   6359:   /* Reads comments: lines beginning with '#' */
                   6360:   numlinepar=0;
                   6361:   while((c=getc(ficpar))=='#' && c!= EOF){
                   6362:     ungetc(c,ficpar);
                   6363:     fgets(line, MAXLINE, ficpar);
                   6364:     numlinepar++;
1.141     brouard  6365:     fputs(line,stdout);
1.126     brouard  6366:     fputs(line,ficparo);
                   6367:     fputs(line,ficlog);
                   6368:   }
                   6369:   ungetc(c,ficpar);
                   6370: 
1.187   ! brouard  6371:   fscanf(ficpar,"title=%s datafile=%s lastobs=%d firstpass=%d lastpass=%d\nftol=%lf stepm=%d ncovcol=%d nlstate=%d ndeath=%d maxwav=%d mle=%d weight=%d model=1+age+%s\n",title, datafile, &lastobs, &firstpass,&lastpass,&ftol, &stepm, &ncovcol, &nlstate,&ndeath, &maxwav, &mle, &weightopt,model);
1.126     brouard  6372:   numlinepar++;
1.187   ! brouard  6373:   printf("title=%s datafile=%s lastobs=%d firstpass=%d lastpass=%d\nftol=%e stepm=%d ncovcol=%d nlstate=%d ndeath=%d maxwav=%d mle=%d weight=%d\nmodel=1+age+%s\n", title, datafile, lastobs, firstpass,lastpass,ftol, stepm, ncovcol, nlstate,ndeath, maxwav, mle, weightopt,model);
        !          6374:   if(model[strlen(model)-1]=='.') /* Suppressing leading dot in the model */
        !          6375:     model[strlen(model)-1]='\0';
        !          6376:   fprintf(ficparo,"title=%s datafile=%s lastobs=%d firstpass=%d lastpass=%d\nftol=%e stepm=%d ncovcol=%d nlstate=%d ndeath=%d maxwav=%d mle=%d weight=%d\nmodel=1+age+%s.\n", title, datafile, lastobs, firstpass,lastpass,ftol,stepm,ncovcol,nlstate,ndeath,maxwav, mle, weightopt,model);
        !          6377:   fprintf(ficlog,"title=%s datafile=%s lastobs=%d firstpass=%d lastpass=%d\nftol=%e stepm=%d ncovcol=%d nlstate=%d ndeath=%d maxwav=%d mle=%d weight=%d\nmodel=1+age+%s.\n", title, datafile, lastobs, firstpass,lastpass,ftol,stepm,ncovcol,nlstate,ndeath,maxwav, mle, weightopt,model);
1.126     brouard  6378:   fflush(ficlog);
1.187   ! brouard  6379:   if(model[0]=='#'|| model[0]== '\0'){
        !          6380:     printf("Error in 'model' line: model should start with 'model=1+age+' and end with '.' \n \
        !          6381:  'model=1+age+.' or 'model=1+age+V1.' or 'model=1+age+age*age+V1+V1*age.' or \n \
        !          6382:  'model=1+age+V1+V2.' or 'model=1+age+V1+V2+V1*V2.' etc. \n");         \
        !          6383:     if(mle != -1){
        !          6384:       printf("Fix the model line and run imach with mle=-1 to get a correct template of the parameter file.\n");
        !          6385:       exit(1);
        !          6386:     }
        !          6387:   }
1.126     brouard  6388:   while((c=getc(ficpar))=='#' && c!= EOF){
                   6389:     ungetc(c,ficpar);
                   6390:     fgets(line, MAXLINE, ficpar);
                   6391:     numlinepar++;
1.141     brouard  6392:     fputs(line, stdout);
                   6393:     //puts(line);
1.126     brouard  6394:     fputs(line,ficparo);
                   6395:     fputs(line,ficlog);
                   6396:   }
                   6397:   ungetc(c,ficpar);
                   6398: 
                   6399:    
1.145     brouard  6400:   covar=matrix(0,NCOVMAX,1,n);  /**< used in readdata */
1.136     brouard  6401:   cptcovn=0; /*Number of covariates, i.e. number of '+' in model statement plus one, indepently of n in Vn*/
                   6402:   /* v1+v2+v3+v2*v4+v5*age makes cptcovn = 5
                   6403:      v1+v2*age+v2*v3 makes cptcovn = 3
                   6404:   */
                   6405:   if (strlen(model)>1) 
1.187   ! brouard  6406:     ncovmodel=2+nbocc(model,'+')+1; /*Number of variables including intercept and age = cptcovn + intercept + age : v1+v2+v3+v2*v4+v5*age makes 5+2=7,age*age makes 3*/
1.145     brouard  6407:   else
1.187   ! brouard  6408:     ncovmodel=2; /* Constant and age */
1.133     brouard  6409:   nforce= (nlstate+ndeath-1)*nlstate; /* Number of forces ij from state i to j */
                   6410:   npar= nforce*ncovmodel; /* Number of parameters like aij*/
1.131     brouard  6411:   if(npar >MAXPARM || nlstate >NLSTATEMAX || ndeath >NDEATHMAX || ncovmodel>NCOVMAX){
                   6412:     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);
                   6413:     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);
                   6414:     fflush(stdout);
                   6415:     fclose (ficlog);
                   6416:     goto end;
                   6417:   }
1.126     brouard  6418:   delti3= ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel);
                   6419:   delti=delti3[1][1];
                   6420:   /*delti=vector(1,npar); *//* Scale of each paramater (output from hesscov)*/
                   6421:   if(mle==-1){ /* Print a wizard for help writing covariance matrix */
                   6422:     prwizard(ncovmodel, nlstate, ndeath, model, ficparo);
                   6423:     printf(" You choose mle=-1, look at file %s for a template of covariance matrix \n",filereso);
                   6424:     fprintf(ficlog," You choose mle=-1, look at file %s for a template of covariance matrix \n",filereso);
                   6425:     free_ma3x(delti3,1,nlstate,1, nlstate+ndeath-1,1,ncovmodel); 
                   6426:     fclose (ficparo);
                   6427:     fclose (ficlog);
                   6428:     goto end;
                   6429:     exit(0);
                   6430:   }
1.186     brouard  6431:   else if(mle==-3) { /* Main Wizard */
1.126     brouard  6432:     prwizard(ncovmodel, nlstate, ndeath, model, ficparo);
                   6433:     printf(" You choose mle=-3, look at file %s for a template of covariance matrix \n",filereso);
                   6434:     fprintf(ficlog," You choose mle=-3, look at file %s for a template of covariance matrix \n",filereso);
                   6435:     param= ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel);
                   6436:     matcov=matrix(1,npar,1,npar);
                   6437:   }
                   6438:   else{
1.145     brouard  6439:     /* Read guessed parameters */
1.126     brouard  6440:     /* Reads comments: lines beginning with '#' */
                   6441:     while((c=getc(ficpar))=='#' && c!= EOF){
                   6442:       ungetc(c,ficpar);
                   6443:       fgets(line, MAXLINE, ficpar);
                   6444:       numlinepar++;
1.141     brouard  6445:       fputs(line,stdout);
1.126     brouard  6446:       fputs(line,ficparo);
                   6447:       fputs(line,ficlog);
                   6448:     }
                   6449:     ungetc(c,ficpar);
                   6450:     
                   6451:     param= ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel);
                   6452:     for(i=1; i <=nlstate; i++){
                   6453:       j=0;
                   6454:       for(jj=1; jj <=nlstate+ndeath; jj++){
                   6455:        if(jj==i) continue;
                   6456:        j++;
                   6457:        fscanf(ficpar,"%1d%1d",&i1,&j1);
                   6458:        if ((i1 != i) && (j1 != j)){
                   6459:          printf("Error in line parameters number %d, %1d%1d instead of %1d%1d \n \
                   6460: It might be a problem of design; if ncovcol and the model are correct\n \
                   6461: run imach with mle=-1 to get a correct template of the parameter file.\n",numlinepar, i,j, i1, j1);
                   6462:          exit(1);
                   6463:        }
                   6464:        fprintf(ficparo,"%1d%1d",i1,j1);
                   6465:        if(mle==1)
                   6466:          printf("%1d%1d",i,j);
                   6467:        fprintf(ficlog,"%1d%1d",i,j);
                   6468:        for(k=1; k<=ncovmodel;k++){
                   6469:          fscanf(ficpar," %lf",&param[i][j][k]);
                   6470:          if(mle==1){
                   6471:            printf(" %lf",param[i][j][k]);
                   6472:            fprintf(ficlog," %lf",param[i][j][k]);
                   6473:          }
                   6474:          else
                   6475:            fprintf(ficlog," %lf",param[i][j][k]);
                   6476:          fprintf(ficparo," %lf",param[i][j][k]);
                   6477:        }
                   6478:        fscanf(ficpar,"\n");
                   6479:        numlinepar++;
                   6480:        if(mle==1)
                   6481:          printf("\n");
                   6482:        fprintf(ficlog,"\n");
                   6483:        fprintf(ficparo,"\n");
                   6484:       }
                   6485:     }  
                   6486:     fflush(ficlog);
                   6487: 
1.145     brouard  6488:     /* Reads scales values */
1.126     brouard  6489:     p=param[1][1];
                   6490:     
                   6491:     /* Reads comments: lines beginning with '#' */
                   6492:     while((c=getc(ficpar))=='#' && c!= EOF){
                   6493:       ungetc(c,ficpar);
                   6494:       fgets(line, MAXLINE, ficpar);
                   6495:       numlinepar++;
1.141     brouard  6496:       fputs(line,stdout);
1.126     brouard  6497:       fputs(line,ficparo);
                   6498:       fputs(line,ficlog);
                   6499:     }
                   6500:     ungetc(c,ficpar);
                   6501: 
                   6502:     for(i=1; i <=nlstate; i++){
                   6503:       for(j=1; j <=nlstate+ndeath-1; j++){
                   6504:        fscanf(ficpar,"%1d%1d",&i1,&j1);
1.164     brouard  6505:        if ( (i1-i) * (j1-j) != 0){
1.126     brouard  6506:          printf("Error in line parameters number %d, %1d%1d instead of %1d%1d \n",numlinepar, i,j, i1, j1);
                   6507:          exit(1);
                   6508:        }
                   6509:        printf("%1d%1d",i,j);
                   6510:        fprintf(ficparo,"%1d%1d",i1,j1);
                   6511:        fprintf(ficlog,"%1d%1d",i1,j1);
                   6512:        for(k=1; k<=ncovmodel;k++){
                   6513:          fscanf(ficpar,"%le",&delti3[i][j][k]);
                   6514:          printf(" %le",delti3[i][j][k]);
                   6515:          fprintf(ficparo," %le",delti3[i][j][k]);
                   6516:          fprintf(ficlog," %le",delti3[i][j][k]);
                   6517:        }
                   6518:        fscanf(ficpar,"\n");
                   6519:        numlinepar++;
                   6520:        printf("\n");
                   6521:        fprintf(ficparo,"\n");
                   6522:        fprintf(ficlog,"\n");
                   6523:       }
                   6524:     }
                   6525:     fflush(ficlog);
                   6526: 
1.145     brouard  6527:     /* Reads covariance matrix */
1.126     brouard  6528:     delti=delti3[1][1];
                   6529: 
                   6530: 
                   6531:     /* free_ma3x(delti3,1,nlstate,1,nlstate+ndeath-1,1,ncovmodel); */ /* Hasn't to to freed here otherwise delti is no more allocated */
                   6532:   
                   6533:     /* Reads comments: lines beginning with '#' */
                   6534:     while((c=getc(ficpar))=='#' && c!= EOF){
                   6535:       ungetc(c,ficpar);
                   6536:       fgets(line, MAXLINE, ficpar);
                   6537:       numlinepar++;
1.141     brouard  6538:       fputs(line,stdout);
1.126     brouard  6539:       fputs(line,ficparo);
                   6540:       fputs(line,ficlog);
                   6541:     }
                   6542:     ungetc(c,ficpar);
                   6543:   
                   6544:     matcov=matrix(1,npar,1,npar);
1.131     brouard  6545:     for(i=1; i <=npar; i++)
                   6546:       for(j=1; j <=npar; j++) matcov[i][j]=0.;
                   6547:       
1.126     brouard  6548:     for(i=1; i <=npar; i++){
1.145     brouard  6549:       fscanf(ficpar,"%s",str);
1.126     brouard  6550:       if(mle==1)
                   6551:        printf("%s",str);
                   6552:       fprintf(ficlog,"%s",str);
                   6553:       fprintf(ficparo,"%s",str);
                   6554:       for(j=1; j <=i; j++){
                   6555:        fscanf(ficpar," %le",&matcov[i][j]);
                   6556:        if(mle==1){
                   6557:          printf(" %.5le",matcov[i][j]);
                   6558:        }
                   6559:        fprintf(ficlog," %.5le",matcov[i][j]);
                   6560:        fprintf(ficparo," %.5le",matcov[i][j]);
                   6561:       }
                   6562:       fscanf(ficpar,"\n");
                   6563:       numlinepar++;
                   6564:       if(mle==1)
                   6565:        printf("\n");
                   6566:       fprintf(ficlog,"\n");
                   6567:       fprintf(ficparo,"\n");
                   6568:     }
                   6569:     for(i=1; i <=npar; i++)
                   6570:       for(j=i+1;j<=npar;j++)
                   6571:        matcov[i][j]=matcov[j][i];
                   6572:     
                   6573:     if(mle==1)
                   6574:       printf("\n");
                   6575:     fprintf(ficlog,"\n");
                   6576:     
                   6577:     fflush(ficlog);
                   6578:     
                   6579:     /*-------- Rewriting parameter file ----------*/
                   6580:     strcpy(rfileres,"r");    /* "Rparameterfile */
                   6581:     strcat(rfileres,optionfilefiname);    /* Parameter file first name*/
                   6582:     strcat(rfileres,".");    /* */
                   6583:     strcat(rfileres,optionfilext);    /* Other files have txt extension */
                   6584:     if((ficres =fopen(rfileres,"w"))==NULL) {
                   6585:       printf("Problem writing new parameter file: %s\n", fileres);goto end;
                   6586:       fprintf(ficlog,"Problem writing new parameter file: %s\n", fileres);goto end;
                   6587:     }
                   6588:     fprintf(ficres,"#%s\n",version);
                   6589:   }    /* End of mle != -3 */
                   6590: 
1.186     brouard  6591:   /*  Main data
                   6592:    */
1.126     brouard  6593:   n= lastobs;
                   6594:   num=lvector(1,n);
                   6595:   moisnais=vector(1,n);
                   6596:   annais=vector(1,n);
                   6597:   moisdc=vector(1,n);
                   6598:   andc=vector(1,n);
                   6599:   agedc=vector(1,n);
                   6600:   cod=ivector(1,n);
                   6601:   weight=vector(1,n);
                   6602:   for(i=1;i<=n;i++) weight[i]=1.0; /* Equal weights, 1 by default */
                   6603:   mint=matrix(1,maxwav,1,n);
                   6604:   anint=matrix(1,maxwav,1,n);
1.131     brouard  6605:   s=imatrix(1,maxwav+1,1,n); /* s[i][j] health state for wave i and individual j */ 
1.126     brouard  6606:   tab=ivector(1,NCOVMAX);
1.144     brouard  6607:   ncodemax=ivector(1,NCOVMAX); /* Number of code per covariate; if O and 1 only, 2**ncov; V1+V2+V3+V4=>16 */
1.126     brouard  6608: 
1.136     brouard  6609:   /* Reads data from file datafile */
                   6610:   if (readdata(datafile, firstobs, lastobs, &imx)==1)
                   6611:     goto end;
                   6612: 
                   6613:   /* Calculation of the number of parameters from char model */
1.137     brouard  6614:     /*    modelsav=V2+V1+V4+age*V3 strb=age*V3 stra=V2+V1+V4 
                   6615:        k=4 (age*V3) Tvar[k=4]= 3 (from V3) Tag[cptcovage=1]=4
                   6616:        k=3 V4 Tvar[k=3]= 4 (from V4)
                   6617:        k=2 V1 Tvar[k=2]= 1 (from V1)
                   6618:        k=1 Tvar[1]=2 (from V2)
                   6619:     */
                   6620:   Tvar=ivector(1,NCOVMAX); /* Was 15 changed to NCOVMAX. */
                   6621:   /*  V2+V1+V4+age*V3 is a model with 4 covariates (3 plus signs). 
                   6622:       For each model-covariate stores the data-covariate id. Tvar[1]=2, Tvar[2]=1, Tvar[3]=4, 
                   6623:       Tvar[4=age*V3] is 3 and 'age' is recorded in Tage.
                   6624:   */
                   6625:   /* For model-covariate k tells which data-covariate to use but
                   6626:     because this model-covariate is a construction we invent a new column
                   6627:     ncovcol + k1
                   6628:     If already ncovcol=4 and model=V2+V1+V1*V4+age*V3
                   6629:     Tvar[3=V1*V4]=4+1 etc */
1.145     brouard  6630:   Tprod=ivector(1,NCOVMAX); /* Gives the position of a product */
1.137     brouard  6631:   /* Tprod[k1=1]=3(=V1*V4) for V2+V1+V1*V4+age*V3
                   6632:      if  V2+V1+V1*V4+age*V3+V3*V2   TProd[k1=2]=5 (V3*V2)
                   6633:   */
1.145     brouard  6634:   Tvaraff=ivector(1,NCOVMAX); /* Unclear */
                   6635:   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  6636:                            * For V3*V2 (in V2+V1+V1*V4+age*V3+V3*V2), V3*V2 position is 2nd. 
                   6637:                            * Tvard[k1=2][1]=3 (V3) Tvard[k1=2][2]=2(V2) */
1.145     brouard  6638:   Tage=ivector(1,NCOVMAX); /* Gives the covariate id of covariates associated with age: V2 + V1 + age*V4 + V3*age
1.137     brouard  6639:                         4 covariates (3 plus signs)
                   6640:                         Tage[1=V3*age]= 4; Tage[2=age*V4] = 3
                   6641:                      */  
1.136     brouard  6642: 
1.186     brouard  6643: /* Main decodemodel */
                   6644: 
1.187   ! brouard  6645: 
1.136     brouard  6646:   if(decodemodel(model, lastobs) == 1)
                   6647:     goto end;
                   6648: 
1.137     brouard  6649:   if((double)(lastobs-imx)/(double)imx > 1.10){
                   6650:     nbwarn++;
                   6651:     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); 
                   6652:     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); 
                   6653:   }
1.136     brouard  6654:     /*  if(mle==1){*/
1.137     brouard  6655:   if (weightopt != 1) { /* Maximisation without weights. We can have weights different from 1 but want no weight*/
                   6656:     for(i=1;i<=imx;i++) weight[i]=1.0; /* changed to imx */
1.136     brouard  6657:   }
                   6658: 
                   6659:     /*-calculation of age at interview from date of interview and age at death -*/
                   6660:   agev=matrix(1,maxwav,1,imx);
                   6661: 
                   6662:   if(calandcheckages(imx, maxwav, &agemin, &agemax, &nberr, &nbwarn) == 1)
                   6663:     goto end;
                   6664: 
1.126     brouard  6665: 
1.136     brouard  6666:   agegomp=(int)agemin;
                   6667:   free_vector(moisnais,1,n);
                   6668:   free_vector(annais,1,n);
1.126     brouard  6669:   /* free_matrix(mint,1,maxwav,1,n);
                   6670:      free_matrix(anint,1,maxwav,1,n);*/
                   6671:   free_vector(moisdc,1,n);
                   6672:   free_vector(andc,1,n);
1.145     brouard  6673:   /* */
                   6674:   
1.126     brouard  6675:   wav=ivector(1,imx);
                   6676:   dh=imatrix(1,lastpass-firstpass+1,1,imx);
                   6677:   bh=imatrix(1,lastpass-firstpass+1,1,imx);
                   6678:   mw=imatrix(1,lastpass-firstpass+1,1,imx);
                   6679:    
                   6680:   /* Concatenates waves */
                   6681:   concatwav(wav, dh, bh, mw, s, agedc, agev,  firstpass, lastpass, imx, nlstate, stepm);
1.145     brouard  6682:   /* */
                   6683:  
1.126     brouard  6684:   /* Routine tricode is to calculate cptcoveff (real number of unique covariates) and to associate covariable number and modality */
                   6685: 
                   6686:   nbcode=imatrix(0,NCOVMAX,0,NCOVMAX); 
                   6687:   ncodemax[1]=1;
1.145     brouard  6688:   Ndum =ivector(-1,NCOVMAX);  
1.187   ! brouard  6689:   if (ncovmodel-nagesqr > 2 ) /* That is if covariate other than cst, age and age*age */
1.145     brouard  6690:     tricode(Tvar,nbcode,imx, Ndum); /**< Fills nbcode[Tvar[j]][l]; */
1.186     brouard  6691:   /* Nbcode gives the value of the lth modality of jth covariate, in
                   6692:      V2+V1*age, there are 3 covariates Tvar[2]=1 (V1).*/
                   6693:   /* 1 to ncodemax[j] is the maximum value of this jth covariate */
1.145     brouard  6694: 
                   6695:   codtab=imatrix(1,100,1,10); /* codtab[h,k]=( (h-1) - mod(k-1,2**(k-1) )/2**(k-1) */
                   6696:   /*printf(" codtab[1,1],codtab[100,10]=%d,%d\n", codtab[1][1],codtab[100][10]);*/
1.186     brouard  6697:   /* codtab gives the value 1 or 2 of the hth combination of k covariates (1 or 2).*/
1.145     brouard  6698:   h=0;
                   6699: 
                   6700: 
                   6701:   /*if (cptcovn > 0) */
1.126     brouard  6702:       
1.145     brouard  6703:  
1.126     brouard  6704:   m=pow(2,cptcoveff);
                   6705:  
1.131     brouard  6706:   for(k=1;k<=cptcoveff; k++){ /* scans any effective covariate */
1.143     brouard  6707:     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 */ 
                   6708:       for(j=1; j <= ncodemax[k]; j++){ /* For each modality of this covariate ncodemax=2*/
                   6709:        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  6710:          h++;
1.141     brouard  6711:          if (h>m) 
1.136     brouard  6712:            h=1;
1.144     brouard  6713:          /**< codtab(h,k)  k   = codtab[h,k]=( (h-1) - mod(k-1,2**(k-1) )/2**(k-1) + 1
1.186     brouard  6714:           * For k=4 covariates, h goes from 1 to 2**k
                   6715:           * codtabm(h,k)=  1 & (h-1) >> (k-1) ;
                   6716:           *     h\k   1     2     3     4
1.143     brouard  6717:           *______________________________  
                   6718:           *     1 i=1 1 i=1 1 i=1 1 i=1 1
                   6719:           *     2     2     1     1     1
                   6720:           *     3 i=2 1     2     1     1
                   6721:           *     4     2     2     1     1
                   6722:           *     5 i=3 1 i=2 1     2     1
                   6723:           *     6     2     1     2     1
                   6724:           *     7 i=4 1     2     2     1
                   6725:           *     8     2     2     2     1
                   6726:           *     9 i=5 1 i=3 1 i=2 1     1
                   6727:           *    10     2     1     1     1
                   6728:           *    11 i=6 1     2     1     1
                   6729:           *    12     2     2     1     1
                   6730:           *    13 i=7 1 i=4 1     2     1    
                   6731:           *    14     2     1     2     1
                   6732:           *    15 i=8 1     2     2     1
                   6733:           *    16     2     2     2     1
                   6734:           */
1.141     brouard  6735:          codtab[h][k]=j;
1.186     brouard  6736:          /* codtab[12][3]=1; */
1.145     brouard  6737:          /*codtab[h][Tvar[k]]=j;*/
1.130     brouard  6738:          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  6739:        } 
                   6740:       }
                   6741:     }
                   6742:   } 
                   6743:   /* printf("codtab[1][2]=%d codtab[2][2]=%d",codtab[1][2],codtab[2][2]); 
                   6744:      codtab[1][2]=1;codtab[2][2]=2; */
                   6745:   /* for(i=1; i <=m ;i++){ 
                   6746:      for(k=1; k <=cptcovn; k++){
1.131     brouard  6747:        printf("i=%d k=%d %d %d ",i,k,codtab[i][k], cptcoveff);
1.126     brouard  6748:      }
                   6749:      printf("\n");
                   6750:      }
                   6751:      scanf("%d",i);*/
1.145     brouard  6752: 
                   6753:  free_ivector(Ndum,-1,NCOVMAX);
                   6754: 
                   6755: 
1.126     brouard  6756:     
1.186     brouard  6757:   /* Initialisation of ----------- gnuplot -------------*/
1.126     brouard  6758:   strcpy(optionfilegnuplot,optionfilefiname);
                   6759:   if(mle==-3)
                   6760:     strcat(optionfilegnuplot,"-mort");
                   6761:   strcat(optionfilegnuplot,".gp");
                   6762: 
                   6763:   if((ficgp=fopen(optionfilegnuplot,"w"))==NULL) {
                   6764:     printf("Problem with file %s",optionfilegnuplot);
                   6765:   }
                   6766:   else{
                   6767:     fprintf(ficgp,"\n# %s\n", version); 
                   6768:     fprintf(ficgp,"# %s\n", optionfilegnuplot); 
1.141     brouard  6769:     //fprintf(ficgp,"set missing 'NaNq'\n");
                   6770:     fprintf(ficgp,"set datafile missing 'NaNq'\n");
1.126     brouard  6771:   }
                   6772:   /*  fclose(ficgp);*/
1.186     brouard  6773: 
                   6774: 
                   6775:   /* Initialisation of --------- index.htm --------*/
1.126     brouard  6776: 
                   6777:   strcpy(optionfilehtm,optionfilefiname); /* Main html file */
                   6778:   if(mle==-3)
                   6779:     strcat(optionfilehtm,"-mort");
                   6780:   strcat(optionfilehtm,".htm");
                   6781:   if((fichtm=fopen(optionfilehtm,"w"))==NULL)    {
1.131     brouard  6782:     printf("Problem with %s \n",optionfilehtm);
                   6783:     exit(0);
1.126     brouard  6784:   }
                   6785: 
                   6786:   strcpy(optionfilehtmcov,optionfilefiname); /* Only for matrix of covariance */
                   6787:   strcat(optionfilehtmcov,"-cov.htm");
                   6788:   if((fichtmcov=fopen(optionfilehtmcov,"w"))==NULL)    {
                   6789:     printf("Problem with %s \n",optionfilehtmcov), exit(0);
                   6790:   }
                   6791:   else{
                   6792:   fprintf(fichtmcov,"<html><head>\n<title>IMaCh Cov %s</title></head>\n <body><font size=\"2\">%s <br> %s</font> \
                   6793: <hr size=\"2\" color=\"#EC5E5E\"> \n\
                   6794: Title=%s <br>Datafile=%s Firstpass=%d Lastpass=%d Stepm=%d Weight=%d Model=%s<br>\n",\
                   6795:          optionfilehtmcov,version,fullversion,title,datafile,firstpass,lastpass,stepm, weightopt, model);
                   6796:   }
                   6797: 
                   6798:   fprintf(fichtm,"<html><head>\n<title>IMaCh %s</title></head>\n <body><font size=\"2\">%s <br> %s</font> \
                   6799: <hr size=\"2\" color=\"#EC5E5E\"> \n\
                   6800: Title=%s <br>Datafile=%s Firstpass=%d Lastpass=%d Stepm=%d Weight=%d Model=%s<br>\n\
                   6801: \n\
                   6802: <hr  size=\"2\" color=\"#EC5E5E\">\
                   6803:  <ul><li><h4>Parameter files</h4>\n\
                   6804:  - Parameter file: <a href=\"%s.%s\">%s.%s</a><br>\n\
                   6805:  - Copy of the parameter file: <a href=\"o%s\">o%s</a><br>\n\
                   6806:  - Log file of the run: <a href=\"%s\">%s</a><br>\n\
                   6807:  - Gnuplot file name: <a href=\"%s\">%s</a><br>\n\
                   6808:  - Date and time at start: %s</ul>\n",\
                   6809:          optionfilehtm,version,fullversion,title,datafile,firstpass,lastpass,stepm, weightopt, model,\
                   6810:          optionfilefiname,optionfilext,optionfilefiname,optionfilext,\
                   6811:          fileres,fileres,\
                   6812:          filelog,filelog,optionfilegnuplot,optionfilegnuplot,strstart);
                   6813:   fflush(fichtm);
                   6814: 
                   6815:   strcpy(pathr,path);
                   6816:   strcat(pathr,optionfilefiname);
1.184     brouard  6817: #ifdef WIN32
                   6818:   _chdir(optionfilefiname); /* Move to directory named optionfile */
                   6819: #else
1.126     brouard  6820:   chdir(optionfilefiname); /* Move to directory named optionfile */
1.184     brouard  6821: #endif
                   6822:          
1.126     brouard  6823:   
                   6824:   /* Calculates basic frequencies. Computes observed prevalence at single age
                   6825:      and prints on file fileres'p'. */
                   6826:   freqsummary(fileres, agemin, agemax, s, agev, nlstate, imx,Tvaraff,nbcode, ncodemax,mint,anint,strstart);
                   6827: 
                   6828:   fprintf(fichtm,"\n");
                   6829:   fprintf(fichtm,"<br>Total number of observations=%d <br>\n\
                   6830: Youngest age at first (selected) pass %.2f, oldest age %.2f<br>\n\
                   6831: Interval (in months) between two waves: Min=%d Max=%d Mean=%.2lf<br>\n",\
                   6832:          imx,agemin,agemax,jmin,jmax,jmean);
                   6833:   pmmij= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
                   6834:     oldms= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
                   6835:     newms= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
                   6836:     savms= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
                   6837:     oldm=oldms; newm=newms; savm=savms; /* Keeps fixed addresses to free */
                   6838:     
                   6839:    
                   6840:   /* For Powell, parameters are in a vector p[] starting at p[1]
                   6841:      so we point p on param[1][1] so that p[1] maps on param[1][1][1] */
                   6842:   p=param[1][1]; /* *(*(*(param +1)+1)+0) */
                   6843: 
                   6844:   globpr=0; /* To get the number ipmx of contributions and the sum of weights*/
1.186     brouard  6845:   /* For mortality only */
1.126     brouard  6846:   if (mle==-3){
1.136     brouard  6847:     ximort=matrix(1,NDIM,1,NDIM); 
1.186     brouard  6848:     /*     ximort=gsl_matrix_alloc(1,NDIM,1,NDIM); */
1.126     brouard  6849:     cens=ivector(1,n);
                   6850:     ageexmed=vector(1,n);
                   6851:     agecens=vector(1,n);
                   6852:     dcwave=ivector(1,n);
                   6853:  
                   6854:     for (i=1; i<=imx; i++){
                   6855:       dcwave[i]=-1;
                   6856:       for (m=firstpass; m<=lastpass; m++)
                   6857:        if (s[m][i]>nlstate) {
                   6858:          dcwave[i]=m;
                   6859:          /*    printf("i=%d j=%d s=%d dcwave=%d\n",i,j, s[j][i],dcwave[i]);*/
                   6860:          break;
                   6861:        }
                   6862:     }
                   6863: 
                   6864:     for (i=1; i<=imx; i++) {
                   6865:       if (wav[i]>0){
                   6866:        ageexmed[i]=agev[mw[1][i]][i];
                   6867:        j=wav[i];
                   6868:        agecens[i]=1.; 
                   6869: 
                   6870:        if (ageexmed[i]> 1 && wav[i] > 0){
                   6871:          agecens[i]=agev[mw[j][i]][i];
                   6872:          cens[i]= 1;
                   6873:        }else if (ageexmed[i]< 1) 
                   6874:          cens[i]= -1;
                   6875:        if (agedc[i]< AGESUP && agedc[i]>1 && dcwave[i]>firstpass && dcwave[i]<=lastpass)
                   6876:          cens[i]=0 ;
                   6877:       }
                   6878:       else cens[i]=-1;
                   6879:     }
                   6880:     
                   6881:     for (i=1;i<=NDIM;i++) {
                   6882:       for (j=1;j<=NDIM;j++)
                   6883:        ximort[i][j]=(i == j ? 1.0 : 0.0);
                   6884:     }
                   6885:     
1.145     brouard  6886:     /*p[1]=0.0268; p[NDIM]=0.083;*/
1.126     brouard  6887:     /*printf("%lf %lf", p[1], p[2]);*/
                   6888:     
                   6889:     
1.136     brouard  6890: #ifdef GSL
                   6891:     printf("GSL optimization\n");  fprintf(ficlog,"Powell\n");
1.162     brouard  6892: #else
1.126     brouard  6893:     printf("Powell\n");  fprintf(ficlog,"Powell\n");
1.136     brouard  6894: #endif
1.126     brouard  6895:     strcpy(filerespow,"pow-mort"); 
                   6896:     strcat(filerespow,fileres);
                   6897:     if((ficrespow=fopen(filerespow,"w"))==NULL) {
                   6898:       printf("Problem with resultfile: %s\n", filerespow);
                   6899:       fprintf(ficlog,"Problem with resultfile: %s\n", filerespow);
                   6900:     }
1.136     brouard  6901: #ifdef GSL
                   6902:     fprintf(ficrespow,"# GSL optimization\n# iter -2*LL");
1.162     brouard  6903: #else
1.126     brouard  6904:     fprintf(ficrespow,"# Powell\n# iter -2*LL");
1.136     brouard  6905: #endif
1.126     brouard  6906:     /*  for (i=1;i<=nlstate;i++)
                   6907:        for(j=1;j<=nlstate+ndeath;j++)
                   6908:        if(j!=i)fprintf(ficrespow," p%1d%1d",i,j);
                   6909:     */
                   6910:     fprintf(ficrespow,"\n");
1.136     brouard  6911: #ifdef GSL
                   6912:     /* gsl starts here */ 
                   6913:     T = gsl_multimin_fminimizer_nmsimplex;
                   6914:     gsl_multimin_fminimizer *sfm = NULL;
                   6915:     gsl_vector *ss, *x;
                   6916:     gsl_multimin_function minex_func;
                   6917: 
                   6918:     /* Initial vertex size vector */
                   6919:     ss = gsl_vector_alloc (NDIM);
                   6920:     
                   6921:     if (ss == NULL){
                   6922:       GSL_ERROR_VAL ("failed to allocate space for ss", GSL_ENOMEM, 0);
                   6923:     }
                   6924:     /* Set all step sizes to 1 */
                   6925:     gsl_vector_set_all (ss, 0.001);
                   6926: 
                   6927:     /* Starting point */
1.126     brouard  6928:     
1.136     brouard  6929:     x = gsl_vector_alloc (NDIM);
                   6930:     
                   6931:     if (x == NULL){
                   6932:       gsl_vector_free(ss);
                   6933:       GSL_ERROR_VAL ("failed to allocate space for x", GSL_ENOMEM, 0);
                   6934:     }
                   6935:   
                   6936:     /* Initialize method and iterate */
                   6937:     /*     p[1]=0.0268; p[NDIM]=0.083; */
1.186     brouard  6938:     /*     gsl_vector_set(x, 0, 0.0268); */
                   6939:     /*     gsl_vector_set(x, 1, 0.083); */
1.136     brouard  6940:     gsl_vector_set(x, 0, p[1]);
                   6941:     gsl_vector_set(x, 1, p[2]);
                   6942: 
                   6943:     minex_func.f = &gompertz_f;
                   6944:     minex_func.n = NDIM;
                   6945:     minex_func.params = (void *)&p; /* ??? */
                   6946:     
                   6947:     sfm = gsl_multimin_fminimizer_alloc (T, NDIM);
                   6948:     gsl_multimin_fminimizer_set (sfm, &minex_func, x, ss);
                   6949:     
                   6950:     printf("Iterations beginning .....\n\n");
                   6951:     printf("Iter. #    Intercept       Slope     -Log Likelihood     Simplex size\n");
                   6952: 
                   6953:     iteri=0;
                   6954:     while (rval == GSL_CONTINUE){
                   6955:       iteri++;
                   6956:       status = gsl_multimin_fminimizer_iterate(sfm);
                   6957:       
                   6958:       if (status) printf("error: %s\n", gsl_strerror (status));
                   6959:       fflush(0);
                   6960:       
                   6961:       if (status) 
                   6962:         break;
                   6963:       
                   6964:       rval = gsl_multimin_test_size (gsl_multimin_fminimizer_size (sfm), 1e-6);
                   6965:       ssval = gsl_multimin_fminimizer_size (sfm);
                   6966:       
                   6967:       if (rval == GSL_SUCCESS)
                   6968:         printf ("converged to a local maximum at\n");
                   6969:       
                   6970:       printf("%5d ", iteri);
                   6971:       for (it = 0; it < NDIM; it++){
                   6972:        printf ("%10.5f ", gsl_vector_get (sfm->x, it));
                   6973:       }
                   6974:       printf("f() = %-10.5f ssize = %.7f\n", sfm->fval, ssval);
                   6975:     }
                   6976:     
                   6977:     printf("\n\n Please note: Program should be run many times with varying starting points to detemine global maximum\n\n");
                   6978:     
                   6979:     gsl_vector_free(x); /* initial values */
                   6980:     gsl_vector_free(ss); /* inital step size */
                   6981:     for (it=0; it<NDIM; it++){
                   6982:       p[it+1]=gsl_vector_get(sfm->x,it);
                   6983:       fprintf(ficrespow," %.12lf", p[it]);
                   6984:     }
                   6985:     gsl_multimin_fminimizer_free (sfm); /* p *(sfm.x.data) et p *(sfm.x.data+1)  */
                   6986: #endif
                   6987: #ifdef POWELL
                   6988:      powell(p,ximort,NDIM,ftol,&iter,&fret,gompertz);
                   6989: #endif  
1.126     brouard  6990:     fclose(ficrespow);
                   6991:     
                   6992:     hesscov(matcov, p, NDIM, delti, 1e-4, gompertz); 
                   6993: 
                   6994:     for(i=1; i <=NDIM; i++)
                   6995:       for(j=i+1;j<=NDIM;j++)
                   6996:        matcov[i][j]=matcov[j][i];
                   6997:     
                   6998:     printf("\nCovariance matrix\n ");
                   6999:     for(i=1; i <=NDIM; i++) {
                   7000:       for(j=1;j<=NDIM;j++){ 
                   7001:        printf("%f ",matcov[i][j]);
                   7002:       }
                   7003:       printf("\n ");
                   7004:     }
                   7005:     
                   7006:     printf("iter=%d MLE=%f Eq=%lf*exp(%lf*(age-%d))\n",iter,-gompertz(p),p[1],p[2],agegomp);
                   7007:     for (i=1;i<=NDIM;i++) 
                   7008:       printf("%f [%f ; %f]\n",p[i],p[i]-2*sqrt(matcov[i][i]),p[i]+2*sqrt(matcov[i][i]));
                   7009: 
                   7010:     lsurv=vector(1,AGESUP);
                   7011:     lpop=vector(1,AGESUP);
                   7012:     tpop=vector(1,AGESUP);
                   7013:     lsurv[agegomp]=100000;
                   7014:     
                   7015:     for (k=agegomp;k<=AGESUP;k++) {
                   7016:       agemortsup=k;
                   7017:       if (p[1]*exp(p[2]*(k-agegomp))>1) break;
                   7018:     }
                   7019:     
                   7020:     for (k=agegomp;k<agemortsup;k++)
                   7021:       lsurv[k+1]=lsurv[k]-lsurv[k]*(p[1]*exp(p[2]*(k-agegomp)));
                   7022:     
                   7023:     for (k=agegomp;k<agemortsup;k++){
                   7024:       lpop[k]=(lsurv[k]+lsurv[k+1])/2.;
                   7025:       sumlpop=sumlpop+lpop[k];
                   7026:     }
                   7027:     
                   7028:     tpop[agegomp]=sumlpop;
                   7029:     for (k=agegomp;k<(agemortsup-3);k++){
                   7030:       /*  tpop[k+1]=2;*/
                   7031:       tpop[k+1]=tpop[k]-lpop[k];
                   7032:     }
                   7033:     
                   7034:     
                   7035:     printf("\nAge   lx     qx    dx    Lx     Tx     e(x)\n");
                   7036:     for (k=agegomp;k<(agemortsup-2);k++) 
                   7037:       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]);
                   7038:     
                   7039:     
                   7040:     replace_back_to_slash(pathc,pathcd); /* Even gnuplot wants a / */
                   7041:     printinggnuplotmort(fileres, optionfilefiname,ageminpar,agemaxpar,fage, pathc,p);
                   7042:     
                   7043:     printinghtmlmort(fileres,title,datafile, firstpass, lastpass, \
                   7044:                     stepm, weightopt,\
                   7045:                     model,imx,p,matcov,agemortsup);
                   7046:     
                   7047:     free_vector(lsurv,1,AGESUP);
                   7048:     free_vector(lpop,1,AGESUP);
                   7049:     free_vector(tpop,1,AGESUP);
1.136     brouard  7050: #ifdef GSL
                   7051:     free_ivector(cens,1,n);
                   7052:     free_vector(agecens,1,n);
                   7053:     free_ivector(dcwave,1,n);
                   7054:     free_matrix(ximort,1,NDIM,1,NDIM);
                   7055: #endif
1.186     brouard  7056:   } /* Endof if mle==-3 mortality only */
                   7057:   /* Standard maximisation */
1.126     brouard  7058:   else{ /* For mle >=1 */
1.132     brouard  7059:     globpr=0;/* debug */
1.186     brouard  7060:     /* Computes likelihood for initial parameters */
1.132     brouard  7061:     likelione(ficres, p, npar, nlstate, &globpr, &ipmx, &sw, &fretone, funcone); /* Prints the contributions to the likelihood */
1.126     brouard  7062:     printf("First Likeli=%12.6f ipmx=%ld sw=%12.6f",fretone,ipmx,sw);
                   7063:     for (k=1; k<=npar;k++)
                   7064:       printf(" %d %8.5f",k,p[k]);
                   7065:     printf("\n");
1.186     brouard  7066:     globpr=1; /* again, to print the contributions */
1.126     brouard  7067:     likelione(ficres, p, npar, nlstate, &globpr, &ipmx, &sw, &fretone, funcone); /* Prints the contributions to the likelihood */
                   7068:     printf("Second Likeli=%12.6f ipmx=%ld sw=%12.6f",fretone,ipmx,sw);
                   7069:     for (k=1; k<=npar;k++)
                   7070:       printf(" %d %8.5f",k,p[k]);
                   7071:     printf("\n");
1.186     brouard  7072:     if(mle>=1){ /* Could be 1 or 2, Real Maximisation */
1.126     brouard  7073:       mlikeli(ficres,p, npar, ncovmodel, nlstate, ftol, func);
                   7074:     }
                   7075:     
                   7076:     /*--------- results files --------------*/
1.187   ! brouard  7077:     fprintf(ficres,"title=%s datafile=%s lastobs=%d firstpass=%d lastpass=%d\nftol=%e stepm=%d ncovcol=%d nlstate=%d ndeath=%d maxwav=%d mle= 0 weight=%d\nmodel=1+age+%s\n", title, datafile, lastobs, firstpass,lastpass,ftol, stepm, ncovcol, nlstate, ndeath, maxwav, weightopt,model);
1.126     brouard  7078:     
                   7079:     
                   7080:     fprintf(ficres,"# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
                   7081:     printf("# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
                   7082:     fprintf(ficlog,"# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
                   7083:     for(i=1,jk=1; i <=nlstate; i++){
                   7084:       for(k=1; k <=(nlstate+ndeath); k++){
                   7085:        if (k != i) {
                   7086:          printf("%d%d ",i,k);
                   7087:          fprintf(ficlog,"%d%d ",i,k);
                   7088:          fprintf(ficres,"%1d%1d ",i,k);
                   7089:          for(j=1; j <=ncovmodel; j++){
                   7090:            printf("%lf ",p[jk]);
                   7091:            fprintf(ficlog,"%lf ",p[jk]);
                   7092:            fprintf(ficres,"%lf ",p[jk]);
                   7093:            jk++; 
                   7094:          }
                   7095:          printf("\n");
                   7096:          fprintf(ficlog,"\n");
                   7097:          fprintf(ficres,"\n");
                   7098:        }
                   7099:       }
                   7100:     }
                   7101:     if(mle!=0){
                   7102:       /* Computing hessian and covariance matrix */
                   7103:       ftolhess=ftol; /* Usually correct */
                   7104:       hesscov(matcov, p, npar, delti, ftolhess, func);
                   7105:     }
                   7106:     fprintf(ficres,"# Scales (for hessian or gradient estimation)\n");
                   7107:     printf("# Scales (for hessian or gradient estimation)\n");
                   7108:     fprintf(ficlog,"# Scales (for hessian or gradient estimation)\n");
                   7109:     for(i=1,jk=1; i <=nlstate; i++){
                   7110:       for(j=1; j <=nlstate+ndeath; j++){
                   7111:        if (j!=i) {
                   7112:          fprintf(ficres,"%1d%1d",i,j);
                   7113:          printf("%1d%1d",i,j);
                   7114:          fprintf(ficlog,"%1d%1d",i,j);
                   7115:          for(k=1; k<=ncovmodel;k++){
                   7116:            printf(" %.5e",delti[jk]);
                   7117:            fprintf(ficlog," %.5e",delti[jk]);
                   7118:            fprintf(ficres," %.5e",delti[jk]);
                   7119:            jk++;
                   7120:          }
                   7121:          printf("\n");
                   7122:          fprintf(ficlog,"\n");
                   7123:          fprintf(ficres,"\n");
                   7124:        }
                   7125:       }
                   7126:     }
                   7127:     
                   7128:     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");
                   7129:     if(mle>=1)
                   7130:       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");
                   7131:     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");
                   7132:     /* # 121 Var(a12)\n\ */
                   7133:     /* # 122 Cov(b12,a12) Var(b12)\n\ */
                   7134:     /* # 131 Cov(a13,a12) Cov(a13,b12, Var(a13)\n\ */
                   7135:     /* # 132 Cov(b13,a12) Cov(b13,b12, Cov(b13,a13) Var(b13)\n\ */
                   7136:     /* # 212 Cov(a21,a12) Cov(a21,b12, Cov(a21,a13) Cov(a21,b13) Var(a21)\n\ */
                   7137:     /* # 212 Cov(b21,a12) Cov(b21,b12, Cov(b21,a13) Cov(b21,b13) Cov(b21,a21) Var(b21)\n\ */
                   7138:     /* # 232 Cov(a23,a12) Cov(a23,b12, Cov(a23,a13) Cov(a23,b13) Cov(a23,a21) Cov(a23,b21) Var(a23)\n\ */
                   7139:     /* # 232 Cov(b23,a12) Cov(b23,b12) ... Var (b23)\n" */
                   7140:     
                   7141:     
                   7142:     /* Just to have a covariance matrix which will be more understandable
                   7143:        even is we still don't want to manage dictionary of variables
                   7144:     */
                   7145:     for(itimes=1;itimes<=2;itimes++){
                   7146:       jj=0;
                   7147:       for(i=1; i <=nlstate; i++){
                   7148:        for(j=1; j <=nlstate+ndeath; j++){
                   7149:          if(j==i) continue;
                   7150:          for(k=1; k<=ncovmodel;k++){
                   7151:            jj++;
                   7152:            ca[0]= k+'a'-1;ca[1]='\0';
                   7153:            if(itimes==1){
                   7154:              if(mle>=1)
                   7155:                printf("#%1d%1d%d",i,j,k);
                   7156:              fprintf(ficlog,"#%1d%1d%d",i,j,k);
                   7157:              fprintf(ficres,"#%1d%1d%d",i,j,k);
                   7158:            }else{
                   7159:              if(mle>=1)
                   7160:                printf("%1d%1d%d",i,j,k);
                   7161:              fprintf(ficlog,"%1d%1d%d",i,j,k);
                   7162:              fprintf(ficres,"%1d%1d%d",i,j,k);
                   7163:            }
                   7164:            ll=0;
                   7165:            for(li=1;li <=nlstate; li++){
                   7166:              for(lj=1;lj <=nlstate+ndeath; lj++){
                   7167:                if(lj==li) continue;
                   7168:                for(lk=1;lk<=ncovmodel;lk++){
                   7169:                  ll++;
                   7170:                  if(ll<=jj){
                   7171:                    cb[0]= lk +'a'-1;cb[1]='\0';
                   7172:                    if(ll<jj){
                   7173:                      if(itimes==1){
                   7174:                        if(mle>=1)
                   7175:                          printf(" Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
                   7176:                        fprintf(ficlog," Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
                   7177:                        fprintf(ficres," Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
                   7178:                      }else{
                   7179:                        if(mle>=1)
                   7180:                          printf(" %.5e",matcov[jj][ll]); 
                   7181:                        fprintf(ficlog," %.5e",matcov[jj][ll]); 
                   7182:                        fprintf(ficres," %.5e",matcov[jj][ll]); 
                   7183:                      }
                   7184:                    }else{
                   7185:                      if(itimes==1){
                   7186:                        if(mle>=1)
                   7187:                          printf(" Var(%s%1d%1d)",ca,i,j);
                   7188:                        fprintf(ficlog," Var(%s%1d%1d)",ca,i,j);
                   7189:                        fprintf(ficres," Var(%s%1d%1d)",ca,i,j);
                   7190:                      }else{
                   7191:                        if(mle>=1)
                   7192:                          printf(" %.5e",matcov[jj][ll]); 
                   7193:                        fprintf(ficlog," %.5e",matcov[jj][ll]); 
                   7194:                        fprintf(ficres," %.5e",matcov[jj][ll]); 
                   7195:                      }
                   7196:                    }
                   7197:                  }
                   7198:                } /* end lk */
                   7199:              } /* end lj */
                   7200:            } /* end li */
                   7201:            if(mle>=1)
                   7202:              printf("\n");
                   7203:            fprintf(ficlog,"\n");
                   7204:            fprintf(ficres,"\n");
                   7205:            numlinepar++;
                   7206:          } /* end k*/
                   7207:        } /*end j */
                   7208:       } /* end i */
                   7209:     } /* end itimes */
                   7210:     
                   7211:     fflush(ficlog);
                   7212:     fflush(ficres);
                   7213:     
                   7214:     while((c=getc(ficpar))=='#' && c!= EOF){
                   7215:       ungetc(c,ficpar);
                   7216:       fgets(line, MAXLINE, ficpar);
1.141     brouard  7217:       fputs(line,stdout);
1.126     brouard  7218:       fputs(line,ficparo);
                   7219:     }
                   7220:     ungetc(c,ficpar);
                   7221:     
                   7222:     estepm=0;
                   7223:     fscanf(ficpar,"agemin=%lf agemax=%lf bage=%lf fage=%lf estepm=%d\n",&ageminpar,&agemaxpar, &bage, &fage, &estepm);
                   7224:     if (estepm==0 || estepm < stepm) estepm=stepm;
                   7225:     if (fage <= 2) {
                   7226:       bage = ageminpar;
                   7227:       fage = agemaxpar;
                   7228:     }
                   7229:     
                   7230:     fprintf(ficres,"# agemin agemax for life expectancy, bage fage (if mle==0 ie no data nor Max likelihood).\n");
                   7231:     fprintf(ficres,"agemin=%.0f agemax=%.0f bage=%.0f fage=%.0f estepm=%d\n",ageminpar,agemaxpar,bage,fage, estepm);
                   7232:     fprintf(ficparo,"agemin=%.0f agemax=%.0f bage=%.0f fage=%.0f estepm=%d\n",ageminpar,agemaxpar,bage,fage, estepm);
1.186     brouard  7233: 
                   7234:     /* Other stuffs, more or less useful */    
1.126     brouard  7235:     while((c=getc(ficpar))=='#' && c!= EOF){
                   7236:       ungetc(c,ficpar);
                   7237:       fgets(line, MAXLINE, ficpar);
1.141     brouard  7238:       fputs(line,stdout);
1.126     brouard  7239:       fputs(line,ficparo);
                   7240:     }
                   7241:     ungetc(c,ficpar);
                   7242:     
                   7243:     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);
                   7244:     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);
                   7245:     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);
                   7246:     printf("begin-prev-date=%.lf/%.lf/%.lf end-prev-date=%.lf/%.lf/%.lf mov_average=%d\n",jprev1, mprev1,anprev1,jprev2, mprev2,anprev2,mobilav);
                   7247:     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);
                   7248:     
                   7249:     while((c=getc(ficpar))=='#' && c!= EOF){
                   7250:       ungetc(c,ficpar);
                   7251:       fgets(line, MAXLINE, ficpar);
1.141     brouard  7252:       fputs(line,stdout);
1.126     brouard  7253:       fputs(line,ficparo);
                   7254:     }
                   7255:     ungetc(c,ficpar);
                   7256:     
                   7257:     
                   7258:     dateprev1=anprev1+(mprev1-1)/12.+(jprev1-1)/365.;
                   7259:     dateprev2=anprev2+(mprev2-1)/12.+(jprev2-1)/365.;
                   7260:     
                   7261:     fscanf(ficpar,"pop_based=%d\n",&popbased);
                   7262:     fprintf(ficparo,"pop_based=%d\n",popbased);   
                   7263:     fprintf(ficres,"pop_based=%d\n",popbased);   
                   7264:     
                   7265:     while((c=getc(ficpar))=='#' && c!= EOF){
                   7266:       ungetc(c,ficpar);
                   7267:       fgets(line, MAXLINE, ficpar);
1.141     brouard  7268:       fputs(line,stdout);
1.126     brouard  7269:       fputs(line,ficparo);
                   7270:     }
                   7271:     ungetc(c,ficpar);
                   7272:     
                   7273:     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);
                   7274:     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);
                   7275:     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);
                   7276:     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);
                   7277:     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);
                   7278:     /* day and month of proj2 are not used but only year anproj2.*/
                   7279:     
                   7280:     
                   7281:     
1.145     brouard  7282:      /* freqsummary(fileres, agemin, agemax, s, agev, nlstate, imx,Tvaraff,nbcode, ncodemax,mint,anint); */
                   7283:     /* ,dateprev1,dateprev2,jprev1, mprev1,anprev1,jprev2, mprev2,anprev2); */
1.126     brouard  7284:     
                   7285:     replace_back_to_slash(pathc,pathcd); /* Even gnuplot wants a / */
                   7286:     printinggnuplot(fileres, optionfilefiname,ageminpar,agemaxpar,fage, pathc,p);
                   7287:     
                   7288:     printinghtml(fileres,title,datafile, firstpass, lastpass, stepm, weightopt,\
                   7289:                 model,imx,jmin,jmax,jmean,rfileres,popforecast,estepm,\
                   7290:                 jprev1,mprev1,anprev1,jprev2,mprev2,anprev2);
                   7291:       
                   7292:    /*------------ free_vector  -------------*/
                   7293:    /*  chdir(path); */
                   7294:  
                   7295:     free_ivector(wav,1,imx);
                   7296:     free_imatrix(dh,1,lastpass-firstpass+1,1,imx);
                   7297:     free_imatrix(bh,1,lastpass-firstpass+1,1,imx);
                   7298:     free_imatrix(mw,1,lastpass-firstpass+1,1,imx);   
                   7299:     free_lvector(num,1,n);
                   7300:     free_vector(agedc,1,n);
                   7301:     /*free_matrix(covar,0,NCOVMAX,1,n);*/
                   7302:     /*free_matrix(covar,1,NCOVMAX,1,n);*/
                   7303:     fclose(ficparo);
                   7304:     fclose(ficres);
                   7305: 
                   7306: 
1.186     brouard  7307:     /* Other results (useful)*/
                   7308: 
                   7309: 
1.126     brouard  7310:     /*--------------- Prevalence limit  (period or stable prevalence) --------------*/
1.180     brouard  7311:     /*#include "prevlim.h"*/  /* Use ficrespl, ficlog */
                   7312:     prlim=matrix(1,nlstate,1,nlstate);
                   7313:     prevalence_limit(p, prlim,  ageminpar, agemaxpar);
1.126     brouard  7314:     fclose(ficrespl);
                   7315: 
1.145     brouard  7316: #ifdef FREEEXIT2
                   7317: #include "freeexit2.h"
                   7318: #endif
                   7319: 
1.126     brouard  7320:     /*------------- h Pij x at various ages ------------*/
1.180     brouard  7321:     /*#include "hpijx.h"*/
                   7322:     hPijx(p, bage, fage);
1.145     brouard  7323:     fclose(ficrespij);
1.126     brouard  7324: 
1.145     brouard  7325:   /*-------------- Variance of one-step probabilities---*/
                   7326:     k=1;
1.126     brouard  7327:     varprob(optionfilefiname, matcov, p, delti, nlstate, bage, fage,k,Tvar,nbcode, ncodemax,strstart);
                   7328: 
                   7329: 
                   7330:     probs= ma3x(1,AGESUP,1,NCOVMAX, 1,NCOVMAX);
                   7331:     for(i=1;i<=AGESUP;i++)
                   7332:       for(j=1;j<=NCOVMAX;j++)
                   7333:        for(k=1;k<=NCOVMAX;k++)
                   7334:          probs[i][j][k]=0.;
                   7335: 
                   7336:     /*---------- Forecasting ------------------*/
                   7337:     /*if((stepm == 1) && (strcmp(model,".")==0)){*/
                   7338:     if(prevfcast==1){
                   7339:       /*    if(stepm ==1){*/
                   7340:       prevforecast(fileres, anproj1, mproj1, jproj1, agemin, agemax, dateprev1, dateprev2, mobilavproj, bage, fage, firstpass, lastpass, anproj2, p, cptcoveff);
                   7341:       /* (popforecast==1) populforecast(fileres, anpyram,mpyram,jpyram, agemin,agemax, dateprev1, dateprev2,mobilav, agedeb, fage, popforecast, popfile, anpyram1,p, i1);*/
                   7342:       /*      }  */
                   7343:       /*      else{ */
                   7344:       /*        erreur=108; */
                   7345:       /*        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); */
                   7346:       /*        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); */
                   7347:       /*      } */
                   7348:     }
1.186     brouard  7349:  
                   7350:     /* ------ Other prevalence ratios------------ */
1.126     brouard  7351: 
1.127     brouard  7352:     /* Computes prevalence between agemin (i.e minimal age computed) and no more ageminpar */
                   7353: 
                   7354:     prevalence(probs, agemin, agemax, s, agev, nlstate, imx, Tvar, nbcode, ncodemax, mint, anint, dateprev1, dateprev2, firstpass, lastpass);
                   7355:     /*  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",\
                   7356:        ageminpar, agemax, s[lastpass][imx], agev[lastpass][imx], nlstate, imx, mint[lastpass][imx],anint[lastpass][imx], dateprev1, dateprev2, firstpass, lastpass);
                   7357:     */
1.126     brouard  7358: 
1.127     brouard  7359:     if (mobilav!=0) {
                   7360:       mobaverage= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
                   7361:       if (movingaverage(probs, bage, fage, mobaverage,mobilav)!=0){
                   7362:        fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav);
                   7363:        printf(" Error in movingaverage mobilav=%d\n",mobilav);
                   7364:       }
1.126     brouard  7365:     }
                   7366: 
                   7367: 
1.127     brouard  7368:     /*---------- Health expectancies, no variances ------------*/
                   7369: 
1.126     brouard  7370:     strcpy(filerese,"e");
                   7371:     strcat(filerese,fileres);
                   7372:     if((ficreseij=fopen(filerese,"w"))==NULL) {
                   7373:       printf("Problem with Health Exp. resultfile: %s\n", filerese); exit(0);
                   7374:       fprintf(ficlog,"Problem with Health Exp. resultfile: %s\n", filerese); exit(0);
                   7375:     }
                   7376:     printf("Computing Health Expectancies: result on file '%s' \n", filerese);
                   7377:     fprintf(ficlog,"Computing Health Expectancies: result on file '%s' \n", filerese);
1.145     brouard  7378:     /*for(cptcov=1,k=0;cptcov<=i1;cptcov++){
                   7379:       for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){*/
                   7380:           
                   7381:     for (k=1; k <= (int) pow(2,cptcoveff); k++){
1.127     brouard  7382:        fprintf(ficreseij,"\n#****** ");
                   7383:        for(j=1;j<=cptcoveff;j++) {
                   7384:          fprintf(ficreseij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
                   7385:        }
                   7386:        fprintf(ficreseij,"******\n");
                   7387: 
                   7388:        eij=ma3x(1,nlstate,1,nlstate,(int) bage, (int) fage);
                   7389:        oldm=oldms;savm=savms;
                   7390:        evsij(eij, p, nlstate, stepm, (int) bage, (int)fage, oldm, savm, k, estepm, strstart);  
                   7391:       
                   7392:        free_ma3x(eij,1,nlstate,1,nlstate,(int) bage, (int)fage);
1.145     brouard  7393:       /*}*/
1.127     brouard  7394:     }
                   7395:     fclose(ficreseij);
                   7396: 
                   7397: 
                   7398:     /*---------- Health expectancies and variances ------------*/
                   7399: 
                   7400: 
                   7401:     strcpy(filerest,"t");
                   7402:     strcat(filerest,fileres);
                   7403:     if((ficrest=fopen(filerest,"w"))==NULL) {
                   7404:       printf("Problem with total LE resultfile: %s\n", filerest);goto end;
                   7405:       fprintf(ficlog,"Problem with total LE resultfile: %s\n", filerest);goto end;
                   7406:     }
                   7407:     printf("Computing Total Life expectancies with their standard errors: file '%s' \n", filerest); 
                   7408:     fprintf(ficlog,"Computing Total Life expectancies with their standard errors: file '%s' \n", filerest); 
                   7409: 
1.126     brouard  7410: 
                   7411:     strcpy(fileresstde,"stde");
                   7412:     strcat(fileresstde,fileres);
                   7413:     if((ficresstdeij=fopen(fileresstde,"w"))==NULL) {
                   7414:       printf("Problem with Health Exp. and std errors resultfile: %s\n", fileresstde); exit(0);
                   7415:       fprintf(ficlog,"Problem with Health Exp. and std errors resultfile: %s\n", fileresstde); exit(0);
                   7416:     }
                   7417:     printf("Computing Health Expectancies and standard errors: result on file '%s' \n", fileresstde);
                   7418:     fprintf(ficlog,"Computing Health Expectancies and standard errors: result on file '%s' \n", fileresstde);
                   7419: 
                   7420:     strcpy(filerescve,"cve");
                   7421:     strcat(filerescve,fileres);
                   7422:     if((ficrescveij=fopen(filerescve,"w"))==NULL) {
                   7423:       printf("Problem with Covar. Health Exp. resultfile: %s\n", filerescve); exit(0);
                   7424:       fprintf(ficlog,"Problem with Covar. Health Exp. resultfile: %s\n", filerescve); exit(0);
                   7425:     }
                   7426:     printf("Computing Covar. of Health Expectancies: result on file '%s' \n", filerescve);
                   7427:     fprintf(ficlog,"Computing Covar. of Health Expectancies: result on file '%s' \n", filerescve);
                   7428: 
                   7429:     strcpy(fileresv,"v");
                   7430:     strcat(fileresv,fileres);
                   7431:     if((ficresvij=fopen(fileresv,"w"))==NULL) {
                   7432:       printf("Problem with variance resultfile: %s\n", fileresv);exit(0);
                   7433:       fprintf(ficlog,"Problem with variance resultfile: %s\n", fileresv);exit(0);
                   7434:     }
                   7435:     printf("Computing Variance-covariance of DFLEs: file '%s' \n", fileresv);
                   7436:     fprintf(ficlog,"Computing Variance-covariance of DFLEs: file '%s' \n", fileresv);
                   7437: 
1.145     brouard  7438:     /*for(cptcov=1,k=0;cptcov<=i1;cptcov++){
                   7439:       for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){*/
                   7440:           
                   7441:     for (k=1; k <= (int) pow(2,cptcoveff); k++){
                   7442:        fprintf(ficrest,"\n#****** ");
1.126     brouard  7443:        for(j=1;j<=cptcoveff;j++) 
                   7444:          fprintf(ficrest,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
                   7445:        fprintf(ficrest,"******\n");
                   7446: 
                   7447:        fprintf(ficresstdeij,"\n#****** ");
                   7448:        fprintf(ficrescveij,"\n#****** ");
                   7449:        for(j=1;j<=cptcoveff;j++) {
                   7450:          fprintf(ficresstdeij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
                   7451:          fprintf(ficrescveij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
                   7452:        }
                   7453:        fprintf(ficresstdeij,"******\n");
                   7454:        fprintf(ficrescveij,"******\n");
                   7455: 
                   7456:        fprintf(ficresvij,"\n#****** ");
                   7457:        for(j=1;j<=cptcoveff;j++) 
                   7458:          fprintf(ficresvij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
                   7459:        fprintf(ficresvij,"******\n");
                   7460: 
                   7461:        eij=ma3x(1,nlstate,1,nlstate,(int) bage, (int) fage);
                   7462:        oldm=oldms;savm=savms;
1.127     brouard  7463:        cvevsij(eij, p, nlstate, stepm, (int) bage, (int)fage, oldm, savm, k, estepm, delti, matcov, strstart);  
1.145     brouard  7464:        /*
                   7465:         */
                   7466:        /* goto endfree; */
1.126     brouard  7467:  
                   7468:        vareij=ma3x(1,nlstate,1,nlstate,(int) bage, (int) fage);
                   7469:        pstamp(ficrest);
1.145     brouard  7470: 
                   7471: 
1.128     brouard  7472:        for(vpopbased=0; vpopbased <= popbased; vpopbased++){ /* Done for vpopbased=0 and vpopbased=1 if popbased==1*/
1.145     brouard  7473:          oldm=oldms;savm=savms; /* Segmentation fault */
1.161     brouard  7474:          cptcod= 0; /* To be deleted */
                   7475:          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  7476:          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  7477:          if(vpopbased==1)
                   7478:            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);
                   7479:          else
                   7480:            fprintf(ficrest,"the age specific period (stable) prevalences in each health state \n");
                   7481:          fprintf(ficrest,"# Age e.. (std) ");
                   7482:          for (i=1;i<=nlstate;i++) fprintf(ficrest,"e.%d (std) ",i);
                   7483:          fprintf(ficrest,"\n");
1.126     brouard  7484: 
1.128     brouard  7485:          epj=vector(1,nlstate+1);
                   7486:          for(age=bage; age <=fage ;age++){
                   7487:            prevalim(prlim, nlstate, p, age, oldm, savm,ftolpl,k);
                   7488:            if (vpopbased==1) {
                   7489:              if(mobilav ==0){
                   7490:                for(i=1; i<=nlstate;i++)
                   7491:                  prlim[i][i]=probs[(int)age][i][k];
                   7492:              }else{ /* mobilav */ 
                   7493:                for(i=1; i<=nlstate;i++)
                   7494:                  prlim[i][i]=mobaverage[(int)age][i][k];
                   7495:              }
1.126     brouard  7496:            }
                   7497:        
1.128     brouard  7498:            fprintf(ficrest," %4.0f",age);
                   7499:            for(j=1, epj[nlstate+1]=0.;j <=nlstate;j++){
                   7500:              for(i=1, epj[j]=0.;i <=nlstate;i++) {
                   7501:                epj[j] += prlim[i][i]*eij[i][j][(int)age];
                   7502:                /*  printf("%lf %lf ", prlim[i][i] ,eij[i][j][(int)age]);*/
                   7503:              }
                   7504:              epj[nlstate+1] +=epj[j];
1.126     brouard  7505:            }
                   7506: 
1.128     brouard  7507:            for(i=1, vepp=0.;i <=nlstate;i++)
                   7508:              for(j=1;j <=nlstate;j++)
                   7509:                vepp += vareij[i][j][(int)age];
                   7510:            fprintf(ficrest," %7.3f (%7.3f)", epj[nlstate+1],sqrt(vepp));
                   7511:            for(j=1;j <=nlstate;j++){
                   7512:              fprintf(ficrest," %7.3f (%7.3f)", epj[j],sqrt(vareij[j][j][(int)age]));
                   7513:            }
                   7514:            fprintf(ficrest,"\n");
1.126     brouard  7515:          }
                   7516:        }
                   7517:        free_ma3x(eij,1,nlstate,1,nlstate,(int) bage, (int)fage);
                   7518:        free_ma3x(vareij,1,nlstate,1,nlstate,(int) bage, (int)fage);
                   7519:        free_vector(epj,1,nlstate+1);
1.145     brouard  7520:       /*}*/
1.126     brouard  7521:     }
                   7522:     free_vector(weight,1,n);
1.145     brouard  7523:     free_imatrix(Tvard,1,NCOVMAX,1,2);
1.126     brouard  7524:     free_imatrix(s,1,maxwav+1,1,n);
                   7525:     free_matrix(anint,1,maxwav,1,n); 
                   7526:     free_matrix(mint,1,maxwav,1,n);
                   7527:     free_ivector(cod,1,n);
                   7528:     free_ivector(tab,1,NCOVMAX);
                   7529:     fclose(ficresstdeij);
                   7530:     fclose(ficrescveij);
                   7531:     fclose(ficresvij);
                   7532:     fclose(ficrest);
                   7533:     fclose(ficpar);
                   7534:   
                   7535:     /*------- Variance of period (stable) prevalence------*/   
                   7536: 
                   7537:     strcpy(fileresvpl,"vpl");
                   7538:     strcat(fileresvpl,fileres);
                   7539:     if((ficresvpl=fopen(fileresvpl,"w"))==NULL) {
                   7540:       printf("Problem with variance of period (stable) prevalence  resultfile: %s\n", fileresvpl);
                   7541:       exit(0);
                   7542:     }
                   7543:     printf("Computing Variance-covariance of period (stable) prevalence: file '%s' \n", fileresvpl);
                   7544: 
1.145     brouard  7545:     /*for(cptcov=1,k=0;cptcov<=i1;cptcov++){
                   7546:       for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){*/
                   7547:           
                   7548:     for (k=1; k <= (int) pow(2,cptcoveff); k++){
                   7549:        fprintf(ficresvpl,"\n#****** ");
1.126     brouard  7550:        for(j=1;j<=cptcoveff;j++) 
                   7551:          fprintf(ficresvpl,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
                   7552:        fprintf(ficresvpl,"******\n");
                   7553:       
                   7554:        varpl=matrix(1,nlstate,(int) bage, (int) fage);
                   7555:        oldm=oldms;savm=savms;
                   7556:        varprevlim(fileres, varpl, matcov, p, delti, nlstate, stepm, (int) bage, (int) fage, oldm, savm, prlim, ftolpl,k,strstart);
                   7557:        free_matrix(varpl,1,nlstate,(int) bage, (int)fage);
1.145     brouard  7558:       /*}*/
1.126     brouard  7559:     }
                   7560: 
                   7561:     fclose(ficresvpl);
                   7562: 
                   7563:     /*---------- End : free ----------------*/
                   7564:     if (mobilav!=0) free_ma3x(mobaverage,1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
                   7565:     free_ma3x(probs,1,AGESUP,1,NCOVMAX, 1,NCOVMAX);
                   7566:   }  /* mle==-3 arrives here for freeing */
1.164     brouard  7567:  /* endfree:*/
1.141     brouard  7568:     free_matrix(prlim,1,nlstate,1,nlstate); /*here or after loop ? */
1.126     brouard  7569:     free_matrix(pmmij,1,nlstate+ndeath,1,nlstate+ndeath);
                   7570:     free_matrix(oldms, 1,nlstate+ndeath,1,nlstate+ndeath);
                   7571:     free_matrix(newms, 1,nlstate+ndeath,1,nlstate+ndeath);
                   7572:     free_matrix(savms, 1,nlstate+ndeath,1,nlstate+ndeath);
                   7573:     free_matrix(covar,0,NCOVMAX,1,n);
                   7574:     free_matrix(matcov,1,npar,1,npar);
                   7575:     /*free_vector(delti,1,npar);*/
                   7576:     free_ma3x(delti3,1,nlstate,1, nlstate+ndeath-1,1,ncovmodel); 
                   7577:     free_matrix(agev,1,maxwav,1,imx);
                   7578:     free_ma3x(param,1,nlstate,1, nlstate+ndeath-1,1,ncovmodel);
                   7579: 
1.145     brouard  7580:     free_ivector(ncodemax,1,NCOVMAX);
                   7581:     free_ivector(Tvar,1,NCOVMAX);
                   7582:     free_ivector(Tprod,1,NCOVMAX);
                   7583:     free_ivector(Tvaraff,1,NCOVMAX);
                   7584:     free_ivector(Tage,1,NCOVMAX);
1.126     brouard  7585: 
                   7586:     free_imatrix(nbcode,0,NCOVMAX,0,NCOVMAX);
                   7587:     free_imatrix(codtab,1,100,1,10);
                   7588:   fflush(fichtm);
                   7589:   fflush(ficgp);
                   7590:   
                   7591: 
                   7592:   if((nberr >0) || (nbwarn>0)){
                   7593:     printf("End of Imach with %d errors and/or %d warnings\n",nberr,nbwarn);
                   7594:     fprintf(ficlog,"End of Imach with %d errors and/or warnings %d\n",nberr,nbwarn);
                   7595:   }else{
                   7596:     printf("End of Imach\n");
                   7597:     fprintf(ficlog,"End of Imach\n");
                   7598:   }
                   7599:   printf("See log file on %s\n",filelog);
                   7600:   /*  gettimeofday(&end_time, (struct timezone*)0);*/  /* after time */
1.157     brouard  7601:   /*(void) gettimeofday(&end_time,&tzp);*/
                   7602:   rend_time = time(NULL);  
                   7603:   end_time = *localtime(&rend_time);
                   7604:   /* tml = *localtime(&end_time.tm_sec); */
                   7605:   strcpy(strtend,asctime(&end_time));
1.126     brouard  7606:   printf("Local time at start %s\nLocal time at end   %s",strstart, strtend); 
                   7607:   fprintf(ficlog,"Local time at start %s\nLocal time at end   %s\n",strstart, strtend); 
1.157     brouard  7608:   printf("Total time used %s\n", asc_diff_time(rend_time -rstart_time,tmpout));
1.126     brouard  7609: 
1.157     brouard  7610:   printf("Total time was %.0lf Sec.\n", difftime(rend_time,rstart_time));
                   7611:   fprintf(ficlog,"Total time used %s\n", asc_diff_time(rend_time -rstart_time,tmpout));
                   7612:   fprintf(ficlog,"Total time was %.0lf Sec.\n", difftime(rend_time,rstart_time));
1.126     brouard  7613:   /*  printf("Total time was %d uSec.\n", total_usecs);*/
                   7614: /*   if(fileappend(fichtm,optionfilehtm)){ */
                   7615:   fprintf(fichtm,"<br>Local time at start %s<br>Local time at end   %s<br>\n</body></html>",strstart, strtend);
                   7616:   fclose(fichtm);
                   7617:   fprintf(fichtmcov,"<br>Local time at start %s<br>Local time at end   %s<br>\n</body></html>",strstart, strtend);
                   7618:   fclose(fichtmcov);
                   7619:   fclose(ficgp);
                   7620:   fclose(ficlog);
                   7621:   /*------ End -----------*/
                   7622: 
                   7623: 
                   7624:    printf("Before Current directory %s!\n",pathcd);
1.184     brouard  7625: #ifdef WIN32
                   7626:    if (_chdir(pathcd) != 0)
                   7627:           printf("Can't move to directory %s!\n",path);
                   7628:    if(_getcwd(pathcd,MAXLINE) > 0)
                   7629: #else
1.126     brouard  7630:    if(chdir(pathcd) != 0)
1.184     brouard  7631:           printf("Can't move to directory %s!\n", path);
                   7632:    if (getcwd(pathcd, MAXLINE) > 0)
                   7633: #endif 
1.126     brouard  7634:     printf("Current directory %s!\n",pathcd);
                   7635:   /*strcat(plotcmd,CHARSEPARATOR);*/
                   7636:   sprintf(plotcmd,"gnuplot");
1.157     brouard  7637: #ifdef _WIN32
1.126     brouard  7638:   sprintf(plotcmd,"\"%sgnuplot.exe\"",pathimach);
                   7639: #endif
                   7640:   if(!stat(plotcmd,&info)){
1.158     brouard  7641:     printf("Error or gnuplot program not found: '%s'\n",plotcmd);fflush(stdout);
1.126     brouard  7642:     if(!stat(getenv("GNUPLOTBIN"),&info)){
1.158     brouard  7643:       printf("Error or gnuplot program not found: '%s' Environment GNUPLOTBIN not set.\n",plotcmd);fflush(stdout);
1.126     brouard  7644:     }else
                   7645:       strcpy(pplotcmd,plotcmd);
1.157     brouard  7646: #ifdef __unix
1.126     brouard  7647:     strcpy(plotcmd,GNUPLOTPROGRAM);
                   7648:     if(!stat(plotcmd,&info)){
1.158     brouard  7649:       printf("Error gnuplot program not found: '%s'\n",plotcmd);fflush(stdout);
1.126     brouard  7650:     }else
                   7651:       strcpy(pplotcmd,plotcmd);
                   7652: #endif
                   7653:   }else
                   7654:     strcpy(pplotcmd,plotcmd);
                   7655:   
                   7656:   sprintf(plotcmd,"%s %s",pplotcmd, optionfilegnuplot);
1.158     brouard  7657:   printf("Starting graphs with: '%s'\n",plotcmd);fflush(stdout);
1.126     brouard  7658: 
                   7659:   if((outcmd=system(plotcmd)) != 0){
1.158     brouard  7660:     printf("gnuplot command might not be in your path: '%s', err=%d\n", plotcmd, outcmd);
1.154     brouard  7661:     printf("\n Trying if gnuplot resides on the same directory that IMaCh\n");
1.152     brouard  7662:     sprintf(plotcmd,"%sgnuplot %s", pathimach, optionfilegnuplot);
1.150     brouard  7663:     if((outcmd=system(plotcmd)) != 0)
1.153     brouard  7664:       printf("\n Still a problem with gnuplot command %s, err=%d\n", plotcmd, outcmd);
1.126     brouard  7665:   }
1.158     brouard  7666:   printf(" Successful, please wait...");
1.126     brouard  7667:   while (z[0] != 'q') {
                   7668:     /* chdir(path); */
1.154     brouard  7669:     printf("\nType e to edit results with your browser, g to graph again and q for exit: ");
1.126     brouard  7670:     scanf("%s",z);
                   7671: /*     if (z[0] == 'c') system("./imach"); */
                   7672:     if (z[0] == 'e') {
1.158     brouard  7673: #ifdef __APPLE__
1.152     brouard  7674:       sprintf(pplotcmd, "open %s", optionfilehtm);
1.157     brouard  7675: #elif __linux
                   7676:       sprintf(pplotcmd, "xdg-open %s", optionfilehtm);
1.153     brouard  7677: #else
1.152     brouard  7678:       sprintf(pplotcmd, "%s", optionfilehtm);
1.153     brouard  7679: #endif
                   7680:       printf("Starting browser with: %s",pplotcmd);fflush(stdout);
                   7681:       system(pplotcmd);
1.126     brouard  7682:     }
                   7683:     else if (z[0] == 'g') system(plotcmd);
                   7684:     else if (z[0] == 'q') exit(0);
                   7685:   }
                   7686:   end:
                   7687:   while (z[0] != 'q') {
                   7688:     printf("\nType  q for exiting: ");
                   7689:     scanf("%s",z);
                   7690:   }
                   7691: }

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