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

1.201   ! brouard     1: /* $Id: imach.c,v 1.200 2015/09/09 16:53:55 brouard Exp $
1.126     brouard     2:   $State: Exp $
1.163     brouard     3:   $Log: imach.c,v $
1.201   ! brouard     4:   Revision 1.200  2015/09/09 16:53:55  brouard
        !             5:   Summary: Big bug thanks to Flavia
        !             6: 
        !             7:   Even model=1+age+V2. did not work anymore
        !             8: 
1.200     brouard     9:   Revision 1.199  2015/09/07 14:09:23  brouard
                     10:   Summary: 0.98q6 changing default small png format for graph to vectorized svg.
                     11: 
1.199     brouard    12:   Revision 1.198  2015/09/03 07:14:39  brouard
                     13:   Summary: 0.98q5 Flavia
                     14: 
1.198     brouard    15:   Revision 1.197  2015/09/01 18:24:39  brouard
                     16:   *** empty log message ***
                     17: 
1.197     brouard    18:   Revision 1.196  2015/08/18 23:17:52  brouard
                     19:   Summary: 0.98q5
                     20: 
1.196     brouard    21:   Revision 1.195  2015/08/18 16:28:39  brouard
                     22:   Summary: Adding a hack for testing purpose
                     23: 
                     24:   After reading the title, ftol and model lines, if the comment line has
                     25:   a q, starting with #q, the answer at the end of the run is quit. It
                     26:   permits to run test files in batch with ctest. The former workaround was
                     27:   $ echo q | imach foo.imach
                     28: 
1.195     brouard    29:   Revision 1.194  2015/08/18 13:32:00  brouard
                     30:   Summary:  Adding error when the covariance matrix doesn't contain the exact number of lines required by the model line.
                     31: 
1.194     brouard    32:   Revision 1.193  2015/08/04 07:17:42  brouard
                     33:   Summary: 0.98q4
                     34: 
1.193     brouard    35:   Revision 1.192  2015/07/16 16:49:02  brouard
                     36:   Summary: Fixing some outputs
                     37: 
1.192     brouard    38:   Revision 1.191  2015/07/14 10:00:33  brouard
                     39:   Summary: Some fixes
                     40: 
1.191     brouard    41:   Revision 1.190  2015/05/05 08:51:13  brouard
                     42:   Summary: Adding digits in output parameters (7 digits instead of 6)
                     43: 
                     44:   Fix 1+age+.
                     45: 
1.190     brouard    46:   Revision 1.189  2015/04/30 14:45:16  brouard
                     47:   Summary: 0.98q2
                     48: 
1.189     brouard    49:   Revision 1.188  2015/04/30 08:27:53  brouard
                     50:   *** empty log message ***
                     51: 
1.188     brouard    52:   Revision 1.187  2015/04/29 09:11:15  brouard
                     53:   *** empty log message ***
                     54: 
1.187     brouard    55:   Revision 1.186  2015/04/23 12:01:52  brouard
                     56:   Summary: V1*age is working now, version 0.98q1
                     57: 
                     58:   Some codes had been disabled in order to simplify and Vn*age was
                     59:   working in the optimization phase, ie, giving correct MLE parameters,
                     60:   but, as usual, outputs were not correct and program core dumped.
                     61: 
1.186     brouard    62:   Revision 1.185  2015/03/11 13:26:42  brouard
                     63:   Summary: Inclusion of compile and links command line for Intel Compiler
                     64: 
1.185     brouard    65:   Revision 1.184  2015/03/11 11:52:39  brouard
                     66:   Summary: Back from Windows 8. Intel Compiler
                     67: 
1.184     brouard    68:   Revision 1.183  2015/03/10 20:34:32  brouard
                     69:   Summary: 0.98q0, trying with directest, mnbrak fixed
                     70: 
                     71:   We use directest instead of original Powell test; probably no
                     72:   incidence on the results, but better justifications;
                     73:   We fixed Numerical Recipes mnbrak routine which was wrong and gave
                     74:   wrong results.
                     75: 
1.183     brouard    76:   Revision 1.182  2015/02/12 08:19:57  brouard
                     77:   Summary: Trying to keep directest which seems simpler and more general
                     78:   Author: Nicolas Brouard
                     79: 
1.182     brouard    80:   Revision 1.181  2015/02/11 23:22:24  brouard
                     81:   Summary: Comments on Powell added
                     82: 
                     83:   Author:
                     84: 
1.181     brouard    85:   Revision 1.180  2015/02/11 17:33:45  brouard
                     86:   Summary: Finishing move from main to function (hpijx and prevalence_limit)
                     87: 
1.180     brouard    88:   Revision 1.179  2015/01/04 09:57:06  brouard
                     89:   Summary: back to OS/X
                     90: 
1.179     brouard    91:   Revision 1.178  2015/01/04 09:35:48  brouard
                     92:   *** empty log message ***
                     93: 
1.178     brouard    94:   Revision 1.177  2015/01/03 18:40:56  brouard
                     95:   Summary: Still testing ilc32 on OSX
                     96: 
1.177     brouard    97:   Revision 1.176  2015/01/03 16:45:04  brouard
                     98:   *** empty log message ***
                     99: 
1.176     brouard   100:   Revision 1.175  2015/01/03 16:33:42  brouard
                    101:   *** empty log message ***
                    102: 
1.175     brouard   103:   Revision 1.174  2015/01/03 16:15:49  brouard
                    104:   Summary: Still in cross-compilation
                    105: 
1.174     brouard   106:   Revision 1.173  2015/01/03 12:06:26  brouard
                    107:   Summary: trying to detect cross-compilation
                    108: 
1.173     brouard   109:   Revision 1.172  2014/12/27 12:07:47  brouard
                    110:   Summary: Back from Visual Studio and Intel, options for compiling for Windows XP
                    111: 
1.172     brouard   112:   Revision 1.171  2014/12/23 13:26:59  brouard
                    113:   Summary: Back from Visual C
                    114: 
                    115:   Still problem with utsname.h on Windows
                    116: 
1.171     brouard   117:   Revision 1.170  2014/12/23 11:17:12  brouard
                    118:   Summary: Cleaning some \%% back to %%
                    119: 
                    120:   The escape was mandatory for a specific compiler (which one?), but too many warnings.
                    121: 
1.170     brouard   122:   Revision 1.169  2014/12/22 23:08:31  brouard
                    123:   Summary: 0.98p
                    124: 
                    125:   Outputs some informations on compiler used, OS etc. Testing on different platforms.
                    126: 
1.169     brouard   127:   Revision 1.168  2014/12/22 15:17:42  brouard
1.170     brouard   128:   Summary: update
1.169     brouard   129: 
1.168     brouard   130:   Revision 1.167  2014/12/22 13:50:56  brouard
                    131:   Summary: Testing uname and compiler version and if compiled 32 or 64
                    132: 
                    133:   Testing on Linux 64
                    134: 
1.167     brouard   135:   Revision 1.166  2014/12/22 11:40:47  brouard
                    136:   *** empty log message ***
                    137: 
1.166     brouard   138:   Revision 1.165  2014/12/16 11:20:36  brouard
                    139:   Summary: After compiling on Visual C
                    140: 
                    141:   * imach.c (Module): Merging 1.61 to 1.162
                    142: 
1.165     brouard   143:   Revision 1.164  2014/12/16 10:52:11  brouard
                    144:   Summary: Merging with Visual C after suppressing some warnings for unused variables. Also fixing Saito's bug 0.98Xn
                    145: 
                    146:   * imach.c (Module): Merging 1.61 to 1.162
                    147: 
1.164     brouard   148:   Revision 1.163  2014/12/16 10:30:11  brouard
                    149:   * imach.c (Module): Merging 1.61 to 1.162
                    150: 
1.163     brouard   151:   Revision 1.162  2014/09/25 11:43:39  brouard
                    152:   Summary: temporary backup 0.99!
                    153: 
1.162     brouard   154:   Revision 1.1  2014/09/16 11:06:58  brouard
                    155:   Summary: With some code (wrong) for nlopt
                    156: 
                    157:   Author:
                    158: 
                    159:   Revision 1.161  2014/09/15 20:41:41  brouard
                    160:   Summary: Problem with macro SQR on Intel compiler
                    161: 
1.161     brouard   162:   Revision 1.160  2014/09/02 09:24:05  brouard
                    163:   *** empty log message ***
                    164: 
1.160     brouard   165:   Revision 1.159  2014/09/01 10:34:10  brouard
                    166:   Summary: WIN32
                    167:   Author: Brouard
                    168: 
1.159     brouard   169:   Revision 1.158  2014/08/27 17:11:51  brouard
                    170:   *** empty log message ***
                    171: 
1.158     brouard   172:   Revision 1.157  2014/08/27 16:26:55  brouard
                    173:   Summary: Preparing windows Visual studio version
                    174:   Author: Brouard
                    175: 
                    176:   In order to compile on Visual studio, time.h is now correct and time_t
                    177:   and tm struct should be used. difftime should be used but sometimes I
                    178:   just make the differences in raw time format (time(&now).
                    179:   Trying to suppress #ifdef LINUX
                    180:   Add xdg-open for __linux in order to open default browser.
                    181: 
1.157     brouard   182:   Revision 1.156  2014/08/25 20:10:10  brouard
                    183:   *** empty log message ***
                    184: 
1.156     brouard   185:   Revision 1.155  2014/08/25 18:32:34  brouard
                    186:   Summary: New compile, minor changes
                    187:   Author: Brouard
                    188: 
1.155     brouard   189:   Revision 1.154  2014/06/20 17:32:08  brouard
                    190:   Summary: Outputs now all graphs of convergence to period prevalence
                    191: 
1.154     brouard   192:   Revision 1.153  2014/06/20 16:45:46  brouard
                    193:   Summary: If 3 live state, convergence to period prevalence on same graph
                    194:   Author: Brouard
                    195: 
1.153     brouard   196:   Revision 1.152  2014/06/18 17:54:09  brouard
                    197:   Summary: open browser, use gnuplot on same dir than imach if not found in the path
                    198: 
1.152     brouard   199:   Revision 1.151  2014/06/18 16:43:30  brouard
                    200:   *** empty log message ***
                    201: 
1.151     brouard   202:   Revision 1.150  2014/06/18 16:42:35  brouard
                    203:   Summary: If gnuplot is not in the path try on same directory than imach binary (OSX)
                    204:   Author: brouard
                    205: 
1.150     brouard   206:   Revision 1.149  2014/06/18 15:51:14  brouard
                    207:   Summary: Some fixes in parameter files errors
                    208:   Author: Nicolas Brouard
                    209: 
1.149     brouard   210:   Revision 1.148  2014/06/17 17:38:48  brouard
                    211:   Summary: Nothing new
                    212:   Author: Brouard
                    213: 
                    214:   Just a new packaging for OS/X version 0.98nS
                    215: 
1.148     brouard   216:   Revision 1.147  2014/06/16 10:33:11  brouard
                    217:   *** empty log message ***
                    218: 
1.147     brouard   219:   Revision 1.146  2014/06/16 10:20:28  brouard
                    220:   Summary: Merge
                    221:   Author: Brouard
                    222: 
                    223:   Merge, before building revised version.
                    224: 
1.146     brouard   225:   Revision 1.145  2014/06/10 21:23:15  brouard
                    226:   Summary: Debugging with valgrind
                    227:   Author: Nicolas Brouard
                    228: 
                    229:   Lot of changes in order to output the results with some covariates
                    230:   After the Edimburgh REVES conference 2014, it seems mandatory to
                    231:   improve the code.
                    232:   No more memory valgrind error but a lot has to be done in order to
                    233:   continue the work of splitting the code into subroutines.
                    234:   Also, decodemodel has been improved. Tricode is still not
                    235:   optimal. nbcode should be improved. Documentation has been added in
                    236:   the source code.
                    237: 
1.144     brouard   238:   Revision 1.143  2014/01/26 09:45:38  brouard
                    239:   Summary: Version 0.98nR (to be improved, but gives same optimization results as 0.98k. Nice, promising
                    240: 
                    241:   * imach.c (Module): Trying to merge old staffs together while being at Tokyo. Not tested...
                    242:   (Module): Version 0.98nR Running ok, but output format still only works for three covariates.
                    243: 
1.143     brouard   244:   Revision 1.142  2014/01/26 03:57:36  brouard
                    245:   Summary: gnuplot changed plot w l 1 has to be changed to plot w l lt 2
                    246: 
                    247:   * imach.c (Module): Trying to merge old staffs together while being at Tokyo. Not tested...
                    248: 
1.142     brouard   249:   Revision 1.141  2014/01/26 02:42:01  brouard
                    250:   * imach.c (Module): Trying to merge old staffs together while being at Tokyo. Not tested...
                    251: 
1.141     brouard   252:   Revision 1.140  2011/09/02 10:37:54  brouard
                    253:   Summary: times.h is ok with mingw32 now.
                    254: 
1.140     brouard   255:   Revision 1.139  2010/06/14 07:50:17  brouard
                    256:   After the theft of my laptop, I probably lost some lines of codes which were not uploaded to the CVS tree.
                    257:   I remember having already fixed agemin agemax which are pointers now but not cvs saved.
                    258: 
1.139     brouard   259:   Revision 1.138  2010/04/30 18:19:40  brouard
                    260:   *** empty log message ***
                    261: 
1.138     brouard   262:   Revision 1.137  2010/04/29 18:11:38  brouard
                    263:   (Module): Checking covariates for more complex models
                    264:   than V1+V2. A lot of change to be done. Unstable.
                    265: 
1.137     brouard   266:   Revision 1.136  2010/04/26 20:30:53  brouard
                    267:   (Module): merging some libgsl code. Fixing computation
                    268:   of likelione (using inter/intrapolation if mle = 0) in order to
                    269:   get same likelihood as if mle=1.
                    270:   Some cleaning of code and comments added.
                    271: 
1.136     brouard   272:   Revision 1.135  2009/10/29 15:33:14  brouard
                    273:   (Module): Now imach stops if date of birth, at least year of birth, is not given. Some cleaning of the code.
                    274: 
1.135     brouard   275:   Revision 1.134  2009/10/29 13:18:53  brouard
                    276:   (Module): Now imach stops if date of birth, at least year of birth, is not given. Some cleaning of the code.
                    277: 
1.134     brouard   278:   Revision 1.133  2009/07/06 10:21:25  brouard
                    279:   just nforces
                    280: 
1.133     brouard   281:   Revision 1.132  2009/07/06 08:22:05  brouard
                    282:   Many tings
                    283: 
1.132     brouard   284:   Revision 1.131  2009/06/20 16:22:47  brouard
                    285:   Some dimensions resccaled
                    286: 
1.131     brouard   287:   Revision 1.130  2009/05/26 06:44:34  brouard
                    288:   (Module): Max Covariate is now set to 20 instead of 8. A
                    289:   lot of cleaning with variables initialized to 0. Trying to make
                    290:   V2+V3*age+V1+V4 strb=V3*age+V1+V4 working better.
                    291: 
1.130     brouard   292:   Revision 1.129  2007/08/31 13:49:27  lievre
                    293:   Modification of the way of exiting when the covariate is not binary in order to see on the window the error message before exiting
                    294: 
1.129     lievre    295:   Revision 1.128  2006/06/30 13:02:05  brouard
                    296:   (Module): Clarifications on computing e.j
                    297: 
1.128     brouard   298:   Revision 1.127  2006/04/28 18:11:50  brouard
                    299:   (Module): Yes the sum of survivors was wrong since
                    300:   imach-114 because nhstepm was no more computed in the age
                    301:   loop. Now we define nhstepma in the age loop.
                    302:   (Module): In order to speed up (in case of numerous covariates) we
                    303:   compute health expectancies (without variances) in a first step
                    304:   and then all the health expectancies with variances or standard
                    305:   deviation (needs data from the Hessian matrices) which slows the
                    306:   computation.
                    307:   In the future we should be able to stop the program is only health
                    308:   expectancies and graph are needed without standard deviations.
                    309: 
1.127     brouard   310:   Revision 1.126  2006/04/28 17:23:28  brouard
                    311:   (Module): Yes the sum of survivors was wrong since
                    312:   imach-114 because nhstepm was no more computed in the age
                    313:   loop. Now we define nhstepma in the age loop.
                    314:   Version 0.98h
                    315: 
1.126     brouard   316:   Revision 1.125  2006/04/04 15:20:31  lievre
                    317:   Errors in calculation of health expectancies. Age was not initialized.
                    318:   Forecasting file added.
                    319: 
                    320:   Revision 1.124  2006/03/22 17:13:53  lievre
                    321:   Parameters are printed with %lf instead of %f (more numbers after the comma).
                    322:   The log-likelihood is printed in the log file
                    323: 
                    324:   Revision 1.123  2006/03/20 10:52:43  brouard
                    325:   * imach.c (Module): <title> changed, corresponds to .htm file
                    326:   name. <head> headers where missing.
                    327: 
                    328:   * imach.c (Module): Weights can have a decimal point as for
                    329:   English (a comma might work with a correct LC_NUMERIC environment,
                    330:   otherwise the weight is truncated).
                    331:   Modification of warning when the covariates values are not 0 or
                    332:   1.
                    333:   Version 0.98g
                    334: 
                    335:   Revision 1.122  2006/03/20 09:45:41  brouard
                    336:   (Module): Weights can have a decimal point as for
                    337:   English (a comma might work with a correct LC_NUMERIC environment,
                    338:   otherwise the weight is truncated).
                    339:   Modification of warning when the covariates values are not 0 or
                    340:   1.
                    341:   Version 0.98g
                    342: 
                    343:   Revision 1.121  2006/03/16 17:45:01  lievre
                    344:   * imach.c (Module): Comments concerning covariates added
                    345: 
                    346:   * imach.c (Module): refinements in the computation of lli if
                    347:   status=-2 in order to have more reliable computation if stepm is
                    348:   not 1 month. Version 0.98f
                    349: 
                    350:   Revision 1.120  2006/03/16 15:10:38  lievre
                    351:   (Module): refinements in the computation of lli if
                    352:   status=-2 in order to have more reliable computation if stepm is
                    353:   not 1 month. Version 0.98f
                    354: 
                    355:   Revision 1.119  2006/03/15 17:42:26  brouard
                    356:   (Module): Bug if status = -2, the loglikelihood was
                    357:   computed as likelihood omitting the logarithm. Version O.98e
                    358: 
                    359:   Revision 1.118  2006/03/14 18:20:07  brouard
                    360:   (Module): varevsij Comments added explaining the second
                    361:   table of variances if popbased=1 .
                    362:   (Module): Covariances of eij, ekl added, graphs fixed, new html link.
                    363:   (Module): Function pstamp added
                    364:   (Module): Version 0.98d
                    365: 
                    366:   Revision 1.117  2006/03/14 17:16:22  brouard
                    367:   (Module): varevsij Comments added explaining the second
                    368:   table of variances if popbased=1 .
                    369:   (Module): Covariances of eij, ekl added, graphs fixed, new html link.
                    370:   (Module): Function pstamp added
                    371:   (Module): Version 0.98d
                    372: 
                    373:   Revision 1.116  2006/03/06 10:29:27  brouard
                    374:   (Module): Variance-covariance wrong links and
                    375:   varian-covariance of ej. is needed (Saito).
                    376: 
                    377:   Revision 1.115  2006/02/27 12:17:45  brouard
                    378:   (Module): One freematrix added in mlikeli! 0.98c
                    379: 
                    380:   Revision 1.114  2006/02/26 12:57:58  brouard
                    381:   (Module): Some improvements in processing parameter
                    382:   filename with strsep.
                    383: 
                    384:   Revision 1.113  2006/02/24 14:20:24  brouard
                    385:   (Module): Memory leaks checks with valgrind and:
                    386:   datafile was not closed, some imatrix were not freed and on matrix
                    387:   allocation too.
                    388: 
                    389:   Revision 1.112  2006/01/30 09:55:26  brouard
                    390:   (Module): Back to gnuplot.exe instead of wgnuplot.exe
                    391: 
                    392:   Revision 1.111  2006/01/25 20:38:18  brouard
                    393:   (Module): Lots of cleaning and bugs added (Gompertz)
                    394:   (Module): Comments can be added in data file. Missing date values
                    395:   can be a simple dot '.'.
                    396: 
                    397:   Revision 1.110  2006/01/25 00:51:50  brouard
                    398:   (Module): Lots of cleaning and bugs added (Gompertz)
                    399: 
                    400:   Revision 1.109  2006/01/24 19:37:15  brouard
                    401:   (Module): Comments (lines starting with a #) are allowed in data.
                    402: 
                    403:   Revision 1.108  2006/01/19 18:05:42  lievre
                    404:   Gnuplot problem appeared...
                    405:   To be fixed
                    406: 
                    407:   Revision 1.107  2006/01/19 16:20:37  brouard
                    408:   Test existence of gnuplot in imach path
                    409: 
                    410:   Revision 1.106  2006/01/19 13:24:36  brouard
                    411:   Some cleaning and links added in html output
                    412: 
                    413:   Revision 1.105  2006/01/05 20:23:19  lievre
                    414:   *** empty log message ***
                    415: 
                    416:   Revision 1.104  2005/09/30 16:11:43  lievre
                    417:   (Module): sump fixed, loop imx fixed, and simplifications.
                    418:   (Module): If the status is missing at the last wave but we know
                    419:   that the person is alive, then we can code his/her status as -2
                    420:   (instead of missing=-1 in earlier versions) and his/her
                    421:   contributions to the likelihood is 1 - Prob of dying from last
                    422:   health status (= 1-p13= p11+p12 in the easiest case of somebody in
                    423:   the healthy state at last known wave). Version is 0.98
                    424: 
                    425:   Revision 1.103  2005/09/30 15:54:49  lievre
                    426:   (Module): sump fixed, loop imx fixed, and simplifications.
                    427: 
                    428:   Revision 1.102  2004/09/15 17:31:30  brouard
                    429:   Add the possibility to read data file including tab characters.
                    430: 
                    431:   Revision 1.101  2004/09/15 10:38:38  brouard
                    432:   Fix on curr_time
                    433: 
                    434:   Revision 1.100  2004/07/12 18:29:06  brouard
                    435:   Add version for Mac OS X. Just define UNIX in Makefile
                    436: 
                    437:   Revision 1.99  2004/06/05 08:57:40  brouard
                    438:   *** empty log message ***
                    439: 
                    440:   Revision 1.98  2004/05/16 15:05:56  brouard
                    441:   New version 0.97 . First attempt to estimate force of mortality
                    442:   directly from the data i.e. without the need of knowing the health
                    443:   state at each age, but using a Gompertz model: log u =a + b*age .
                    444:   This is the basic analysis of mortality and should be done before any
                    445:   other analysis, in order to test if the mortality estimated from the
                    446:   cross-longitudinal survey is different from the mortality estimated
                    447:   from other sources like vital statistic data.
                    448: 
                    449:   The same imach parameter file can be used but the option for mle should be -3.
                    450: 
1.133     brouard   451:   Agnès, who wrote this part of the code, tried to keep most of the
1.126     brouard   452:   former routines in order to include the new code within the former code.
                    453: 
                    454:   The output is very simple: only an estimate of the intercept and of
                    455:   the slope with 95% confident intervals.
                    456: 
                    457:   Current limitations:
                    458:   A) Even if you enter covariates, i.e. with the
                    459:   model= V1+V2 equation for example, the programm does only estimate a unique global model without covariates.
                    460:   B) There is no computation of Life Expectancy nor Life Table.
                    461: 
                    462:   Revision 1.97  2004/02/20 13:25:42  lievre
                    463:   Version 0.96d. Population forecasting command line is (temporarily)
                    464:   suppressed.
                    465: 
                    466:   Revision 1.96  2003/07/15 15:38:55  brouard
                    467:   * imach.c (Repository): Errors in subdirf, 2, 3 while printing tmpout is
                    468:   rewritten within the same printf. Workaround: many printfs.
                    469: 
                    470:   Revision 1.95  2003/07/08 07:54:34  brouard
                    471:   * imach.c (Repository):
                    472:   (Repository): Using imachwizard code to output a more meaningful covariance
                    473:   matrix (cov(a12,c31) instead of numbers.
                    474: 
                    475:   Revision 1.94  2003/06/27 13:00:02  brouard
                    476:   Just cleaning
                    477: 
                    478:   Revision 1.93  2003/06/25 16:33:55  brouard
                    479:   (Module): On windows (cygwin) function asctime_r doesn't
                    480:   exist so I changed back to asctime which exists.
                    481:   (Module): Version 0.96b
                    482: 
                    483:   Revision 1.92  2003/06/25 16:30:45  brouard
                    484:   (Module): On windows (cygwin) function asctime_r doesn't
                    485:   exist so I changed back to asctime which exists.
                    486: 
                    487:   Revision 1.91  2003/06/25 15:30:29  brouard
                    488:   * imach.c (Repository): Duplicated warning errors corrected.
                    489:   (Repository): Elapsed time after each iteration is now output. It
                    490:   helps to forecast when convergence will be reached. Elapsed time
                    491:   is stamped in powell.  We created a new html file for the graphs
                    492:   concerning matrix of covariance. It has extension -cov.htm.
                    493: 
                    494:   Revision 1.90  2003/06/24 12:34:15  brouard
                    495:   (Module): Some bugs corrected for windows. Also, when
                    496:   mle=-1 a template is output in file "or"mypar.txt with the design
                    497:   of the covariance matrix to be input.
                    498: 
                    499:   Revision 1.89  2003/06/24 12:30:52  brouard
                    500:   (Module): Some bugs corrected for windows. Also, when
                    501:   mle=-1 a template is output in file "or"mypar.txt with the design
                    502:   of the covariance matrix to be input.
                    503: 
                    504:   Revision 1.88  2003/06/23 17:54:56  brouard
                    505:   * 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.
                    506: 
                    507:   Revision 1.87  2003/06/18 12:26:01  brouard
                    508:   Version 0.96
                    509: 
                    510:   Revision 1.86  2003/06/17 20:04:08  brouard
                    511:   (Module): Change position of html and gnuplot routines and added
                    512:   routine fileappend.
                    513: 
                    514:   Revision 1.85  2003/06/17 13:12:43  brouard
                    515:   * imach.c (Repository): Check when date of death was earlier that
                    516:   current date of interview. It may happen when the death was just
                    517:   prior to the death. In this case, dh was negative and likelihood
                    518:   was wrong (infinity). We still send an "Error" but patch by
                    519:   assuming that the date of death was just one stepm after the
                    520:   interview.
                    521:   (Repository): Because some people have very long ID (first column)
                    522:   we changed int to long in num[] and we added a new lvector for
                    523:   memory allocation. But we also truncated to 8 characters (left
                    524:   truncation)
                    525:   (Repository): No more line truncation errors.
                    526: 
                    527:   Revision 1.84  2003/06/13 21:44:43  brouard
                    528:   * imach.c (Repository): Replace "freqsummary" at a correct
                    529:   place. It differs from routine "prevalence" which may be called
                    530:   many times. Probs is memory consuming and must be used with
                    531:   parcimony.
                    532:   Version 0.95a3 (should output exactly the same maximization than 0.8a2)
                    533: 
                    534:   Revision 1.83  2003/06/10 13:39:11  lievre
                    535:   *** empty log message ***
                    536: 
                    537:   Revision 1.82  2003/06/05 15:57:20  brouard
                    538:   Add log in  imach.c and  fullversion number is now printed.
                    539: 
                    540: */
                    541: /*
                    542:    Interpolated Markov Chain
                    543: 
                    544:   Short summary of the programme:
                    545:   
                    546:   This program computes Healthy Life Expectancies from
                    547:   cross-longitudinal data. Cross-longitudinal data consist in: -1- a
                    548:   first survey ("cross") where individuals from different ages are
                    549:   interviewed on their health status or degree of disability (in the
                    550:   case of a health survey which is our main interest) -2- at least a
                    551:   second wave of interviews ("longitudinal") which measure each change
                    552:   (if any) in individual health status.  Health expectancies are
                    553:   computed from the time spent in each health state according to a
                    554:   model. More health states you consider, more time is necessary to reach the
                    555:   Maximum Likelihood of the parameters involved in the model.  The
                    556:   simplest model is the multinomial logistic model where pij is the
                    557:   probability to be observed in state j at the second wave
                    558:   conditional to be observed in state i at the first wave. Therefore
                    559:   the model is: log(pij/pii)= aij + bij*age+ cij*sex + etc , where
                    560:   'age' is age and 'sex' is a covariate. If you want to have a more
                    561:   complex model than "constant and age", you should modify the program
                    562:   where the markup *Covariates have to be included here again* invites
                    563:   you to do it.  More covariates you add, slower the
                    564:   convergence.
                    565: 
                    566:   The advantage of this computer programme, compared to a simple
                    567:   multinomial logistic model, is clear when the delay between waves is not
                    568:   identical for each individual. Also, if a individual missed an
                    569:   intermediate interview, the information is lost, but taken into
                    570:   account using an interpolation or extrapolation.  
                    571: 
                    572:   hPijx is the probability to be observed in state i at age x+h
                    573:   conditional to the observed state i at age x. The delay 'h' can be
                    574:   split into an exact number (nh*stepm) of unobserved intermediate
                    575:   states. This elementary transition (by month, quarter,
                    576:   semester or year) is modelled as a multinomial logistic.  The hPx
                    577:   matrix is simply the matrix product of nh*stepm elementary matrices
                    578:   and the contribution of each individual to the likelihood is simply
                    579:   hPijx.
                    580: 
                    581:   Also this programme outputs the covariance matrix of the parameters but also
                    582:   of the life expectancies. It also computes the period (stable) prevalence. 
                    583:   
1.133     brouard   584:   Authors: Nicolas Brouard (brouard@ined.fr) and Agnès Lièvre (lievre@ined.fr).
                    585:            Institut national d'études démographiques, Paris.
1.126     brouard   586:   This software have been partly granted by Euro-REVES, a concerted action
                    587:   from the European Union.
                    588:   It is copyrighted identically to a GNU software product, ie programme and
                    589:   software can be distributed freely for non commercial use. Latest version
                    590:   can be accessed at http://euroreves.ined.fr/imach .
                    591: 
                    592:   Help to debug: LD_PRELOAD=/usr/local/lib/libnjamd.so ./imach foo.imach
                    593:   or better on gdb : set env LD_PRELOAD=/usr/local/lib/libnjamd.so
                    594:   
                    595:   **********************************************************************/
                    596: /*
                    597:   main
                    598:   read parameterfile
                    599:   read datafile
                    600:   concatwav
                    601:   freqsummary
                    602:   if (mle >= 1)
                    603:     mlikeli
                    604:   print results files
                    605:   if mle==1 
                    606:      computes hessian
                    607:   read end of parameter file: agemin, agemax, bage, fage, estepm
                    608:       begin-prev-date,...
                    609:   open gnuplot file
                    610:   open html file
1.145     brouard   611:   period (stable) prevalence      | pl_nom    1-1 2-2 etc by covariate
                    612:    for age prevalim()             | #****** V1=0  V2=1  V3=1  V4=0 ******
                    613:                                   | 65 1 0 2 1 3 1 4 0  0.96326 0.03674
                    614:     freexexit2 possible for memory heap.
                    615: 
                    616:   h Pij x                         | pij_nom  ficrestpij
                    617:    # Cov Agex agex+h hpijx with i,j= 1-1 1-2     1-3     2-1     2-2     2-3
                    618:        1  85   85    1.00000             0.00000 0.00000 0.00000 1.00000 0.00000
                    619:        1  85   86    0.68299             0.22291 0.09410 0.71093 0.00000 0.28907
                    620: 
                    621:        1  65   99    0.00364             0.00322 0.99314 0.00350 0.00310 0.99340
                    622:        1  65  100    0.00214             0.00204 0.99581 0.00206 0.00196 0.99597
                    623:   variance of p one-step probabilities varprob  | prob_nom   ficresprob #One-step probabilities and stand. devi in ()
                    624:    Standard deviation of one-step probabilities | probcor_nom   ficresprobcor #One-step probabilities and correlation matrix
                    625:    Matrix of variance covariance of one-step probabilities |  probcov_nom ficresprobcov #One-step probabilities and covariance matrix
                    626: 
1.126     brouard   627:   forecasting if prevfcast==1 prevforecast call prevalence()
                    628:   health expectancies
                    629:   Variance-covariance of DFLE
                    630:   prevalence()
                    631:    movingaverage()
                    632:   varevsij() 
                    633:   if popbased==1 varevsij(,popbased)
                    634:   total life expectancies
                    635:   Variance of period (stable) prevalence
                    636:  end
                    637: */
                    638: 
1.187     brouard   639: /* #define DEBUG */
                    640: /* #define DEBUGBRENT */
1.165     brouard   641: #define POWELL /* Instead of NLOPT */
1.192     brouard   642: #define POWELLF1F3 /* Skip test */
1.186     brouard   643: /* #define POWELLORIGINAL /\* Don't use Directest to decide new direction but original Powell test *\/ */
                    644: /* #define MNBRAKORIGINAL /\* Don't use mnbrak fix *\/ */
1.126     brouard   645: 
                    646: #include <math.h>
                    647: #include <stdio.h>
                    648: #include <stdlib.h>
                    649: #include <string.h>
1.159     brouard   650: 
                    651: #ifdef _WIN32
                    652: #include <io.h>
1.172     brouard   653: #include <windows.h>
                    654: #include <tchar.h>
1.159     brouard   655: #else
1.126     brouard   656: #include <unistd.h>
1.159     brouard   657: #endif
1.126     brouard   658: 
                    659: #include <limits.h>
                    660: #include <sys/types.h>
1.171     brouard   661: 
                    662: #if defined(__GNUC__)
                    663: #include <sys/utsname.h> /* Doesn't work on Windows */
                    664: #endif
                    665: 
1.126     brouard   666: #include <sys/stat.h>
                    667: #include <errno.h>
1.159     brouard   668: /* extern int errno; */
1.126     brouard   669: 
1.157     brouard   670: /* #ifdef LINUX */
                    671: /* #include <time.h> */
                    672: /* #include "timeval.h" */
                    673: /* #else */
                    674: /* #include <sys/time.h> */
                    675: /* #endif */
                    676: 
1.126     brouard   677: #include <time.h>
                    678: 
1.136     brouard   679: #ifdef GSL
                    680: #include <gsl/gsl_errno.h>
                    681: #include <gsl/gsl_multimin.h>
                    682: #endif
                    683: 
1.167     brouard   684: 
1.162     brouard   685: #ifdef NLOPT
                    686: #include <nlopt.h>
                    687: typedef struct {
                    688:   double (* function)(double [] );
                    689: } myfunc_data ;
                    690: #endif
                    691: 
1.126     brouard   692: /* #include <libintl.h> */
                    693: /* #define _(String) gettext (String) */
                    694: 
1.141     brouard   695: #define MAXLINE 1024 /* Was 256. Overflow with 312 with 2 states and 4 covariates. Should be ok */
1.126     brouard   696: 
                    697: #define GNUPLOTPROGRAM "gnuplot"
                    698: /*#define GNUPLOTPROGRAM "..\\gp37mgw\\wgnuplot"*/
                    699: #define FILENAMELENGTH 132
                    700: 
                    701: #define        GLOCK_ERROR_NOPATH              -1      /* empty path */
                    702: #define        GLOCK_ERROR_GETCWD              -2      /* cannot get cwd */
                    703: 
1.144     brouard   704: #define MAXPARM 128 /**< Maximum number of parameters for the optimization */
                    705: #define NPARMAX 64 /**< (nlstate+ndeath-1)*nlstate*ncovmodel */
1.126     brouard   706: 
                    707: #define NINTERVMAX 8
1.144     brouard   708: #define NLSTATEMAX 8 /**< Maximum number of live states (for func) */
                    709: #define NDEATHMAX 8 /**< Maximum number of dead states (for func) */
                    710: #define NCOVMAX 20 /**< Maximum number of covariates, including generated covariates V1*V2 */
1.197     brouard   711: #define codtabm(h,k)  (1 & (h-1) >> (k-1))+1
1.126     brouard   712: #define MAXN 20000
1.144     brouard   713: #define YEARM 12. /**< Number of months per year */
1.126     brouard   714: #define AGESUP 130
                    715: #define AGEBASE 40
1.194     brouard   716: #define AGEOVERFLOW 1.e20
1.164     brouard   717: #define AGEGOMP 10 /**< Minimal age for Gompertz adjustment */
1.157     brouard   718: #ifdef _WIN32
                    719: #define DIRSEPARATOR '\\'
                    720: #define CHARSEPARATOR "\\"
                    721: #define ODIRSEPARATOR '/'
                    722: #else
1.126     brouard   723: #define DIRSEPARATOR '/'
                    724: #define CHARSEPARATOR "/"
                    725: #define ODIRSEPARATOR '\\'
                    726: #endif
                    727: 
1.201   ! brouard   728: /* $Id: imach.c,v 1.200 2015/09/09 16:53:55 brouard Exp $ */
1.126     brouard   729: /* $State: Exp $ */
1.196     brouard   730: #include "version.h"
                    731: char version[]=__IMACH_VERSION__;
1.197     brouard   732: char copyright[]="September 2015,INED-EUROREVES-Institut de longevite-Japan Society for the Promotion of Science (Grant-in-Aid for Scientific Research 25293121), Intel Software 2015";
1.201   ! brouard   733: char fullversion[]="$Revision: 1.200 $ $Date: 2015/09/09 16:53:55 $"; 
1.126     brouard   734: char strstart[80];
                    735: char optionfilext[10], optionfilefiname[FILENAMELENGTH];
1.130     brouard   736: int erreur=0, nberr=0, nbwarn=0; /* Error number, number of errors number of warnings  */
1.187     brouard   737: int nagesqr=0, nforce=0; /* nagesqr=1 if model is including age*age, number of forces */
1.145     brouard   738: /* Number of covariates model=V2+V1+ V3*age+V2*V4 */
                    739: int cptcovn=0; /**< cptcovn number of covariates added in the model (excepting constant and age and age*product) */
                    740: int cptcovt=0; /**< cptcovt number of covariates added in the model (excepting constant and age) */
                    741: int cptcovs=0; /**< cptcovs number of simple covariates V2+V1 =2 */
                    742: int cptcovage=0; /**< Number of covariates with age: V3*age only =1 */
                    743: int cptcovprodnoage=0; /**< Number of covariate products without age */   
                    744: int cptcoveff=0; /* Total number of covariates to vary for printing results */
                    745: int cptcov=0; /* Working variable */
1.126     brouard   746: int npar=NPARMAX;
                    747: int nlstate=2; /* Number of live states */
                    748: int ndeath=1; /* Number of dead states */
1.130     brouard   749: int ncovmodel=0, ncovcol=0;     /* Total number of covariables including constant a12*1 +b12*x ncovmodel=2 */
1.126     brouard   750: int popbased=0;
                    751: 
                    752: int *wav; /* Number of waves for this individuual 0 is possible */
1.130     brouard   753: int maxwav=0; /* Maxim number of waves */
                    754: int jmin=0, jmax=0; /* min, max spacing between 2 waves */
                    755: int ijmin=0, ijmax=0; /* Individuals having jmin and jmax */ 
                    756: int gipmx=0, gsw=0; /* Global variables on the number of contributions 
1.126     brouard   757:                   to the likelihood and the sum of weights (done by funcone)*/
1.130     brouard   758: int mle=1, weightopt=0;
1.126     brouard   759: int **mw; /* mw[mi][i] is number of the mi wave for this individual */
                    760: int **dh; /* dh[mi][i] is number of steps between mi,mi+1 for this individual */
                    761: int **bh; /* bh[mi][i] is the bias (+ or -) for this individual if the delay between
                    762:           * wave mi and wave mi+1 is not an exact multiple of stepm. */
1.162     brouard   763: int countcallfunc=0;  /* Count the number of calls to func */
1.130     brouard   764: double jmean=1; /* Mean space between 2 waves */
1.145     brouard   765: double **matprod2(); /* test */
1.126     brouard   766: double **oldm, **newm, **savm; /* Working pointers to matrices */
                    767: double **oldms, **newms, **savms; /* Fixed working pointers to matrices */
1.136     brouard   768: /*FILE *fic ; */ /* Used in readdata only */
                    769: FILE *ficpar, *ficparo,*ficres, *ficresp, *ficrespl, *ficrespij, *ficrest,*ficresf,*ficrespop;
1.126     brouard   770: FILE *ficlog, *ficrespow;
1.130     brouard   771: int globpr=0; /* Global variable for printing or not */
1.126     brouard   772: double fretone; /* Only one call to likelihood */
1.130     brouard   773: long ipmx=0; /* Number of contributions */
1.126     brouard   774: double sw; /* Sum of weights */
                    775: char filerespow[FILENAMELENGTH];
                    776: char fileresilk[FILENAMELENGTH]; /* File of individual contributions to the likelihood */
                    777: FILE *ficresilk;
                    778: FILE *ficgp,*ficresprob,*ficpop, *ficresprobcov, *ficresprobcor;
                    779: FILE *ficresprobmorprev;
                    780: FILE *fichtm, *fichtmcov; /* Html File */
                    781: FILE *ficreseij;
                    782: char filerese[FILENAMELENGTH];
                    783: FILE *ficresstdeij;
                    784: char fileresstde[FILENAMELENGTH];
                    785: FILE *ficrescveij;
                    786: char filerescve[FILENAMELENGTH];
                    787: FILE  *ficresvij;
                    788: char fileresv[FILENAMELENGTH];
                    789: FILE  *ficresvpl;
                    790: char fileresvpl[FILENAMELENGTH];
                    791: char title[MAXLINE];
                    792: char optionfile[FILENAMELENGTH], datafile[FILENAMELENGTH],  filerespl[FILENAMELENGTH];
                    793: char plotcmd[FILENAMELENGTH], pplotcmd[FILENAMELENGTH];
                    794: char tmpout[FILENAMELENGTH],  tmpout2[FILENAMELENGTH]; 
                    795: char command[FILENAMELENGTH];
                    796: int  outcmd=0;
                    797: 
                    798: char fileres[FILENAMELENGTH], filerespij[FILENAMELENGTH], filereso[FILENAMELENGTH], rfileres[FILENAMELENGTH];
1.201   ! brouard   799: char fileresu[FILENAMELENGTH]; /* Without r in front */
1.126     brouard   800: char filelog[FILENAMELENGTH]; /* Log file */
                    801: char filerest[FILENAMELENGTH];
                    802: char fileregp[FILENAMELENGTH];
                    803: char popfile[FILENAMELENGTH];
                    804: 
                    805: char optionfilegnuplot[FILENAMELENGTH], optionfilehtm[FILENAMELENGTH], optionfilehtmcov[FILENAMELENGTH] ;
                    806: 
1.157     brouard   807: /* struct timeval start_time, end_time, curr_time, last_time, forecast_time; */
                    808: /* struct timezone tzp; */
                    809: /* extern int gettimeofday(); */
                    810: struct tm tml, *gmtime(), *localtime();
                    811: 
                    812: extern time_t time();
                    813: 
                    814: struct tm start_time, end_time, curr_time, last_time, forecast_time;
                    815: time_t  rstart_time, rend_time, rcurr_time, rlast_time, rforecast_time; /* raw time */
                    816: struct tm tm;
                    817: 
1.126     brouard   818: char strcurr[80], strfor[80];
                    819: 
                    820: char *endptr;
                    821: long lval;
                    822: double dval;
                    823: 
                    824: #define NR_END 1
                    825: #define FREE_ARG char*
                    826: #define FTOL 1.0e-10
                    827: 
                    828: #define NRANSI 
                    829: #define ITMAX 200 
                    830: 
                    831: #define TOL 2.0e-4 
                    832: 
                    833: #define CGOLD 0.3819660 
                    834: #define ZEPS 1.0e-10 
                    835: #define SHFT(a,b,c,d) (a)=(b);(b)=(c);(c)=(d); 
                    836: 
                    837: #define GOLD 1.618034 
                    838: #define GLIMIT 100.0 
                    839: #define TINY 1.0e-20 
                    840: 
                    841: static double maxarg1,maxarg2;
                    842: #define FMAX(a,b) (maxarg1=(a),maxarg2=(b),(maxarg1)>(maxarg2)? (maxarg1):(maxarg2))
                    843: #define FMIN(a,b) (maxarg1=(a),maxarg2=(b),(maxarg1)<(maxarg2)? (maxarg1):(maxarg2))
                    844:   
                    845: #define SIGN(a,b) ((b)>0.0 ? fabs(a) : -fabs(a))
                    846: #define rint(a) floor(a+0.5)
1.166     brouard   847: /* http://www.thphys.uni-heidelberg.de/~robbers/cmbeasy/doc/html/myutils_8h-source.html */
1.183     brouard   848: #define mytinydouble 1.0e-16
1.166     brouard   849: /* #define DEQUAL(a,b) (fabs((a)-(b))<mytinydouble) */
                    850: /* http://www.thphys.uni-heidelberg.de/~robbers/cmbeasy/doc/html/mynrutils_8h-source.html */
                    851: /* static double dsqrarg; */
                    852: /* #define DSQR(a) (DEQUAL((dsqrarg=(a)),0.0) ? 0.0 : dsqrarg*dsqrarg) */
1.126     brouard   853: static double sqrarg;
                    854: #define SQR(a) ((sqrarg=(a)) == 0.0 ? 0.0 :sqrarg*sqrarg)
                    855: #define SWAP(a,b) {temp=(a);(a)=(b);(b)=temp;} 
                    856: int agegomp= AGEGOMP;
                    857: 
                    858: int imx; 
                    859: int stepm=1;
                    860: /* Stepm, step in month: minimum step interpolation*/
                    861: 
                    862: int estepm;
                    863: /* Estepm, step in month to interpolate survival function in order to approximate Life Expectancy*/
                    864: 
                    865: int m,nb;
                    866: long *num;
1.197     brouard   867: int firstpass=0, lastpass=4,*cod, *cens;
1.192     brouard   868: int *ncodemax;  /* ncodemax[j]= Number of modalities of the j th
                    869:                   covariate for which somebody answered excluding 
                    870:                   undefined. Usually 2: 0 and 1. */
                    871: int *ncodemaxwundef;  /* ncodemax[j]= Number of modalities of the j th
                    872:                             covariate for which somebody answered including 
                    873:                             undefined. Usually 3: -1, 0 and 1. */
1.126     brouard   874: double **agev,*moisnais, *annais, *moisdc, *andc,**mint, **anint;
                    875: double **pmmij, ***probs;
                    876: double *ageexmed,*agecens;
                    877: double dateintmean=0;
                    878: 
                    879: double *weight;
                    880: int **s; /* Status */
1.141     brouard   881: double *agedc;
1.145     brouard   882: double  **covar; /**< covar[j,i], value of jth covariate for individual i,
1.141     brouard   883:                  * covar=matrix(0,NCOVMAX,1,n); 
1.187     brouard   884:                  * cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*age; */
1.141     brouard   885: double  idx; 
                    886: int **nbcode, *Tvar; /**< model=V2 => Tvar[1]= 2 */
1.197     brouard   887: int *Tage;
1.145     brouard   888: int *Ndum; /** Freq of modality (tricode */
1.200     brouard   889: /* int **codtab;*/ /**< codtab=imatrix(1,100,1,10); */
1.141     brouard   890: int **Tvard, *Tprod, cptcovprod, *Tvaraff;
1.126     brouard   891: double *lsurv, *lpop, *tpop;
                    892: 
1.143     brouard   893: double ftol=FTOL; /**< Tolerance for computing Max Likelihood */
                    894: double ftolhess; /**< Tolerance for computing hessian */
1.126     brouard   895: 
                    896: /**************** split *************************/
                    897: static int split( char *path, char *dirc, char *name, char *ext, char *finame )
                    898: {
                    899:   /* From a file name with (full) path (either Unix or Windows) we extract the directory (dirc)
                    900:      the name of the file (name), its extension only (ext) and its first part of the name (finame)
                    901:   */ 
                    902:   char *ss;                            /* pointer */
1.186     brouard   903:   int  l1=0, l2=0;                             /* length counters */
1.126     brouard   904: 
                    905:   l1 = strlen(path );                  /* length of path */
                    906:   if ( l1 == 0 ) return( GLOCK_ERROR_NOPATH );
                    907:   ss= strrchr( path, DIRSEPARATOR );           /* find last / */
                    908:   if ( ss == NULL ) {                  /* no directory, so determine current directory */
                    909:     strcpy( name, path );              /* we got the fullname name because no directory */
                    910:     /*if(strrchr(path, ODIRSEPARATOR )==NULL)
                    911:       printf("Warning you should use %s as a separator\n",DIRSEPARATOR);*/
                    912:     /* get current working directory */
                    913:     /*    extern  char* getcwd ( char *buf , int len);*/
1.184     brouard   914: #ifdef WIN32
                    915:     if (_getcwd( dirc, FILENAME_MAX ) == NULL ) {
                    916: #else
                    917:        if (getcwd(dirc, FILENAME_MAX) == NULL) {
                    918: #endif
1.126     brouard   919:       return( GLOCK_ERROR_GETCWD );
                    920:     }
                    921:     /* got dirc from getcwd*/
                    922:     printf(" DIRC = %s \n",dirc);
                    923:   } else {                             /* strip direcotry from path */
                    924:     ss++;                              /* after this, the filename */
                    925:     l2 = strlen( ss );                 /* length of filename */
                    926:     if ( l2 == 0 ) return( GLOCK_ERROR_NOPATH );
                    927:     strcpy( name, ss );                /* save file name */
                    928:     strncpy( dirc, path, l1 - l2 );    /* now the directory */
1.186     brouard   929:     dirc[l1-l2] = '\0';                        /* add zero */
1.126     brouard   930:     printf(" DIRC2 = %s \n",dirc);
                    931:   }
                    932:   /* We add a separator at the end of dirc if not exists */
                    933:   l1 = strlen( dirc );                 /* length of directory */
                    934:   if( dirc[l1-1] != DIRSEPARATOR ){
                    935:     dirc[l1] =  DIRSEPARATOR;
                    936:     dirc[l1+1] = 0; 
                    937:     printf(" DIRC3 = %s \n",dirc);
                    938:   }
                    939:   ss = strrchr( name, '.' );           /* find last / */
                    940:   if (ss >0){
                    941:     ss++;
                    942:     strcpy(ext,ss);                    /* save extension */
                    943:     l1= strlen( name);
                    944:     l2= strlen(ss)+1;
                    945:     strncpy( finame, name, l1-l2);
                    946:     finame[l1-l2]= 0;
                    947:   }
                    948: 
                    949:   return( 0 );                         /* we're done */
                    950: }
                    951: 
                    952: 
                    953: /******************************************/
                    954: 
                    955: void replace_back_to_slash(char *s, char*t)
                    956: {
                    957:   int i;
                    958:   int lg=0;
                    959:   i=0;
                    960:   lg=strlen(t);
                    961:   for(i=0; i<= lg; i++) {
                    962:     (s[i] = t[i]);
                    963:     if (t[i]== '\\') s[i]='/';
                    964:   }
                    965: }
                    966: 
1.132     brouard   967: char *trimbb(char *out, char *in)
1.137     brouard   968: { /* Trim multiple blanks in line but keeps first blanks if line starts with blanks */
1.132     brouard   969:   char *s;
                    970:   s=out;
                    971:   while (*in != '\0'){
1.137     brouard   972:     while( *in == ' ' && *(in+1) == ' '){ /* && *(in+1) != '\0'){*/
1.132     brouard   973:       in++;
                    974:     }
                    975:     *out++ = *in++;
                    976:   }
                    977:   *out='\0';
                    978:   return s;
                    979: }
                    980: 
1.187     brouard   981: /* char *substrchaine(char *out, char *in, char *chain) */
                    982: /* { */
                    983: /*   /\* Substract chain 'chain' from 'in', return and output 'out' *\/ */
                    984: /*   char *s, *t; */
                    985: /*   t=in;s=out; */
                    986: /*   while ((*in != *chain) && (*in != '\0')){ */
                    987: /*     *out++ = *in++; */
                    988: /*   } */
                    989: 
                    990: /*   /\* *in matches *chain *\/ */
                    991: /*   while ((*in++ == *chain++) && (*in != '\0')){ */
                    992: /*     printf("*in = %c, *out= %c *chain= %c \n", *in, *out, *chain);  */
                    993: /*   } */
                    994: /*   in--; chain--; */
                    995: /*   while ( (*in != '\0')){ */
                    996: /*     printf("Bef *in = %c, *out= %c *chain= %c \n", *in, *out, *chain);  */
                    997: /*     *out++ = *in++; */
                    998: /*     printf("Aft *in = %c, *out= %c *chain= %c \n", *in, *out, *chain);  */
                    999: /*   } */
                   1000: /*   *out='\0'; */
                   1001: /*   out=s; */
                   1002: /*   return out; */
                   1003: /* } */
                   1004: char *substrchaine(char *out, char *in, char *chain)
                   1005: {
                   1006:   /* Substract chain 'chain' from 'in', return and output 'out' */
                   1007:   /* in="V1+V1*age+age*age+V2", chain="age*age" */
                   1008: 
                   1009:   char *strloc;
                   1010: 
                   1011:   strcpy (out, in); 
                   1012:   strloc = strstr(out, chain); /* strloc points to out at age*age+V2 */
                   1013:   printf("Bef strloc=%s chain=%s out=%s \n", strloc, chain, out);
                   1014:   if(strloc != NULL){ 
                   1015:     /* will affect out */ /* strloc+strlenc(chain)=+V2 */ /* Will also work in Unicode */
                   1016:     memmove(strloc,strloc+strlen(chain), strlen(strloc+strlen(chain))+1);
                   1017:     /* strcpy (strloc, strloc +strlen(chain));*/
                   1018:   }
                   1019:   printf("Aft strloc=%s chain=%s in=%s out=%s \n", strloc, chain, in, out);
                   1020:   return out;
                   1021: }
                   1022: 
                   1023: 
1.145     brouard  1024: char *cutl(char *blocc, char *alocc, char *in, char occ)
                   1025: {
1.187     brouard  1026:   /* cuts string in into blocc and alocc where blocc ends before FIRST occurence of char 'occ' 
1.145     brouard  1027:      and alocc starts after first occurence of char 'occ' : ex cutv(blocc,alocc,"abcdef2ghi2j",'2')
1.187     brouard  1028:      gives blocc="abcdef" and alocc="ghi2j".
1.145     brouard  1029:      If occ is not found blocc is null and alocc is equal to in. Returns blocc
                   1030:   */
1.160     brouard  1031:   char *s, *t;
1.145     brouard  1032:   t=in;s=in;
                   1033:   while ((*in != occ) && (*in != '\0')){
                   1034:     *alocc++ = *in++;
                   1035:   }
                   1036:   if( *in == occ){
                   1037:     *(alocc)='\0';
                   1038:     s=++in;
                   1039:   }
                   1040:  
                   1041:   if (s == t) {/* occ not found */
                   1042:     *(alocc-(in-s))='\0';
                   1043:     in=s;
                   1044:   }
                   1045:   while ( *in != '\0'){
                   1046:     *blocc++ = *in++;
                   1047:   }
                   1048: 
                   1049:   *blocc='\0';
                   1050:   return t;
                   1051: }
1.137     brouard  1052: char *cutv(char *blocc, char *alocc, char *in, char occ)
                   1053: {
1.187     brouard  1054:   /* cuts string in into blocc and alocc where blocc ends before LAST occurence of char 'occ' 
1.137     brouard  1055:      and alocc starts after last occurence of char 'occ' : ex cutv(blocc,alocc,"abcdef2ghi2j",'2')
                   1056:      gives blocc="abcdef2ghi" and alocc="j".
                   1057:      If occ is not found blocc is null and alocc is equal to in. Returns alocc
                   1058:   */
                   1059:   char *s, *t;
                   1060:   t=in;s=in;
                   1061:   while (*in != '\0'){
                   1062:     while( *in == occ){
                   1063:       *blocc++ = *in++;
                   1064:       s=in;
                   1065:     }
                   1066:     *blocc++ = *in++;
                   1067:   }
                   1068:   if (s == t) /* occ not found */
                   1069:     *(blocc-(in-s))='\0';
                   1070:   else
                   1071:     *(blocc-(in-s)-1)='\0';
                   1072:   in=s;
                   1073:   while ( *in != '\0'){
                   1074:     *alocc++ = *in++;
                   1075:   }
                   1076: 
                   1077:   *alocc='\0';
                   1078:   return s;
                   1079: }
                   1080: 
1.126     brouard  1081: int nbocc(char *s, char occ)
                   1082: {
                   1083:   int i,j=0;
                   1084:   int lg=20;
                   1085:   i=0;
                   1086:   lg=strlen(s);
                   1087:   for(i=0; i<= lg; i++) {
                   1088:   if  (s[i] == occ ) j++;
                   1089:   }
                   1090:   return j;
                   1091: }
                   1092: 
1.137     brouard  1093: /* void cutv(char *u,char *v, char*t, char occ) */
                   1094: /* { */
                   1095: /*   /\* cuts string t into u and v where u ends before last occurence of char 'occ'  */
                   1096: /*      and v starts after last occurence of char 'occ' : ex cutv(u,v,"abcdef2ghi2j",'2') */
                   1097: /*      gives u="abcdef2ghi" and v="j" *\/ */
                   1098: /*   int i,lg,j,p=0; */
                   1099: /*   i=0; */
                   1100: /*   lg=strlen(t); */
                   1101: /*   for(j=0; j<=lg-1; j++) { */
                   1102: /*     if((t[j]!= occ) && (t[j+1]== occ)) p=j+1; */
                   1103: /*   } */
1.126     brouard  1104: 
1.137     brouard  1105: /*   for(j=0; j<p; j++) { */
                   1106: /*     (u[j] = t[j]); */
                   1107: /*   } */
                   1108: /*      u[p]='\0'; */
1.126     brouard  1109: 
1.137     brouard  1110: /*    for(j=0; j<= lg; j++) { */
                   1111: /*     if (j>=(p+1))(v[j-p-1] = t[j]); */
                   1112: /*   } */
                   1113: /* } */
1.126     brouard  1114: 
1.160     brouard  1115: #ifdef _WIN32
                   1116: char * strsep(char **pp, const char *delim)
                   1117: {
                   1118:   char *p, *q;
                   1119:          
                   1120:   if ((p = *pp) == NULL)
                   1121:     return 0;
                   1122:   if ((q = strpbrk (p, delim)) != NULL)
                   1123:   {
                   1124:     *pp = q + 1;
                   1125:     *q = '\0';
                   1126:   }
                   1127:   else
                   1128:     *pp = 0;
                   1129:   return p;
                   1130: }
                   1131: #endif
                   1132: 
1.126     brouard  1133: /********************** nrerror ********************/
                   1134: 
                   1135: void nrerror(char error_text[])
                   1136: {
                   1137:   fprintf(stderr,"ERREUR ...\n");
                   1138:   fprintf(stderr,"%s\n",error_text);
                   1139:   exit(EXIT_FAILURE);
                   1140: }
                   1141: /*********************** vector *******************/
                   1142: double *vector(int nl, int nh)
                   1143: {
                   1144:   double *v;
                   1145:   v=(double *) malloc((size_t)((nh-nl+1+NR_END)*sizeof(double)));
                   1146:   if (!v) nrerror("allocation failure in vector");
                   1147:   return v-nl+NR_END;
                   1148: }
                   1149: 
                   1150: /************************ free vector ******************/
                   1151: void free_vector(double*v, int nl, int nh)
                   1152: {
                   1153:   free((FREE_ARG)(v+nl-NR_END));
                   1154: }
                   1155: 
                   1156: /************************ivector *******************************/
                   1157: int *ivector(long nl,long nh)
                   1158: {
                   1159:   int *v;
                   1160:   v=(int *) malloc((size_t)((nh-nl+1+NR_END)*sizeof(int)));
                   1161:   if (!v) nrerror("allocation failure in ivector");
                   1162:   return v-nl+NR_END;
                   1163: }
                   1164: 
                   1165: /******************free ivector **************************/
                   1166: void free_ivector(int *v, long nl, long nh)
                   1167: {
                   1168:   free((FREE_ARG)(v+nl-NR_END));
                   1169: }
                   1170: 
                   1171: /************************lvector *******************************/
                   1172: long *lvector(long nl,long nh)
                   1173: {
                   1174:   long *v;
                   1175:   v=(long *) malloc((size_t)((nh-nl+1+NR_END)*sizeof(long)));
                   1176:   if (!v) nrerror("allocation failure in ivector");
                   1177:   return v-nl+NR_END;
                   1178: }
                   1179: 
                   1180: /******************free lvector **************************/
                   1181: void free_lvector(long *v, long nl, long nh)
                   1182: {
                   1183:   free((FREE_ARG)(v+nl-NR_END));
                   1184: }
                   1185: 
                   1186: /******************* imatrix *******************************/
                   1187: int **imatrix(long nrl, long nrh, long ncl, long nch) 
                   1188:      /* allocate a int matrix with subscript range m[nrl..nrh][ncl..nch] */ 
                   1189: { 
                   1190:   long i, nrow=nrh-nrl+1,ncol=nch-ncl+1; 
                   1191:   int **m; 
                   1192:   
                   1193:   /* allocate pointers to rows */ 
                   1194:   m=(int **) malloc((size_t)((nrow+NR_END)*sizeof(int*))); 
                   1195:   if (!m) nrerror("allocation failure 1 in matrix()"); 
                   1196:   m += NR_END; 
                   1197:   m -= nrl; 
                   1198:   
                   1199:   
                   1200:   /* allocate rows and set pointers to them */ 
                   1201:   m[nrl]=(int *) malloc((size_t)((nrow*ncol+NR_END)*sizeof(int))); 
                   1202:   if (!m[nrl]) nrerror("allocation failure 2 in matrix()"); 
                   1203:   m[nrl] += NR_END; 
                   1204:   m[nrl] -= ncl; 
                   1205:   
                   1206:   for(i=nrl+1;i<=nrh;i++) m[i]=m[i-1]+ncol; 
                   1207:   
                   1208:   /* return pointer to array of pointers to rows */ 
                   1209:   return m; 
                   1210: } 
                   1211: 
                   1212: /****************** free_imatrix *************************/
                   1213: void free_imatrix(m,nrl,nrh,ncl,nch)
                   1214:       int **m;
                   1215:       long nch,ncl,nrh,nrl; 
                   1216:      /* free an int matrix allocated by imatrix() */ 
                   1217: { 
                   1218:   free((FREE_ARG) (m[nrl]+ncl-NR_END)); 
                   1219:   free((FREE_ARG) (m+nrl-NR_END)); 
                   1220: } 
                   1221: 
                   1222: /******************* matrix *******************************/
                   1223: double **matrix(long nrl, long nrh, long ncl, long nch)
                   1224: {
                   1225:   long i, nrow=nrh-nrl+1, ncol=nch-ncl+1;
                   1226:   double **m;
                   1227: 
                   1228:   m=(double **) malloc((size_t)((nrow+NR_END)*sizeof(double*)));
                   1229:   if (!m) nrerror("allocation failure 1 in matrix()");
                   1230:   m += NR_END;
                   1231:   m -= nrl;
                   1232: 
                   1233:   m[nrl]=(double *) malloc((size_t)((nrow*ncol+NR_END)*sizeof(double)));
                   1234:   if (!m[nrl]) nrerror("allocation failure 2 in matrix()");
                   1235:   m[nrl] += NR_END;
                   1236:   m[nrl] -= ncl;
                   1237: 
                   1238:   for (i=nrl+1; i<=nrh; i++) m[i]=m[i-1]+ncol;
                   1239:   return m;
1.145     brouard  1240:   /* print *(*(m+1)+70) or print m[1][70]; print m+1 or print &(m[1]) or &(m[1][0])
                   1241: m[i] = address of ith row of the table. &(m[i]) is its value which is another adress
                   1242: that of m[i][0]. In order to get the value p m[i][0] but it is unitialized.
1.126     brouard  1243:    */
                   1244: }
                   1245: 
                   1246: /*************************free matrix ************************/
                   1247: void free_matrix(double **m, long nrl, long nrh, long ncl, long nch)
                   1248: {
                   1249:   free((FREE_ARG)(m[nrl]+ncl-NR_END));
                   1250:   free((FREE_ARG)(m+nrl-NR_END));
                   1251: }
                   1252: 
                   1253: /******************* ma3x *******************************/
                   1254: double ***ma3x(long nrl, long nrh, long ncl, long nch, long nll, long nlh)
                   1255: {
                   1256:   long i, j, nrow=nrh-nrl+1, ncol=nch-ncl+1, nlay=nlh-nll+1;
                   1257:   double ***m;
                   1258: 
                   1259:   m=(double ***) malloc((size_t)((nrow+NR_END)*sizeof(double*)));
                   1260:   if (!m) nrerror("allocation failure 1 in matrix()");
                   1261:   m += NR_END;
                   1262:   m -= nrl;
                   1263: 
                   1264:   m[nrl]=(double **) malloc((size_t)((nrow*ncol+NR_END)*sizeof(double)));
                   1265:   if (!m[nrl]) nrerror("allocation failure 2 in matrix()");
                   1266:   m[nrl] += NR_END;
                   1267:   m[nrl] -= ncl;
                   1268: 
                   1269:   for (i=nrl+1; i<=nrh; i++) m[i]=m[i-1]+ncol;
                   1270: 
                   1271:   m[nrl][ncl]=(double *) malloc((size_t)((nrow*ncol*nlay+NR_END)*sizeof(double)));
                   1272:   if (!m[nrl][ncl]) nrerror("allocation failure 3 in matrix()");
                   1273:   m[nrl][ncl] += NR_END;
                   1274:   m[nrl][ncl] -= nll;
                   1275:   for (j=ncl+1; j<=nch; j++) 
                   1276:     m[nrl][j]=m[nrl][j-1]+nlay;
                   1277:   
                   1278:   for (i=nrl+1; i<=nrh; i++) {
                   1279:     m[i][ncl]=m[i-1l][ncl]+ncol*nlay;
                   1280:     for (j=ncl+1; j<=nch; j++) 
                   1281:       m[i][j]=m[i][j-1]+nlay;
                   1282:   }
                   1283:   return m; 
                   1284:   /*  gdb: p *(m+1) <=> p m[1] and p (m+1) <=> p (m+1) <=> p &(m[1])
                   1285:            &(m[i][j][k]) <=> *((*(m+i) + j)+k)
                   1286:   */
                   1287: }
                   1288: 
                   1289: /*************************free ma3x ************************/
                   1290: void free_ma3x(double ***m, long nrl, long nrh, long ncl, long nch,long nll, long nlh)
                   1291: {
                   1292:   free((FREE_ARG)(m[nrl][ncl]+ nll-NR_END));
                   1293:   free((FREE_ARG)(m[nrl]+ncl-NR_END));
                   1294:   free((FREE_ARG)(m+nrl-NR_END));
                   1295: }
                   1296: 
                   1297: /*************** function subdirf ***********/
                   1298: char *subdirf(char fileres[])
                   1299: {
                   1300:   /* Caution optionfilefiname is hidden */
                   1301:   strcpy(tmpout,optionfilefiname);
                   1302:   strcat(tmpout,"/"); /* Add to the right */
                   1303:   strcat(tmpout,fileres);
                   1304:   return tmpout;
                   1305: }
                   1306: 
                   1307: /*************** function subdirf2 ***********/
                   1308: char *subdirf2(char fileres[], char *preop)
                   1309: {
                   1310:   
                   1311:   /* Caution optionfilefiname is hidden */
                   1312:   strcpy(tmpout,optionfilefiname);
                   1313:   strcat(tmpout,"/");
                   1314:   strcat(tmpout,preop);
                   1315:   strcat(tmpout,fileres);
                   1316:   return tmpout;
                   1317: }
                   1318: 
                   1319: /*************** function subdirf3 ***********/
                   1320: char *subdirf3(char fileres[], char *preop, char *preop2)
                   1321: {
                   1322:   
                   1323:   /* Caution optionfilefiname is hidden */
                   1324:   strcpy(tmpout,optionfilefiname);
                   1325:   strcat(tmpout,"/");
                   1326:   strcat(tmpout,preop);
                   1327:   strcat(tmpout,preop2);
                   1328:   strcat(tmpout,fileres);
                   1329:   return tmpout;
                   1330: }
                   1331: 
1.162     brouard  1332: char *asc_diff_time(long time_sec, char ascdiff[])
                   1333: {
                   1334:   long sec_left, days, hours, minutes;
                   1335:   days = (time_sec) / (60*60*24);
                   1336:   sec_left = (time_sec) % (60*60*24);
                   1337:   hours = (sec_left) / (60*60) ;
                   1338:   sec_left = (sec_left) %(60*60);
                   1339:   minutes = (sec_left) /60;
                   1340:   sec_left = (sec_left) % (60);
                   1341:   sprintf(ascdiff,"%ld day(s) %ld hour(s) %ld minute(s) %ld second(s)",days, hours, minutes, sec_left);  
                   1342:   return ascdiff;
                   1343: }
                   1344: 
1.126     brouard  1345: /***************** f1dim *************************/
                   1346: extern int ncom; 
                   1347: extern double *pcom,*xicom;
                   1348: extern double (*nrfunc)(double []); 
                   1349:  
                   1350: double f1dim(double x) 
                   1351: { 
                   1352:   int j; 
                   1353:   double f;
                   1354:   double *xt; 
                   1355:  
                   1356:   xt=vector(1,ncom); 
                   1357:   for (j=1;j<=ncom;j++) xt[j]=pcom[j]+x*xicom[j]; 
                   1358:   f=(*nrfunc)(xt); 
                   1359:   free_vector(xt,1,ncom); 
                   1360:   return f; 
                   1361: } 
                   1362: 
                   1363: /*****************brent *************************/
                   1364: double brent(double ax, double bx, double cx, double (*f)(double), double tol,         double *xmin) 
1.187     brouard  1365: {
                   1366:   /* Given a function f, and given a bracketing triplet of abscissas ax, bx, cx (such that bx is
                   1367:    * between ax and cx, and f(bx) is less than both f(ax) and f(cx) ), this routine isolates
                   1368:    * the minimum to a fractional precision of about tol using Brent’s method. The abscissa of
                   1369:    * the minimum is returned as xmin, and the minimum function value is returned as brent , the
                   1370:    * returned function value. 
                   1371:   */
1.126     brouard  1372:   int iter; 
                   1373:   double a,b,d,etemp;
1.159     brouard  1374:   double fu=0,fv,fw,fx;
1.164     brouard  1375:   double ftemp=0.;
1.126     brouard  1376:   double p,q,r,tol1,tol2,u,v,w,x,xm; 
                   1377:   double e=0.0; 
                   1378:  
                   1379:   a=(ax < cx ? ax : cx); 
                   1380:   b=(ax > cx ? ax : cx); 
                   1381:   x=w=v=bx; 
                   1382:   fw=fv=fx=(*f)(x); 
                   1383:   for (iter=1;iter<=ITMAX;iter++) { 
                   1384:     xm=0.5*(a+b); 
                   1385:     tol2=2.0*(tol1=tol*fabs(x)+ZEPS); 
                   1386:     /*         if (2.0*fabs(fp-(*fret)) <= ftol*(fabs(fp)+fabs(*fret)))*/
                   1387:     printf(".");fflush(stdout);
                   1388:     fprintf(ficlog,".");fflush(ficlog);
1.162     brouard  1389: #ifdef DEBUGBRENT
1.126     brouard  1390:     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);
                   1391:     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);
                   1392:     /*         if ((fabs(x-xm) <= (tol2-0.5*(b-a)))||(2.0*fabs(fu-ftemp) <= ftol*1.e-2*(fabs(fu)+fabs(ftemp)))) { */
                   1393: #endif
                   1394:     if (fabs(x-xm) <= (tol2-0.5*(b-a))){ 
                   1395:       *xmin=x; 
                   1396:       return fx; 
                   1397:     } 
                   1398:     ftemp=fu;
                   1399:     if (fabs(e) > tol1) { 
                   1400:       r=(x-w)*(fx-fv); 
                   1401:       q=(x-v)*(fx-fw); 
                   1402:       p=(x-v)*q-(x-w)*r; 
                   1403:       q=2.0*(q-r); 
                   1404:       if (q > 0.0) p = -p; 
                   1405:       q=fabs(q); 
                   1406:       etemp=e; 
                   1407:       e=d; 
                   1408:       if (fabs(p) >= fabs(0.5*q*etemp) || p <= q*(a-x) || p >= q*(b-x)) 
                   1409:        d=CGOLD*(e=(x >= xm ? a-x : b-x)); 
                   1410:       else { 
                   1411:        d=p/q; 
                   1412:        u=x+d; 
                   1413:        if (u-a < tol2 || b-u < tol2) 
                   1414:          d=SIGN(tol1,xm-x); 
                   1415:       } 
                   1416:     } else { 
                   1417:       d=CGOLD*(e=(x >= xm ? a-x : b-x)); 
                   1418:     } 
                   1419:     u=(fabs(d) >= tol1 ? x+d : x+SIGN(tol1,d)); 
                   1420:     fu=(*f)(u); 
                   1421:     if (fu <= fx) { 
                   1422:       if (u >= x) a=x; else b=x; 
                   1423:       SHFT(v,w,x,u) 
1.183     brouard  1424:       SHFT(fv,fw,fx,fu) 
                   1425:     } else { 
                   1426:       if (u < x) a=u; else b=u; 
                   1427:       if (fu <= fw || w == x) { 
                   1428:        v=w; 
                   1429:        w=u; 
                   1430:        fv=fw; 
                   1431:        fw=fu; 
                   1432:       } else if (fu <= fv || v == x || v == w) { 
                   1433:        v=u; 
                   1434:        fv=fu; 
                   1435:       } 
                   1436:     } 
1.126     brouard  1437:   } 
                   1438:   nrerror("Too many iterations in brent"); 
                   1439:   *xmin=x; 
                   1440:   return fx; 
                   1441: } 
                   1442: 
                   1443: /****************** mnbrak ***********************/
                   1444: 
                   1445: void mnbrak(double *ax, double *bx, double *cx, double *fa, double *fb, double *fc, 
                   1446:            double (*func)(double)) 
1.183     brouard  1447: { /* Given a function func , and given distinct initial points ax and bx , this routine searches in
                   1448: the downhill direction (defined by the function as evaluated at the initial points) and returns
                   1449: new points ax , bx , cx that bracket a minimum of the function. Also returned are the function
                   1450: values at the three points, fa, fb , and fc such that fa > fb and fb < fc.
                   1451:    */
1.126     brouard  1452:   double ulim,u,r,q, dum;
                   1453:   double fu; 
1.187     brouard  1454: 
                   1455:   double scale=10.;
                   1456:   int iterscale=0;
                   1457: 
                   1458:   *fa=(*func)(*ax); /*  xta[j]=pcom[j]+(*ax)*xicom[j]; fa=f(xta[j])*/
                   1459:   *fb=(*func)(*bx); /*  xtb[j]=pcom[j]+(*bx)*xicom[j]; fb=f(xtb[j]) */
                   1460: 
                   1461: 
                   1462:   /* while(*fb != *fb){ /\* *ax should be ok, reducing distance to *ax *\/ */
                   1463:   /*   printf("Warning mnbrak *fb = %lf, *bx=%lf *ax=%lf *fa==%lf iter=%d\n",*fb, *bx, *ax, *fa, iterscale++); */
                   1464:   /*   *bx = *ax - (*ax - *bx)/scale; */
                   1465:   /*   *fb=(*func)(*bx);  /\*  xtb[j]=pcom[j]+(*bx)*xicom[j]; fb=f(xtb[j]) *\/ */
                   1466:   /* } */
                   1467: 
1.126     brouard  1468:   if (*fb > *fa) { 
                   1469:     SHFT(dum,*ax,*bx,dum) 
1.183     brouard  1470:     SHFT(dum,*fb,*fa,dum) 
                   1471:   } 
1.126     brouard  1472:   *cx=(*bx)+GOLD*(*bx-*ax); 
                   1473:   *fc=(*func)(*cx); 
1.183     brouard  1474: #ifdef DEBUG
                   1475:   printf("mnbrak0 *fb=%.12e *fc=%.12e\n",*fb,*fc);
                   1476:   fprintf(ficlog,"mnbrak0 *fb=%.12e *fc=%.12e\n",*fb,*fc);
                   1477: #endif
                   1478:   while (*fb > *fc) { /* Declining a,b,c with fa> fb > fc */
1.126     brouard  1479:     r=(*bx-*ax)*(*fb-*fc); 
                   1480:     q=(*bx-*cx)*(*fb-*fa); 
                   1481:     u=(*bx)-((*bx-*cx)*q-(*bx-*ax)*r)/ 
1.183     brouard  1482:       (2.0*SIGN(FMAX(fabs(q-r),TINY),q-r)); /* Minimum abscissa of a parabolic estimated from (a,fa), (b,fb) and (c,fc). */
                   1483:     ulim=(*bx)+GLIMIT*(*cx-*bx); /* Maximum abscissa where function should be evaluated */
                   1484:     if ((*bx-u)*(u-*cx) > 0.0) { /* if u_p is between b and c */
1.126     brouard  1485:       fu=(*func)(u); 
1.163     brouard  1486: #ifdef DEBUG
                   1487:       /* f(x)=A(x-u)**2+f(u) */
                   1488:       double A, fparabu; 
                   1489:       A= (*fb - *fa)/(*bx-*ax)/(*bx+*ax-2*u);
                   1490:       fparabu= *fa - A*(*ax-u)*(*ax-u);
                   1491:       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);
                   1492:       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  1493:       /* And thus,it can be that fu > *fc even if fparabu < *fc */
                   1494:       /* mnbrak (*ax=7.666299858533, *fa=299039.693133272231), (*bx=8.595447774979, *fb=298976.598289369489),
                   1495:         (*cx=10.098840694817, *fc=298946.631474258087),  (*u=9.852501168332, fu=298948.773013752128, fparabu=298945.434711494134) */
                   1496:       /* In that case, there is no bracket in the output! Routine is wrong with many consequences.*/
1.163     brouard  1497: #endif 
1.184     brouard  1498: #ifdef MNBRAKORIGINAL
1.183     brouard  1499: #else
1.191     brouard  1500: /*       if (fu > *fc) { */
                   1501: /* #ifdef DEBUG */
                   1502: /*       printf("mnbrak4  fu > fc \n"); */
                   1503: /*       fprintf(ficlog, "mnbrak4 fu > fc\n"); */
                   1504: /* #endif */
                   1505: /*     /\* 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 *\\/  *\/ */
                   1506: /*     /\* SHFT(*fa,*fc,fu,*fc) /\\* (b, u, c) is a bracket while test fb > fc will be fu > fc  will exit *\\/ *\/ */
                   1507: /*     dum=u; /\* Shifting c and u *\/ */
                   1508: /*     u = *cx; */
                   1509: /*     *cx = dum; */
                   1510: /*     dum = fu; */
                   1511: /*     fu = *fc; */
                   1512: /*     *fc =dum; */
                   1513: /*       } else { /\* end *\/ */
                   1514: /* #ifdef DEBUG */
                   1515: /*       printf("mnbrak3  fu < fc \n"); */
                   1516: /*       fprintf(ficlog, "mnbrak3 fu < fc\n"); */
                   1517: /* #endif */
                   1518: /*     dum=u; /\* Shifting c and u *\/ */
                   1519: /*     u = *cx; */
                   1520: /*     *cx = dum; */
                   1521: /*     dum = fu; */
                   1522: /*     fu = *fc; */
                   1523: /*     *fc =dum; */
                   1524: /*       } */
1.183     brouard  1525: #ifdef DEBUG
1.191     brouard  1526:       printf("mnbrak34  fu < or >= fc \n");
                   1527:       fprintf(ficlog, "mnbrak34 fu < fc\n");
1.183     brouard  1528: #endif
1.191     brouard  1529:       dum=u; /* Shifting c and u */
                   1530:       u = *cx;
                   1531:       *cx = dum;
                   1532:       dum = fu;
                   1533:       fu = *fc;
                   1534:       *fc =dum;
1.183     brouard  1535: #endif
1.162     brouard  1536:     } else if ((*cx-u)*(u-ulim) > 0.0) { /* u is after c but before ulim */
1.183     brouard  1537: #ifdef DEBUG
                   1538:       printf("mnbrak2  u after c but before ulim\n");
                   1539:       fprintf(ficlog, "mnbrak2 u after c but before ulim\n");
                   1540: #endif
1.126     brouard  1541:       fu=(*func)(u); 
                   1542:       if (fu < *fc) { 
1.183     brouard  1543: #ifdef DEBUG
                   1544:       printf("mnbrak2  u after c but before ulim AND fu < fc\n");
                   1545:       fprintf(ficlog, "mnbrak2 u after c but before ulim AND fu <fc \n");
                   1546: #endif
1.126     brouard  1547:        SHFT(*bx,*cx,u,*cx+GOLD*(*cx-*bx)) 
1.183     brouard  1548:        SHFT(*fb,*fc,fu,(*func)(u)) 
                   1549:       } 
1.162     brouard  1550:     } else if ((u-ulim)*(ulim-*cx) >= 0.0) { /* u outside ulim (verifying that ulim is beyond c) */
1.183     brouard  1551: #ifdef DEBUG
                   1552:       printf("mnbrak2  u outside ulim (verifying that ulim is beyond c)\n");
                   1553:       fprintf(ficlog, "mnbrak2 u outside ulim (verifying that ulim is beyond c)\n");
                   1554: #endif
1.126     brouard  1555:       u=ulim; 
                   1556:       fu=(*func)(u); 
1.183     brouard  1557:     } else { /* u could be left to b (if r > q parabola has a maximum) */
                   1558: #ifdef DEBUG
                   1559:       printf("mnbrak2  u could be left to b (if r > q parabola has a maximum)\n");
                   1560:       fprintf(ficlog, "mnbrak2  u could be left to b (if r > q parabola has a maximum)\n");
                   1561: #endif
1.126     brouard  1562:       u=(*cx)+GOLD*(*cx-*bx); 
                   1563:       fu=(*func)(u); 
1.183     brouard  1564:     } /* end tests */
1.126     brouard  1565:     SHFT(*ax,*bx,*cx,u) 
1.183     brouard  1566:     SHFT(*fa,*fb,*fc,fu) 
                   1567: #ifdef DEBUG
                   1568:       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);
                   1569:       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);
                   1570: #endif
                   1571:   } /* 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  1572: } 
                   1573: 
                   1574: /*************** linmin ************************/
1.162     brouard  1575: /* Given an n -dimensional point p[1..n] and an n -dimensional direction xi[1..n] , moves and
                   1576: resets p to where the function func(p) takes on a minimum along the direction xi from p ,
                   1577: and replaces xi by the actual vector displacement that p was moved. Also returns as fret
                   1578: the value of func at the returned location p . This is actually all accomplished by calling the
                   1579: routines mnbrak and brent .*/
1.126     brouard  1580: int ncom; 
                   1581: double *pcom,*xicom;
                   1582: double (*nrfunc)(double []); 
                   1583:  
                   1584: void linmin(double p[], double xi[], int n, double *fret,double (*func)(double [])) 
                   1585: { 
                   1586:   double brent(double ax, double bx, double cx, 
                   1587:               double (*f)(double), double tol, double *xmin); 
                   1588:   double f1dim(double x); 
                   1589:   void mnbrak(double *ax, double *bx, double *cx, double *fa, double *fb, 
                   1590:              double *fc, double (*func)(double)); 
                   1591:   int j; 
                   1592:   double xx,xmin,bx,ax; 
                   1593:   double fx,fb,fa;
1.187     brouard  1594: 
                   1595:   double scale=10., axs, xxs, xxss; /* Scale added for infinity */
1.126     brouard  1596:  
                   1597:   ncom=n; 
                   1598:   pcom=vector(1,n); 
                   1599:   xicom=vector(1,n); 
                   1600:   nrfunc=func; 
                   1601:   for (j=1;j<=n;j++) { 
                   1602:     pcom[j]=p[j]; 
                   1603:     xicom[j]=xi[j]; 
                   1604:   } 
1.187     brouard  1605: 
1.192     brouard  1606:   /* axs=0.0; */
                   1607:   /* xxss=1; /\* 1 and using scale *\/ */
1.187     brouard  1608:   xxs=1;
1.192     brouard  1609:   /* do{ */
1.187     brouard  1610:     ax=0.;
                   1611:     xx= xxs;
                   1612:     mnbrak(&ax,&xx,&bx,&fa,&fx,&fb,f1dim);  /* Outputs: xtx[j]=pcom[j]+(*xx)*xicom[j]; fx=f(xtx[j]) */
                   1613:     /* brackets with inputs ax=0 and xx=1, but points, pcom=p, and directions values, xicom=xi, are sent via f1dim(x) */
                   1614:     /* 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))   */
                   1615:     /* Outputs: fa=f(p(j)) and fx=f(p(j) + xxs * xi(j) ) and f(bx)= f(p(j)+ bx* xi(j)) */
                   1616:     /* Given input ax=axs and xx=xxs, xx might be too far from ax to get a finite f(xx) */
                   1617:     /* Searches on line, outputs (ax, xx, bx) such that fx < min(fa and fb) */
                   1618:     /* Find a bracket a,x,b in direction n=xi ie xicom, order may change. Scale is [0:xxs*xi[j]] et non plus  [0:xi[j]]*/
1.192     brouard  1619:   /*   if (fx != fx){ */
                   1620:   /*   xxs=xxs/scale; /\* Trying a smaller xx, closer to initial ax=0 *\/ */
                   1621:   /*   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); */
                   1622:   /*   } */
                   1623:   /* }while(fx != fx); */
1.187     brouard  1624: 
1.191     brouard  1625: #ifdef DEBUGLINMIN
                   1626:   printf("\nLinmin after mnbrak: ax=%12.7f xx=%12.7f bx=%12.7f fa=%12.2f fx=%12.2f fb=%12.2f\n",  ax,xx,bx,fa,fx,fb);
                   1627: #endif
1.187     brouard  1628:   *fret=brent(ax,xx,bx,f1dim,TOL,&xmin); /* Giving a bracketting triplet (ax, xx, bx), find a minimum, xmin, according to f1dim, *fret(xmin),*/
                   1629:   /* fa = f(p[j] + ax * xi[j]), fx = f(p[j] + xx * xi[j]), fb = f(p[j] + bx * xi[j]) */
                   1630:   /* fmin = f(p[j] + xmin * xi[j]) */
                   1631:   /* P+lambda n in that direction (lambdamin), with TOL between abscisses */
                   1632:   /* f1dim(xmin): for (j=1;j<=ncom;j++) xt[j]=pcom[j]+xmin*xicom[j]; */
1.126     brouard  1633: #ifdef DEBUG
                   1634:   printf("retour brent fret=%.12e xmin=%.12e\n",*fret,xmin);
                   1635:   fprintf(ficlog,"retour brent fret=%.12e xmin=%.12e\n",*fret,xmin);
                   1636: #endif
1.191     brouard  1637: #ifdef DEBUGLINMIN
                   1638:   printf("linmin end ");
                   1639: #endif
1.126     brouard  1640:   for (j=1;j<=n;j++) { 
1.188     brouard  1641:     /* printf(" before xi[%d]=%12.8f", j,xi[j]); */
1.187     brouard  1642:     xi[j] *= xmin; /* xi rescaled by xmin: if xmin=-1.237 and xi=(1,0,...,0) xi=(-1.237,0,...,0) */
1.189     brouard  1643:     /* if(xxs <1.0) */
                   1644:     /*   printf(" after xi[%d]=%12.8f, xmin=%12.8f, ax=%12.8f, xx=%12.8f, bx=%12.8f, xxs=%12.8f", j,xi[j], xmin, ax, xx, bx,xxs ); */
1.187     brouard  1645:     p[j] += xi[j]; /* Parameters values are updated accordingly */
1.126     brouard  1646:   } 
1.189     brouard  1647:   /* printf("\n"); */
1.191     brouard  1648: #ifdef DEBUGLINMIN
                   1649:   printf("Comparing last *frec(xmin=%12.8f)=%12.8f from Brent and frec(0.)=%12.8f \n", xmin, *fret, (*func)(p));
                   1650:   for (j=1;j<=n;j++) { 
                   1651:     printf(" xi[%d]= %12.7f p[%d]= %12.7f",j,xi[j],j,p[j]);
                   1652:     if(j % ncovmodel == 0)
                   1653:       printf("\n");
                   1654:   }
                   1655: #endif
1.126     brouard  1656:   free_vector(xicom,1,n); 
                   1657:   free_vector(pcom,1,n); 
                   1658: } 
                   1659: 
                   1660: 
                   1661: /*************** powell ************************/
1.162     brouard  1662: /*
                   1663: Minimization of a function func of n variables. Input consists of an initial starting point
                   1664: p[1..n] ; an initial matrix xi[1..n][1..n] , whose columns contain the initial set of di-
                   1665: rections (usually the n unit vectors); and ftol , the fractional tolerance in the function value
                   1666: such that failure to decrease by more than this amount on one iteration signals doneness. On
                   1667: output, p is set to the best point found, xi is the then-current direction set, fret is the returned
                   1668: function value at p , and iter is the number of iterations taken. The routine linmin is used.
                   1669:  */
1.126     brouard  1670: void powell(double p[], double **xi, int n, double ftol, int *iter, double *fret, 
                   1671:            double (*func)(double [])) 
                   1672: { 
                   1673:   void linmin(double p[], double xi[], int n, double *fret, 
                   1674:              double (*func)(double [])); 
                   1675:   int i,ibig,j; 
                   1676:   double del,t,*pt,*ptt,*xit;
1.181     brouard  1677:   double directest;
1.126     brouard  1678:   double fp,fptt;
                   1679:   double *xits;
                   1680:   int niterf, itmp;
                   1681: 
                   1682:   pt=vector(1,n); 
                   1683:   ptt=vector(1,n); 
                   1684:   xit=vector(1,n); 
                   1685:   xits=vector(1,n); 
                   1686:   *fret=(*func)(p); 
                   1687:   for (j=1;j<=n;j++) pt[j]=p[j]; 
1.157     brouard  1688:     rcurr_time = time(NULL);  
1.126     brouard  1689:   for (*iter=1;;++(*iter)) { 
1.187     brouard  1690:     fp=(*fret); /* From former iteration or initial value */
1.126     brouard  1691:     ibig=0; 
                   1692:     del=0.0; 
1.157     brouard  1693:     rlast_time=rcurr_time;
                   1694:     /* (void) gettimeofday(&curr_time,&tzp); */
                   1695:     rcurr_time = time(NULL);  
                   1696:     curr_time = *localtime(&rcurr_time);
                   1697:     printf("\nPowell iter=%d -2*LL=%.12f %ld sec. %ld sec.",*iter,*fret, rcurr_time-rlast_time, rcurr_time-rstart_time);fflush(stdout);
                   1698:     fprintf(ficlog,"\nPowell iter=%d -2*LL=%.12f %ld sec. %ld sec.",*iter,*fret,rcurr_time-rlast_time, rcurr_time-rstart_time); fflush(ficlog);
                   1699: /*     fprintf(ficrespow,"%d %.12f %ld",*iter,*fret,curr_time.tm_sec-start_time.tm_sec); */
1.192     brouard  1700:     for (i=1;i<=n;i++) {
1.126     brouard  1701:       printf(" %d %.12f",i, p[i]);
                   1702:       fprintf(ficlog," %d %.12lf",i, p[i]);
                   1703:       fprintf(ficrespow," %.12lf", p[i]);
                   1704:     }
                   1705:     printf("\n");
                   1706:     fprintf(ficlog,"\n");
                   1707:     fprintf(ficrespow,"\n");fflush(ficrespow);
                   1708:     if(*iter <=3){
1.157     brouard  1709:       tml = *localtime(&rcurr_time);
                   1710:       strcpy(strcurr,asctime(&tml));
                   1711:       rforecast_time=rcurr_time; 
1.126     brouard  1712:       itmp = strlen(strcurr);
                   1713:       if(strcurr[itmp-1]=='\n')  /* Windows outputs with a new line */
                   1714:        strcurr[itmp-1]='\0';
1.162     brouard  1715:       printf("\nConsidering the time needed for the last iteration #%d: %ld seconds,\n",*iter,rcurr_time-rlast_time);
1.157     brouard  1716:       fprintf(ficlog,"\nConsidering the time needed for this last iteration #%d: %ld seconds,\n",*iter,rcurr_time-rlast_time);
1.126     brouard  1717:       for(niterf=10;niterf<=30;niterf+=10){
1.157     brouard  1718:        rforecast_time=rcurr_time+(niterf-*iter)*(rcurr_time-rlast_time);
                   1719:        forecast_time = *localtime(&rforecast_time);
                   1720:        strcpy(strfor,asctime(&forecast_time));
1.126     brouard  1721:        itmp = strlen(strfor);
                   1722:        if(strfor[itmp-1]=='\n')
                   1723:        strfor[itmp-1]='\0';
1.157     brouard  1724:        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);
                   1725:        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  1726:       }
                   1727:     }
1.187     brouard  1728:     for (i=1;i<=n;i++) { /* For each direction i */
                   1729:       for (j=1;j<=n;j++) xit[j]=xi[j][i]; /* Directions stored from previous iteration with previous scales */
1.126     brouard  1730:       fptt=(*fret); 
                   1731: #ifdef DEBUG
1.164     brouard  1732:          printf("fret=%lf, %lf, %lf \n", *fret, *fret, *fret);
                   1733:          fprintf(ficlog, "fret=%lf, %lf, %lf \n", *fret, *fret, *fret);
1.126     brouard  1734: #endif
1.187     brouard  1735:          printf("%d",i);fflush(stdout); /* print direction (parameter) i */
1.126     brouard  1736:       fprintf(ficlog,"%d",i);fflush(ficlog);
1.188     brouard  1737:       linmin(p,xit,n,fret,func); /* Point p[n]. xit[n] has been loaded for direction i as input.*/
                   1738:                                    /* Outputs are fret(new point p) p is updated and xit rescaled */
                   1739:       if (fabs(fptt-(*fret)) > del) { /* We are keeping the max gain on each of the n directions */
                   1740:        /* because that direction will be replaced unless the gain del is small */
                   1741:        /* in comparison with the 'probable' gain, mu^2, with the last average direction. */
                   1742:        /* Unless the n directions are conjugate some gain in the determinant may be obtained */
                   1743:        /* with the new direction. */
1.126     brouard  1744:        del=fabs(fptt-(*fret)); 
                   1745:        ibig=i; 
                   1746:       } 
                   1747: #ifdef DEBUG
                   1748:       printf("%d %.12e",i,(*fret));
                   1749:       fprintf(ficlog,"%d %.12e",i,(*fret));
                   1750:       for (j=1;j<=n;j++) {
                   1751:        xits[j]=FMAX(fabs(p[j]-pt[j]),1.e-5);
                   1752:        printf(" x(%d)=%.12e",j,xit[j]);
                   1753:        fprintf(ficlog," x(%d)=%.12e",j,xit[j]);
                   1754:       }
                   1755:       for(j=1;j<=n;j++) {
1.162     brouard  1756:        printf(" p(%d)=%.12e",j,p[j]);
                   1757:        fprintf(ficlog," p(%d)=%.12e",j,p[j]);
1.126     brouard  1758:       }
                   1759:       printf("\n");
                   1760:       fprintf(ficlog,"\n");
                   1761: #endif
1.187     brouard  1762:     } /* end loop on each direction i */
                   1763:     /* Convergence test will use last linmin estimation (fret) and compare former iteration (fp) */ 
1.188     brouard  1764:     /* But p and xit have been updated at the end of linmin, *fret corresponds to new p, xit  */
1.187     brouard  1765:     /* New value of last point Pn is not computed, P(n-1) */
1.182     brouard  1766:     if (2.0*fabs(fp-(*fret)) <= ftol*(fabs(fp)+fabs(*fret))) { /* Did we reach enough precision? */
1.188     brouard  1767:       /* We could compare with a chi^2. chisquare(0.95,ddl=1)=3.84 */
                   1768:       /* By adding age*age in a model, the new -2LL should be lower and the difference follows a */
                   1769:       /* a chisquare statistics with 1 degree. To be significant at the 95% level, it should have */
                   1770:       /* decreased of more than 3.84  */
                   1771:       /* By adding age*age and V1*age the gain (-2LL) should be more than 5.99 (ddl=2) */
                   1772:       /* By using V1+V2+V3, the gain should be  7.82, compared with basic 1+age. */
                   1773:       /* By adding 10 parameters more the gain should be 18.31 */
                   1774: 
                   1775:       /* Starting the program with initial values given by a former maximization will simply change */
                   1776:       /* the scales of the directions and the directions, because the are reset to canonical directions */
                   1777:       /* Thus the first calls to linmin will give new points and better maximizations until fp-(*fret) is */
                   1778:       /* under the tolerance value. If the tolerance is very small 1.e-9, it could last long.  */
1.126     brouard  1779: #ifdef DEBUG
                   1780:       int k[2],l;
                   1781:       k[0]=1;
                   1782:       k[1]=-1;
                   1783:       printf("Max: %.12e",(*func)(p));
                   1784:       fprintf(ficlog,"Max: %.12e",(*func)(p));
                   1785:       for (j=1;j<=n;j++) {
                   1786:        printf(" %.12e",p[j]);
                   1787:        fprintf(ficlog," %.12e",p[j]);
                   1788:       }
                   1789:       printf("\n");
                   1790:       fprintf(ficlog,"\n");
                   1791:       for(l=0;l<=1;l++) {
                   1792:        for (j=1;j<=n;j++) {
                   1793:          ptt[j]=p[j]+(p[j]-pt[j])*k[l];
                   1794:          printf("l=%d j=%d ptt=%.12e, xits=%.12e, p=%.12e, xit=%.12e", l,j,ptt[j],xits[j],p[j],xit[j]);
                   1795:          fprintf(ficlog,"l=%d j=%d ptt=%.12e, xits=%.12e, p=%.12e, xit=%.12e", l,j,ptt[j],xits[j],p[j],xit[j]);
                   1796:        }
                   1797:        printf("func(ptt)=%.12e, deriv=%.12e\n",(*func)(ptt),(ptt[j]-p[j])/((*func)(ptt)-(*func)(p)));
                   1798:        fprintf(ficlog,"func(ptt)=%.12e, deriv=%.12e\n",(*func)(ptt),(ptt[j]-p[j])/((*func)(ptt)-(*func)(p)));
                   1799:       }
                   1800: #endif
                   1801: 
                   1802: 
                   1803:       free_vector(xit,1,n); 
                   1804:       free_vector(xits,1,n); 
                   1805:       free_vector(ptt,1,n); 
                   1806:       free_vector(pt,1,n); 
                   1807:       return; 
1.192     brouard  1808:     } /* enough precision */ 
1.126     brouard  1809:     if (*iter == ITMAX) nrerror("powell exceeding maximum iterations."); 
1.181     brouard  1810:     for (j=1;j<=n;j++) { /* Computes the extrapolated point P_0 + 2 (P_n-P_0) */
1.126     brouard  1811:       ptt[j]=2.0*p[j]-pt[j]; 
                   1812:       xit[j]=p[j]-pt[j]; 
                   1813:       pt[j]=p[j]; 
                   1814:     } 
1.181     brouard  1815:     fptt=(*func)(ptt); /* f_3 */
1.192     brouard  1816: #ifdef POWELLF1F3
                   1817: #else
1.161     brouard  1818:     if (fptt < fp) { /* If extrapolated point is better, decide if we keep that new direction or not */
1.192     brouard  1819: #endif
1.162     brouard  1820:       /* (x1 f1=fp), (x2 f2=*fret), (x3 f3=fptt), (xm fm) */
1.161     brouard  1821:       /* From x1 (P0) distance of x2 is at h and x3 is 2h */
1.162     brouard  1822:       /* Let f"(x2) be the 2nd derivative equal everywhere.  */
                   1823:       /* Then the parabolic through (x1,f1), (x2,f2) and (x3,f3) */
                   1824:       /* will reach at f3 = fm + h^2/2 f"m  ; f" = (f1 -2f2 +f3 ) / h**2 */
1.181     brouard  1825:       /* Conditional for using this new direction is that mu^2 = (f1-2f2+f3)^2 /2 < del */
1.161     brouard  1826:       /* t=2.0*(fp-2.0*(*fret)+fptt)*SQR(fp-(*fret)-del)-del*SQR(fp-fptt); */
1.183     brouard  1827: #ifdef NRCORIGINAL
                   1828:       t=2.0*(fp-2.0*(*fret)+fptt)*SQR(fp-(*fret)-del)- del*SQR(fp-fptt); /* Original Numerical Recipes in C*/
                   1829: #else
                   1830:       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  1831:       t= t- del*SQR(fp-fptt);
1.183     brouard  1832: #endif
1.182     brouard  1833:       directest = fp-2.0*(*fret)+fptt - 2.0 * del; /* If del was big enough we change it for a new direction */
1.161     brouard  1834: #ifdef DEBUG
1.181     brouard  1835:       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);
                   1836:       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  1837:       printf("t3= %.12lf, t4= %.12lf, t3*= %.12lf, t4*= %.12lf\n",SQR(fp-(*fret)-del),SQR(fp-fptt),
                   1838:             (fp-(*fret)-del)*(fp-(*fret)-del),(fp-fptt)*(fp-fptt));
                   1839:       fprintf(ficlog,"t3= %.12lf, t4= %.12lf, t3*= %.12lf, t4*= %.12lf\n",SQR(fp-(*fret)-del),SQR(fp-fptt),
                   1840:             (fp-(*fret)-del)*(fp-(*fret)-del),(fp-fptt)*(fp-fptt));
                   1841:       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);
                   1842:       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);
                   1843: #endif
1.183     brouard  1844: #ifdef POWELLORIGINAL
                   1845:       if (t < 0.0) { /* Then we use it for new direction */
                   1846: #else
1.182     brouard  1847:       if (directest*t < 0.0) { /* Contradiction between both tests */
1.192     brouard  1848:        printf("directest= %.12lf, t= %.12lf, f1= %.12lf,f2= %.12lf,f3= %.12lf, del= %.12lf\n",directest, t, fp,(*fret),fptt,del);
                   1849:         printf("f1-2f2+f3= %.12lf, f1-f2-del= %.12lf, f1-f3= %.12lf\n",fp-2.0*(*fret)+fptt, fp -(*fret) -del, fp-fptt);
                   1850:         fprintf(ficlog,"directest= %.12lf, t= %.12lf, f1= %.12lf,f2= %.12lf,f3= %.12lf, del= %.12lf\n",directest, t, fp,(*fret),fptt, del);
                   1851:         fprintf(ficlog,"f1-2f2+f3= %.12lf, f1-f2-del= %.12lf, f1-f3= %.12lf\n",fp-2.0*(*fret)+fptt, fp -(*fret) -del, fp-fptt);
                   1852:       } 
1.181     brouard  1853:       if (directest < 0.0) { /* Then we use it for new direction */
                   1854: #endif
1.191     brouard  1855: #ifdef DEBUGLINMIN
                   1856:        printf("Before linmin in direction P%d-P0\n",n);
                   1857:        for (j=1;j<=n;j++) { 
                   1858:          printf("Before xit[%d]= %12.7f p[%d]= %12.7f",j,xit[j],j,p[j]);
                   1859:          if(j % ncovmodel == 0)
                   1860:            printf("\n");
                   1861:        }
                   1862: #endif
1.187     brouard  1863:        linmin(p,xit,n,fret,func); /* computes minimum on the extrapolated direction: changes p and rescales xit.*/
1.191     brouard  1864: #ifdef DEBUGLINMIN
                   1865:        for (j=1;j<=n;j++) { 
                   1866:          printf("After xit[%d]= %12.7f p[%d]= %12.7f",j,xit[j],j,p[j]);
                   1867:          if(j % ncovmodel == 0)
                   1868:            printf("\n");
                   1869:        }
                   1870: #endif
1.126     brouard  1871:        for (j=1;j<=n;j++) { 
1.181     brouard  1872:          xi[j][ibig]=xi[j][n]; /* Replace direction with biggest decrease by last direction n */
                   1873:          xi[j][n]=xit[j];      /* and this nth direction by the by the average p_0 p_n */
1.126     brouard  1874:        }
1.181     brouard  1875:        printf("Gaining to use new average direction of P0 P%d instead of biggest increase direction %d :\n",n,ibig);
                   1876:        fprintf(ficlog,"Gaining to use new average direction of P0 P%d instead of biggest increase direction %d :\n",n,ibig);
1.161     brouard  1877: 
1.126     brouard  1878: #ifdef DEBUG
1.164     brouard  1879:        printf("Direction changed  last moved %d in place of ibig=%d, new last is the average:\n",n,ibig);
                   1880:        fprintf(ficlog,"Direction changed  last moved %d in place of ibig=%d, new last is the average:\n",n,ibig);
1.126     brouard  1881:        for(j=1;j<=n;j++){
                   1882:          printf(" %.12e",xit[j]);
                   1883:          fprintf(ficlog," %.12e",xit[j]);
                   1884:        }
                   1885:        printf("\n");
                   1886:        fprintf(ficlog,"\n");
                   1887: #endif
1.192     brouard  1888:       } /* end of t or directest negative */
                   1889: #ifdef POWELLF1F3
                   1890: #else
1.162     brouard  1891:     } /* end if (fptt < fp)  */
1.192     brouard  1892: #endif
                   1893:   } /* loop iteration */ 
1.126     brouard  1894: } 
                   1895: 
                   1896: /**** Prevalence limit (stable or period prevalence)  ****************/
                   1897: 
                   1898: double **prevalim(double **prlim, int nlstate, double x[], double age, double **oldm, double **savm, double ftolpl, int ij)
                   1899: {
                   1900:   /* Computes the prevalence limit in each live state at age x by left multiplying the unit
                   1901:      matrix by transitions matrix until convergence is reached */
1.169     brouard  1902:   
1.126     brouard  1903:   int i, ii,j,k;
                   1904:   double min, max, maxmin, maxmax,sumnew=0.;
1.145     brouard  1905:   /* double **matprod2(); */ /* test */
1.131     brouard  1906:   double **out, cov[NCOVMAX+1], **pmij();
1.126     brouard  1907:   double **newm;
                   1908:   double agefin, delaymax=50 ; /* Max number of years to converge */
1.169     brouard  1909:   
1.126     brouard  1910:   for (ii=1;ii<=nlstate+ndeath;ii++)
                   1911:     for (j=1;j<=nlstate+ndeath;j++){
                   1912:       oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   1913:     }
1.169     brouard  1914:   
                   1915:   cov[1]=1.;
                   1916:   
                   1917:   /* Even if hstepm = 1, at least one multiplication by the unit matrix */
1.126     brouard  1918:   for(agefin=age-stepm/YEARM; agefin>=age-delaymax; agefin=agefin-stepm/YEARM){
                   1919:     newm=savm;
                   1920:     /* Covariates have to be included here again */
1.138     brouard  1921:     cov[2]=agefin;
1.187     brouard  1922:     if(nagesqr==1)
                   1923:       cov[3]= agefin*agefin;;
1.138     brouard  1924:     for (k=1; k<=cptcovn;k++) {
1.200     brouard  1925:       /* cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(ij,Tvar[k])]; */
                   1926:       cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(ij,k)];
1.198     brouard  1927:       /* printf("prevalim ij=%d k=%d Tvar[%d]=%d nbcode=%d cov=%lf codtabm(%d,Tvar[%d])=%d \n",ij,k, k, Tvar[k],nbcode[Tvar[k]][codtabm(ij,Tvar[k])],cov[2+k], ij, k, codtabm(ij,Tvar[k])]); */
1.138     brouard  1928:     }
1.186     brouard  1929:     /*wrong? for (k=1; k<=cptcovage;k++) cov[2+Tage[k]]=cov[2+Tage[k]]*cov[2]; */
1.200     brouard  1930:     /* for (k=1; k<=cptcovage;k++) cov[2+nagesqr+Tage[k]]=nbcode[Tvar[k]][codtabm(ij,Tvar[k])]*cov[2]; */
                   1931:     for (k=1; k<=cptcovage;k++) cov[2+nagesqr+Tage[k]]=nbcode[Tvar[k]][codtabm(ij,k)]*cov[2];
1.186     brouard  1932:     for (k=1; k<=cptcovprod;k++) /* Useless */
1.200     brouard  1933:       /* cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,Tvard[k][1])] * nbcode[Tvard[k][2]][codtabm(ij,Tvard[k][2])]; */
                   1934:       cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,k)] * nbcode[Tvard[k][2]][codtabm(ij,k)];
1.138     brouard  1935:     
                   1936:     /*printf("ij=%d cptcovprod=%d tvar=%d ", ij, cptcovprod, Tvar[1]);*/
                   1937:     /*printf("ij=%d cov[3]=%lf cov[4]=%lf \n",ij, cov[3],cov[4]);*/
                   1938:     /*printf("ij=%d cov[3]=%lf \n",ij, cov[3]);*/
1.145     brouard  1939:     /* savm=pmij(pmmij,cov,ncovmodel,x,nlstate); */
                   1940:     /* out=matprod2(newm, pmij(pmmij,cov,ncovmodel,x,nlstate),1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, oldm); /\* Bug Valgrind *\/ */
1.142     brouard  1941:     out=matprod2(newm, pmij(pmmij,cov,ncovmodel,x,nlstate),1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, oldm); /* Bug Valgrind */
1.138     brouard  1942:     
1.126     brouard  1943:     savm=oldm;
                   1944:     oldm=newm;
                   1945:     maxmax=0.;
                   1946:     for(j=1;j<=nlstate;j++){
                   1947:       min=1.;
                   1948:       max=0.;
                   1949:       for(i=1; i<=nlstate; i++) {
                   1950:        sumnew=0;
                   1951:        for(k=1; k<=ndeath; k++) sumnew+=newm[i][nlstate+k];
                   1952:        prlim[i][j]= newm[i][j]/(1-sumnew);
1.145     brouard  1953:         /*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  1954:        max=FMAX(max,prlim[i][j]);
                   1955:        min=FMIN(min,prlim[i][j]);
                   1956:       }
                   1957:       maxmin=max-min;
                   1958:       maxmax=FMAX(maxmax,maxmin);
1.169     brouard  1959:     } /* j loop */
1.126     brouard  1960:     if(maxmax < ftolpl){
                   1961:       return prlim;
                   1962:     }
1.169     brouard  1963:   } /* age loop */
                   1964:   return prlim; /* should not reach here */
1.126     brouard  1965: }
                   1966: 
                   1967: /*************** transition probabilities ***************/ 
                   1968: 
                   1969: double **pmij(double **ps, double *cov, int ncovmodel, double *x, int nlstate )
                   1970: {
1.138     brouard  1971:   /* According to parameters values stored in x and the covariate's values stored in cov,
                   1972:      computes the probability to be observed in state j being in state i by appying the
                   1973:      model to the ncovmodel covariates (including constant and age).
                   1974:      lnpijopii=ln(pij/pii)= aij+bij*age+cij*v1+dij*v2+... = sum_nc=1^ncovmodel xij(nc)*cov[nc]
                   1975:      and, according on how parameters are entered, the position of the coefficient xij(nc) of the
                   1976:      ncth covariate in the global vector x is given by the formula:
                   1977:      j<i nc+((i-1)*(nlstate+ndeath-1)+j-1)*ncovmodel
                   1978:      j>=i nc + ((i-1)*(nlstate+ndeath-1)+(j-2))*ncovmodel
                   1979:      Computes ln(pij/pii) (lnpijopii), deduces pij/pii by exponentiation,
                   1980:      sums on j different of i to get 1-pii/pii, deduces pii, and then all pij.
                   1981:      Outputs ps[i][j] the probability to be observed in j being in j according to
                   1982:      the values of the covariates cov[nc] and corresponding parameter values x[nc+shiftij]
                   1983:   */
                   1984:   double s1, lnpijopii;
1.126     brouard  1985:   /*double t34;*/
1.164     brouard  1986:   int i,j, nc, ii, jj;
1.126     brouard  1987: 
                   1988:     for(i=1; i<= nlstate; i++){
                   1989:       for(j=1; j<i;j++){
1.138     brouard  1990:        for (nc=1, lnpijopii=0.;nc <=ncovmodel; nc++){
                   1991:          /*lnpijopii += param[i][j][nc]*cov[nc];*/
                   1992:          lnpijopii += x[nc+((i-1)*(nlstate+ndeath-1)+j-1)*ncovmodel]*cov[nc];
                   1993: /*      printf("Int j<i s1=%.17e, lnpijopii=%.17e\n",s1,lnpijopii); */
1.126     brouard  1994:        }
1.138     brouard  1995:        ps[i][j]=lnpijopii; /* In fact ln(pij/pii) */
                   1996: /*     printf("s1=%.17e, lnpijopii=%.17e\n",s1,lnpijopii); */
1.126     brouard  1997:       }
                   1998:       for(j=i+1; j<=nlstate+ndeath;j++){
1.138     brouard  1999:        for (nc=1, lnpijopii=0.;nc <=ncovmodel; nc++){
                   2000:          /*lnpijopii += x[(i-1)*nlstate*ncovmodel+(j-2)*ncovmodel+nc+(i-1)*(ndeath-1)*ncovmodel]*cov[nc];*/
                   2001:          lnpijopii += x[nc + ((i-1)*(nlstate+ndeath-1)+(j-2))*ncovmodel]*cov[nc];
                   2002: /*       printf("Int j>i s1=%.17e, lnpijopii=%.17e %lx %lx\n",s1,lnpijopii,s1,lnpijopii); */
1.126     brouard  2003:        }
1.138     brouard  2004:        ps[i][j]=lnpijopii; /* In fact ln(pij/pii) */
1.126     brouard  2005:       }
                   2006:     }
                   2007:     
                   2008:     for(i=1; i<= nlstate; i++){
                   2009:       s1=0;
1.131     brouard  2010:       for(j=1; j<i; j++){
1.138     brouard  2011:        s1+=exp(ps[i][j]); /* In fact sums pij/pii */
1.131     brouard  2012:        /*printf("debug1 %d %d ps=%lf exp(ps)=%lf s1+=%lf\n",i,j,ps[i][j],exp(ps[i][j]),s1); */
                   2013:       }
                   2014:       for(j=i+1; j<=nlstate+ndeath; j++){
1.138     brouard  2015:        s1+=exp(ps[i][j]); /* In fact sums pij/pii */
1.131     brouard  2016:        /*printf("debug2 %d %d ps=%lf exp(ps)=%lf s1+=%lf\n",i,j,ps[i][j],exp(ps[i][j]),s1); */
                   2017:       }
1.138     brouard  2018:       /* s1= sum_{j<>i} pij/pii=(1-pii)/pii and thus pii is known from s1 */
1.126     brouard  2019:       ps[i][i]=1./(s1+1.);
1.138     brouard  2020:       /* Computing other pijs */
1.126     brouard  2021:       for(j=1; j<i; j++)
                   2022:        ps[i][j]= exp(ps[i][j])*ps[i][i];
                   2023:       for(j=i+1; j<=nlstate+ndeath; j++)
                   2024:        ps[i][j]= exp(ps[i][j])*ps[i][i];
                   2025:       /* ps[i][nlstate+1]=1.-s1- ps[i][i];*/ /* Sum should be 1 */
                   2026:     } /* end i */
                   2027:     
                   2028:     for(ii=nlstate+1; ii<= nlstate+ndeath; ii++){
                   2029:       for(jj=1; jj<= nlstate+ndeath; jj++){
                   2030:        ps[ii][jj]=0;
                   2031:        ps[ii][ii]=1;
                   2032:       }
                   2033:     }
                   2034:     
1.145     brouard  2035:     
                   2036:     /* for(ii=1; ii<= nlstate+ndeath; ii++){ */
                   2037:     /*   for(jj=1; jj<= nlstate+ndeath; jj++){ */
                   2038:     /*         printf(" pmij  ps[%d][%d]=%lf ",ii,jj,ps[ii][jj]); */
                   2039:     /*   } */
                   2040:     /*   printf("\n "); */
                   2041:     /* } */
                   2042:     /* printf("\n ");printf("%lf ",cov[2]);*/
                   2043:     /*
1.126     brouard  2044:       for(i=1; i<= npar; i++) printf("%f ",x[i]);
                   2045:       goto end;*/
                   2046:     return ps;
                   2047: }
                   2048: 
                   2049: /**************** Product of 2 matrices ******************/
                   2050: 
1.145     brouard  2051: double **matprod2(double **out, double **in,int nrl, int nrh, int ncl, int nch, int ncolol, int ncoloh, double **b)
1.126     brouard  2052: {
                   2053:   /* Computes the matrix product of in(1,nrh-nrl+1)(1,nch-ncl+1) times
                   2054:      b(1,nch-ncl+1)(1,ncoloh-ncolol+1) into out(...) */
                   2055:   /* in, b, out are matrice of pointers which should have been initialized 
                   2056:      before: only the contents of out is modified. The function returns
                   2057:      a pointer to pointers identical to out */
1.145     brouard  2058:   int i, j, k;
1.126     brouard  2059:   for(i=nrl; i<= nrh; i++)
1.145     brouard  2060:     for(k=ncolol; k<=ncoloh; k++){
                   2061:       out[i][k]=0.;
                   2062:       for(j=ncl; j<=nch; j++)
                   2063:        out[i][k] +=in[i][j]*b[j][k];
                   2064:     }
1.126     brouard  2065:   return out;
                   2066: }
                   2067: 
                   2068: 
                   2069: /************* Higher Matrix Product ***************/
                   2070: 
                   2071: double ***hpxij(double ***po, int nhstepm, double age, int hstepm, double *x, int nlstate, int stepm, double **oldm, double **savm, int ij )
                   2072: {
                   2073:   /* Computes the transition matrix starting at age 'age' over 
                   2074:      'nhstepm*hstepm*stepm' months (i.e. until
                   2075:      age (in years)  age+nhstepm*hstepm*stepm/12) by multiplying 
                   2076:      nhstepm*hstepm matrices. 
                   2077:      Output is stored in matrix po[i][j][h] for h every 'hstepm' step 
                   2078:      (typically every 2 years instead of every month which is too big 
                   2079:      for the memory).
                   2080:      Model is determined by parameters x and covariates have to be 
                   2081:      included manually here. 
                   2082: 
                   2083:      */
                   2084: 
                   2085:   int i, j, d, h, k;
1.131     brouard  2086:   double **out, cov[NCOVMAX+1];
1.126     brouard  2087:   double **newm;
1.187     brouard  2088:   double agexact;
1.126     brouard  2089: 
                   2090:   /* Hstepm could be zero and should return the unit matrix */
                   2091:   for (i=1;i<=nlstate+ndeath;i++)
                   2092:     for (j=1;j<=nlstate+ndeath;j++){
                   2093:       oldm[i][j]=(i==j ? 1.0 : 0.0);
                   2094:       po[i][j][0]=(i==j ? 1.0 : 0.0);
                   2095:     }
                   2096:   /* Even if hstepm = 1, at least one multiplication by the unit matrix */
                   2097:   for(h=1; h <=nhstepm; h++){
                   2098:     for(d=1; d <=hstepm; d++){
                   2099:       newm=savm;
                   2100:       /* Covariates have to be included here again */
                   2101:       cov[1]=1.;
1.187     brouard  2102:       agexact=age+((h-1)*hstepm + (d-1))*stepm/YEARM;
                   2103:       cov[2]=agexact;
                   2104:       if(nagesqr==1)
                   2105:        cov[3]= agexact*agexact;
1.131     brouard  2106:       for (k=1; k<=cptcovn;k++) 
1.200     brouard  2107:        cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(ij,k)];
                   2108:        /* cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(ij,Tvar[k])]; */
1.186     brouard  2109:       for (k=1; k<=cptcovage;k++) /* Should start at cptcovn+1 */
                   2110:        /* cov[2+Tage[k]]=cov[2+Tage[k]]*cov[2]; */
1.200     brouard  2111:        cov[2+nagesqr+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(ij,k)]*cov[2];
                   2112:        /* cov[2+nagesqr+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(ij,Tvar[Tage[k]])]*cov[2]; */
1.145     brouard  2113:       for (k=1; k<=cptcovprod;k++) /* Useless because included in cptcovn */
1.200     brouard  2114:        cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,k)]*nbcode[Tvard[k][2]][codtabm(ij,k)];
                   2115:        /* cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,Tvard[k][1])]*nbcode[Tvard[k][2]][codtabm(ij,Tvard[k][2])]; */
1.126     brouard  2116: 
                   2117: 
                   2118:       /*printf("hxi cptcov=%d cptcode=%d\n",cptcov,cptcode);*/
                   2119:       /*printf("h=%d d=%d age=%f cov=%f\n",h,d,age,cov[2]);*/
                   2120:       out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, 
                   2121:                   pmij(pmmij,cov,ncovmodel,x,nlstate));
                   2122:       savm=oldm;
                   2123:       oldm=newm;
                   2124:     }
                   2125:     for(i=1; i<=nlstate+ndeath; i++)
                   2126:       for(j=1;j<=nlstate+ndeath;j++) {
                   2127:        po[i][j][h]=newm[i][j];
1.128     brouard  2128:        /*if(h==nhstepm) printf("po[%d][%d][%d]=%f ",i,j,h,po[i][j][h]);*/
1.126     brouard  2129:       }
1.128     brouard  2130:     /*printf("h=%d ",h);*/
1.126     brouard  2131:   } /* end h */
1.128     brouard  2132: /*     printf("\n H=%d \n",h); */
1.126     brouard  2133:   return po;
                   2134: }
                   2135: 
1.162     brouard  2136: #ifdef NLOPT
                   2137:   double  myfunc(unsigned n, const double *p1, double *grad, void *pd){
                   2138:   double fret;
                   2139:   double *xt;
                   2140:   int j;
                   2141:   myfunc_data *d2 = (myfunc_data *) pd;
                   2142: /* xt = (p1-1); */
                   2143:   xt=vector(1,n); 
                   2144:   for (j=1;j<=n;j++)   xt[j]=p1[j-1]; /* xt[1]=p1[0] */
                   2145: 
                   2146:   fret=(d2->function)(xt); /*  p xt[1]@8 is fine */
                   2147:   /* fret=(*func)(xt); /\*  p xt[1]@8 is fine *\/ */
                   2148:   printf("Function = %.12lf ",fret);
                   2149:   for (j=1;j<=n;j++) printf(" %d %.8lf", j, xt[j]); 
                   2150:   printf("\n");
                   2151:  free_vector(xt,1,n);
                   2152:   return fret;
                   2153: }
                   2154: #endif
1.126     brouard  2155: 
                   2156: /*************** log-likelihood *************/
                   2157: double func( double *x)
                   2158: {
                   2159:   int i, ii, j, k, mi, d, kk;
1.131     brouard  2160:   double l, ll[NLSTATEMAX+1], cov[NCOVMAX+1];
1.126     brouard  2161:   double **out;
                   2162:   double sw; /* Sum of weights */
                   2163:   double lli; /* Individual log likelihood */
                   2164:   int s1, s2;
                   2165:   double bbh, survp;
                   2166:   long ipmx;
1.187     brouard  2167:   double agexact;
1.126     brouard  2168:   /*extern weight */
                   2169:   /* We are differentiating ll according to initial status */
                   2170:   /*  for (i=1;i<=npar;i++) printf("%f ", x[i]);*/
                   2171:   /*for(i=1;i<imx;i++) 
                   2172:     printf(" %d\n",s[4][i]);
                   2173:   */
1.162     brouard  2174: 
                   2175:   ++countcallfunc;
                   2176: 
1.126     brouard  2177:   cov[1]=1.;
                   2178: 
                   2179:   for(k=1; k<=nlstate; k++) ll[k]=0.;
                   2180: 
                   2181:   if(mle==1){
                   2182:     for (i=1,ipmx=0, sw=0.; i<=imx; i++){
1.138     brouard  2183:       /* Computes the values of the ncovmodel covariates of the model
                   2184:         depending if the covariates are fixed or variying (age dependent) and stores them in cov[]
                   2185:         Then computes with function pmij which return a matrix p[i][j] giving the elementary probability
                   2186:         to be observed in j being in i according to the model.
                   2187:        */
1.145     brouard  2188:       for (k=1; k<=cptcovn;k++){ /* Simple and product covariates without age* products */
1.187     brouard  2189:          cov[2+nagesqr+k]=covar[Tvar[k]][i];
1.145     brouard  2190:       }
1.137     brouard  2191:       /* In model V2+V1*V4+age*V3+V3*V2 Tvar[1] is V2, Tvar[2=V1*V4] 
1.138     brouard  2192:         is 6, Tvar[3=age*V3] should not be computed because of age Tvar[4=V3*V2] 
1.137     brouard  2193:         has been calculated etc */
1.126     brouard  2194:       for(mi=1; mi<= wav[i]-1; mi++){
                   2195:        for (ii=1;ii<=nlstate+ndeath;ii++)
                   2196:          for (j=1;j<=nlstate+ndeath;j++){
                   2197:            oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   2198:            savm[ii][j]=(ii==j ? 1.0 : 0.0);
                   2199:          }
                   2200:        for(d=0; d<dh[mi][i]; d++){
                   2201:          newm=savm;
1.187     brouard  2202:          agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;
                   2203:          cov[2]=agexact;
                   2204:          if(nagesqr==1)
                   2205:            cov[3]= agexact*agexact;
1.126     brouard  2206:          for (kk=1; kk<=cptcovage;kk++) {
1.187     brouard  2207:            cov[Tage[kk]+2+nagesqr]=covar[Tvar[Tage[kk]]][i]*agexact; /* Tage[kk] gives the data-covariate associated with age */
1.126     brouard  2208:          }
                   2209:          out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
                   2210:                       1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
                   2211:          savm=oldm;
                   2212:          oldm=newm;
                   2213:        } /* end mult */
                   2214:       
                   2215:        /*lli=log(out[s[mw[mi][i]][i]][s[mw[mi+1][i]][i]]);*/ /* Original formula */
                   2216:        /* But now since version 0.9 we anticipate for bias at large stepm.
                   2217:         * If stepm is larger than one month (smallest stepm) and if the exact delay 
                   2218:         * (in months) between two waves is not a multiple of stepm, we rounded to 
                   2219:         * the nearest (and in case of equal distance, to the lowest) interval but now
                   2220:         * we keep into memory the bias bh[mi][i] and also the previous matrix product
                   2221:         * (i.e to dh[mi][i]-1) saved in 'savm'. Then we inter(extra)polate the
                   2222:         * probability in order to take into account the bias as a fraction of the way
                   2223:         * from savm to out if bh is negative or even beyond if bh is positive. bh varies
                   2224:         * -stepm/2 to stepm/2 .
                   2225:         * For stepm=1 the results are the same as for previous versions of Imach.
                   2226:         * For stepm > 1 the results are less biased than in previous versions. 
                   2227:         */
                   2228:        s1=s[mw[mi][i]][i];
                   2229:        s2=s[mw[mi+1][i]][i];
                   2230:        bbh=(double)bh[mi][i]/(double)stepm; 
                   2231:        /* bias bh is positive if real duration
                   2232:         * is higher than the multiple of stepm and negative otherwise.
                   2233:         */
                   2234:        /* lli= (savm[s1][s2]>1.e-8 ?(1.+bbh)*log(out[s1][s2])- bbh*log(savm[s1][s2]):log((1.+bbh)*out[s1][s2]));*/
                   2235:        if( s2 > nlstate){ 
                   2236:          /* i.e. if s2 is a death state and if the date of death is known 
                   2237:             then the contribution to the likelihood is the probability to 
                   2238:             die between last step unit time and current  step unit time, 
                   2239:             which is also equal to probability to die before dh 
                   2240:             minus probability to die before dh-stepm . 
                   2241:             In version up to 0.92 likelihood was computed
                   2242:        as if date of death was unknown. Death was treated as any other
                   2243:        health state: the date of the interview describes the actual state
                   2244:        and not the date of a change in health state. The former idea was
                   2245:        to consider that at each interview the state was recorded
                   2246:        (healthy, disable or death) and IMaCh was corrected; but when we
                   2247:        introduced the exact date of death then we should have modified
                   2248:        the contribution of an exact death to the likelihood. This new
                   2249:        contribution is smaller and very dependent of the step unit
                   2250:        stepm. It is no more the probability to die between last interview
                   2251:        and month of death but the probability to survive from last
                   2252:        interview up to one month before death multiplied by the
                   2253:        probability to die within a month. Thanks to Chris
                   2254:        Jackson for correcting this bug.  Former versions increased
                   2255:        mortality artificially. The bad side is that we add another loop
                   2256:        which slows down the processing. The difference can be up to 10%
                   2257:        lower mortality.
                   2258:          */
1.183     brouard  2259:        /* If, at the beginning of the maximization mostly, the
                   2260:           cumulative probability or probability to be dead is
                   2261:           constant (ie = 1) over time d, the difference is equal to
                   2262:           0.  out[s1][3] = savm[s1][3]: probability, being at state
                   2263:           s1 at precedent wave, to be dead a month before current
                   2264:           wave is equal to probability, being at state s1 at
                   2265:           precedent wave, to be dead at mont of the current
                   2266:           wave. Then the observed probability (that this person died)
                   2267:           is null according to current estimated parameter. In fact,
                   2268:           it should be very low but not zero otherwise the log go to
                   2269:           infinity.
                   2270:        */
                   2271: /* #ifdef INFINITYORIGINAL */
                   2272: /*         lli=log(out[s1][s2] - savm[s1][s2]); */
                   2273: /* #else */
                   2274: /*       if ((out[s1][s2] - savm[s1][s2]) < mytinydouble)  */
                   2275: /*         lli=log(mytinydouble); */
                   2276: /*       else */
                   2277: /*         lli=log(out[s1][s2] - savm[s1][s2]); */
                   2278: /* #endif */
                   2279:            lli=log(out[s1][s2] - savm[s1][s2]);
1.126     brouard  2280: 
                   2281:        } else if  (s2==-2) {
                   2282:          for (j=1,survp=0. ; j<=nlstate; j++) 
                   2283:            survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j];
                   2284:          /*survp += out[s1][j]; */
                   2285:          lli= log(survp);
                   2286:        }
                   2287:        
                   2288:        else if  (s2==-4) { 
                   2289:          for (j=3,survp=0. ; j<=nlstate; j++)  
                   2290:            survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j];
                   2291:          lli= log(survp); 
                   2292:        } 
                   2293: 
                   2294:        else if  (s2==-5) { 
                   2295:          for (j=1,survp=0. ; j<=2; j++)  
                   2296:            survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j];
                   2297:          lli= log(survp); 
                   2298:        } 
                   2299:        
                   2300:        else{
                   2301:          lli= log((1.+bbh)*out[s1][s2]- bbh*savm[s1][s2]); /* linear interpolation */
                   2302:          /*  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 */
                   2303:        } 
                   2304:        /*lli=(1.+bbh)*log(out[s1][s2])- bbh*log(savm[s1][s2]);*/
                   2305:        /*if(lli ==000.0)*/
                   2306:        /*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); */
                   2307:        ipmx +=1;
                   2308:        sw += weight[i];
                   2309:        ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
1.183     brouard  2310:        /* if (lli < log(mytinydouble)){ */
                   2311:        /*   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); */
                   2312:        /*   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]); */
                   2313:        /* } */
1.126     brouard  2314:       } /* end of wave */
                   2315:     } /* end of individual */
                   2316:   }  else if(mle==2){
                   2317:     for (i=1,ipmx=0, sw=0.; i<=imx; i++){
1.187     brouard  2318:       for (k=1; k<=cptcovn;k++) cov[2+nagesqr+k]=covar[Tvar[k]][i];
1.126     brouard  2319:       for(mi=1; mi<= wav[i]-1; mi++){
                   2320:        for (ii=1;ii<=nlstate+ndeath;ii++)
                   2321:          for (j=1;j<=nlstate+ndeath;j++){
                   2322:            oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   2323:            savm[ii][j]=(ii==j ? 1.0 : 0.0);
                   2324:          }
                   2325:        for(d=0; d<=dh[mi][i]; d++){
                   2326:          newm=savm;
1.187     brouard  2327:          agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;
                   2328:          cov[2]=agexact;
                   2329:          if(nagesqr==1)
                   2330:            cov[3]= agexact*agexact;
1.126     brouard  2331:          for (kk=1; kk<=cptcovage;kk++) {
1.187     brouard  2332:            cov[Tage[kk]+2+nagesqr]=covar[Tvar[Tage[kk]]][i]*agexact;
1.126     brouard  2333:          }
                   2334:          out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
                   2335:                       1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
                   2336:          savm=oldm;
                   2337:          oldm=newm;
                   2338:        } /* end mult */
                   2339:       
                   2340:        s1=s[mw[mi][i]][i];
                   2341:        s2=s[mw[mi+1][i]][i];
                   2342:        bbh=(double)bh[mi][i]/(double)stepm; 
                   2343:        lli= (savm[s1][s2]>(double)1.e-8 ?log((1.+bbh)*out[s1][s2]- bbh*(savm[s1][s2])):log((1.+bbh)*out[s1][s2])); /* linear interpolation */
                   2344:        ipmx +=1;
                   2345:        sw += weight[i];
                   2346:        ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
                   2347:       } /* end of wave */
                   2348:     } /* end of individual */
                   2349:   }  else if(mle==3){  /* exponential inter-extrapolation */
                   2350:     for (i=1,ipmx=0, sw=0.; i<=imx; i++){
1.187     brouard  2351:       for (k=1; k<=cptcovn;k++) cov[2+nagesqr+k]=covar[Tvar[k]][i];
1.126     brouard  2352:       for(mi=1; mi<= wav[i]-1; mi++){
                   2353:        for (ii=1;ii<=nlstate+ndeath;ii++)
                   2354:          for (j=1;j<=nlstate+ndeath;j++){
                   2355:            oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   2356:            savm[ii][j]=(ii==j ? 1.0 : 0.0);
                   2357:          }
                   2358:        for(d=0; d<dh[mi][i]; d++){
                   2359:          newm=savm;
1.187     brouard  2360:          agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;
                   2361:          cov[2]=agexact;
                   2362:          if(nagesqr==1)
                   2363:            cov[3]= agexact*agexact;
1.126     brouard  2364:          for (kk=1; kk<=cptcovage;kk++) {
1.187     brouard  2365:            cov[Tage[kk]+2+nagesqr]=covar[Tvar[Tage[kk]]][i]*agexact;
1.126     brouard  2366:          }
                   2367:          out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
                   2368:                       1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
                   2369:          savm=oldm;
                   2370:          oldm=newm;
                   2371:        } /* end mult */
                   2372:       
                   2373:        s1=s[mw[mi][i]][i];
                   2374:        s2=s[mw[mi+1][i]][i];
                   2375:        bbh=(double)bh[mi][i]/(double)stepm; 
                   2376:        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 */
                   2377:        ipmx +=1;
                   2378:        sw += weight[i];
                   2379:        ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
                   2380:       } /* end of wave */
                   2381:     } /* end of individual */
                   2382:   }else if (mle==4){  /* ml=4 no inter-extrapolation */
                   2383:     for (i=1,ipmx=0, sw=0.; i<=imx; i++){
1.187     brouard  2384:       for (k=1; k<=cptcovn;k++) cov[2+nagesqr+k]=covar[Tvar[k]][i];
1.126     brouard  2385:       for(mi=1; mi<= wav[i]-1; mi++){
                   2386:        for (ii=1;ii<=nlstate+ndeath;ii++)
                   2387:          for (j=1;j<=nlstate+ndeath;j++){
                   2388:            oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   2389:            savm[ii][j]=(ii==j ? 1.0 : 0.0);
                   2390:          }
                   2391:        for(d=0; d<dh[mi][i]; d++){
                   2392:          newm=savm;
1.187     brouard  2393:          agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;
                   2394:          cov[2]=agexact;
                   2395:          if(nagesqr==1)
                   2396:            cov[3]= agexact*agexact;
1.126     brouard  2397:          for (kk=1; kk<=cptcovage;kk++) {
1.187     brouard  2398:            cov[Tage[kk]+2+nagesqr]=covar[Tvar[Tage[kk]]][i]*agexact;
1.126     brouard  2399:          }
                   2400:        
                   2401:          out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
                   2402:                       1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
                   2403:          savm=oldm;
                   2404:          oldm=newm;
                   2405:        } /* end mult */
                   2406:       
                   2407:        s1=s[mw[mi][i]][i];
                   2408:        s2=s[mw[mi+1][i]][i];
                   2409:        if( s2 > nlstate){ 
                   2410:          lli=log(out[s1][s2] - savm[s1][s2]);
                   2411:        }else{
                   2412:          lli=log(out[s[mw[mi][i]][i]][s[mw[mi+1][i]][i]]); /* Original formula */
                   2413:        }
                   2414:        ipmx +=1;
                   2415:        sw += weight[i];
                   2416:        ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
                   2417: /*     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]); */
                   2418:       } /* end of wave */
                   2419:     } /* end of individual */
                   2420:   }else{  /* ml=5 no inter-extrapolation no jackson =0.8a */
                   2421:     for (i=1,ipmx=0, sw=0.; i<=imx; i++){
1.187     brouard  2422:       for (k=1; k<=cptcovn;k++) cov[2+nagesqr+k]=covar[Tvar[k]][i];
1.126     brouard  2423:       for(mi=1; mi<= wav[i]-1; mi++){
                   2424:        for (ii=1;ii<=nlstate+ndeath;ii++)
                   2425:          for (j=1;j<=nlstate+ndeath;j++){
                   2426:            oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   2427:            savm[ii][j]=(ii==j ? 1.0 : 0.0);
                   2428:          }
                   2429:        for(d=0; d<dh[mi][i]; d++){
                   2430:          newm=savm;
1.187     brouard  2431:          agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;
                   2432:          cov[2]=agexact;
                   2433:          if(nagesqr==1)
                   2434:            cov[3]= agexact*agexact;
1.126     brouard  2435:          for (kk=1; kk<=cptcovage;kk++) {
1.187     brouard  2436:            cov[Tage[kk]+2+nagesqr]=covar[Tvar[Tage[kk]]][i]*agexact;
1.126     brouard  2437:          }
                   2438:        
                   2439:          out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
                   2440:                       1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
                   2441:          savm=oldm;
                   2442:          oldm=newm;
                   2443:        } /* end mult */
                   2444:       
                   2445:        s1=s[mw[mi][i]][i];
                   2446:        s2=s[mw[mi+1][i]][i];
                   2447:        lli=log(out[s[mw[mi][i]][i]][s[mw[mi+1][i]][i]]); /* Original formula */
                   2448:        ipmx +=1;
                   2449:        sw += weight[i];
                   2450:        ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
                   2451:        /*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]);*/
                   2452:       } /* end of wave */
                   2453:     } /* end of individual */
                   2454:   } /* End of if */
                   2455:   for(k=1,l=0.; k<=nlstate; k++) l += ll[k];
                   2456:   /* printf("l1=%f l2=%f ",ll[1],ll[2]); */
                   2457:   l= l*ipmx/sw; /* To get the same order of magnitude as if weight=1 for every body */
                   2458:   return -l;
                   2459: }
                   2460: 
                   2461: /*************** log-likelihood *************/
                   2462: double funcone( double *x)
                   2463: {
                   2464:   /* Same as likeli but slower because of a lot of printf and if */
                   2465:   int i, ii, j, k, mi, d, kk;
1.131     brouard  2466:   double l, ll[NLSTATEMAX+1], cov[NCOVMAX+1];
1.126     brouard  2467:   double **out;
                   2468:   double lli; /* Individual log likelihood */
                   2469:   double llt;
                   2470:   int s1, s2;
                   2471:   double bbh, survp;
1.187     brouard  2472:   double agexact;
1.126     brouard  2473:   /*extern weight */
                   2474:   /* We are differentiating ll according to initial status */
                   2475:   /*  for (i=1;i<=npar;i++) printf("%f ", x[i]);*/
                   2476:   /*for(i=1;i<imx;i++) 
                   2477:     printf(" %d\n",s[4][i]);
                   2478:   */
                   2479:   cov[1]=1.;
                   2480: 
                   2481:   for(k=1; k<=nlstate; k++) ll[k]=0.;
                   2482: 
                   2483:   for (i=1,ipmx=0, sw=0.; i<=imx; i++){
1.187     brouard  2484:     for (k=1; k<=cptcovn;k++) cov[2+nagesqr+k]=covar[Tvar[k]][i];
1.126     brouard  2485:     for(mi=1; mi<= wav[i]-1; mi++){
                   2486:       for (ii=1;ii<=nlstate+ndeath;ii++)
                   2487:        for (j=1;j<=nlstate+ndeath;j++){
                   2488:          oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   2489:          savm[ii][j]=(ii==j ? 1.0 : 0.0);
                   2490:        }
                   2491:       for(d=0; d<dh[mi][i]; d++){
                   2492:        newm=savm;
1.187     brouard  2493:        agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;
                   2494:        cov[2]=agexact;
                   2495:        if(nagesqr==1)
                   2496:          cov[3]= agexact*agexact;
1.126     brouard  2497:        for (kk=1; kk<=cptcovage;kk++) {
1.187     brouard  2498:          cov[Tage[kk]+2+nagesqr]=covar[Tvar[Tage[kk]]][i]*agexact;
1.126     brouard  2499:        }
1.187     brouard  2500: 
1.145     brouard  2501:        /* savm=pmij(pmmij,cov,ncovmodel,x,nlstate); */
1.126     brouard  2502:        out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
                   2503:                     1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
1.145     brouard  2504:        /* out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath, */
                   2505:        /*           1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate)); */
1.126     brouard  2506:        savm=oldm;
                   2507:        oldm=newm;
                   2508:       } /* end mult */
                   2509:       
                   2510:       s1=s[mw[mi][i]][i];
                   2511:       s2=s[mw[mi+1][i]][i];
                   2512:       bbh=(double)bh[mi][i]/(double)stepm; 
                   2513:       /* bias is positive if real duration
                   2514:        * is higher than the multiple of stepm and negative otherwise.
                   2515:        */
                   2516:       if( s2 > nlstate && (mle <5) ){  /* Jackson */
                   2517:        lli=log(out[s1][s2] - savm[s1][s2]);
                   2518:       } else if  (s2==-2) {
                   2519:        for (j=1,survp=0. ; j<=nlstate; j++) 
                   2520:          survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j];
                   2521:        lli= log(survp);
                   2522:       }else if (mle==1){
                   2523:        lli= log((1.+bbh)*out[s1][s2]- bbh*savm[s1][s2]); /* linear interpolation */
                   2524:       } else if(mle==2){
                   2525:        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 */
                   2526:       } else if(mle==3){  /* exponential inter-extrapolation */
                   2527:        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 */
                   2528:       } else if (mle==4){  /* mle=4 no inter-extrapolation */
                   2529:        lli=log(out[s1][s2]); /* Original formula */
1.136     brouard  2530:       } else{  /* mle=0 back to 1 */
                   2531:        lli= log((1.+bbh)*out[s1][s2]- bbh*savm[s1][s2]); /* linear interpolation */
                   2532:        /*lli=log(out[s1][s2]); */ /* Original formula */
1.126     brouard  2533:       } /* End of if */
                   2534:       ipmx +=1;
                   2535:       sw += weight[i];
                   2536:       ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
1.132     brouard  2537:       /*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  2538:       if(globpr){
1.141     brouard  2539:        fprintf(ficresilk,"%9ld %6d %2d %2d %1d %1d %3d %11.6f %8.4f\
1.126     brouard  2540:  %11.6f %11.6f %11.6f ", \
                   2541:                num[i],i,s1,s2,mi,mw[mi][i],dh[mi][i],exp(lli),weight[i],
                   2542:                2*weight[i]*lli,out[s1][s2],savm[s1][s2]);
                   2543:        for(k=1,llt=0.,l=0.; k<=nlstate; k++){
                   2544:          llt +=ll[k]*gipmx/gsw;
                   2545:          fprintf(ficresilk," %10.6f",-ll[k]*gipmx/gsw);
                   2546:        }
                   2547:        fprintf(ficresilk," %10.6f\n", -llt);
                   2548:       }
                   2549:     } /* end of wave */
                   2550:   } /* end of individual */
                   2551:   for(k=1,l=0.; k<=nlstate; k++) l += ll[k];
                   2552:   /* printf("l1=%f l2=%f ",ll[1],ll[2]); */
                   2553:   l= l*ipmx/sw; /* To get the same order of magnitude as if weight=1 for every body */
                   2554:   if(globpr==0){ /* First time we count the contributions and weights */
                   2555:     gipmx=ipmx;
                   2556:     gsw=sw;
                   2557:   }
                   2558:   return -l;
                   2559: }
                   2560: 
                   2561: 
                   2562: /*************** function likelione ***********/
                   2563: void likelione(FILE *ficres,double p[], int npar, int nlstate, int *globpri, long *ipmx, double *sw, double *fretone, double (*funcone)(double []))
                   2564: {
                   2565:   /* This routine should help understanding what is done with 
                   2566:      the selection of individuals/waves and
                   2567:      to check the exact contribution to the likelihood.
                   2568:      Plotting could be done.
                   2569:    */
                   2570:   int k;
                   2571: 
                   2572:   if(*globpri !=0){ /* Just counts and sums, no printings */
1.201   ! brouard  2573:     strcpy(fileresilk,"ILK_"); 
1.126     brouard  2574:     strcat(fileresilk,fileres);
                   2575:     if((ficresilk=fopen(fileresilk,"w"))==NULL) {
                   2576:       printf("Problem with resultfile: %s\n", fileresilk);
                   2577:       fprintf(ficlog,"Problem with resultfile: %s\n", fileresilk);
                   2578:     }
                   2579:     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");
                   2580:     fprintf(ficresilk, "#num_i i s1 s2 mi mw dh likeli weight 2wlli out sav ");
                   2581:     /*         i,s1,s2,mi,mw[mi][i],dh[mi][i],exp(lli),weight[i],2*weight[i]*lli,out[s1][s2],savm[s1][s2]); */
                   2582:     for(k=1; k<=nlstate; k++) 
                   2583:       fprintf(ficresilk," -2*gipw/gsw*weight*ll[%d]++",k);
                   2584:     fprintf(ficresilk," -2*gipw/gsw*weight*ll(total)\n");
                   2585:   }
                   2586: 
                   2587:   *fretone=(*funcone)(p);
                   2588:   if(*globpri !=0){
                   2589:     fclose(ficresilk);
1.201   ! brouard  2590:     fprintf(fichtm,"\n<br>File of contributions to the likelihood (if mle=1): <a href=\"%s\">%s</a><br>\n",subdirf(fileresilk),subdirf(fileresilk));
1.126     brouard  2591:     fflush(fichtm); 
                   2592:   } 
                   2593:   return;
                   2594: }
                   2595: 
                   2596: 
                   2597: /*********** Maximum Likelihood Estimation ***************/
                   2598: 
                   2599: void mlikeli(FILE *ficres,double p[], int npar, int ncovmodel, int nlstate, double ftol, double (*func)(double []))
                   2600: {
1.165     brouard  2601:   int i,j, iter=0;
1.126     brouard  2602:   double **xi;
                   2603:   double fret;
                   2604:   double fretone; /* Only one call to likelihood */
                   2605:   /*  char filerespow[FILENAMELENGTH];*/
1.162     brouard  2606: 
                   2607: #ifdef NLOPT
                   2608:   int creturn;
                   2609:   nlopt_opt opt;
                   2610:   /* double lb[9] = { -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL }; /\* lower bounds *\/ */
                   2611:   double *lb;
                   2612:   double minf; /* the minimum objective value, upon return */
                   2613:   double * p1; /* Shifted parameters from 0 instead of 1 */
                   2614:   myfunc_data dinst, *d = &dinst;
                   2615: #endif
                   2616: 
                   2617: 
1.126     brouard  2618:   xi=matrix(1,npar,1,npar);
                   2619:   for (i=1;i<=npar;i++)
                   2620:     for (j=1;j<=npar;j++)
                   2621:       xi[i][j]=(i==j ? 1.0 : 0.0);
                   2622:   printf("Powell\n");  fprintf(ficlog,"Powell\n");
1.201   ! brouard  2623:   strcpy(filerespow,"POW_"); 
1.126     brouard  2624:   strcat(filerespow,fileres);
                   2625:   if((ficrespow=fopen(filerespow,"w"))==NULL) {
                   2626:     printf("Problem with resultfile: %s\n", filerespow);
                   2627:     fprintf(ficlog,"Problem with resultfile: %s\n", filerespow);
                   2628:   }
                   2629:   fprintf(ficrespow,"# Powell\n# iter -2*LL");
                   2630:   for (i=1;i<=nlstate;i++)
                   2631:     for(j=1;j<=nlstate+ndeath;j++)
                   2632:       if(j!=i)fprintf(ficrespow," p%1d%1d",i,j);
                   2633:   fprintf(ficrespow,"\n");
1.162     brouard  2634: #ifdef POWELL
1.126     brouard  2635:   powell(p,xi,npar,ftol,&iter,&fret,func);
1.162     brouard  2636: #endif
1.126     brouard  2637: 
1.162     brouard  2638: #ifdef NLOPT
                   2639: #ifdef NEWUOA
                   2640:   opt = nlopt_create(NLOPT_LN_NEWUOA,npar);
                   2641: #else
                   2642:   opt = nlopt_create(NLOPT_LN_BOBYQA,npar);
                   2643: #endif
                   2644:   lb=vector(0,npar-1);
                   2645:   for (i=0;i<npar;i++) lb[i]= -HUGE_VAL;
                   2646:   nlopt_set_lower_bounds(opt, lb);
                   2647:   nlopt_set_initial_step1(opt, 0.1);
                   2648:   
                   2649:   p1= (p+1); /*  p *(p+1)@8 and p *(p1)@8 are equal p1[0]=p[1] */
                   2650:   d->function = func;
                   2651:   printf(" Func %.12lf \n",myfunc(npar,p1,NULL,d));
                   2652:   nlopt_set_min_objective(opt, myfunc, d);
                   2653:   nlopt_set_xtol_rel(opt, ftol);
                   2654:   if ((creturn=nlopt_optimize(opt, p1, &minf)) < 0) {
                   2655:     printf("nlopt failed! %d\n",creturn); 
                   2656:   }
                   2657:   else {
                   2658:     printf("found minimum after %d evaluations (NLOPT=%d)\n", countcallfunc ,NLOPT);
                   2659:     printf("found minimum at f(%g,%g) = %0.10g\n", p[0], p[1], minf);
                   2660:     iter=1; /* not equal */
                   2661:   }
                   2662:   nlopt_destroy(opt);
                   2663: #endif
1.126     brouard  2664:   free_matrix(xi,1,npar,1,npar);
                   2665:   fclose(ficrespow);
1.180     brouard  2666:   printf("#Number of iterations & function calls = %d & %d, -2 Log likelihood = %.12f\n",iter, countcallfunc,func(p));
                   2667:   fprintf(ficlog,"#Number of iterations & function calls = %d & %d, -2 Log likelihood = %.12f\n",iter, countcallfunc,func(p));
                   2668:   fprintf(ficres,"#Number of iterations & function calls = %d & %d, -2 Log likelihood = %.12f\n",iter, countcallfunc,func(p));
1.126     brouard  2669: 
                   2670: }
                   2671: 
                   2672: /**** Computes Hessian and covariance matrix ***/
                   2673: void hesscov(double **matcov, double p[], int npar, double delti[], double ftolhess, double (*func)(double []))
                   2674: {
                   2675:   double  **a,**y,*x,pd;
                   2676:   double **hess;
1.164     brouard  2677:   int i, j;
1.126     brouard  2678:   int *indx;
                   2679: 
                   2680:   double hessii(double p[], double delta, int theta, double delti[],double (*func)(double []),int npar);
                   2681:   double hessij(double p[], double delti[], int i, int j,double (*func)(double []),int npar);
                   2682:   void lubksb(double **a, int npar, int *indx, double b[]) ;
                   2683:   void ludcmp(double **a, int npar, int *indx, double *d) ;
                   2684:   double gompertz(double p[]);
                   2685:   hess=matrix(1,npar,1,npar);
                   2686: 
                   2687:   printf("\nCalculation of the hessian matrix. Wait...\n");
                   2688:   fprintf(ficlog,"\nCalculation of the hessian matrix. Wait...\n");
                   2689:   for (i=1;i<=npar;i++){
                   2690:     printf("%d",i);fflush(stdout);
                   2691:     fprintf(ficlog,"%d",i);fflush(ficlog);
                   2692:    
                   2693:      hess[i][i]=hessii(p,ftolhess,i,delti,func,npar);
                   2694:     
                   2695:     /*  printf(" %f ",p[i]);
                   2696:        printf(" %lf %lf %lf",hess[i][i],ftolhess,delti[i]);*/
                   2697:   }
                   2698:   
                   2699:   for (i=1;i<=npar;i++) {
                   2700:     for (j=1;j<=npar;j++)  {
                   2701:       if (j>i) { 
                   2702:        printf(".%d%d",i,j);fflush(stdout);
                   2703:        fprintf(ficlog,".%d%d",i,j);fflush(ficlog);
                   2704:        hess[i][j]=hessij(p,delti,i,j,func,npar);
                   2705:        
                   2706:        hess[j][i]=hess[i][j];    
                   2707:        /*printf(" %lf ",hess[i][j]);*/
                   2708:       }
                   2709:     }
                   2710:   }
                   2711:   printf("\n");
                   2712:   fprintf(ficlog,"\n");
                   2713: 
                   2714:   printf("\nInverting the hessian to get the covariance matrix. Wait...\n");
                   2715:   fprintf(ficlog,"\nInverting the hessian to get the covariance matrix. Wait...\n");
                   2716:   
                   2717:   a=matrix(1,npar,1,npar);
                   2718:   y=matrix(1,npar,1,npar);
                   2719:   x=vector(1,npar);
                   2720:   indx=ivector(1,npar);
                   2721:   for (i=1;i<=npar;i++)
                   2722:     for (j=1;j<=npar;j++) a[i][j]=hess[i][j];
                   2723:   ludcmp(a,npar,indx,&pd);
                   2724: 
                   2725:   for (j=1;j<=npar;j++) {
                   2726:     for (i=1;i<=npar;i++) x[i]=0;
                   2727:     x[j]=1;
                   2728:     lubksb(a,npar,indx,x);
                   2729:     for (i=1;i<=npar;i++){ 
                   2730:       matcov[i][j]=x[i];
                   2731:     }
                   2732:   }
                   2733: 
                   2734:   printf("\n#Hessian matrix#\n");
                   2735:   fprintf(ficlog,"\n#Hessian matrix#\n");
                   2736:   for (i=1;i<=npar;i++) { 
                   2737:     for (j=1;j<=npar;j++) { 
                   2738:       printf("%.3e ",hess[i][j]);
                   2739:       fprintf(ficlog,"%.3e ",hess[i][j]);
                   2740:     }
                   2741:     printf("\n");
                   2742:     fprintf(ficlog,"\n");
                   2743:   }
                   2744: 
                   2745:   /* Recompute Inverse */
                   2746:   for (i=1;i<=npar;i++)
                   2747:     for (j=1;j<=npar;j++) a[i][j]=matcov[i][j];
                   2748:   ludcmp(a,npar,indx,&pd);
                   2749: 
                   2750:   /*  printf("\n#Hessian matrix recomputed#\n");
                   2751: 
                   2752:   for (j=1;j<=npar;j++) {
                   2753:     for (i=1;i<=npar;i++) x[i]=0;
                   2754:     x[j]=1;
                   2755:     lubksb(a,npar,indx,x);
                   2756:     for (i=1;i<=npar;i++){ 
                   2757:       y[i][j]=x[i];
                   2758:       printf("%.3e ",y[i][j]);
                   2759:       fprintf(ficlog,"%.3e ",y[i][j]);
                   2760:     }
                   2761:     printf("\n");
                   2762:     fprintf(ficlog,"\n");
                   2763:   }
                   2764:   */
                   2765: 
                   2766:   free_matrix(a,1,npar,1,npar);
                   2767:   free_matrix(y,1,npar,1,npar);
                   2768:   free_vector(x,1,npar);
                   2769:   free_ivector(indx,1,npar);
                   2770:   free_matrix(hess,1,npar,1,npar);
                   2771: 
                   2772: 
                   2773: }
                   2774: 
                   2775: /*************** hessian matrix ****************/
                   2776: double hessii(double x[], double delta, int theta, double delti[], double (*func)(double []), int npar)
                   2777: {
                   2778:   int i;
                   2779:   int l=1, lmax=20;
                   2780:   double k1,k2;
1.132     brouard  2781:   double p2[MAXPARM+1]; /* identical to x */
1.126     brouard  2782:   double res;
                   2783:   double delt=0.0001, delts, nkhi=10.,nkhif=1., khi=1.e-4;
                   2784:   double fx;
                   2785:   int k=0,kmax=10;
                   2786:   double l1;
                   2787: 
                   2788:   fx=func(x);
                   2789:   for (i=1;i<=npar;i++) p2[i]=x[i];
1.145     brouard  2790:   for(l=0 ; l <=lmax; l++){  /* Enlarging the zone around the Maximum */
1.126     brouard  2791:     l1=pow(10,l);
                   2792:     delts=delt;
                   2793:     for(k=1 ; k <kmax; k=k+1){
                   2794:       delt = delta*(l1*k);
                   2795:       p2[theta]=x[theta] +delt;
1.145     brouard  2796:       k1=func(p2)-fx;   /* Might be negative if too close to the theoretical maximum */
1.126     brouard  2797:       p2[theta]=x[theta]-delt;
                   2798:       k2=func(p2)-fx;
                   2799:       /*res= (k1-2.0*fx+k2)/delt/delt; */
                   2800:       res= (k1+k2)/delt/delt/2.; /* Divided by because L and not 2*L */
                   2801:       
1.132     brouard  2802: #ifdef DEBUGHESS
1.126     brouard  2803:       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);
                   2804:       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);
                   2805: #endif
                   2806:       /*if(fabs(k1-2.0*fx+k2) <1.e-13){ */
                   2807:       if((k1 <khi/nkhi/2.) || (k2 <khi/nkhi/2.)){
                   2808:        k=kmax;
                   2809:       }
                   2810:       else if((k1 >khi/nkhif) || (k2 >khi/nkhif)){ /* Keeps lastvalue before 3.84/2 KHI2 5% 1d.f. */
1.164     brouard  2811:        k=kmax; l=lmax*10;
1.126     brouard  2812:       }
                   2813:       else if((k1 >khi/nkhi) || (k2 >khi/nkhi)){ 
                   2814:        delts=delt;
                   2815:       }
                   2816:     }
                   2817:   }
                   2818:   delti[theta]=delts;
                   2819:   return res; 
                   2820:   
                   2821: }
                   2822: 
                   2823: double hessij( double x[], double delti[], int thetai,int thetaj,double (*func)(double []),int npar)
                   2824: {
                   2825:   int i;
1.164     brouard  2826:   int l=1, lmax=20;
1.126     brouard  2827:   double k1,k2,k3,k4,res,fx;
1.132     brouard  2828:   double p2[MAXPARM+1];
1.126     brouard  2829:   int k;
                   2830: 
                   2831:   fx=func(x);
                   2832:   for (k=1; k<=2; k++) {
                   2833:     for (i=1;i<=npar;i++) p2[i]=x[i];
                   2834:     p2[thetai]=x[thetai]+delti[thetai]/k;
                   2835:     p2[thetaj]=x[thetaj]+delti[thetaj]/k;
                   2836:     k1=func(p2)-fx;
                   2837:   
                   2838:     p2[thetai]=x[thetai]+delti[thetai]/k;
                   2839:     p2[thetaj]=x[thetaj]-delti[thetaj]/k;
                   2840:     k2=func(p2)-fx;
                   2841:   
                   2842:     p2[thetai]=x[thetai]-delti[thetai]/k;
                   2843:     p2[thetaj]=x[thetaj]+delti[thetaj]/k;
                   2844:     k3=func(p2)-fx;
                   2845:   
                   2846:     p2[thetai]=x[thetai]-delti[thetai]/k;
                   2847:     p2[thetaj]=x[thetaj]-delti[thetaj]/k;
                   2848:     k4=func(p2)-fx;
                   2849:     res=(k1-k2-k3+k4)/4.0/delti[thetai]*k/delti[thetaj]*k/2.; /* Because of L not 2*L */
                   2850: #ifdef DEBUG
                   2851:     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);
                   2852:     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);
                   2853: #endif
                   2854:   }
                   2855:   return res;
                   2856: }
                   2857: 
                   2858: /************** Inverse of matrix **************/
                   2859: void ludcmp(double **a, int n, int *indx, double *d) 
                   2860: { 
                   2861:   int i,imax,j,k; 
                   2862:   double big,dum,sum,temp; 
                   2863:   double *vv; 
                   2864:  
                   2865:   vv=vector(1,n); 
                   2866:   *d=1.0; 
                   2867:   for (i=1;i<=n;i++) { 
                   2868:     big=0.0; 
                   2869:     for (j=1;j<=n;j++) 
                   2870:       if ((temp=fabs(a[i][j])) > big) big=temp; 
                   2871:     if (big == 0.0) nrerror("Singular matrix in routine ludcmp"); 
                   2872:     vv[i]=1.0/big; 
                   2873:   } 
                   2874:   for (j=1;j<=n;j++) { 
                   2875:     for (i=1;i<j;i++) { 
                   2876:       sum=a[i][j]; 
                   2877:       for (k=1;k<i;k++) sum -= a[i][k]*a[k][j]; 
                   2878:       a[i][j]=sum; 
                   2879:     } 
                   2880:     big=0.0; 
                   2881:     for (i=j;i<=n;i++) { 
                   2882:       sum=a[i][j]; 
                   2883:       for (k=1;k<j;k++) 
                   2884:        sum -= a[i][k]*a[k][j]; 
                   2885:       a[i][j]=sum; 
                   2886:       if ( (dum=vv[i]*fabs(sum)) >= big) { 
                   2887:        big=dum; 
                   2888:        imax=i; 
                   2889:       } 
                   2890:     } 
                   2891:     if (j != imax) { 
                   2892:       for (k=1;k<=n;k++) { 
                   2893:        dum=a[imax][k]; 
                   2894:        a[imax][k]=a[j][k]; 
                   2895:        a[j][k]=dum; 
                   2896:       } 
                   2897:       *d = -(*d); 
                   2898:       vv[imax]=vv[j]; 
                   2899:     } 
                   2900:     indx[j]=imax; 
                   2901:     if (a[j][j] == 0.0) a[j][j]=TINY; 
                   2902:     if (j != n) { 
                   2903:       dum=1.0/(a[j][j]); 
                   2904:       for (i=j+1;i<=n;i++) a[i][j] *= dum; 
                   2905:     } 
                   2906:   } 
                   2907:   free_vector(vv,1,n);  /* Doesn't work */
                   2908: ;
                   2909: } 
                   2910: 
                   2911: void lubksb(double **a, int n, int *indx, double b[]) 
                   2912: { 
                   2913:   int i,ii=0,ip,j; 
                   2914:   double sum; 
                   2915:  
                   2916:   for (i=1;i<=n;i++) { 
                   2917:     ip=indx[i]; 
                   2918:     sum=b[ip]; 
                   2919:     b[ip]=b[i]; 
                   2920:     if (ii) 
                   2921:       for (j=ii;j<=i-1;j++) sum -= a[i][j]*b[j]; 
                   2922:     else if (sum) ii=i; 
                   2923:     b[i]=sum; 
                   2924:   } 
                   2925:   for (i=n;i>=1;i--) { 
                   2926:     sum=b[i]; 
                   2927:     for (j=i+1;j<=n;j++) sum -= a[i][j]*b[j]; 
                   2928:     b[i]=sum/a[i][i]; 
                   2929:   } 
                   2930: } 
                   2931: 
                   2932: void pstamp(FILE *fichier)
                   2933: {
1.196     brouard  2934:   fprintf(fichier,"# %s.%s\n#IMaCh version %s, %s\n#%s\n# %s", optionfilefiname,optionfilext,version,copyright, fullversion, strstart);
1.126     brouard  2935: }
                   2936: 
                   2937: /************ Frequencies ********************/
                   2938: 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[])
                   2939: {  /* Some frequencies */
                   2940:   
1.164     brouard  2941:   int i, m, jk, j1, bool, z1,j;
1.126     brouard  2942:   int first;
                   2943:   double ***freq; /* Frequencies */
                   2944:   double *pp, **prop;
                   2945:   double pos,posprop, k2, dateintsum=0,k2cpt=0;
                   2946:   char fileresp[FILENAMELENGTH];
                   2947:   
                   2948:   pp=vector(1,nlstate);
                   2949:   prop=matrix(1,nlstate,iagemin,iagemax+3);
1.201   ! brouard  2950:   strcpy(fileresp,"P_");
        !          2951:   strcat(fileresp,fileresu);
1.126     brouard  2952:   if((ficresp=fopen(fileresp,"w"))==NULL) {
                   2953:     printf("Problem with prevalence resultfile: %s\n", fileresp);
                   2954:     fprintf(ficlog,"Problem with prevalence resultfile: %s\n", fileresp);
                   2955:     exit(0);
                   2956:   }
                   2957:   freq= ma3x(-5,nlstate+ndeath,-5,nlstate+ndeath,iagemin,iagemax+3);
                   2958:   j1=0;
                   2959:   
                   2960:   j=cptcoveff;
                   2961:   if (cptcovn<1) {j=1;ncodemax[1]=1;}
                   2962: 
                   2963:   first=1;
                   2964: 
1.169     brouard  2965:   /* for(k1=1; k1<=j ; k1++){ */  /* Loop on covariates */
                   2966:   /*  for(i1=1; i1<=ncodemax[k1];i1++){ */ /* Now it is 2 */
                   2967:   /*    j1++; */
1.145     brouard  2968:   for (j1 = 1; j1 <= (int) pow(2,cptcoveff); j1++){
1.126     brouard  2969:       /*printf("cptcoveff=%d Tvaraff=%d", cptcoveff,Tvaraff[1]);
                   2970:        scanf("%d", i);*/
                   2971:       for (i=-5; i<=nlstate+ndeath; i++)  
                   2972:        for (jk=-5; jk<=nlstate+ndeath; jk++)  
                   2973:          for(m=iagemin; m <= iagemax+3; m++)
                   2974:            freq[i][jk][m]=0;
1.143     brouard  2975:       
                   2976:       for (i=1; i<=nlstate; i++)  
                   2977:        for(m=iagemin; m <= iagemax+3; m++)
                   2978:          prop[i][m]=0;
1.126     brouard  2979:       
                   2980:       dateintsum=0;
                   2981:       k2cpt=0;
                   2982:       for (i=1; i<=imx; i++) {
                   2983:        bool=1;
1.144     brouard  2984:        if  (cptcovn>0) { /* Filter is here: Must be looked at for model=V1+V2+V3+V4 */
                   2985:          for (z1=1; z1<=cptcoveff; z1++)       
1.198     brouard  2986:             if (covar[Tvaraff[z1]][i]!= nbcode[Tvaraff[z1]][codtabm(j1,z1)]){
1.145     brouard  2987:                 /* Tests if the value of each of the covariates of i is equal to filter j1 */
1.144     brouard  2988:               bool=0;
1.198     brouard  2989:               /* printf("bool=%d i=%d, z1=%d, Tvaraff[%d]=%d, covar[Tvarff][%d]=%2f, codtabm(%d,%d)=%d, nbcode[Tvaraff][codtabm(%d,%d)=%d, j1=%d\n", 
                   2990:                 bool,i,z1, z1, Tvaraff[z1],i,covar[Tvaraff[z1]][i],j1,z1,codtabm(j1,z1),
                   2991:                 j1,z1,nbcode[Tvaraff[z1]][codtabm(j1,z1)],j1);*/
                   2992:               /* For j1=7 in V1+V2+V3+V4 = 0 1 1 0 and codtabm(7,3)=1 and nbcde[3][?]=1*/
1.144     brouard  2993:             } 
1.126     brouard  2994:        }
1.144     brouard  2995:  
1.126     brouard  2996:        if (bool==1){
                   2997:          for(m=firstpass; m<=lastpass; m++){
                   2998:            k2=anint[m][i]+(mint[m][i]/12.);
                   2999:            /*if ((k2>=dateprev1) && (k2<=dateprev2)) {*/
                   3000:              if(agev[m][i]==0) agev[m][i]=iagemax+1;
                   3001:              if(agev[m][i]==1) agev[m][i]=iagemax+2;
                   3002:              if (s[m][i]>0 && s[m][i]<=nlstate) prop[s[m][i]][(int)agev[m][i]] += weight[i];
                   3003:              if (m<lastpass) {
                   3004:                freq[s[m][i]][s[m+1][i]][(int)agev[m][i]] += weight[i];
                   3005:                freq[s[m][i]][s[m+1][i]][iagemax+3] += weight[i];
                   3006:              }
                   3007:              
                   3008:              if ((agev[m][i]>1) && (agev[m][i]< (iagemax+3))) {
                   3009:                dateintsum=dateintsum+k2;
                   3010:                k2cpt++;
                   3011:              }
                   3012:              /*}*/
                   3013:          }
                   3014:        }
1.145     brouard  3015:       } /* end i */
1.126     brouard  3016:        
                   3017:       /*      fprintf(ficresp, "#Count between %.lf/%.lf/%.lf and %.lf/%.lf/%.lf\n",jprev1, mprev1,anprev1,jprev2, mprev2,anprev2);*/
                   3018:       pstamp(ficresp);
                   3019:       if  (cptcovn>0) {
                   3020:        fprintf(ficresp, "\n#********** Variable "); 
1.198     brouard  3021:        for (z1=1; z1<=cptcoveff; z1++) fprintf(ficresp, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
1.126     brouard  3022:        fprintf(ficresp, "**********\n#");
1.143     brouard  3023:        fprintf(ficlog, "\n#********** Variable "); 
1.198     brouard  3024:        for (z1=1; z1<=cptcoveff; z1++) fprintf(ficlog, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
1.143     brouard  3025:        fprintf(ficlog, "**********\n#");
1.126     brouard  3026:       }
                   3027:       for(i=1; i<=nlstate;i++) 
                   3028:        fprintf(ficresp, " Age Prev(%d) N(%d) N",i,i);
                   3029:       fprintf(ficresp, "\n");
                   3030:       
                   3031:       for(i=iagemin; i <= iagemax+3; i++){
                   3032:        if(i==iagemax+3){
                   3033:          fprintf(ficlog,"Total");
                   3034:        }else{
                   3035:          if(first==1){
                   3036:            first=0;
                   3037:            printf("See log file for details...\n");
                   3038:          }
                   3039:          fprintf(ficlog,"Age %d", i);
                   3040:        }
                   3041:        for(jk=1; jk <=nlstate ; jk++){
                   3042:          for(m=-1, pp[jk]=0; m <=nlstate+ndeath ; m++)
                   3043:            pp[jk] += freq[jk][m][i]; 
                   3044:        }
                   3045:        for(jk=1; jk <=nlstate ; jk++){
                   3046:          for(m=-1, pos=0; m <=0 ; m++)
                   3047:            pos += freq[jk][m][i];
                   3048:          if(pp[jk]>=1.e-10){
                   3049:            if(first==1){
1.132     brouard  3050:              printf(" %d.=%.0f loss[%d]=%.1f%%",jk,pp[jk],jk,100*pos/pp[jk]);
1.126     brouard  3051:            }
                   3052:            fprintf(ficlog," %d.=%.0f loss[%d]=%.1f%%",jk,pp[jk],jk,100*pos/pp[jk]);
                   3053:          }else{
                   3054:            if(first==1)
                   3055:              printf(" %d.=%.0f loss[%d]=NaNQ%%",jk,pp[jk],jk);
                   3056:            fprintf(ficlog," %d.=%.0f loss[%d]=NaNQ%%",jk,pp[jk],jk);
                   3057:          }
                   3058:        }
                   3059: 
                   3060:        for(jk=1; jk <=nlstate ; jk++){
                   3061:          for(m=0, pp[jk]=0; m <=nlstate+ndeath; m++)
                   3062:            pp[jk] += freq[jk][m][i];
                   3063:        }       
                   3064:        for(jk=1,pos=0,posprop=0; jk <=nlstate ; jk++){
                   3065:          pos += pp[jk];
                   3066:          posprop += prop[jk][i];
                   3067:        }
                   3068:        for(jk=1; jk <=nlstate ; jk++){
                   3069:          if(pos>=1.e-5){
                   3070:            if(first==1)
                   3071:              printf(" %d.=%.0f prev[%d]=%.1f%%",jk,pp[jk],jk,100*pp[jk]/pos);
                   3072:            fprintf(ficlog," %d.=%.0f prev[%d]=%.1f%%",jk,pp[jk],jk,100*pp[jk]/pos);
                   3073:          }else{
                   3074:            if(first==1)
                   3075:              printf(" %d.=%.0f prev[%d]=NaNQ%%",jk,pp[jk],jk);
                   3076:            fprintf(ficlog," %d.=%.0f prev[%d]=NaNQ%%",jk,pp[jk],jk);
                   3077:          }
                   3078:          if( i <= iagemax){
                   3079:            if(pos>=1.e-5){
                   3080:              fprintf(ficresp," %d %.5f %.0f %.0f",i,prop[jk][i]/posprop, prop[jk][i],posprop);
                   3081:              /*probs[i][jk][j1]= pp[jk]/pos;*/
                   3082:              /*printf("\ni=%d jk=%d j1=%d %.5f %.0f %.0f %f",i,jk,j1,pp[jk]/pos, pp[jk],pos,probs[i][jk][j1]);*/
                   3083:            }
                   3084:            else
                   3085:              fprintf(ficresp," %d NaNq %.0f %.0f",i,prop[jk][i],posprop);
                   3086:          }
                   3087:        }
                   3088:        
                   3089:        for(jk=-1; jk <=nlstate+ndeath; jk++)
                   3090:          for(m=-1; m <=nlstate+ndeath; m++)
                   3091:            if(freq[jk][m][i] !=0 ) {
                   3092:            if(first==1)
                   3093:              printf(" %d%d=%.0f",jk,m,freq[jk][m][i]);
                   3094:              fprintf(ficlog," %d%d=%.0f",jk,m,freq[jk][m][i]);
                   3095:            }
                   3096:        if(i <= iagemax)
                   3097:          fprintf(ficresp,"\n");
                   3098:        if(first==1)
                   3099:          printf("Others in log...\n");
                   3100:        fprintf(ficlog,"\n");
                   3101:       }
1.145     brouard  3102:       /*}*/
1.126     brouard  3103:   }
                   3104:   dateintmean=dateintsum/k2cpt; 
                   3105:  
                   3106:   fclose(ficresp);
                   3107:   free_ma3x(freq,-5,nlstate+ndeath,-5,nlstate+ndeath, iagemin, iagemax+3);
                   3108:   free_vector(pp,1,nlstate);
                   3109:   free_matrix(prop,1,nlstate,iagemin, iagemax+3);
                   3110:   /* End of Freq */
                   3111: }
                   3112: 
                   3113: /************ Prevalence ********************/
                   3114: 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)
                   3115: {  
                   3116:   /* Compute observed prevalence between dateprev1 and dateprev2 by counting the number of people
                   3117:      in each health status at the date of interview (if between dateprev1 and dateprev2).
                   3118:      We still use firstpass and lastpass as another selection.
                   3119:   */
                   3120:  
1.164     brouard  3121:   int i, m, jk, j1, bool, z1,j;
                   3122: 
                   3123:   double **prop;
                   3124:   double posprop; 
1.126     brouard  3125:   double  y2; /* in fractional years */
                   3126:   int iagemin, iagemax;
1.145     brouard  3127:   int first; /** to stop verbosity which is redirected to log file */
1.126     brouard  3128: 
                   3129:   iagemin= (int) agemin;
                   3130:   iagemax= (int) agemax;
                   3131:   /*pp=vector(1,nlstate);*/
                   3132:   prop=matrix(1,nlstate,iagemin,iagemax+3); 
                   3133:   /*  freq=ma3x(-1,nlstate+ndeath,-1,nlstate+ndeath,iagemin,iagemax+3);*/
                   3134:   j1=0;
                   3135:   
1.145     brouard  3136:   /*j=cptcoveff;*/
1.126     brouard  3137:   if (cptcovn<1) {j=1;ncodemax[1]=1;}
                   3138:   
1.145     brouard  3139:   first=1;
                   3140:   for(j1=1; j1<= (int) pow(2,cptcoveff);j1++){
                   3141:     /*for(i1=1; i1<=ncodemax[k1];i1++){
                   3142:       j1++;*/
1.126     brouard  3143:       
                   3144:       for (i=1; i<=nlstate; i++)  
                   3145:        for(m=iagemin; m <= iagemax+3; m++)
                   3146:          prop[i][m]=0.0;
                   3147:      
                   3148:       for (i=1; i<=imx; i++) { /* Each individual */
                   3149:        bool=1;
                   3150:        if  (cptcovn>0) {
                   3151:          for (z1=1; z1<=cptcoveff; z1++) 
1.198     brouard  3152:            if (covar[Tvaraff[z1]][i]!= nbcode[Tvaraff[z1]][codtabm(j1,z1)]) 
1.126     brouard  3153:              bool=0;
                   3154:        } 
                   3155:        if (bool==1) { 
                   3156:          for(m=firstpass; m<=lastpass; m++){/* Other selection (we can limit to certain interviews*/
                   3157:            y2=anint[m][i]+(mint[m][i]/12.); /* Fractional date in year */
                   3158:            if ((y2>=dateprev1) && (y2<=dateprev2)) { /* Here is the main selection (fractional years) */
                   3159:              if(agev[m][i]==0) agev[m][i]=iagemax+1;
                   3160:              if(agev[m][i]==1) agev[m][i]=iagemax+2;
                   3161:              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); 
                   3162:              if (s[m][i]>0 && s[m][i]<=nlstate) { 
                   3163:                /*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]]);*/
                   3164:                prop[s[m][i]][(int)agev[m][i]] += weight[i];
                   3165:                prop[s[m][i]][iagemax+3] += weight[i]; 
                   3166:              } 
                   3167:            }
                   3168:          } /* end selection of waves */
                   3169:        }
                   3170:       }
                   3171:       for(i=iagemin; i <= iagemax+3; i++){  
                   3172:        for(jk=1,posprop=0; jk <=nlstate ; jk++) { 
                   3173:          posprop += prop[jk][i]; 
                   3174:        } 
1.145     brouard  3175:        
1.126     brouard  3176:        for(jk=1; jk <=nlstate ; jk++){     
                   3177:          if( i <=  iagemax){ 
                   3178:            if(posprop>=1.e-5){ 
                   3179:              probs[i][jk][j1]= prop[jk][i]/posprop;
1.145     brouard  3180:            } else{
                   3181:              if(first==1){
                   3182:                first=0;
                   3183:                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]);
                   3184:              }
                   3185:            }
1.126     brouard  3186:          } 
                   3187:        }/* end jk */ 
                   3188:       }/* end i */ 
1.145     brouard  3189:     /*} *//* end i1 */
                   3190:   } /* end j1 */
1.126     brouard  3191:   
                   3192:   /*  free_ma3x(freq,-1,nlstate+ndeath,-1,nlstate+ndeath, iagemin, iagemax+3);*/
                   3193:   /*free_vector(pp,1,nlstate);*/
                   3194:   free_matrix(prop,1,nlstate, iagemin,iagemax+3);
                   3195: }  /* End of prevalence */
                   3196: 
                   3197: /************* Waves Concatenation ***************/
                   3198: 
                   3199: 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)
                   3200: {
                   3201:   /* Concatenates waves: wav[i] is the number of effective (useful waves) of individual i.
                   3202:      Death is a valid wave (if date is known).
                   3203:      mw[mi][i] is the mi (mi=1 to wav[i])  effective wave of individual i
                   3204:      dh[m][i] or dh[mw[mi][i]][i] is the delay between two effective waves m=mw[mi][i]
                   3205:      and mw[mi+1][i]. dh depends on stepm.
                   3206:      */
                   3207: 
                   3208:   int i, mi, m;
                   3209:   /* int j, k=0,jk, ju, jl,jmin=1e+5, jmax=-1;
                   3210:      double sum=0., jmean=0.;*/
                   3211:   int first;
                   3212:   int j, k=0,jk, ju, jl;
                   3213:   double sum=0.;
                   3214:   first=0;
1.164     brouard  3215:   jmin=100000;
1.126     brouard  3216:   jmax=-1;
                   3217:   jmean=0.;
                   3218:   for(i=1; i<=imx; i++){
                   3219:     mi=0;
                   3220:     m=firstpass;
                   3221:     while(s[m][i] <= nlstate){
                   3222:       if(s[m][i]>=1 || s[m][i]==-2 || s[m][i]==-4 || s[m][i]==-5)
                   3223:        mw[++mi][i]=m;
                   3224:       if(m >=lastpass)
                   3225:        break;
                   3226:       else
                   3227:        m++;
                   3228:     }/* end while */
                   3229:     if (s[m][i] > nlstate){
                   3230:       mi++;    /* Death is another wave */
                   3231:       /* if(mi==0)  never been interviewed correctly before death */
                   3232:         /* Only death is a correct wave */
                   3233:       mw[mi][i]=m;
                   3234:     }
                   3235: 
                   3236:     wav[i]=mi;
                   3237:     if(mi==0){
                   3238:       nbwarn++;
                   3239:       if(first==0){
                   3240:        printf("Warning! No valid information for individual %ld line=%d (skipped) and may be others, see log file\n",num[i],i);
                   3241:        first=1;
                   3242:       }
                   3243:       if(first==1){
                   3244:        fprintf(ficlog,"Warning! No valid information for individual %ld line=%d (skipped)\n",num[i],i);
                   3245:       }
                   3246:     } /* end mi==0 */
                   3247:   } /* End individuals */
                   3248: 
                   3249:   for(i=1; i<=imx; i++){
                   3250:     for(mi=1; mi<wav[i];mi++){
                   3251:       if (stepm <=0)
                   3252:        dh[mi][i]=1;
                   3253:       else{
                   3254:        if (s[mw[mi+1][i]][i] > nlstate) { /* A death */
                   3255:          if (agedc[i] < 2*AGESUP) {
                   3256:            j= rint(agedc[i]*12-agev[mw[mi][i]][i]*12); 
                   3257:            if(j==0) j=1;  /* Survives at least one month after exam */
                   3258:            else if(j<0){
                   3259:              nberr++;
                   3260:              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]);
                   3261:              j=1; /* Temporary Dangerous patch */
                   3262:              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);
                   3263:              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]);
                   3264:              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);
                   3265:            }
                   3266:            k=k+1;
                   3267:            if (j >= jmax){
                   3268:              jmax=j;
                   3269:              ijmax=i;
                   3270:            }
                   3271:            if (j <= jmin){
                   3272:              jmin=j;
                   3273:              ijmin=i;
                   3274:            }
                   3275:            sum=sum+j;
                   3276:            /*if (j<0) printf("j=%d num=%d \n",j,i);*/
                   3277:            /*    printf("%d %d %d %d\n", s[mw[mi][i]][i] ,s[mw[mi+1][i]][i],j,i);*/
                   3278:          }
                   3279:        }
                   3280:        else{
                   3281:          j= rint( (agev[mw[mi+1][i]][i]*12 - agev[mw[mi][i]][i]*12));
                   3282: /*       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]); */
                   3283: 
                   3284:          k=k+1;
                   3285:          if (j >= jmax) {
                   3286:            jmax=j;
                   3287:            ijmax=i;
                   3288:          }
                   3289:          else if (j <= jmin){
                   3290:            jmin=j;
                   3291:            ijmin=i;
                   3292:          }
                   3293:          /*        if (j<10) printf("j=%d jmin=%d num=%d ",j,jmin,i); */
                   3294:          /*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]);*/
                   3295:          if(j<0){
                   3296:            nberr++;
                   3297:            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]);
                   3298:            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]);
                   3299:          }
                   3300:          sum=sum+j;
                   3301:        }
                   3302:        jk= j/stepm;
                   3303:        jl= j -jk*stepm;
                   3304:        ju= j -(jk+1)*stepm;
                   3305:        if(mle <=1){ /* only if we use a the linear-interpoloation pseudo-likelihood */
                   3306:          if(jl==0){
                   3307:            dh[mi][i]=jk;
                   3308:            bh[mi][i]=0;
                   3309:          }else{ /* We want a negative bias in order to only have interpolation ie
1.136     brouard  3310:                  * to avoid the price of an extra matrix product in likelihood */
1.126     brouard  3311:            dh[mi][i]=jk+1;
                   3312:            bh[mi][i]=ju;
                   3313:          }
                   3314:        }else{
                   3315:          if(jl <= -ju){
                   3316:            dh[mi][i]=jk;
                   3317:            bh[mi][i]=jl;       /* bias is positive if real duration
                   3318:                                 * is higher than the multiple of stepm and negative otherwise.
                   3319:                                 */
                   3320:          }
                   3321:          else{
                   3322:            dh[mi][i]=jk+1;
                   3323:            bh[mi][i]=ju;
                   3324:          }
                   3325:          if(dh[mi][i]==0){
                   3326:            dh[mi][i]=1; /* At least one step */
                   3327:            bh[mi][i]=ju; /* At least one step */
                   3328:            /*  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);*/
                   3329:          }
                   3330:        } /* end if mle */
                   3331:       }
                   3332:     } /* end wave */
                   3333:   }
                   3334:   jmean=sum/k;
                   3335:   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  3336:   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  3337:  }
                   3338: 
                   3339: /*********** Tricode ****************************/
1.145     brouard  3340: void tricode(int *Tvar, int **nbcode, int imx, int *Ndum)
1.126     brouard  3341: {
1.144     brouard  3342:   /**< Uses cptcovn+2*cptcovprod as the number of covariates */
                   3343:   /*     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  3344:    * Boring subroutine which should only output nbcode[Tvar[j]][k]
1.145     brouard  3345:    * Tvar[5] in V2+V1+V3*age+V2*V4 is 2 (V2)
1.169     brouard  3346:    * nbcode[Tvar[j]][1]= 
1.144     brouard  3347:   */
1.130     brouard  3348: 
1.145     brouard  3349:   int ij=1, k=0, j=0, i=0, maxncov=NCOVMAX;
1.136     brouard  3350:   int modmaxcovj=0; /* Modality max of covariates j */
1.145     brouard  3351:   int cptcode=0; /* Modality max of covariates j */
                   3352:   int modmincovj=0; /* Modality min of covariates j */
                   3353: 
                   3354: 
1.126     brouard  3355:   cptcoveff=0; 
                   3356:  
1.144     brouard  3357:   for (k=1; k <= maxncov; k++) ncodemax[k]=0; /* Horrible constant again replaced by NCOVMAX */
1.126     brouard  3358: 
1.145     brouard  3359:   /* Loop on covariates without age and products */
1.186     brouard  3360:   for (j=1; j<=(cptcovs); j++) { /* From model V1 + V2*age+ V3 + V3*V4 keeps V1 + V3 = 2 only */
1.192     brouard  3361:     for (k=-1; k < maxncov; k++) Ndum[k]=0;
1.186     brouard  3362:     for (i=1; i<=imx; i++) { /* Loop on individuals: reads the data file to get the maximum value of the 
1.136     brouard  3363:                               modality of this covariate Vj*/ 
1.145     brouard  3364:       ij=(int)(covar[Tvar[j]][i]); /* ij=0 or 1 or -1. Value of the covariate Tvar[j] for individual i
                   3365:                                    * If product of Vn*Vm, still boolean *:
                   3366:                                    * If it was coded 1, 2, 3, 4 should be splitted into 3 boolean variables
                   3367:                                    * 1 => 0 0 0, 2 => 0 0 1, 3 => 0 1 1, 4=1 0 0   */
                   3368:       /* Finds for covariate j, n=Tvar[j] of Vn . ij is the
1.136     brouard  3369:                                      modality of the nth covariate of individual i. */
1.145     brouard  3370:       if (ij > modmaxcovj)
                   3371:         modmaxcovj=ij; 
                   3372:       else if (ij < modmincovj) 
                   3373:        modmincovj=ij; 
                   3374:       if ((ij < -1) && (ij > NCOVMAX)){
                   3375:        printf( "Error: minimal is less than -1 or maximal is bigger than %d. Exiting. \n", NCOVMAX );
                   3376:        exit(1);
                   3377:       }else
1.136     brouard  3378:       Ndum[ij]++; /*counts and stores the occurence of this modality 0, 1, -1*/
1.145     brouard  3379:       /*  If coded 1, 2, 3 , counts the number of 1 Ndum[1], number of 2, Ndum[2], etc */
1.126     brouard  3380:       /*printf("i=%d ij=%d Ndum[ij]=%d imx=%d",i,ij,Ndum[ij],imx);*/
1.136     brouard  3381:       /* getting the maximum value of the modality of the covariate
                   3382:         (should be 0 or 1 now) Tvar[j]. If V=sex and male is coded 0 and
                   3383:         female is 1, then modmaxcovj=1.*/
1.192     brouard  3384:     } /* end for loop on individuals i */
1.145     brouard  3385:     printf(" Minimal and maximal values of %d th covariate V%d: min=%d max=%d \n", j, Tvar[j], modmincovj, modmaxcovj);
1.192     brouard  3386:     fprintf(ficlog," Minimal and maximal values of %d th covariate V%d: min=%d max=%d \n", j, Tvar[j], modmincovj, modmaxcovj);
1.145     brouard  3387:     cptcode=modmaxcovj;
1.137     brouard  3388:     /* Ndum[0] = frequency of 0 for model-covariate j, Ndum[1] frequency of 1 etc. */
1.145     brouard  3389:    /*for (i=0; i<=cptcode; i++) {*/
1.192     brouard  3390:     for (k=modmincovj;  k<=modmaxcovj; k++) { /* k=-1 ? 0 and 1*//* For each value k of the modality of model-cov j */
                   3391:       printf("Frequencies of covariates %d ie V%d with value %d: %d\n", j, Tvar[j], k, Ndum[k]);
                   3392:       fprintf(ficlog, "Frequencies of covariates %d ie V%d with value %d: %d\n", j, Tvar[j], k, Ndum[k]);
                   3393:       if( Ndum[k] != 0 ){ /* Counts if nobody answered modality k ie empty modality, we skip it and reorder */
                   3394:        if( k != -1){
                   3395:          ncodemax[j]++;  /* ncodemax[j]= Number of modalities of the j th
                   3396:                             covariate for which somebody answered excluding 
                   3397:                             undefined. Usually 2: 0 and 1. */
                   3398:        }
                   3399:        ncodemaxwundef[j]++; /* ncodemax[j]= Number of modalities of the j th
                   3400:                             covariate for which somebody answered including 
                   3401:                             undefined. Usually 3: -1, 0 and 1. */
1.145     brouard  3402:       }
                   3403:       /* In fact  ncodemax[j]=2 (dichotom. variables only) but it could be more for
                   3404:         historical reasons: 3 if coded 1, 2, 3 and 4 and Ndum[2]=0 */
1.131     brouard  3405:     } /* Ndum[-1] number of undefined modalities */
1.126     brouard  3406: 
1.136     brouard  3407:     /* j is a covariate, n=Tvar[j] of Vn; Fills nbcode */
1.186     brouard  3408:     /* For covariate j, modalities could be 1, 2, 3, 4, 5, 6, 7. 
                   3409:        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  3410:        modmincovj=3; modmaxcovj = 7;
1.186     brouard  3411:        There are only 3 modalities non empty 3, 6, 7 (or 2 if 27 is too few) : ncodemax[j]=3;
                   3412:        which will be coded 0, 1, 2 which in binary on 2=3-1 digits are 0=00 1=01, 2=10;
                   3413:        defining two dummy variables: variables V1_1 and V1_2.
1.145     brouard  3414:        nbcode[Tvar[j]][ij]=k;
                   3415:        nbcode[Tvar[j]][1]=0;
                   3416:        nbcode[Tvar[j]][2]=1;
                   3417:        nbcode[Tvar[j]][3]=2;
1.197     brouard  3418:        To be continued (not working yet).
1.145     brouard  3419:     */
1.197     brouard  3420:     ij=0; /* ij is similar to i but can jump over null modalities */
                   3421:     for (i=modmincovj; i<=modmaxcovj; i++) { /* i= 1 to 2 for dichotomous, or from 1 to 3 or from -1 or 0 to 1 currently*/
                   3422:        if (Ndum[i] == 0) { /* If nobody responded to this modality k */
1.192     brouard  3423:          break;
                   3424:        }
                   3425:        ij++;
1.197     brouard  3426:        nbcode[Tvar[j]][ij]=i;  /* stores the original value of modality i in an array nbcode, ij modality from 1 to last non-nul modality.*/
1.192     brouard  3427:        cptcode = ij; /* New max modality for covar j */
                   3428:     } /* end of loop on modality i=-1 to 1 or more */
                   3429:       
                   3430:     /*   for (k=0; k<= cptcode; k++) { /\* k=-1 ? k=0 to 1 *\//\* Could be 1 to 4 *\//\* cptcode=modmaxcovj *\/ */
                   3431:     /*         /\*recode from 0 *\/ */
                   3432:     /*                                      k is a modality. If we have model=V1+V1*sex  */
                   3433:     /*                                      then: nbcode[1][1]=0 ; nbcode[1][2]=1; nbcode[2][1]=0 ; nbcode[2][2]=1; */
                   3434:     /*                                   But if some modality were not used, it is recoded from 0 to a newer modmaxcovj=cptcode *\/ */
                   3435:     /*         } */
                   3436:     /*         /\* cptcode = ij; *\/ /\* New max modality for covar j *\/ */
                   3437:     /*         if (ij > ncodemax[j]) { */
                   3438:     /*           printf( " Error ij=%d > ncodemax[%d]=%d\n", ij, j, ncodemax[j]);  */
                   3439:     /*           fprintf(ficlog, " Error ij=%d > ncodemax[%d]=%d\n", ij, j, ncodemax[j]); */
                   3440:     /*           break; */
                   3441:     /*         } */
                   3442:     /*   }  /\* end of loop on modality k *\/ */
1.137     brouard  3443:   } /* end of loop on model-covariate j. nbcode[Tvarj][1]=0 and nbcode[Tvarj][2]=1 sets the value of covariate j*/  
                   3444:   
1.145     brouard  3445:  for (k=-1; k< maxncov; k++) Ndum[k]=0; 
1.137     brouard  3446:   
1.187     brouard  3447:   for (i=1; i<=ncovmodel-2-nagesqr; i++) { /* -2, cste and age and eventually age*age */ 
1.145     brouard  3448:    /* Listing of all covariables in statement model to see if some covariates appear twice. For example, V1 appears twice in V1+V1*V2.*/ 
                   3449:    ij=Tvar[i]; /* Tvar might be -1 if status was unknown */ 
1.187     brouard  3450:    Ndum[ij]++; /* Might be supersed V1 + V1*age */
1.145     brouard  3451:  } 
1.126     brouard  3452: 
1.192     brouard  3453:  ij=0;
1.145     brouard  3454:  for (i=0; i<=  maxncov-1; i++) { /* modmaxcovj is unknown here. Only Ndum[2(V2),3(age*V3), 5(V3*V2) 6(V1*V4) */
                   3455:    /*printf("Ndum[%d]=%d\n",i, Ndum[i]);*/
1.126     brouard  3456:    if((Ndum[i]!=0) && (i<=ncovcol)){
1.192     brouard  3457:      ij++;
1.145     brouard  3458:      /*printf("diff Ndum[%d]=%d\n",i, Ndum[i]);*/
                   3459:      Tvaraff[ij]=i; /*For printing (unclear) */
1.192     brouard  3460:    }else{
                   3461:        /* Tvaraff[ij]=0; */
                   3462:    }
1.126     brouard  3463:  }
1.192     brouard  3464:  /* ij--; */
1.144     brouard  3465:  cptcoveff=ij; /*Number of total covariates*/
1.145     brouard  3466: 
1.126     brouard  3467: }
                   3468: 
1.145     brouard  3469: 
1.126     brouard  3470: /*********** Health Expectancies ****************/
                   3471: 
1.127     brouard  3472: 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  3473: 
                   3474: {
                   3475:   /* Health expectancies, no variances */
1.164     brouard  3476:   int i, j, nhstepm, hstepm, h, nstepm;
1.126     brouard  3477:   int nhstepma, nstepma; /* Decreasing with age */
                   3478:   double age, agelim, hf;
                   3479:   double ***p3mat;
                   3480:   double eip;
                   3481: 
                   3482:   pstamp(ficreseij);
                   3483:   fprintf(ficreseij,"# (a) Life expectancies by health status at initial age and (b) health expectancies by health status at initial age\n");
                   3484:   fprintf(ficreseij,"# Age");
                   3485:   for(i=1; i<=nlstate;i++){
                   3486:     for(j=1; j<=nlstate;j++){
                   3487:       fprintf(ficreseij," e%1d%1d ",i,j);
                   3488:     }
                   3489:     fprintf(ficreseij," e%1d. ",i);
                   3490:   }
                   3491:   fprintf(ficreseij,"\n");
                   3492: 
                   3493:   
                   3494:   if(estepm < stepm){
                   3495:     printf ("Problem %d lower than %d\n",estepm, stepm);
                   3496:   }
                   3497:   else  hstepm=estepm;   
                   3498:   /* We compute the life expectancy from trapezoids spaced every estepm months
                   3499:    * This is mainly to measure the difference between two models: for example
                   3500:    * if stepm=24 months pijx are given only every 2 years and by summing them
                   3501:    * we are calculating an estimate of the Life Expectancy assuming a linear 
                   3502:    * progression in between and thus overestimating or underestimating according
                   3503:    * to the curvature of the survival function. If, for the same date, we 
                   3504:    * estimate the model with stepm=1 month, we can keep estepm to 24 months
                   3505:    * to compare the new estimate of Life expectancy with the same linear 
                   3506:    * hypothesis. A more precise result, taking into account a more precise
                   3507:    * curvature will be obtained if estepm is as small as stepm. */
                   3508: 
                   3509:   /* For example we decided to compute the life expectancy with the smallest unit */
                   3510:   /* hstepm beeing the number of stepms, if hstepm=1 the length of hstepm is stepm. 
                   3511:      nhstepm is the number of hstepm from age to agelim 
                   3512:      nstepm is the number of stepm from age to agelin. 
                   3513:      Look at hpijx to understand the reason of that which relies in memory size
                   3514:      and note for a fixed period like estepm months */
                   3515:   /* We decided (b) to get a life expectancy respecting the most precise curvature of the
                   3516:      survival function given by stepm (the optimization length). Unfortunately it
                   3517:      means that if the survival funtion is printed only each two years of age and if
                   3518:      you sum them up and add 1 year (area under the trapezoids) you won't get the same 
                   3519:      results. So we changed our mind and took the option of the best precision.
                   3520:   */
                   3521:   hstepm=hstepm/stepm; /* Typically in stepm units, if stepm=6 & estepm=24 , = 24/6 months = 4 */ 
                   3522: 
                   3523:   agelim=AGESUP;
                   3524:   /* If stepm=6 months */
                   3525:     /* Computed by stepm unit matrices, product of hstepm matrices, stored
                   3526:        in an array of nhstepm length: nhstepm=10, hstepm=4, stepm=6 months */
                   3527:     
                   3528: /* nhstepm age range expressed in number of stepm */
                   3529:   nstepm=(int) rint((agelim-bage)*YEARM/stepm); /* Biggest nstepm */
                   3530:   /* Typically if 20 years nstepm = 20*12/6=40 stepm */ 
                   3531:   /* if (stepm >= YEARM) hstepm=1;*/
                   3532:   nhstepm = nstepm/hstepm;/* Expressed in hstepm, typically nhstepm=40/4=10 */
                   3533:   p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   3534: 
                   3535:   for (age=bage; age<=fage; age ++){ 
                   3536:     nstepma=(int) rint((agelim-bage)*YEARM/stepm); /* Biggest nstepm */
                   3537:     /* Typically if 20 years nstepm = 20*12/6=40 stepm */ 
                   3538:     /* if (stepm >= YEARM) hstepm=1;*/
                   3539:     nhstepma = nstepma/hstepm;/* Expressed in hstepm, typically nhstepma=40/4=10 */
                   3540: 
                   3541:     /* If stepm=6 months */
                   3542:     /* Computed by stepm unit matrices, product of hstepma matrices, stored
                   3543:        in an array of nhstepma length: nhstepma=10, hstepm=4, stepm=6 months */
                   3544:     
                   3545:     hpxij(p3mat,nhstepma,age,hstepm,x,nlstate,stepm,oldm, savm, cij);  
                   3546:     
                   3547:     hf=hstepm*stepm/YEARM;  /* Duration of hstepm expressed in year unit. */
                   3548:     
                   3549:     printf("%d|",(int)age);fflush(stdout);
                   3550:     fprintf(ficlog,"%d|",(int)age);fflush(ficlog);
                   3551:     
                   3552:     /* Computing expectancies */
                   3553:     for(i=1; i<=nlstate;i++)
                   3554:       for(j=1; j<=nlstate;j++)
                   3555:        for (h=0, eij[i][j][(int)age]=0; h<=nhstepm-1; h++){
                   3556:          eij[i][j][(int)age] += (p3mat[i][j][h]+p3mat[i][j][h+1])/2.0*hf;
                   3557:          
                   3558:          /* 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]);*/
                   3559: 
                   3560:        }
                   3561: 
                   3562:     fprintf(ficreseij,"%3.0f",age );
                   3563:     for(i=1; i<=nlstate;i++){
                   3564:       eip=0;
                   3565:       for(j=1; j<=nlstate;j++){
                   3566:        eip +=eij[i][j][(int)age];
                   3567:        fprintf(ficreseij,"%9.4f", eij[i][j][(int)age] );
                   3568:       }
                   3569:       fprintf(ficreseij,"%9.4f", eip );
                   3570:     }
                   3571:     fprintf(ficreseij,"\n");
                   3572:     
                   3573:   }
                   3574:   free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   3575:   printf("\n");
                   3576:   fprintf(ficlog,"\n");
                   3577:   
                   3578: }
                   3579: 
1.127     brouard  3580: 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  3581: 
                   3582: {
                   3583:   /* Covariances of health expectancies eij and of total life expectancies according
                   3584:    to initial status i, ei. .
                   3585:   */
                   3586:   int i, j, nhstepm, hstepm, h, nstepm, k, cptj, cptj2, i2, j2, ij, ji;
                   3587:   int nhstepma, nstepma; /* Decreasing with age */
                   3588:   double age, agelim, hf;
                   3589:   double ***p3matp, ***p3matm, ***varhe;
                   3590:   double **dnewm,**doldm;
                   3591:   double *xp, *xm;
                   3592:   double **gp, **gm;
                   3593:   double ***gradg, ***trgradg;
                   3594:   int theta;
                   3595: 
                   3596:   double eip, vip;
                   3597: 
                   3598:   varhe=ma3x(1,nlstate*nlstate,1,nlstate*nlstate,(int) bage, (int) fage);
                   3599:   xp=vector(1,npar);
                   3600:   xm=vector(1,npar);
                   3601:   dnewm=matrix(1,nlstate*nlstate,1,npar);
                   3602:   doldm=matrix(1,nlstate*nlstate,1,nlstate*nlstate);
                   3603:   
                   3604:   pstamp(ficresstdeij);
                   3605:   fprintf(ficresstdeij,"# Health expectancies with standard errors\n");
                   3606:   fprintf(ficresstdeij,"# Age");
                   3607:   for(i=1; i<=nlstate;i++){
                   3608:     for(j=1; j<=nlstate;j++)
                   3609:       fprintf(ficresstdeij," e%1d%1d (SE)",i,j);
                   3610:     fprintf(ficresstdeij," e%1d. ",i);
                   3611:   }
                   3612:   fprintf(ficresstdeij,"\n");
                   3613: 
                   3614:   pstamp(ficrescveij);
                   3615:   fprintf(ficrescveij,"# Subdiagonal matrix of covariances of health expectancies by age: cov(eij,ekl)\n");
                   3616:   fprintf(ficrescveij,"# Age");
                   3617:   for(i=1; i<=nlstate;i++)
                   3618:     for(j=1; j<=nlstate;j++){
                   3619:       cptj= (j-1)*nlstate+i;
                   3620:       for(i2=1; i2<=nlstate;i2++)
                   3621:        for(j2=1; j2<=nlstate;j2++){
                   3622:          cptj2= (j2-1)*nlstate+i2;
                   3623:          if(cptj2 <= cptj)
                   3624:            fprintf(ficrescveij,"  %1d%1d,%1d%1d",i,j,i2,j2);
                   3625:        }
                   3626:     }
                   3627:   fprintf(ficrescveij,"\n");
                   3628:   
                   3629:   if(estepm < stepm){
                   3630:     printf ("Problem %d lower than %d\n",estepm, stepm);
                   3631:   }
                   3632:   else  hstepm=estepm;   
                   3633:   /* We compute the life expectancy from trapezoids spaced every estepm months
                   3634:    * This is mainly to measure the difference between two models: for example
                   3635:    * if stepm=24 months pijx are given only every 2 years and by summing them
                   3636:    * we are calculating an estimate of the Life Expectancy assuming a linear 
                   3637:    * progression in between and thus overestimating or underestimating according
                   3638:    * to the curvature of the survival function. If, for the same date, we 
                   3639:    * estimate the model with stepm=1 month, we can keep estepm to 24 months
                   3640:    * to compare the new estimate of Life expectancy with the same linear 
                   3641:    * hypothesis. A more precise result, taking into account a more precise
                   3642:    * curvature will be obtained if estepm is as small as stepm. */
                   3643: 
                   3644:   /* For example we decided to compute the life expectancy with the smallest unit */
                   3645:   /* hstepm beeing the number of stepms, if hstepm=1 the length of hstepm is stepm. 
                   3646:      nhstepm is the number of hstepm from age to agelim 
                   3647:      nstepm is the number of stepm from age to agelin. 
                   3648:      Look at hpijx to understand the reason of that which relies in memory size
                   3649:      and note for a fixed period like estepm months */
                   3650:   /* We decided (b) to get a life expectancy respecting the most precise curvature of the
                   3651:      survival function given by stepm (the optimization length). Unfortunately it
                   3652:      means that if the survival funtion is printed only each two years of age and if
                   3653:      you sum them up and add 1 year (area under the trapezoids) you won't get the same 
                   3654:      results. So we changed our mind and took the option of the best precision.
                   3655:   */
                   3656:   hstepm=hstepm/stepm; /* Typically in stepm units, if stepm=6 & estepm=24 , = 24/6 months = 4 */ 
                   3657: 
                   3658:   /* If stepm=6 months */
                   3659:   /* nhstepm age range expressed in number of stepm */
                   3660:   agelim=AGESUP;
                   3661:   nstepm=(int) rint((agelim-bage)*YEARM/stepm); 
                   3662:   /* Typically if 20 years nstepm = 20*12/6=40 stepm */ 
                   3663:   /* if (stepm >= YEARM) hstepm=1;*/
                   3664:   nhstepm = nstepm/hstepm;/* Expressed in hstepm, typically nhstepm=40/4=10 */
                   3665:   
                   3666:   p3matp=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   3667:   p3matm=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   3668:   gradg=ma3x(0,nhstepm,1,npar,1,nlstate*nlstate);
                   3669:   trgradg =ma3x(0,nhstepm,1,nlstate*nlstate,1,npar);
                   3670:   gp=matrix(0,nhstepm,1,nlstate*nlstate);
                   3671:   gm=matrix(0,nhstepm,1,nlstate*nlstate);
                   3672: 
                   3673:   for (age=bage; age<=fage; age ++){ 
                   3674:     nstepma=(int) rint((agelim-bage)*YEARM/stepm); /* Biggest nstepm */
                   3675:     /* Typically if 20 years nstepm = 20*12/6=40 stepm */ 
                   3676:     /* if (stepm >= YEARM) hstepm=1;*/
                   3677:     nhstepma = nstepma/hstepm;/* Expressed in hstepm, typically nhstepma=40/4=10 */
                   3678: 
                   3679:     /* If stepm=6 months */
                   3680:     /* Computed by stepm unit matrices, product of hstepma matrices, stored
                   3681:        in an array of nhstepma length: nhstepma=10, hstepm=4, stepm=6 months */
                   3682:     
                   3683:     hf=hstepm*stepm/YEARM;  /* Duration of hstepm expressed in year unit. */
                   3684: 
                   3685:     /* Computing  Variances of health expectancies */
                   3686:     /* Gradient is computed with plus gp and minus gm. Code is duplicated in order to
                   3687:        decrease memory allocation */
                   3688:     for(theta=1; theta <=npar; theta++){
                   3689:       for(i=1; i<=npar; i++){ 
                   3690:        xp[i] = x[i] + (i==theta ?delti[theta]:0);
                   3691:        xm[i] = x[i] - (i==theta ?delti[theta]:0);
                   3692:       }
                   3693:       hpxij(p3matp,nhstepm,age,hstepm,xp,nlstate,stepm,oldm,savm, cij);  
                   3694:       hpxij(p3matm,nhstepm,age,hstepm,xm,nlstate,stepm,oldm,savm, cij);  
                   3695:   
                   3696:       for(j=1; j<= nlstate; j++){
                   3697:        for(i=1; i<=nlstate; i++){
                   3698:          for(h=0; h<=nhstepm-1; h++){
                   3699:            gp[h][(j-1)*nlstate + i] = (p3matp[i][j][h]+p3matp[i][j][h+1])/2.;
                   3700:            gm[h][(j-1)*nlstate + i] = (p3matm[i][j][h]+p3matm[i][j][h+1])/2.;
                   3701:          }
                   3702:        }
                   3703:       }
                   3704:      
                   3705:       for(ij=1; ij<= nlstate*nlstate; ij++)
                   3706:        for(h=0; h<=nhstepm-1; h++){
                   3707:          gradg[h][theta][ij]= (gp[h][ij]-gm[h][ij])/2./delti[theta];
                   3708:        }
                   3709:     }/* End theta */
                   3710:     
                   3711:     
                   3712:     for(h=0; h<=nhstepm-1; h++)
                   3713:       for(j=1; j<=nlstate*nlstate;j++)
                   3714:        for(theta=1; theta <=npar; theta++)
                   3715:          trgradg[h][j][theta]=gradg[h][theta][j];
                   3716:     
                   3717: 
                   3718:      for(ij=1;ij<=nlstate*nlstate;ij++)
                   3719:       for(ji=1;ji<=nlstate*nlstate;ji++)
                   3720:        varhe[ij][ji][(int)age] =0.;
                   3721: 
                   3722:      printf("%d|",(int)age);fflush(stdout);
                   3723:      fprintf(ficlog,"%d|",(int)age);fflush(ficlog);
                   3724:      for(h=0;h<=nhstepm-1;h++){
                   3725:       for(k=0;k<=nhstepm-1;k++){
                   3726:        matprod2(dnewm,trgradg[h],1,nlstate*nlstate,1,npar,1,npar,matcov);
                   3727:        matprod2(doldm,dnewm,1,nlstate*nlstate,1,npar,1,nlstate*nlstate,gradg[k]);
                   3728:        for(ij=1;ij<=nlstate*nlstate;ij++)
                   3729:          for(ji=1;ji<=nlstate*nlstate;ji++)
                   3730:            varhe[ij][ji][(int)age] += doldm[ij][ji]*hf*hf;
                   3731:       }
                   3732:     }
                   3733: 
                   3734:     /* Computing expectancies */
                   3735:     hpxij(p3matm,nhstepm,age,hstepm,x,nlstate,stepm,oldm, savm, cij);  
                   3736:     for(i=1; i<=nlstate;i++)
                   3737:       for(j=1; j<=nlstate;j++)
                   3738:        for (h=0, eij[i][j][(int)age]=0; h<=nhstepm-1; h++){
                   3739:          eij[i][j][(int)age] += (p3matm[i][j][h]+p3matm[i][j][h+1])/2.0*hf;
                   3740:          
                   3741:          /* 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]);*/
                   3742: 
                   3743:        }
                   3744: 
                   3745:     fprintf(ficresstdeij,"%3.0f",age );
                   3746:     for(i=1; i<=nlstate;i++){
                   3747:       eip=0.;
                   3748:       vip=0.;
                   3749:       for(j=1; j<=nlstate;j++){
                   3750:        eip += eij[i][j][(int)age];
                   3751:        for(k=1; k<=nlstate;k++) /* Sum on j and k of cov(eij,eik) */
                   3752:          vip += varhe[(j-1)*nlstate+i][(k-1)*nlstate+i][(int)age];
                   3753:        fprintf(ficresstdeij," %9.4f (%.4f)", eij[i][j][(int)age], sqrt(varhe[(j-1)*nlstate+i][(j-1)*nlstate+i][(int)age]) );
                   3754:       }
                   3755:       fprintf(ficresstdeij," %9.4f (%.4f)", eip, sqrt(vip));
                   3756:     }
                   3757:     fprintf(ficresstdeij,"\n");
                   3758: 
                   3759:     fprintf(ficrescveij,"%3.0f",age );
                   3760:     for(i=1; i<=nlstate;i++)
                   3761:       for(j=1; j<=nlstate;j++){
                   3762:        cptj= (j-1)*nlstate+i;
                   3763:        for(i2=1; i2<=nlstate;i2++)
                   3764:          for(j2=1; j2<=nlstate;j2++){
                   3765:            cptj2= (j2-1)*nlstate+i2;
                   3766:            if(cptj2 <= cptj)
                   3767:              fprintf(ficrescveij," %.4f", varhe[cptj][cptj2][(int)age]);
                   3768:          }
                   3769:       }
                   3770:     fprintf(ficrescveij,"\n");
                   3771:    
                   3772:   }
                   3773:   free_matrix(gm,0,nhstepm,1,nlstate*nlstate);
                   3774:   free_matrix(gp,0,nhstepm,1,nlstate*nlstate);
                   3775:   free_ma3x(gradg,0,nhstepm,1,npar,1,nlstate*nlstate);
                   3776:   free_ma3x(trgradg,0,nhstepm,1,nlstate*nlstate,1,npar);
                   3777:   free_ma3x(p3matm,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   3778:   free_ma3x(p3matp,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   3779:   printf("\n");
                   3780:   fprintf(ficlog,"\n");
                   3781: 
                   3782:   free_vector(xm,1,npar);
                   3783:   free_vector(xp,1,npar);
                   3784:   free_matrix(dnewm,1,nlstate*nlstate,1,npar);
                   3785:   free_matrix(doldm,1,nlstate*nlstate,1,nlstate*nlstate);
                   3786:   free_ma3x(varhe,1,nlstate*nlstate,1,nlstate*nlstate,(int) bage, (int)fage);
                   3787: }
                   3788: 
                   3789: /************ Variance ******************/
                   3790: 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[])
                   3791: {
                   3792:   /* Variance of health expectancies */
                   3793:   /*  double **prevalim(double **prlim, int nlstate, double *xp, double age, double **oldm, double ** savm,double ftolpl);*/
                   3794:   /* double **newm;*/
1.169     brouard  3795:   /* int movingaverage(double ***probs, double bage,double fage, double ***mobaverage, int mobilav)*/
                   3796:   
                   3797:   int movingaverage();
1.126     brouard  3798:   double **dnewm,**doldm;
                   3799:   double **dnewmp,**doldmp;
                   3800:   int i, j, nhstepm, hstepm, h, nstepm ;
1.164     brouard  3801:   int k;
1.126     brouard  3802:   double *xp;
                   3803:   double **gp, **gm;  /* for var eij */
                   3804:   double ***gradg, ***trgradg; /*for var eij */
                   3805:   double **gradgp, **trgradgp; /* for var p point j */
                   3806:   double *gpp, *gmp; /* for var p point j */
                   3807:   double **varppt; /* for var p point j nlstate to nlstate+ndeath */
                   3808:   double ***p3mat;
                   3809:   double age,agelim, hf;
                   3810:   double ***mobaverage;
                   3811:   int theta;
                   3812:   char digit[4];
                   3813:   char digitp[25];
                   3814: 
                   3815:   char fileresprobmorprev[FILENAMELENGTH];
                   3816: 
                   3817:   if(popbased==1){
                   3818:     if(mobilav!=0)
1.201   ! brouard  3819:       strcpy(digitp,"-POPULBASED-MOBILAV_");
        !          3820:     else strcpy(digitp,"-POPULBASED-NOMOBIL_");
1.126     brouard  3821:   }
                   3822:   else 
1.201   ! brouard  3823:     strcpy(digitp,"-STABLBASED_");
1.126     brouard  3824: 
                   3825:   if (mobilav!=0) {
                   3826:     mobaverage= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
                   3827:     if (movingaverage(probs, bage, fage, mobaverage,mobilav)!=0){
                   3828:       fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav);
                   3829:       printf(" Error in movingaverage mobilav=%d\n",mobilav);
                   3830:     }
                   3831:   }
                   3832: 
1.201   ! brouard  3833:   strcpy(fileresprobmorprev,"PRMORPREV-"); 
1.126     brouard  3834:   sprintf(digit,"%-d",ij);
                   3835:   /*printf("DIGIT=%s, ij=%d ijr=%-d|\n",digit, ij,ij);*/
                   3836:   strcat(fileresprobmorprev,digit); /* Tvar to be done */
                   3837:   strcat(fileresprobmorprev,digitp); /* Popbased or not, mobilav or not */
                   3838:   strcat(fileresprobmorprev,fileres);
                   3839:   if((ficresprobmorprev=fopen(fileresprobmorprev,"w"))==NULL) {
                   3840:     printf("Problem with resultfile: %s\n", fileresprobmorprev);
                   3841:     fprintf(ficlog,"Problem with resultfile: %s\n", fileresprobmorprev);
                   3842:   }
                   3843:   printf("Computing total mortality p.j=w1*p1j+w2*p2j+..: result on file '%s' \n",fileresprobmorprev);
                   3844:  
                   3845:   fprintf(ficlog,"Computing total mortality p.j=w1*p1j+w2*p2j+..: result on file '%s' \n",fileresprobmorprev);
                   3846:   pstamp(ficresprobmorprev);
                   3847:   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);
                   3848:   fprintf(ficresprobmorprev,"# Age cov=%-d",ij);
                   3849:   for(j=nlstate+1; j<=(nlstate+ndeath);j++){
                   3850:     fprintf(ficresprobmorprev," p.%-d SE",j);
                   3851:     for(i=1; i<=nlstate;i++)
                   3852:       fprintf(ficresprobmorprev," w%1d p%-d%-d",i,i,j);
                   3853:   }  
                   3854:   fprintf(ficresprobmorprev,"\n");
                   3855:   fprintf(ficgp,"\n# Routine varevsij");
1.200     brouard  3856:   fprintf(ficgp,"\nunset title \n");
                   3857: /* fprintf(fichtm, "#Local time at start: %s", strstart);*/
1.126     brouard  3858:   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");
                   3859:   fprintf(fichtm,"\n<br>%s  <br>\n",digitp);
                   3860: /*   } */
                   3861:   varppt = matrix(nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);
                   3862:   pstamp(ficresvij);
                   3863:   fprintf(ficresvij,"# Variance and covariance of health expectancies e.j \n#  (weighted average of eij where weights are ");
                   3864:   if(popbased==1)
1.128     brouard  3865:     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  3866:   else
                   3867:     fprintf(ficresvij,"the age specific period (stable) prevalences in each health state \n");
                   3868:   fprintf(ficresvij,"# Age");
                   3869:   for(i=1; i<=nlstate;i++)
                   3870:     for(j=1; j<=nlstate;j++)
                   3871:       fprintf(ficresvij," Cov(e.%1d, e.%1d)",i,j);
                   3872:   fprintf(ficresvij,"\n");
                   3873: 
                   3874:   xp=vector(1,npar);
                   3875:   dnewm=matrix(1,nlstate,1,npar);
                   3876:   doldm=matrix(1,nlstate,1,nlstate);
                   3877:   dnewmp= matrix(nlstate+1,nlstate+ndeath,1,npar);
                   3878:   doldmp= matrix(nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);
                   3879: 
                   3880:   gradgp=matrix(1,npar,nlstate+1,nlstate+ndeath);
                   3881:   gpp=vector(nlstate+1,nlstate+ndeath);
                   3882:   gmp=vector(nlstate+1,nlstate+ndeath);
                   3883:   trgradgp =matrix(nlstate+1,nlstate+ndeath,1,npar); /* mu or p point j*/
                   3884:   
                   3885:   if(estepm < stepm){
                   3886:     printf ("Problem %d lower than %d\n",estepm, stepm);
                   3887:   }
                   3888:   else  hstepm=estepm;   
                   3889:   /* For example we decided to compute the life expectancy with the smallest unit */
                   3890:   /* hstepm beeing the number of stepms, if hstepm=1 the length of hstepm is stepm. 
                   3891:      nhstepm is the number of hstepm from age to agelim 
                   3892:      nstepm is the number of stepm from age to agelin. 
1.128     brouard  3893:      Look at function hpijx to understand why (it is linked to memory size questions) */
1.126     brouard  3894:   /* We decided (b) to get a life expectancy respecting the most precise curvature of the
                   3895:      survival function given by stepm (the optimization length). Unfortunately it
                   3896:      means that if the survival funtion is printed every two years of age and if
                   3897:      you sum them up and add 1 year (area under the trapezoids) you won't get the same 
                   3898:      results. So we changed our mind and took the option of the best precision.
                   3899:   */
                   3900:   hstepm=hstepm/stepm; /* Typically in stepm units, if stepm=6 & estepm=24 , = 24/6 months = 4 */ 
                   3901:   agelim = AGESUP;
                   3902:   for (age=bage; age<=fage; age ++){ /* If stepm=6 months */
                   3903:     nstepm=(int) rint((agelim-age)*YEARM/stepm); /* Typically 20 years = 20*12/6=40 */ 
                   3904:     nhstepm = nstepm/hstepm;/* Expressed in hstepm, typically nhstepm=40/4=10 */
                   3905:     p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   3906:     gradg=ma3x(0,nhstepm,1,npar,1,nlstate);
                   3907:     gp=matrix(0,nhstepm,1,nlstate);
                   3908:     gm=matrix(0,nhstepm,1,nlstate);
                   3909: 
                   3910: 
                   3911:     for(theta=1; theta <=npar; theta++){
                   3912:       for(i=1; i<=npar; i++){ /* Computes gradient x + delta*/
                   3913:        xp[i] = x[i] + (i==theta ?delti[theta]:0);
                   3914:       }
                   3915:       hpxij(p3mat,nhstepm,age,hstepm,xp,nlstate,stepm,oldm,savm, ij);  
                   3916:       prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ij);
                   3917: 
                   3918:       if (popbased==1) {
                   3919:        if(mobilav ==0){
                   3920:          for(i=1; i<=nlstate;i++)
                   3921:            prlim[i][i]=probs[(int)age][i][ij];
                   3922:        }else{ /* mobilav */ 
                   3923:          for(i=1; i<=nlstate;i++)
                   3924:            prlim[i][i]=mobaverage[(int)age][i][ij];
                   3925:        }
                   3926:       }
                   3927:   
                   3928:       for(j=1; j<= nlstate; j++){
                   3929:        for(h=0; h<=nhstepm; h++){
                   3930:          for(i=1, gp[h][j]=0.;i<=nlstate;i++)
                   3931:            gp[h][j] += prlim[i][i]*p3mat[i][j][h];
                   3932:        }
                   3933:       }
                   3934:       /* This for computing probability of death (h=1 means
                   3935:          computed over hstepm matrices product = hstepm*stepm months) 
                   3936:          as a weighted average of prlim.
                   3937:       */
                   3938:       for(j=nlstate+1;j<=nlstate+ndeath;j++){
                   3939:        for(i=1,gpp[j]=0.; i<= nlstate; i++)
                   3940:          gpp[j] += prlim[i][i]*p3mat[i][j][1];
                   3941:       }    
                   3942:       /* end probability of death */
                   3943: 
                   3944:       for(i=1; i<=npar; i++) /* Computes gradient x - delta */
                   3945:        xp[i] = x[i] - (i==theta ?delti[theta]:0);
                   3946:       hpxij(p3mat,nhstepm,age,hstepm,xp,nlstate,stepm,oldm,savm, ij);  
                   3947:       prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ij);
                   3948:  
                   3949:       if (popbased==1) {
                   3950:        if(mobilav ==0){
                   3951:          for(i=1; i<=nlstate;i++)
                   3952:            prlim[i][i]=probs[(int)age][i][ij];
                   3953:        }else{ /* mobilav */ 
                   3954:          for(i=1; i<=nlstate;i++)
                   3955:            prlim[i][i]=mobaverage[(int)age][i][ij];
                   3956:        }
                   3957:       }
                   3958: 
1.128     brouard  3959:       for(j=1; j<= nlstate; j++){  /* Sum of wi * eij = e.j */
1.126     brouard  3960:        for(h=0; h<=nhstepm; h++){
                   3961:          for(i=1, gm[h][j]=0.;i<=nlstate;i++)
                   3962:            gm[h][j] += prlim[i][i]*p3mat[i][j][h];
                   3963:        }
                   3964:       }
                   3965:       /* This for computing probability of death (h=1 means
                   3966:          computed over hstepm matrices product = hstepm*stepm months) 
                   3967:          as a weighted average of prlim.
                   3968:       */
                   3969:       for(j=nlstate+1;j<=nlstate+ndeath;j++){
                   3970:        for(i=1,gmp[j]=0.; i<= nlstate; i++)
                   3971:          gmp[j] += prlim[i][i]*p3mat[i][j][1];
                   3972:       }    
                   3973:       /* end probability of death */
                   3974: 
                   3975:       for(j=1; j<= nlstate; j++) /* vareij */
                   3976:        for(h=0; h<=nhstepm; h++){
                   3977:          gradg[h][theta][j]= (gp[h][j]-gm[h][j])/2./delti[theta];
                   3978:        }
                   3979: 
                   3980:       for(j=nlstate+1; j<= nlstate+ndeath; j++){ /* var mu */
                   3981:        gradgp[theta][j]= (gpp[j]-gmp[j])/2./delti[theta];
                   3982:       }
                   3983: 
                   3984:     } /* End theta */
                   3985: 
                   3986:     trgradg =ma3x(0,nhstepm,1,nlstate,1,npar); /* veij */
                   3987: 
                   3988:     for(h=0; h<=nhstepm; h++) /* veij */
                   3989:       for(j=1; j<=nlstate;j++)
                   3990:        for(theta=1; theta <=npar; theta++)
                   3991:          trgradg[h][j][theta]=gradg[h][theta][j];
                   3992: 
                   3993:     for(j=nlstate+1; j<=nlstate+ndeath;j++) /* mu */
                   3994:       for(theta=1; theta <=npar; theta++)
                   3995:        trgradgp[j][theta]=gradgp[theta][j];
                   3996:   
                   3997: 
                   3998:     hf=hstepm*stepm/YEARM;  /* Duration of hstepm expressed in year unit. */
                   3999:     for(i=1;i<=nlstate;i++)
                   4000:       for(j=1;j<=nlstate;j++)
                   4001:        vareij[i][j][(int)age] =0.;
                   4002: 
                   4003:     for(h=0;h<=nhstepm;h++){
                   4004:       for(k=0;k<=nhstepm;k++){
                   4005:        matprod2(dnewm,trgradg[h],1,nlstate,1,npar,1,npar,matcov);
                   4006:        matprod2(doldm,dnewm,1,nlstate,1,npar,1,nlstate,gradg[k]);
                   4007:        for(i=1;i<=nlstate;i++)
                   4008:          for(j=1;j<=nlstate;j++)
                   4009:            vareij[i][j][(int)age] += doldm[i][j]*hf*hf;
                   4010:       }
                   4011:     }
                   4012:   
                   4013:     /* pptj */
                   4014:     matprod2(dnewmp,trgradgp,nlstate+1,nlstate+ndeath,1,npar,1,npar,matcov);
                   4015:     matprod2(doldmp,dnewmp,nlstate+1,nlstate+ndeath,1,npar,nlstate+1,nlstate+ndeath,gradgp);
                   4016:     for(j=nlstate+1;j<=nlstate+ndeath;j++)
                   4017:       for(i=nlstate+1;i<=nlstate+ndeath;i++)
                   4018:        varppt[j][i]=doldmp[j][i];
                   4019:     /* end ppptj */
                   4020:     /*  x centered again */
                   4021:     hpxij(p3mat,nhstepm,age,hstepm,x,nlstate,stepm,oldm,savm, ij);  
                   4022:     prevalim(prlim,nlstate,x,age,oldm,savm,ftolpl,ij);
                   4023:  
                   4024:     if (popbased==1) {
                   4025:       if(mobilav ==0){
                   4026:        for(i=1; i<=nlstate;i++)
                   4027:          prlim[i][i]=probs[(int)age][i][ij];
                   4028:       }else{ /* mobilav */ 
                   4029:        for(i=1; i<=nlstate;i++)
                   4030:          prlim[i][i]=mobaverage[(int)age][i][ij];
                   4031:       }
                   4032:     }
                   4033:              
                   4034:     /* This for computing probability of death (h=1 means
                   4035:        computed over hstepm (estepm) matrices product = hstepm*stepm months) 
                   4036:        as a weighted average of prlim.
                   4037:     */
                   4038:     for(j=nlstate+1;j<=nlstate+ndeath;j++){
                   4039:       for(i=1,gmp[j]=0.;i<= nlstate; i++) 
                   4040:        gmp[j] += prlim[i][i]*p3mat[i][j][1]; 
                   4041:     }    
                   4042:     /* end probability of death */
                   4043: 
                   4044:     fprintf(ficresprobmorprev,"%3d %d ",(int) age, ij);
                   4045:     for(j=nlstate+1; j<=(nlstate+ndeath);j++){
                   4046:       fprintf(ficresprobmorprev," %11.3e %11.3e",gmp[j], sqrt(varppt[j][j]));
                   4047:       for(i=1; i<=nlstate;i++){
                   4048:        fprintf(ficresprobmorprev," %11.3e %11.3e ",prlim[i][i],p3mat[i][j][1]);
                   4049:       }
                   4050:     } 
                   4051:     fprintf(ficresprobmorprev,"\n");
                   4052: 
                   4053:     fprintf(ficresvij,"%.0f ",age );
                   4054:     for(i=1; i<=nlstate;i++)
                   4055:       for(j=1; j<=nlstate;j++){
                   4056:        fprintf(ficresvij," %.4f", vareij[i][j][(int)age]);
                   4057:       }
                   4058:     fprintf(ficresvij,"\n");
                   4059:     free_matrix(gp,0,nhstepm,1,nlstate);
                   4060:     free_matrix(gm,0,nhstepm,1,nlstate);
                   4061:     free_ma3x(gradg,0,nhstepm,1,npar,1,nlstate);
                   4062:     free_ma3x(trgradg,0,nhstepm,1,nlstate,1,npar);
                   4063:     free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   4064:   } /* End age */
                   4065:   free_vector(gpp,nlstate+1,nlstate+ndeath);
                   4066:   free_vector(gmp,nlstate+1,nlstate+ndeath);
                   4067:   free_matrix(gradgp,1,npar,nlstate+1,nlstate+ndeath);
                   4068:   free_matrix(trgradgp,nlstate+1,nlstate+ndeath,1,npar); /* mu or p point j*/
1.199     brouard  4069:   /* fprintf(ficgp,"\nunset parametric;unset label; set ter png small size 320, 240"); */
                   4070:   fprintf(ficgp,"\nunset parametric;unset label; set ter svg size 640, 480");
1.126     brouard  4071:   /* for(j=nlstate+1; j<= nlstate+ndeath; j++){ *//* Only the first actually */
1.131     brouard  4072:   fprintf(ficgp,"\n set log y; unset log x;set xlabel \"Age\"; set ylabel \"Force of mortality (year-1)\";");
1.201   ! brouard  4073:   fprintf(ficgp,"\nset out \"%s%s.svg\";",subdirf3(optionfilefiname,"VARMUPTJGR-",digitp),digit);
1.126     brouard  4074: /*   fprintf(ficgp,"\n plot \"%s\"  u 1:($3*%6.3f) not w l 1 ",fileresprobmorprev,YEARM/estepm); */
                   4075: /*   fprintf(ficgp,"\n replot \"%s\"  u 1:(($3+1.96*$4)*%6.3f) t \"95\%% interval\" w l 2 ",fileresprobmorprev,YEARM/estepm); */
                   4076: /*   fprintf(ficgp,"\n replot \"%s\"  u 1:(($3-1.96*$4)*%6.3f) not w l 2 ",fileresprobmorprev,YEARM/estepm); */
1.145     brouard  4077:   fprintf(ficgp,"\n plot \"%s\"  u 1:($3) not w l lt 1 ",subdirf(fileresprobmorprev));
1.170     brouard  4078:   fprintf(ficgp,"\n replot \"%s\"  u 1:(($3+1.96*$4)) t \"95%% interval\" w l lt 2 ",subdirf(fileresprobmorprev));
1.145     brouard  4079:   fprintf(ficgp,"\n replot \"%s\"  u 1:(($3-1.96*$4)) not w l lt 2 ",subdirf(fileresprobmorprev));
1.126     brouard  4080:   fprintf(fichtm,"\n<br> File (multiple files are possible if covariates are present): <A href=\"%s\">%s</a>\n",subdirf(fileresprobmorprev),subdirf(fileresprobmorprev));
1.201   ! brouard  4081:   fprintf(fichtm,"\n<br> Probability is computed over estepm=%d months. <br> <img src=\"%s%s.svg\"> <br>\n", estepm,subdirf3(optionfilefiname,"VARMUPTJGR-",digitp),digit);
1.199     brouard  4082:   /*  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.svg\"> <br>\n", stepm,YEARM,digitp,digit);
1.126     brouard  4083: */
1.199     brouard  4084: /*   fprintf(ficgp,"\nset out \"varmuptjgr%s%s%s.svg\";replot;",digitp,optionfilefiname,digit); */
1.201   ! brouard  4085:   fprintf(ficgp,"\nset out;\nset out \"%s%s.svg\";replot;set out;\n",subdirf3(optionfilefiname,"VARMUPTJGR-",digitp),digit);
1.126     brouard  4086: 
                   4087:   free_vector(xp,1,npar);
                   4088:   free_matrix(doldm,1,nlstate,1,nlstate);
                   4089:   free_matrix(dnewm,1,nlstate,1,npar);
                   4090:   free_matrix(doldmp,nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);
                   4091:   free_matrix(dnewmp,nlstate+1,nlstate+ndeath,1,npar);
                   4092:   free_matrix(varppt,nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);
                   4093:   if (mobilav!=0) free_ma3x(mobaverage,1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
                   4094:   fclose(ficresprobmorprev);
                   4095:   fflush(ficgp);
                   4096:   fflush(fichtm); 
                   4097: }  /* end varevsij */
                   4098: 
                   4099: /************ Variance of prevlim ******************/
                   4100: 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[])
                   4101: {
                   4102:   /* Variance of prevalence limit */
                   4103:   /*  double **prevalim(double **prlim, int nlstate, double *xp, double age, double **oldm, double **savm,double ftolpl);*/
1.164     brouard  4104: 
1.126     brouard  4105:   double **dnewm,**doldm;
                   4106:   int i, j, nhstepm, hstepm;
                   4107:   double *xp;
                   4108:   double *gp, *gm;
                   4109:   double **gradg, **trgradg;
                   4110:   double age,agelim;
                   4111:   int theta;
                   4112:   
                   4113:   pstamp(ficresvpl);
                   4114:   fprintf(ficresvpl,"# Standard deviation of period (stable) prevalences \n");
                   4115:   fprintf(ficresvpl,"# Age");
                   4116:   for(i=1; i<=nlstate;i++)
                   4117:       fprintf(ficresvpl," %1d-%1d",i,i);
                   4118:   fprintf(ficresvpl,"\n");
                   4119: 
                   4120:   xp=vector(1,npar);
                   4121:   dnewm=matrix(1,nlstate,1,npar);
                   4122:   doldm=matrix(1,nlstate,1,nlstate);
                   4123:   
                   4124:   hstepm=1*YEARM; /* Every year of age */
                   4125:   hstepm=hstepm/stepm; /* Typically in stepm units, if j= 2 years, = 2/6 months = 4 */ 
                   4126:   agelim = AGESUP;
                   4127:   for (age=bage; age<=fage; age ++){ /* If stepm=6 months */
                   4128:     nhstepm=(int) rint((agelim-age)*YEARM/stepm); /* Typically 20 years = 20*12/6=40 */ 
                   4129:     if (stepm >= YEARM) hstepm=1;
                   4130:     nhstepm = nhstepm/hstepm; /* Typically 40/4=10 */
                   4131:     gradg=matrix(1,npar,1,nlstate);
                   4132:     gp=vector(1,nlstate);
                   4133:     gm=vector(1,nlstate);
                   4134: 
                   4135:     for(theta=1; theta <=npar; theta++){
                   4136:       for(i=1; i<=npar; i++){ /* Computes gradient */
                   4137:        xp[i] = x[i] + (i==theta ?delti[theta]:0);
                   4138:       }
                   4139:       prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ij);
                   4140:       for(i=1;i<=nlstate;i++)
                   4141:        gp[i] = prlim[i][i];
                   4142:     
                   4143:       for(i=1; i<=npar; i++) /* Computes gradient */
                   4144:        xp[i] = x[i] - (i==theta ?delti[theta]:0);
                   4145:       prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ij);
                   4146:       for(i=1;i<=nlstate;i++)
                   4147:        gm[i] = prlim[i][i];
                   4148: 
                   4149:       for(i=1;i<=nlstate;i++)
                   4150:        gradg[theta][i]= (gp[i]-gm[i])/2./delti[theta];
                   4151:     } /* End theta */
                   4152: 
                   4153:     trgradg =matrix(1,nlstate,1,npar);
                   4154: 
                   4155:     for(j=1; j<=nlstate;j++)
                   4156:       for(theta=1; theta <=npar; theta++)
                   4157:        trgradg[j][theta]=gradg[theta][j];
                   4158: 
                   4159:     for(i=1;i<=nlstate;i++)
                   4160:       varpl[i][(int)age] =0.;
                   4161:     matprod2(dnewm,trgradg,1,nlstate,1,npar,1,npar,matcov);
                   4162:     matprod2(doldm,dnewm,1,nlstate,1,npar,1,nlstate,gradg);
                   4163:     for(i=1;i<=nlstate;i++)
                   4164:       varpl[i][(int)age] = doldm[i][i]; /* Covariances are useless */
                   4165: 
                   4166:     fprintf(ficresvpl,"%.0f ",age );
                   4167:     for(i=1; i<=nlstate;i++)
                   4168:       fprintf(ficresvpl," %.5f (%.5f)",prlim[i][i],sqrt(varpl[i][(int)age]));
                   4169:     fprintf(ficresvpl,"\n");
                   4170:     free_vector(gp,1,nlstate);
                   4171:     free_vector(gm,1,nlstate);
                   4172:     free_matrix(gradg,1,npar,1,nlstate);
                   4173:     free_matrix(trgradg,1,nlstate,1,npar);
                   4174:   } /* End age */
                   4175: 
                   4176:   free_vector(xp,1,npar);
                   4177:   free_matrix(doldm,1,nlstate,1,npar);
                   4178:   free_matrix(dnewm,1,nlstate,1,nlstate);
                   4179: 
                   4180: }
                   4181: 
                   4182: /************ Variance of one-step probabilities  ******************/
                   4183: 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[])
                   4184: {
1.164     brouard  4185:   int i, j=0,  k1, l1, tj;
1.126     brouard  4186:   int k2, l2, j1,  z1;
1.164     brouard  4187:   int k=0, l;
1.145     brouard  4188:   int first=1, first1, first2;
1.126     brouard  4189:   double cv12, mu1, mu2, lc1, lc2, v12, v21, v11, v22,v1,v2, c12, tnalp;
                   4190:   double **dnewm,**doldm;
                   4191:   double *xp;
                   4192:   double *gp, *gm;
                   4193:   double **gradg, **trgradg;
                   4194:   double **mu;
1.164     brouard  4195:   double age, cov[NCOVMAX+1];
1.126     brouard  4196:   double std=2.0; /* Number of standard deviation wide of confidence ellipsoids */
                   4197:   int theta;
                   4198:   char fileresprob[FILENAMELENGTH];
                   4199:   char fileresprobcov[FILENAMELENGTH];
                   4200:   char fileresprobcor[FILENAMELENGTH];
                   4201:   double ***varpij;
                   4202: 
1.201   ! brouard  4203:   strcpy(fileresprob,"PROB_"); 
1.126     brouard  4204:   strcat(fileresprob,fileres);
                   4205:   if((ficresprob=fopen(fileresprob,"w"))==NULL) {
                   4206:     printf("Problem with resultfile: %s\n", fileresprob);
                   4207:     fprintf(ficlog,"Problem with resultfile: %s\n", fileresprob);
                   4208:   }
1.201   ! brouard  4209:   strcpy(fileresprobcov,"PROBCOV_"); 
1.126     brouard  4210:   strcat(fileresprobcov,fileres);
                   4211:   if((ficresprobcov=fopen(fileresprobcov,"w"))==NULL) {
                   4212:     printf("Problem with resultfile: %s\n", fileresprobcov);
                   4213:     fprintf(ficlog,"Problem with resultfile: %s\n", fileresprobcov);
                   4214:   }
1.201   ! brouard  4215:   strcpy(fileresprobcor,"PROBCOR_"); 
1.126     brouard  4216:   strcat(fileresprobcor,fileres);
                   4217:   if((ficresprobcor=fopen(fileresprobcor,"w"))==NULL) {
                   4218:     printf("Problem with resultfile: %s\n", fileresprobcor);
                   4219:     fprintf(ficlog,"Problem with resultfile: %s\n", fileresprobcor);
                   4220:   }
                   4221:   printf("Computing standard deviation of one-step probabilities: result on file '%s' \n",fileresprob);
                   4222:   fprintf(ficlog,"Computing standard deviation of one-step probabilities: result on file '%s' \n",fileresprob);
                   4223:   printf("Computing matrix of variance covariance of one-step probabilities: result on file '%s' \n",fileresprobcov);
                   4224:   fprintf(ficlog,"Computing matrix of variance covariance of one-step probabilities: result on file '%s' \n",fileresprobcov);
                   4225:   printf("and correlation matrix of one-step probabilities: result on file '%s' \n",fileresprobcor);
                   4226:   fprintf(ficlog,"and correlation matrix of one-step probabilities: result on file '%s' \n",fileresprobcor);
                   4227:   pstamp(ficresprob);
                   4228:   fprintf(ficresprob,"#One-step probabilities and stand. devi in ()\n");
                   4229:   fprintf(ficresprob,"# Age");
                   4230:   pstamp(ficresprobcov);
                   4231:   fprintf(ficresprobcov,"#One-step probabilities and covariance matrix\n");
                   4232:   fprintf(ficresprobcov,"# Age");
                   4233:   pstamp(ficresprobcor);
                   4234:   fprintf(ficresprobcor,"#One-step probabilities and correlation matrix\n");
                   4235:   fprintf(ficresprobcor,"# Age");
                   4236: 
                   4237: 
                   4238:   for(i=1; i<=nlstate;i++)
                   4239:     for(j=1; j<=(nlstate+ndeath);j++){
                   4240:       fprintf(ficresprob," p%1d-%1d (SE)",i,j);
                   4241:       fprintf(ficresprobcov," p%1d-%1d ",i,j);
                   4242:       fprintf(ficresprobcor," p%1d-%1d ",i,j);
                   4243:     }  
                   4244:  /* fprintf(ficresprob,"\n");
                   4245:   fprintf(ficresprobcov,"\n");
                   4246:   fprintf(ficresprobcor,"\n");
                   4247:  */
1.131     brouard  4248:   xp=vector(1,npar);
1.126     brouard  4249:   dnewm=matrix(1,(nlstate)*(nlstate+ndeath),1,npar);
                   4250:   doldm=matrix(1,(nlstate)*(nlstate+ndeath),1,(nlstate)*(nlstate+ndeath));
                   4251:   mu=matrix(1,(nlstate)*(nlstate+ndeath), (int) bage, (int)fage);
                   4252:   varpij=ma3x(1,nlstate*(nlstate+ndeath),1,nlstate*(nlstate+ndeath),(int) bage, (int) fage);
                   4253:   first=1;
                   4254:   fprintf(ficgp,"\n# Routine varprob");
                   4255:   fprintf(fichtm,"\n<li><h4> Computing and drawing one step probabilities with their confidence intervals</h4></li>\n");
                   4256:   fprintf(fichtm,"\n");
                   4257: 
1.200     brouard  4258:   fprintf(fichtm,"\n<li><h4> <a href=\"%s\">Matrix of variance-covariance of one-step probabilities (drawings)</a></h4> this page is important in order to visualize confidence intervals and especially correlation between disability and recovery, or more generally, way in and way back.</li>\n",optionfilehtmcov);
1.197     brouard  4259:   fprintf(fichtmcov,"Current page is file <a href=\"%s\">%s</a><br>\n\n<h4>Matrix of variance-covariance of pairs of step probabilities</h4>\n",optionfilehtmcov, optionfilehtmcov);
                   4260:   fprintf(fichtmcov,"\nEllipsoids of confidence centered on point (p<inf>ij</inf>, p<inf>kl</inf>) are estimated \
1.126     brouard  4261: and drawn. It helps understanding how is the covariance between two incidences.\
                   4262:  They are expressed in year<sup>-1</sup> in order to be less dependent of stepm.<br>\n");
                   4263:   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. \
                   4264: It can be understood this way: if pij and pkl where uncorrelated the (2x2) matrix of covariance \
                   4265: would have been (1/(var pij), 0 , 0, 1/(var pkl)), and the confidence interval would be 2 \
                   4266: standard deviations wide on each axis. <br>\
                   4267:  Now, if both incidences are correlated (usual case) we diagonalised the inverse of the covariance matrix\
                   4268:  and made the appropriate rotation to look at the uncorrelated principal directions.<br>\
                   4269: To be simple, these graphs help to understand the significativity of each parameter in relation to a second other one.<br> \n");
                   4270: 
                   4271:   cov[1]=1;
1.145     brouard  4272:   /* tj=cptcoveff; */
                   4273:   tj = (int) pow(2,cptcoveff);
1.126     brouard  4274:   if (cptcovn<1) {tj=1;ncodemax[1]=1;}
                   4275:   j1=0;
1.145     brouard  4276:   for(j1=1; j1<=tj;j1++){
                   4277:     /*for(i1=1; i1<=ncodemax[t];i1++){ */
                   4278:     /*j1++;*/
1.126     brouard  4279:       if  (cptcovn>0) {
                   4280:        fprintf(ficresprob, "\n#********** Variable "); 
1.198     brouard  4281:        for (z1=1; z1<=cptcoveff; z1++) fprintf(ficresprob, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
1.126     brouard  4282:        fprintf(ficresprob, "**********\n#\n");
                   4283:        fprintf(ficresprobcov, "\n#********** Variable "); 
1.198     brouard  4284:        for (z1=1; z1<=cptcoveff; z1++) fprintf(ficresprobcov, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
1.126     brouard  4285:        fprintf(ficresprobcov, "**********\n#\n");
                   4286:        
                   4287:        fprintf(ficgp, "\n#********** Variable "); 
1.198     brouard  4288:        for (z1=1; z1<=cptcoveff; z1++) fprintf(ficgp, " V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
1.126     brouard  4289:        fprintf(ficgp, "**********\n#\n");
                   4290:        
                   4291:        
                   4292:        fprintf(fichtmcov, "\n<hr  size=\"2\" color=\"#EC5E5E\">********** Variable "); 
1.198     brouard  4293:        for (z1=1; z1<=cptcoveff; z1++) fprintf(fichtm, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
1.126     brouard  4294:        fprintf(fichtmcov, "**********\n<hr size=\"2\" color=\"#EC5E5E\">");
                   4295:        
                   4296:        fprintf(ficresprobcor, "\n#********** Variable ");    
1.198     brouard  4297:        for (z1=1; z1<=cptcoveff; z1++) fprintf(ficresprobcor, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
1.126     brouard  4298:        fprintf(ficresprobcor, "**********\n#");    
                   4299:       }
                   4300:       
1.145     brouard  4301:       gradg=matrix(1,npar,1,(nlstate)*(nlstate+ndeath));
                   4302:       trgradg=matrix(1,(nlstate)*(nlstate+ndeath),1,npar);
                   4303:       gp=vector(1,(nlstate)*(nlstate+ndeath));
                   4304:       gm=vector(1,(nlstate)*(nlstate+ndeath));
1.126     brouard  4305:       for (age=bage; age<=fage; age ++){ 
                   4306:        cov[2]=age;
1.187     brouard  4307:        if(nagesqr==1)
                   4308:          cov[3]= age*age;
1.126     brouard  4309:        for (k=1; k<=cptcovn;k++) {
1.200     brouard  4310:          cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(j1,k)];
                   4311:          /*cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(j1,Tvar[k])];*//* j1 1 2 3 4
1.145     brouard  4312:                                                         * 1  1 1 1 1
                   4313:                                                         * 2  2 1 1 1
                   4314:                                                         * 3  1 2 1 1
                   4315:                                                         */
                   4316:          /* nbcode[1][1]=0 nbcode[1][2]=1;*/
1.126     brouard  4317:        }
1.186     brouard  4318:        /* for (k=1; k<=cptcovage;k++) cov[2+Tage[k]]=cov[2+Tage[k]]*cov[2]; */
1.200     brouard  4319:        for (k=1; k<=cptcovage;k++) cov[2+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(ij,k)]*cov[2];
1.126     brouard  4320:        for (k=1; k<=cptcovprod;k++)
1.200     brouard  4321:          cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,k)]*nbcode[Tvard[k][2]][codtabm(ij,k)];
1.126     brouard  4322:        
                   4323:     
                   4324:        for(theta=1; theta <=npar; theta++){
                   4325:          for(i=1; i<=npar; i++)
                   4326:            xp[i] = x[i] + (i==theta ?delti[theta]:(double)0);
                   4327:          
                   4328:          pmij(pmmij,cov,ncovmodel,xp,nlstate);
                   4329:          
                   4330:          k=0;
                   4331:          for(i=1; i<= (nlstate); i++){
                   4332:            for(j=1; j<=(nlstate+ndeath);j++){
                   4333:              k=k+1;
                   4334:              gp[k]=pmmij[i][j];
                   4335:            }
                   4336:          }
                   4337:          
                   4338:          for(i=1; i<=npar; i++)
                   4339:            xp[i] = x[i] - (i==theta ?delti[theta]:(double)0);
                   4340:     
                   4341:          pmij(pmmij,cov,ncovmodel,xp,nlstate);
                   4342:          k=0;
                   4343:          for(i=1; i<=(nlstate); i++){
                   4344:            for(j=1; j<=(nlstate+ndeath);j++){
                   4345:              k=k+1;
                   4346:              gm[k]=pmmij[i][j];
                   4347:            }
                   4348:          }
                   4349:      
                   4350:          for(i=1; i<= (nlstate)*(nlstate+ndeath); i++) 
                   4351:            gradg[theta][i]=(gp[i]-gm[i])/(double)2./delti[theta];  
                   4352:        }
                   4353: 
                   4354:        for(j=1; j<=(nlstate)*(nlstate+ndeath);j++)
                   4355:          for(theta=1; theta <=npar; theta++)
                   4356:            trgradg[j][theta]=gradg[theta][j];
                   4357:        
                   4358:        matprod2(dnewm,trgradg,1,(nlstate)*(nlstate+ndeath),1,npar,1,npar,matcov); 
                   4359:        matprod2(doldm,dnewm,1,(nlstate)*(nlstate+ndeath),1,npar,1,(nlstate)*(nlstate+ndeath),gradg);
                   4360: 
                   4361:        pmij(pmmij,cov,ncovmodel,x,nlstate);
                   4362:        
                   4363:        k=0;
                   4364:        for(i=1; i<=(nlstate); i++){
                   4365:          for(j=1; j<=(nlstate+ndeath);j++){
                   4366:            k=k+1;
                   4367:            mu[k][(int) age]=pmmij[i][j];
                   4368:          }
                   4369:        }
                   4370:        for(i=1;i<=(nlstate)*(nlstate+ndeath);i++)
                   4371:          for(j=1;j<=(nlstate)*(nlstate+ndeath);j++)
                   4372:            varpij[i][j][(int)age] = doldm[i][j];
                   4373: 
                   4374:        /*printf("\n%d ",(int)age);
                   4375:          for (i=1; i<=(nlstate)*(nlstate+ndeath);i++){
                   4376:          printf("%e [%e ;%e] ",gm[i],gm[i]-2*sqrt(doldm[i][i]),gm[i]+2*sqrt(doldm[i][i]));
                   4377:          fprintf(ficlog,"%e [%e ;%e] ",gm[i],gm[i]-2*sqrt(doldm[i][i]),gm[i]+2*sqrt(doldm[i][i]));
                   4378:          }*/
                   4379: 
                   4380:        fprintf(ficresprob,"\n%d ",(int)age);
                   4381:        fprintf(ficresprobcov,"\n%d ",(int)age);
                   4382:        fprintf(ficresprobcor,"\n%d ",(int)age);
                   4383: 
                   4384:        for (i=1; i<=(nlstate)*(nlstate+ndeath);i++)
                   4385:          fprintf(ficresprob,"%11.3e (%11.3e) ",mu[i][(int) age],sqrt(varpij[i][i][(int)age]));
                   4386:        for (i=1; i<=(nlstate)*(nlstate+ndeath);i++){
                   4387:          fprintf(ficresprobcov,"%11.3e ",mu[i][(int) age]);
                   4388:          fprintf(ficresprobcor,"%11.3e ",mu[i][(int) age]);
                   4389:        }
                   4390:        i=0;
                   4391:        for (k=1; k<=(nlstate);k++){
                   4392:          for (l=1; l<=(nlstate+ndeath);l++){ 
1.145     brouard  4393:            i++;
1.126     brouard  4394:            fprintf(ficresprobcov,"\n%d %d-%d",(int)age,k,l);
                   4395:            fprintf(ficresprobcor,"\n%d %d-%d",(int)age,k,l);
                   4396:            for (j=1; j<=i;j++){
1.145     brouard  4397:              /* printf(" k=%d l=%d i=%d j=%d\n",k,l,i,j);fflush(stdout); */
1.126     brouard  4398:              fprintf(ficresprobcov," %11.3e",varpij[i][j][(int)age]);
                   4399:              fprintf(ficresprobcor," %11.3e",varpij[i][j][(int) age]/sqrt(varpij[i][i][(int) age])/sqrt(varpij[j][j][(int)age]));
                   4400:            }
                   4401:          }
                   4402:        }/* end of loop for state */
                   4403:       } /* end of loop for age */
1.145     brouard  4404:       free_vector(gp,1,(nlstate+ndeath)*(nlstate+ndeath));
                   4405:       free_vector(gm,1,(nlstate+ndeath)*(nlstate+ndeath));
                   4406:       free_matrix(trgradg,1,(nlstate+ndeath)*(nlstate+ndeath),1,npar);
                   4407:       free_matrix(gradg,1,(nlstate+ndeath)*(nlstate+ndeath),1,npar);
                   4408:       
1.126     brouard  4409:       /* Confidence intervalle of pij  */
                   4410:       /*
1.131     brouard  4411:        fprintf(ficgp,"\nunset parametric;unset label");
1.126     brouard  4412:        fprintf(ficgp,"\nset log y;unset log x; set xlabel \"Age\";set ylabel \"probability (year-1)\"");
                   4413:        fprintf(ficgp,"\nset ter png small\nset size 0.65,0.65");
                   4414:        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);
                   4415:        fprintf(fichtm,"\n<br><img src=\"pijgr%s.png\"> ",optionfilefiname);
                   4416:        fprintf(ficgp,"\nset out \"pijgr%s.png\"",optionfilefiname);
                   4417:        fprintf(ficgp,"\nplot \"%s\" every :::%d::%d u 1:2 \"\%%lf",k1,k2,xfilevarprob);
                   4418:       */
                   4419: 
                   4420:       /* Drawing ellipsoids of confidence of two variables p(k1-l1,k2-l2)*/
1.145     brouard  4421:       first1=1;first2=2;
1.126     brouard  4422:       for (k2=1; k2<=(nlstate);k2++){
                   4423:        for (l2=1; l2<=(nlstate+ndeath);l2++){ 
                   4424:          if(l2==k2) continue;
                   4425:          j=(k2-1)*(nlstate+ndeath)+l2;
                   4426:          for (k1=1; k1<=(nlstate);k1++){
                   4427:            for (l1=1; l1<=(nlstate+ndeath);l1++){ 
                   4428:              if(l1==k1) continue;
                   4429:              i=(k1-1)*(nlstate+ndeath)+l1;
                   4430:              if(i<=j) continue;
                   4431:              for (age=bage; age<=fage; age ++){ 
                   4432:                if ((int)age %5==0){
                   4433:                  v1=varpij[i][i][(int)age]/stepm*YEARM/stepm*YEARM;
                   4434:                  v2=varpij[j][j][(int)age]/stepm*YEARM/stepm*YEARM;
                   4435:                  cv12=varpij[i][j][(int)age]/stepm*YEARM/stepm*YEARM;
                   4436:                  mu1=mu[i][(int) age]/stepm*YEARM ;
                   4437:                  mu2=mu[j][(int) age]/stepm*YEARM;
                   4438:                  c12=cv12/sqrt(v1*v2);
                   4439:                  /* Computing eigen value of matrix of covariance */
                   4440:                  lc1=((v1+v2)+sqrt((v1+v2)*(v1+v2) - 4*(v1*v2-cv12*cv12)))/2.;
                   4441:                  lc2=((v1+v2)-sqrt((v1+v2)*(v1+v2) - 4*(v1*v2-cv12*cv12)))/2.;
1.135     brouard  4442:                  if ((lc2 <0) || (lc1 <0) ){
1.145     brouard  4443:                    if(first2==1){
                   4444:                      first1=0;
                   4445:                    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);
                   4446:                    }
                   4447:                    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);
                   4448:                    /* lc1=fabs(lc1); */ /* If we want to have them positive */
                   4449:                    /* lc2=fabs(lc2); */
1.135     brouard  4450:                  }
                   4451: 
1.126     brouard  4452:                  /* Eigen vectors */
                   4453:                  v11=(1./sqrt(1+(v1-lc1)*(v1-lc1)/cv12/cv12));
                   4454:                  /*v21=sqrt(1.-v11*v11); *//* error */
                   4455:                  v21=(lc1-v1)/cv12*v11;
                   4456:                  v12=-v21;
                   4457:                  v22=v11;
                   4458:                  tnalp=v21/v11;
                   4459:                  if(first1==1){
                   4460:                    first1=0;
                   4461:                    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);
                   4462:                  }
                   4463:                  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);
                   4464:                  /*printf(fignu*/
                   4465:                  /* mu1+ v11*lc1*cost + v12*lc2*sin(t) */
                   4466:                  /* mu2+ v21*lc1*cost + v22*lc2*sin(t) */
                   4467:                  if(first==1){
                   4468:                    first=0;
1.200     brouard  4469:                    fprintf(ficgp,"\n# Ellipsoids of confidence\n#\n");
1.126     brouard  4470:                    fprintf(ficgp,"\nset parametric;unset label");
                   4471:                    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.199     brouard  4472:                    fprintf(ficgp,"\nset ter svg size 640, 480");
1.126     brouard  4473:                    fprintf(fichtmcov,"\n<br>Ellipsoids of confidence cov(p%1d%1d,p%1d%1d) expressed in year<sup>-1</sup>\
1.201   ! brouard  4474:  :<a href=\"%s_%d%1d%1d-%1d%1d.svg\">\
        !          4475: %s_%d%1d%1d-%1d%1d.svg</A>, ",k1,l1,k2,l2,\
        !          4476:                            subdirf2(optionfilefiname,"VARPIJGR_"), j1,k1,l1,k2,l2,\
        !          4477:                            subdirf2(optionfilefiname,"VARPIJGR_"), j1,k1,l1,k2,l2);
        !          4478:                    fprintf(fichtmcov,"\n<br><img src=\"%s_%d%1d%1d-%1d%1d.svg\"> ",subdirf2(optionfilefiname,"VARPIJGR_"), j1,k1,l1,k2,l2);
1.126     brouard  4479:                    fprintf(fichtmcov,"\n<br> Correlation at age %d (%.3f),",(int) age, c12);
1.201   ! brouard  4480:                    fprintf(ficgp,"\nset out \"%s_%d%1d%1d-%1d%1d.svg\"",subdirf2(optionfilefiname,"VARPIJGR_"), j1,k1,l1,k2,l2);
1.126     brouard  4481:                    fprintf(ficgp,"\nset label \"%d\" at %11.3e,%11.3e center",(int) age, mu1,mu2);
                   4482:                    fprintf(ficgp,"\n# Age %d, p%1d%1d - p%1d%1d",(int) age, k1,l1,k2,l2);
                   4483:                    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",\
                   4484:                            mu1,std,v11,sqrt(lc1),v12,sqrt(lc2),\
                   4485:                            mu2,std,v21,sqrt(lc1),v22,sqrt(lc2));
                   4486:                  }else{
                   4487:                    first=0;
                   4488:                    fprintf(fichtmcov," %d (%.3f),",(int) age, c12);
                   4489:                    fprintf(ficgp,"\n# Age %d, p%1d%1d - p%1d%1d",(int) age, k1,l1,k2,l2);
                   4490:                    fprintf(ficgp,"\nset label \"%d\" at %11.3e,%11.3e center",(int) age, mu1,mu2);
                   4491:                    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",\
                   4492:                            mu1,std,v11,sqrt(lc1),v12,sqrt(lc2),\
                   4493:                            mu2,std,v21,sqrt(lc1),v22,sqrt(lc2));
                   4494:                  }/* if first */
                   4495:                } /* age mod 5 */
                   4496:              } /* end loop age */
1.201   ! brouard  4497:              fprintf(ficgp,"\nset out;\nset out \"%s_%d%1d%1d-%1d%1d.svg\";replot;set out;",subdirf2(optionfilefiname,"VARPIJGR_"), j1,k1,l1,k2,l2);
1.126     brouard  4498:              first=1;
                   4499:            } /*l12 */
                   4500:          } /* k12 */
                   4501:        } /*l1 */
                   4502:       }/* k1 */
1.169     brouard  4503:       /* } */ /* loop covariates */
1.126     brouard  4504:   }
                   4505:   free_ma3x(varpij,1,nlstate,1,nlstate+ndeath,(int) bage, (int)fage);
                   4506:   free_matrix(mu,1,(nlstate+ndeath)*(nlstate+ndeath),(int) bage, (int)fage);
                   4507:   free_matrix(doldm,1,(nlstate)*(nlstate+ndeath),1,(nlstate)*(nlstate+ndeath));
                   4508:   free_matrix(dnewm,1,(nlstate)*(nlstate+ndeath),1,npar);
                   4509:   free_vector(xp,1,npar);
                   4510:   fclose(ficresprob);
                   4511:   fclose(ficresprobcov);
                   4512:   fclose(ficresprobcor);
                   4513:   fflush(ficgp);
                   4514:   fflush(fichtmcov);
                   4515: }
                   4516: 
                   4517: 
                   4518: /******************* Printing html file ***********/
1.201   ! brouard  4519: void printinghtml(char fileresu[], char title[], char datafile[], int firstpass, \
1.126     brouard  4520:                  int lastpass, int stepm, int weightopt, char model[],\
                   4521:                  int imx,int jmin, int jmax, double jmeanint,char rfileres[],\
                   4522:                  int popforecast, int estepm ,\
                   4523:                  double jprev1, double mprev1,double anprev1, \
                   4524:                  double jprev2, double mprev2,double anprev2){
                   4525:   int jj1, k1, i1, cpt;
                   4526: 
                   4527:    fprintf(fichtm,"<ul><li><a href='#firstorder'>Result files (first order: no variance)</a>\n \
                   4528:    <li><a href='#secondorder'>Result files (second order (variance)</a>\n \
                   4529: </ul>");
                   4530:    fprintf(fichtm,"<ul><li><h4><a name='firstorder'>Result files (first order: no variance)</a></h4>\n \
                   4531:  - Observed prevalence in each state (during the period defined between %.lf/%.lf/%.lf and %.lf/%.lf/%.lf): <a href=\"%s\">%s</a> <br>\n ",
1.201   ! brouard  4532:           jprev1, mprev1,anprev1,jprev2, mprev2,anprev2,subdirf2(fileresu,"P_"),subdirf2(fileresu,"P_"));
1.126     brouard  4533:    fprintf(fichtm,"\
                   4534:  - Estimated transition probabilities over %d (stepm) months: <a href=\"%s\">%s</a><br>\n ",
1.201   ! brouard  4535:           stepm,subdirf2(fileresu,"PIJ_"),subdirf2(fileresu,"PIJ_"));
1.126     brouard  4536:    fprintf(fichtm,"\
                   4537:  - Period (stable) prevalence in each health state: <a href=\"%s\">%s</a> <br>\n",
1.201   ! brouard  4538:           subdirf2(fileresu,"PL_"),subdirf2(fileresu,"PL_"));
1.126     brouard  4539:    fprintf(fichtm,"\
1.128     brouard  4540:  - (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  4541:    <a href=\"%s\">%s</a> <br>\n",
1.201   ! brouard  4542:           estepm,subdirf2(fileresu,"E_"),subdirf2(fileresu,"E_"));
1.126     brouard  4543:    fprintf(fichtm,"\
                   4544:  - Population projections by age and states: \
1.201   ! brouard  4545:    <a href=\"%s\">%s</a> <br>\n</li>", subdirf2(fileresu,"F_"),subdirf2(fileresu,"F_"));
1.126     brouard  4546: 
                   4547: fprintf(fichtm," \n<ul><li><b>Graphs</b></li><p>");
                   4548: 
1.145     brouard  4549:  m=pow(2,cptcoveff);
1.126     brouard  4550:  if (cptcovn < 1) {m=1;ncodemax[1]=1;}
                   4551: 
                   4552:  jj1=0;
                   4553:  for(k1=1; k1<=m;k1++){
1.192     brouard  4554:    /* for(i1=1; i1<=ncodemax[k1];i1++){ */
1.126     brouard  4555:      jj1++;
                   4556:      if (cptcovn > 0) {
                   4557:        fprintf(fichtm,"<hr  size=\"2\" color=\"#EC5E5E\">************ Results for covariates");
1.192     brouard  4558:        for (cpt=1; cpt<=cptcoveff;cpt++){ 
1.198     brouard  4559:         fprintf(fichtm," V%d=%d ",Tvaraff[cpt],nbcode[Tvaraff[cpt]][codtabm(jj1,cpt)]);
                   4560:         printf(" V%d=%d ",Tvaraff[cpt],nbcode[Tvaraff[cpt]][codtabm(jj1,cpt)]);fflush(stdout);
1.192     brouard  4561:        }
1.126     brouard  4562:        fprintf(fichtm," ************\n<hr size=\"2\" color=\"#EC5E5E\">");
                   4563:      }
1.201   ! brouard  4564:      /* aij, bij */
        !          4565:      fprintf(fichtm,"<br>- Logit model, for example: logit(pij)=log(pij/pii)= aij+ bij age + V1 age + etc. as a function of age: <a href=\"%s_%d-1.svg\">%s_%d-1.svg</a><br> \
        !          4566: <img src=\"%s_%d-1.svg\">",subdirf2(optionfilefiname,"PE_"),jj1,subdirf2(optionfilefiname,"PE_"),jj1,subdirf2(optionfilefiname,"PE_"),jj1);
1.126     brouard  4567:      /* Pij */
1.201   ! brouard  4568:      fprintf(fichtm,"<br>\n- Pij or Conditional probabilities to be observed in state j being in state i, %d (stepm) months before: <a href=\"%s_%d-2.svg\">%s_%d-2.svg</a><br> \
        !          4569: <img src=\"%s_%d-2.svg\">",stepm,subdirf2(optionfilefiname,"PE_"),jj1,subdirf2(optionfilefiname,"PE_"),jj1,subdirf2(optionfilefiname,"PE_"),jj1);     
1.126     brouard  4570:      /* Quasi-incidences */
1.201   ! brouard  4571:      fprintf(fichtm,"<br>\n- Iij or Conditional probabilities to be observed in state j being in state i %d (stepm) months\
        !          4572:  before but expressed in per year i.e. quasi incidences if stepm is small and probabilities too,\
        !          4573:  incidence (rates) are the limit when h tends to zero of the ratio of the probability hPij \
        !          4574: divided by h: hPij/h : <a href=\"%s_%d-3.svg\">%s_%d-3.svg</a><br> \
        !          4575: <img src=\"%s_%d-3.svg\">",stepm,subdirf2(optionfilefiname,"PE_"),jj1,subdirf2(optionfilefiname,"PE_"),jj1,subdirf2(optionfilefiname,"PE_"),jj1); 
        !          4576:      /* Survival functions (period) in state j */
        !          4577:      for(cpt=1; cpt<=nlstate;cpt++){
        !          4578:        fprintf(fichtm,"<br>\n- Survival functions in state %d. Or probability to survive in state %d being in state (1 to %d) at different ages. <a href=\"%s%d_%d.svg\">%s%d_%d.svg</a><br> \
        !          4579: <img src=\"%s_%d-%d.svg\">", cpt, cpt, nlstate, subdirf2(optionfilefiname,"LIJ_"),cpt,jj1,subdirf2(optionfilefiname,"LIJ_"),cpt,jj1,subdirf2(optionfilefiname,"LIJ_"),cpt,jj1);
        !          4580:      }
        !          4581:      /* State specific survival functions (period) */
        !          4582:      for(cpt=1; cpt<=nlstate;cpt++){
        !          4583:        fprintf(fichtm,"<br>\n- Survival functions from state %d in any different live states and total.\
        !          4584:  Or probability to survive in various states (1 to %d) being in state %d at different ages.\
        !          4585:  <a href=\"%s%d_%d.svg\">%s%d_%d.svg</a><br> <img src=\"%s_%d-%d.svg\">", cpt, nlstate, cpt, subdirf2(optionfilefiname,"LIJT_"),cpt,jj1,subdirf2(optionfilefiname,"LIJT_"),cpt,jj1,subdirf2(optionfilefiname,"LIJT_"),cpt,jj1);
        !          4586:      }
        !          4587:      /* Period (stable) prevalence in each health state */
        !          4588:      for(cpt=1; cpt<=nlstate;cpt++){
        !          4589:        fprintf(fichtm,"<br>\n- 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.svg\">%s%d_%d.svg</a><br> \
        !          4590: <img src=\"%s_%d-%d.svg\">", cpt, cpt, nlstate, subdirf2(optionfilefiname,"P_"),cpt,jj1,subdirf2(optionfilefiname,"P_"),cpt,jj1,subdirf2(optionfilefiname,"P_"),cpt,jj1);
        !          4591:      }
1.126     brouard  4592:      for(cpt=1; cpt<=nlstate;cpt++) {
1.201   ! brouard  4593:        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) (or area under each survival functions): <a href=\"%s%d%d.svg\">%s%d%d.svg</a> <br> \
        !          4594: <img src=\"%s_%d%d.svg\">",cpt,nlstate,subdirf2(optionfilefiname,"EXP_"),cpt,jj1,subdirf2(optionfilefiname,"EXP_"),cpt,jj1,subdirf2(optionfilefiname,"EXP_"),cpt,jj1);
1.126     brouard  4595:      }
1.192     brouard  4596:    /* } /\* end i1 *\/ */
1.126     brouard  4597:  }/* End k1 */
                   4598:  fprintf(fichtm,"</ul>");
                   4599: 
                   4600:  fprintf(fichtm,"\
                   4601: \n<br><li><h4> <a name='secondorder'>Result files (second order: variances)</a></h4>\n\
1.193     brouard  4602:  - Parameter file with estimated parameters and covariance matrix: <a href=\"%s\">%s</a> <br> \
1.197     brouard  4603:  - 95%% confidence intervals and Wald tests of the estimated parameters are in the log file.<br> \
                   4604: But because parameters are usually highly correlated (a higher incidence of disability \
                   4605: and a higher incidence of recovery can give very close observed transition) it might \
                   4606: be very useful to look not only at linear confidence intervals estimated from the \
                   4607: variances but at the covariance matrix. And instead of looking at the estimated coefficients \
                   4608: (parameters) of the logistic regression, it might be more meaningful to visualize the \
                   4609: covariance matrix of the one-step probabilities. \
                   4610: See page 'Matrix of variance-covariance of one-step probabilities' below. \n", rfileres,rfileres);
1.126     brouard  4611: 
1.193     brouard  4612:  fprintf(fichtm," - Standard deviation of one-step probabilities: <a href=\"%s\">%s</a> <br>\n",
1.201   ! brouard  4613:         subdirf2(fileresu,"PROB_"),subdirf2(fileresu,"PROB_"));
1.126     brouard  4614:  fprintf(fichtm,"\
                   4615:  - Variance-covariance of one-step probabilities: <a href=\"%s\">%s</a> <br>\n",
1.201   ! brouard  4616:         subdirf2(fileresu,"PROBCOV_"),subdirf2(fileresu,"PROBCOV_"));
1.126     brouard  4617: 
                   4618:  fprintf(fichtm,"\
                   4619:  - Correlation matrix of one-step probabilities: <a href=\"%s\">%s</a> <br>\n",
1.201   ! brouard  4620:         subdirf2(fileresu,"PROBCOR_"),subdirf2(fileresu,"PROBCOR_"));
1.126     brouard  4621:  fprintf(fichtm,"\
                   4622:  - 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): \
                   4623:    <a href=\"%s\">%s</a> <br>\n</li>",
1.201   ! brouard  4624:           estepm,subdirf2(fileresu,"CVE_"),subdirf2(fileresu,"CVE_"));
1.126     brouard  4625:  fprintf(fichtm,"\
                   4626:  - (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): \
                   4627:    <a href=\"%s\">%s</a> <br>\n</li>",
1.201   ! brouard  4628:           estepm,subdirf2(fileresu,"STDE_"),subdirf2(fileresu,"STDE_"));
1.126     brouard  4629:  fprintf(fichtm,"\
1.128     brouard  4630:  - 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.201   ! brouard  4631:         estepm, subdirf2(fileresu,"V_"),subdirf2(fileresu,"V_"));
1.126     brouard  4632:  fprintf(fichtm,"\
1.128     brouard  4633:  - 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",
1.201   ! brouard  4634:         estepm, subdirf2(fileresu,"T_"),subdirf2(fileresu,"T_"));
1.126     brouard  4635:  fprintf(fichtm,"\
                   4636:  - Standard deviation of period (stable) prevalences: <a href=\"%s\">%s</a> <br>\n",\
1.201   ! brouard  4637:         subdirf2(fileresu,"VPL_"),subdirf2(fileresu,"VPL_"));
1.126     brouard  4638: 
                   4639: /*  if(popforecast==1) fprintf(fichtm,"\n */
                   4640: /*  - Prevalences forecasting: <a href=\"f%s\">f%s</a> <br>\n */
                   4641: /*  - Population forecasting (if popforecast=1): <a href=\"pop%s\">pop%s</a> <br>\n */
                   4642: /*     <br>",fileres,fileres,fileres,fileres); */
                   4643: /*  else  */
                   4644: /*    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); */
                   4645:  fflush(fichtm);
                   4646:  fprintf(fichtm," <ul><li><b>Graphs</b></li><p>");
                   4647: 
1.145     brouard  4648:  m=pow(2,cptcoveff);
1.126     brouard  4649:  if (cptcovn < 1) {m=1;ncodemax[1]=1;}
                   4650: 
                   4651:  jj1=0;
                   4652:  for(k1=1; k1<=m;k1++){
1.192     brouard  4653:    /* for(i1=1; i1<=ncodemax[k1];i1++){ */
1.126     brouard  4654:      jj1++;
                   4655:      if (cptcovn > 0) {
                   4656:        fprintf(fichtm,"<hr  size=\"2\" color=\"#EC5E5E\">************ Results for covariates");
                   4657:        for (cpt=1; cpt<=cptcoveff;cpt++) 
1.198     brouard  4658:         fprintf(fichtm," V%d=%d ",Tvaraff[cpt],nbcode[Tvaraff[cpt]][codtabm(jj1,cpt)]);
1.126     brouard  4659:        fprintf(fichtm," ************\n<hr size=\"2\" color=\"#EC5E5E\">");
                   4660:      }
                   4661:      for(cpt=1; cpt<=nlstate;cpt++) {
                   4662:        fprintf(fichtm,"<br>- Observed (cross-sectional) and period (incidence based) \
1.199     brouard  4663: prevalence (with 95%% confidence interval) in state (%d): %s%d_%d.svg <br>\
1.201   ! brouard  4664: <img src=\"%s_%d-%d.svg\">",cpt,subdirf2(optionfilefiname,"V_"),cpt,jj1,subdirf2(optionfilefiname,"V_"),cpt,jj1);  
1.126     brouard  4665:      }
                   4666:      fprintf(fichtm,"\n<br>- Total life expectancy by age and \
1.128     brouard  4667: health expectancies in states (1) and (2). If popbased=1 the smooth (due to the model) \
                   4668: true period expectancies (those weighted with period prevalences are also\
                   4669:  drawn in addition to the population based expectancies computed using\
1.201   ! brouard  4670:  observed and cahotic prevalences: %s_%d.svg<br>\
        !          4671: <img src=\"%s_%d.svg\">",subdirf2(optionfilefiname,"E_"),jj1,subdirf2(optionfilefiname,"E_"),jj1);
1.192     brouard  4672:    /* } /\* end i1 *\/ */
1.126     brouard  4673:  }/* End k1 */
                   4674:  fprintf(fichtm,"</ul>");
                   4675:  fflush(fichtm);
                   4676: }
                   4677: 
                   4678: /******************* Gnuplot file **************/
1.201   ! brouard  4679: void printinggnuplot(char fileresu[], char optionfilefiname[], double ageminpar, double agemaxpar, double fage , char pathc[], double p[]){
1.126     brouard  4680: 
                   4681:   char dirfileres[132],optfileres[132];
1.164     brouard  4682:   int cpt=0,k1=0,i=0,k=0,j=0,jk=0,k2=0,k3=0,ij=0,l=0;
1.130     brouard  4683:   int ng=0;
1.201   ! brouard  4684:   int vpopbased;
1.126     brouard  4685: /*   if((ficgp=fopen(optionfilegnuplot,"a"))==NULL) { */
                   4686: /*     printf("Problem with file %s",optionfilegnuplot); */
                   4687: /*     fprintf(ficlog,"Problem with file %s",optionfilegnuplot); */
                   4688: /*   } */
                   4689: 
                   4690:   /*#ifdef windows */
                   4691:   fprintf(ficgp,"cd \"%s\" \n",pathc);
                   4692:     /*#endif */
                   4693:   m=pow(2,cptcoveff);
                   4694: 
                   4695:   strcpy(dirfileres,optionfilefiname);
                   4696:   strcpy(optfileres,"vpl");
                   4697:  /* 1eme*/
1.201   ! brouard  4698:   fprintf(ficgp,"\n# 1st: Period (stable) prevalence with CI: 'VPL_' files\n");
1.126     brouard  4699:   for (cpt=1; cpt<= nlstate ; cpt ++) {
1.145     brouard  4700:     for (k1=1; k1<= m ; k1 ++) { /* plot [100000000000000000000:-100000000000000000000] "mysbiaspar/vplrmysbiaspar.txt to check */
1.201   ! brouard  4701:      fprintf(ficgp,"\nset out \"%s_%d-%d.svg\" \n",subdirf2(optionfilefiname,"V_"),cpt,k1);
        !          4702:      fprintf(ficgp,"\n#set out \"V_%s_%d-%d.svg\" \n",optionfilefiname,cpt,k1);
1.126     brouard  4703:      fprintf(ficgp,"set xlabel \"Age\" \n\
                   4704: set ylabel \"Probability\" \n\
1.199     brouard  4705: set ter svg size 640, 480\n\
1.201   ! brouard  4706: plot [%.f:%.f] \"%s\" every :::%d::%d u 1:2 \"%%lf",ageminpar,fage,subdirf2(fileresu,"VPL_"),k1-1,k1-1);
1.126     brouard  4707: 
                   4708:      for (i=1; i<= nlstate ; i ++) {
1.170     brouard  4709:        if (i==cpt) fprintf(ficgp," %%lf (%%lf)");
                   4710:        else        fprintf(ficgp," %%*lf (%%*lf)");
1.126     brouard  4711:      }
1.201   ! brouard  4712:      fprintf(ficgp,"\" t\"Period (stable) prevalence\" w l lt 0,\"%s\" every :::%d::%d u 1:($2+1.96*$3) \"%%lf",subdirf2(fileresu,"VPL_"),k1-1,k1-1);
1.126     brouard  4713:      for (i=1; i<= nlstate ; i ++) {
1.170     brouard  4714:        if (i==cpt) fprintf(ficgp," %%lf (%%lf)");
                   4715:        else fprintf(ficgp," %%*lf (%%*lf)");
1.126     brouard  4716:      } 
1.201   ! brouard  4717:      fprintf(ficgp,"\" t\"95%% CI\" w l lt 1,\"%s\" every :::%d::%d u 1:($2-1.96*$3) \"%%lf",subdirf2(fileresu,"VPL_"),k1-1,k1-1); 
1.126     brouard  4718:      for (i=1; i<= nlstate ; i ++) {
1.170     brouard  4719:        if (i==cpt) fprintf(ficgp," %%lf (%%lf)");
                   4720:        else fprintf(ficgp," %%*lf (%%*lf)");
1.126     brouard  4721:      }  
1.201   ! brouard  4722:      fprintf(ficgp,"\" t\"\" w l lt 1,\"%s\" every :::%d::%d u 1:($%d) t\"Observed prevalence \" w l lt 2",subdirf2(fileresu,"P_"),k1-1,k1-1,2+4*(cpt-1));
        !          4723:      fprintf(ficgp,"\nset out \n");
        !          4724:     } /* k1 */
        !          4725:   } /* cpt */
1.126     brouard  4726:   /*2 eme*/
1.153     brouard  4727:   fprintf(ficgp,"\n# 2nd: Total life expectancy with CI: 't' files\n");
1.126     brouard  4728:   for (k1=1; k1<= m ; k1 ++) { 
1.201   ! brouard  4729:     fprintf(ficgp,"\nset out \"%s_%d.svg\" \n",subdirf2(optionfilefiname,"E_"),k1);
        !          4730:     for(vpopbased=0; vpopbased <= popbased; vpopbased++){ /* Done for vpopbased=0 and vpopbased=1 if popbased==1*/
        !          4731:       if(vpopbased==0)
        !          4732:        fprintf(ficgp,"set ylabel \"Years\" \nset ter svg size 640, 480\nplot [%.f:%.f] ",ageminpar,fage);
        !          4733:       else
        !          4734:        fprintf(ficgp,"\nreplot ");
        !          4735:       for (i=1; i<= nlstate+1 ; i ++) {
        !          4736:        k=2*i;
        !          4737:        fprintf(ficgp,"\"%s\" every :::%d::%d u 1:($2==%d && $4!=0 ?$4 : 1/0) \"%%lf %%lf %%lf",subdirf2(fileresu,"T_"),k1-1,k1-1, vpopbased);
        !          4738:        for (j=1; j<= nlstate+1 ; j ++) {
        !          4739:          if (j==i) fprintf(ficgp," %%lf (%%lf)");
        !          4740:          else fprintf(ficgp," %%*lf (%%*lf)");
        !          4741:        }   
        !          4742:        if (i== 1) fprintf(ficgp,"\" t\"TLE\" w l lt %d, \\\n",i);
        !          4743:        else fprintf(ficgp,"\" t\"LE in state (%d)\" w l lt %d, \\\n",i-1,i+1);
        !          4744:        fprintf(ficgp,"\"%s\" every :::%d::%d u 1:($2==%d && $4!=0 ? $4-$5*2 : 1/0) \"%%lf %%lf %%lf",subdirf2(fileresu,"T_"),k1-1,k1-1,vpopbased);
        !          4745:        for (j=1; j<= nlstate+1 ; j ++) {
        !          4746:          if (j==i) fprintf(ficgp," %%lf (%%lf)");
        !          4747:          else fprintf(ficgp," %%*lf (%%*lf)");
        !          4748:        }   
        !          4749:        fprintf(ficgp,"\" t\"\" w l lt 0,");
        !          4750:        fprintf(ficgp,"\"%s\" every :::%d::%d u 1:($2==%d && $4!=0 ? $4+$5*2 : 1/0) \"%%lf %%lf %%lf",subdirf2(fileresu,"T_"),k1-1,k1-1,vpopbased);
        !          4751:        for (j=1; j<= nlstate+1 ; j ++) {
        !          4752:          if (j==i) fprintf(ficgp," %%lf (%%lf)");
        !          4753:          else fprintf(ficgp," %%*lf (%%*lf)");
        !          4754:        }   
        !          4755:        if (i== (nlstate+1)) fprintf(ficgp,"\" t\"\" w l lt 0");
        !          4756:        else fprintf(ficgp,"\" t\"\" w l lt 0,\\\n");
        !          4757:       } /* state */
        !          4758:     } /* vpopbased */
        !          4759:     fprintf(ficgp,"\nset out;set out \"%s_%d.svg\"; replot; set out; \n",subdirf2(optionfilefiname,"E_"),k1); /* Buggy gnuplot */
        !          4760:   } /* k1 */
1.126     brouard  4761:   /*3eme*/
                   4762:   
                   4763:   for (k1=1; k1<= m ; k1 ++) { 
                   4764:     for (cpt=1; cpt<= nlstate ; cpt ++) {
                   4765:       /*       k=2+nlstate*(2*cpt-2); */
                   4766:       k=2+(nlstate+1)*(cpt-1);
1.201   ! brouard  4767:       fprintf(ficgp,"\nset out \"%s_%d%d.svg\" \n",subdirf2(optionfilefiname,"EXP_"),cpt,k1);
1.199     brouard  4768:       fprintf(ficgp,"set ter svg size 640, 480\n\
1.201   ! brouard  4769: plot [%.f:%.f] \"%s\" every :::%d::%d u 1:%d t \"e%d1\" w l",ageminpar,fage,subdirf2(fileresu,"E_"),k1-1,k1-1,k,cpt);
1.126     brouard  4770:       /*fprintf(ficgp,",\"e%s\" every :::%d::%d u 1:($%d-2*$%d) \"\%%lf ",fileres,k1-1,k1-1,k,k+1);
                   4771:        for (i=1; i<= nlstate*2 ; i ++) fprintf(ficgp,"\%%lf (\%%lf) ");
                   4772:        fprintf(ficgp,"\" t \"e%d1\" w l",cpt);
                   4773:        fprintf(ficgp,",\"e%s\" every :::%d::%d u 1:($%d+2*$%d) \"\%%lf ",fileres,k1-1,k1-1,k,k+1);
                   4774:        for (i=1; i<= nlstate*2 ; i ++) fprintf(ficgp,"\%%lf (\%%lf) ");
                   4775:        fprintf(ficgp,"\" t \"e%d1\" w l",cpt);
                   4776:        
                   4777:       */
                   4778:       for (i=1; i< nlstate ; i ++) {
1.201   ! brouard  4779:        fprintf(ficgp," ,\"%s\" every :::%d::%d u 1:%d t \"e%d%d\" w l",subdirf2(fileresu,"E_"),k1-1,k1-1,k+i,cpt,i+1);
1.126     brouard  4780:        /*      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);*/
                   4781:        
                   4782:       } 
1.201   ! brouard  4783:       fprintf(ficgp," ,\"%s\" every :::%d::%d u 1:%d t \"e%d.\" w l",subdirf2(fileresu,"E_"),k1-1,k1-1,k+nlstate,cpt);
1.126     brouard  4784:     }
                   4785:   }
                   4786:   
1.201   ! brouard  4787:   /* Survival functions (period) from state i in state j by initial state i */
        !          4788:   for (k1=1; k1<= m ; k1 ++) { /* For each multivariate if any */
        !          4789:     for (cpt=1; cpt<=nlstate ; cpt ++) { /* For each life state */
        !          4790:       k=3;
        !          4791:       fprintf(ficgp,"\n#\n#\n# Survival functions in state j : 'lij' files, cov=%d state=%d",k1, cpt);
        !          4792:       fprintf(ficgp,"\nset out \"%s_%d-%d.svg\" \n",subdirf2(optionfilefiname,"LIJ_"),cpt,k1);
        !          4793:       fprintf(ficgp,"set xlabel \"Age\" \nset ylabel \"Probability to be alive\" \n\
        !          4794: set ter svg size 640, 480\n\
        !          4795: unset log y\n\
        !          4796: plot [%.f:%.f]  ", ageminpar, agemaxpar);
        !          4797:       for (i=1; i<= nlstate ; i ++){
        !          4798:        if(i==1)
        !          4799:          fprintf(ficgp,"\"%s\"",subdirf2(fileresu,"PIJ_"));
        !          4800:        else
        !          4801:          fprintf(ficgp,", '' ");
        !          4802:        l=(nlstate+ndeath)*(i-1)+1;
        !          4803:        fprintf(ficgp," u ($1==%d ? ($3):1/0):($%d/($%d",k1,k+l+(cpt-1),k+l);
        !          4804:        for (j=2; j<= nlstate+ndeath ; j ++)
        !          4805:          fprintf(ficgp,"+$%d",k+l+j-1);
        !          4806:        fprintf(ficgp,")) t \"l(%d,%d)\" w l",i,cpt);
        !          4807:       } /* nlstate */
        !          4808:       fprintf(ficgp,"\nset out\n");
        !          4809:     } /* end cpt state*/ 
        !          4810:   } /* end covariate */  
        !          4811: 
        !          4812:   /* Survival functions (period) from state i in state j by final state j */
        !          4813:   for (k1=1; k1<= m ; k1 ++) { /* For each multivariate if any */
        !          4814:     for (cpt=1; cpt<=nlstate ; cpt ++) { /* For each inital state  */
        !          4815:       k=3;
        !          4816:       fprintf(ficgp,"\n#\n#\n# Survival functions in state j and all livestates from state i by final state j: 'lij' files, cov=%d state=%d",k1, cpt);
        !          4817:       fprintf(ficgp,"\nset out \"%s_%d-%d.svg\" \n",subdirf2(optionfilefiname,"LIJT_"),cpt,k1);
        !          4818:       fprintf(ficgp,"set xlabel \"Age\" \nset ylabel \"Probability to be alive\" \n\
        !          4819: set ter svg size 640, 480\n\
        !          4820: unset log y\n\
        !          4821: plot [%.f:%.f]  ", ageminpar, agemaxpar);
        !          4822:       for (j=1; j<= nlstate ; j ++){ /* Lived in state j */
        !          4823:        if(j==1)
        !          4824:          fprintf(ficgp,"\"%s\"",subdirf2(fileresu,"PIJ_"));
        !          4825:        else
        !          4826:          fprintf(ficgp,", '' ");
        !          4827:        l=(nlstate+ndeath)*(cpt-1) +j;
        !          4828:        fprintf(ficgp," u (($1==%d && (floor($2)%%5 == 0)) ? ($3):1/0):($%d",k1,k+l);
        !          4829:        /* for (i=2; i<= nlstate+ndeath ; i ++) */
        !          4830:        /*   fprintf(ficgp,"+$%d",k+l+i-1); */
        !          4831:        fprintf(ficgp,") t \"l(%d,%d)\" w l",cpt,j);
        !          4832:       } /* nlstate */
        !          4833:       fprintf(ficgp,", '' ");
        !          4834:       fprintf(ficgp," u (($1==%d && (floor($2)%%5 == 0)) ? ($3):1/0):(",k1);
        !          4835:       for (j=1; j<= nlstate ; j ++){ /* Lived in state j */
        !          4836:        l=(nlstate+ndeath)*(cpt-1) +j;
        !          4837:        if(j < nlstate)
        !          4838:          fprintf(ficgp,"$%d +",k+l);
        !          4839:        else
        !          4840:          fprintf(ficgp,"$%d) t\"l(%d,.)\" w l",k+l,cpt);
        !          4841:       }
        !          4842:       fprintf(ficgp,"\nset out\n");
        !          4843:     } /* end cpt state*/ 
        !          4844:   } /* end covariate */  
        !          4845: 
1.126     brouard  4846:   /* CV preval stable (period) */
1.153     brouard  4847:   for (k1=1; k1<= m ; k1 ++) { /* For each multivariate if any */
                   4848:     for (cpt=1; cpt<=nlstate ; cpt ++) { /* For each life state */
1.126     brouard  4849:       k=3;
1.153     brouard  4850:       fprintf(ficgp,"\n#\n#\n#CV preval stable (period): 'pij' files, cov=%d state=%d",k1, cpt);
1.201   ! brouard  4851:       fprintf(ficgp,"\nset out \"%s_%d-%d.svg\" \n",subdirf2(optionfilefiname,"P_"),cpt,k1);
1.126     brouard  4852:       fprintf(ficgp,"set xlabel \"Age\" \nset ylabel \"Probability\" \n\
1.199     brouard  4853: set ter svg size 640, 480\n\
1.126     brouard  4854: unset log y\n\
1.153     brouard  4855: plot [%.f:%.f]  ", ageminpar, agemaxpar);
                   4856:       for (i=1; i<= nlstate ; i ++){
                   4857:        if(i==1)
1.201   ! brouard  4858:          fprintf(ficgp,"\"%s\"",subdirf2(fileresu,"PIJ_"));
1.153     brouard  4859:        else
                   4860:          fprintf(ficgp,", '' ");
1.154     brouard  4861:        l=(nlstate+ndeath)*(i-1)+1;
                   4862:        fprintf(ficgp," u ($1==%d ? ($3):1/0):($%d/($%d",k1,k+l+(cpt-1),k+l);
1.201   ! brouard  4863:        for (j=2; j<= nlstate ; j ++)
        !          4864:          fprintf(ficgp,"+$%d",k+l+j-1);
1.153     brouard  4865:        fprintf(ficgp,")) t \"prev(%d,%d)\" w l",i,cpt);
                   4866:       } /* nlstate */
1.201   ! brouard  4867:       fprintf(ficgp,"\nset out\n");
1.153     brouard  4868:     } /* end cpt state*/ 
                   4869:   } /* end covariate */  
1.201   ! brouard  4870: 
1.126     brouard  4871:   /* proba elementaires */
1.187     brouard  4872:   fprintf(ficgp,"\n##############\n#MLE estimated parameters\n#############\n");
1.126     brouard  4873:   for(i=1,jk=1; i <=nlstate; i++){
1.187     brouard  4874:     fprintf(ficgp,"# initial state %d\n",i);
1.126     brouard  4875:     for(k=1; k <=(nlstate+ndeath); k++){
                   4876:       if (k != i) {
1.187     brouard  4877:        fprintf(ficgp,"#   current state %d\n",k);
1.126     brouard  4878:        for(j=1; j <=ncovmodel; j++){
1.187     brouard  4879:          fprintf(ficgp,"p%d=%f; ",jk,p[jk]);
1.126     brouard  4880:          jk++; 
                   4881:        }
1.187     brouard  4882:        fprintf(ficgp,"\n");
1.126     brouard  4883:       }
                   4884:     }
                   4885:    }
1.187     brouard  4886:   fprintf(ficgp,"##############\n#\n");
                   4887: 
1.145     brouard  4888:   /*goto avoid;*/
1.200     brouard  4889:   fprintf(ficgp,"\n##############\n#Graphics of probabilities or incidences\n#############\n");
1.187     brouard  4890:   fprintf(ficgp,"# logi(p12/p11)=a12+b12*age+c12age*age+d12*V1+e12*V1*age\n");
                   4891:   fprintf(ficgp,"# logi(p12/p11)=p1 +p2*age +p3*age*age+ p4*V1+ p5*V1*age\n");
                   4892:   fprintf(ficgp,"# logi(p13/p11)=a13+b13*age+c13age*age+d13*V1+e13*V1*age\n");
                   4893:   fprintf(ficgp,"# logi(p13/p11)=p6 +p7*age +p8*age*age+ p9*V1+ p10*V1*age\n");
                   4894:   fprintf(ficgp,"# p12+p13+p14+p11=1=p11(1+exp(a12+b12*age+c12age*age+d12*V1+e12*V1*age)\n");
                   4895:   fprintf(ficgp,"#                      +exp(a13+b13*age+c13age*age+d13*V1+e13*V1*age)+...)\n");
                   4896:   fprintf(ficgp,"# p11=1/(1+exp(a12+b12*age+c12age*age+d12*V1+e12*V1*age)\n");
                   4897:   fprintf(ficgp,"#                      +exp(a13+b13*age+c13age*age+d13*V1+e13*V1*age)+...)\n");
                   4898:   fprintf(ficgp,"# p12=exp(a12+b12*age+c12age*age+d12*V1+e12*V1*age)/\n");
                   4899:   fprintf(ficgp,"#     (1+exp(a12+b12*age+c12age*age+d12*V1+e12*V1*age)\n");
                   4900:   fprintf(ficgp,"#       +exp(a13+b13*age+c13age*age+d13*V1+e13*V1*age))\n");
                   4901:   fprintf(ficgp,"#       +exp(a14+b14*age+c14age*age+d14*V1+e14*V1*age)+...)\n");
                   4902:   fprintf(ficgp,"#\n");
1.201   ! brouard  4903:    for(ng=1; ng<=3;ng++){ /* Number of graphics: first is logit, 2nd is probabilities, third is incidences per year*/
1.187     brouard  4904:      fprintf(ficgp,"# ng=%d\n",ng);
                   4905:      fprintf(ficgp,"#   jk=1 to 2^%d=%d\n",cptcoveff,m);
1.126     brouard  4906:      for(jk=1; jk <=m; jk++) {
1.187     brouard  4907:        fprintf(ficgp,"#    jk=%d\n",jk);
1.201   ! brouard  4908:        fprintf(ficgp,"\nset out \"%s_%d-%d.svg\" ",subdirf2(optionfilefiname,"PE_"),jk,ng);
        !          4909:        fprintf(ficgp,"\nset ter svg size 640, 480 ");
        !          4910:        if (ng==1){
        !          4911:         fprintf(ficgp,"\nset ylabel \"Value of the logit of the model\"\n"); /* exp(a12+b12*x) could be nice */
        !          4912:         fprintf(ficgp,"\nunset log y");
        !          4913:        }else if (ng==2){
        !          4914:         fprintf(ficgp,"\nset ylabel \"Probability\"\n");
        !          4915:         fprintf(ficgp,"\nset log y");
        !          4916:        }else if (ng==3){
1.126     brouard  4917:         fprintf(ficgp,"\nset ylabel \"Quasi-incidence per year\"\n");
1.201   ! brouard  4918:         fprintf(ficgp,"\nset log y");
        !          4919:        }else
        !          4920:         fprintf(ficgp,"\nunset title ");
        !          4921:        fprintf(ficgp,"\nplot  [%.f:%.f] ",ageminpar,agemaxpar);
1.126     brouard  4922:        i=1;
                   4923:        for(k2=1; k2<=nlstate; k2++) {
                   4924:         k3=i;
                   4925:         for(k=1; k<=(nlstate+ndeath); k++) {
                   4926:           if (k != k2){
1.201   ! brouard  4927:             switch( ng) {
        !          4928:             case 1:
1.187     brouard  4929:               if(nagesqr==0)
1.201   ! brouard  4930:                 fprintf(ficgp," p%d+p%d*x",i,i+1);
1.187     brouard  4931:               else /* nagesqr =1 */
1.201   ! brouard  4932:                 fprintf(ficgp," p%d+p%d*x+p%d*x*x",i,i+1,i+1+nagesqr);
        !          4933:               break;
        !          4934:             case 2: /* ng=2 */
1.187     brouard  4935:               if(nagesqr==0)
                   4936:                 fprintf(ficgp," exp(p%d+p%d*x",i,i+1);
                   4937:               else /* nagesqr =1 */
1.201   ! brouard  4938:                   fprintf(ficgp," exp(p%d+p%d*x+p%d*x*x",i,i+1,i+1+nagesqr);
        !          4939:               break;
        !          4940:             case 3:
        !          4941:               if(nagesqr==0)
        !          4942:                 fprintf(ficgp," %f*exp(p%d+p%d*x",YEARM/stepm,i,i+1);
        !          4943:               else /* nagesqr =1 */
        !          4944:                 fprintf(ficgp," %f*exp(p%d+p%d*x+p%d*x*x",YEARM/stepm,i,i+1,i+1+nagesqr);
        !          4945:               break;
        !          4946:             }
1.141     brouard  4947:             ij=1;/* To be checked else nbcode[0][0] wrong */
1.187     brouard  4948:             for(j=3; j <=ncovmodel-nagesqr; j++) {
1.197     brouard  4949:               /* printf("Tage[%d]=%d, j=%d\n", ij, Tage[ij], j); */
                   4950:               if(ij <=cptcovage) { /* Bug valgrind */
                   4951:                 if((j-2)==Tage[ij]) { /* Bug valgrind */
1.200     brouard  4952:                   fprintf(ficgp,"+p%d*%d*x",i+j+nagesqr-1,nbcode[Tvar[j-2]][codtabm(jk,j-2)]);
                   4953:                   /* fprintf(ficgp,"+p%d*%d*x",i+j+nagesqr-1,nbcode[Tvar[j-2]][codtabm(jk,Tvar[j-2])]); */
1.197     brouard  4954:                   ij++;
                   4955:                 }
1.186     brouard  4956:               }
                   4957:               else
1.198     brouard  4958:                 fprintf(ficgp,"+p%d*%d",i+j+nagesqr-1,nbcode[Tvar[j-2]][codtabm(jk,j-2)]);
1.126     brouard  4959:             }
1.201   ! brouard  4960:             if(ng != 1){
        !          4961:               fprintf(ficgp,")/(1");
1.126     brouard  4962:             
1.201   ! brouard  4963:               for(k1=1; k1 <=nlstate; k1++){ 
        !          4964:                 if(nagesqr==0)
        !          4965:                   fprintf(ficgp,"+exp(p%d+p%d*x",k3+(k1-1)*ncovmodel,k3+(k1-1)*ncovmodel+1);
        !          4966:                 else /* nagesqr =1 */
        !          4967:                   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);
        !          4968:                 
        !          4969:                 ij=1;
        !          4970:                 for(j=3; j <=ncovmodel-nagesqr; j++){
        !          4971:                   if(ij <=cptcovage) { /* Bug valgrind */
        !          4972:                     if((j-2)==Tage[ij]) { /* Bug valgrind */
        !          4973:                       fprintf(ficgp,"+p%d*%d*x",k3+(k1-1)*ncovmodel+1+j-2+nagesqr,nbcode[Tvar[j-2]][codtabm(jk,j-2)]);
        !          4974:                       /* fprintf(ficgp,"+p%d*%d*x",k3+(k1-1)*ncovmodel+1+j-2+nagesqr,nbcode[Tvar[j-2]][codtabm(jk,Tvar[j-2])]); */
        !          4975:                       ij++;
        !          4976:                     }
1.197     brouard  4977:                   }
1.201   ! brouard  4978:                   else
        !          4979:                     fprintf(ficgp,"+p%d*%d",k3+(k1-1)*ncovmodel+1+j-2+nagesqr,nbcode[Tvar[j-2]][codtabm(jk,j-2)]);
1.186     brouard  4980:                 }
1.201   ! brouard  4981:                 fprintf(ficgp,")");
1.126     brouard  4982:               }
                   4983:               fprintf(ficgp,")");
1.201   ! brouard  4984:               if(ng ==2)
        !          4985:                 fprintf(ficgp," t \"p%d%d\" ", k2,k);
        !          4986:               else /* ng= 3 */
        !          4987:                 fprintf(ficgp," t \"i%d%d\" ", k2,k);
        !          4988:             }else{ /* end ng <> 1 */
        !          4989:               fprintf(ficgp," t \"logit(p%d%d)\" ", k2,k);
1.126     brouard  4990:             }
                   4991:             if ((k+k2)!= (nlstate*2+ndeath)) fprintf(ficgp,",");
                   4992:             i=i+ncovmodel;
                   4993:           }
                   4994:         } /* end k */
                   4995:        } /* end k2 */
1.201   ! brouard  4996:        fprintf(ficgp,"\n set out\n");
1.126     brouard  4997:      } /* end jk */
                   4998:    } /* end ng */
1.164     brouard  4999:  /* avoid: */
1.126     brouard  5000:    fflush(ficgp); 
                   5001: }  /* end gnuplot */
                   5002: 
                   5003: 
                   5004: /*************** Moving average **************/
                   5005: int movingaverage(double ***probs, double bage,double fage, double ***mobaverage, int mobilav){
                   5006: 
                   5007:   int i, cpt, cptcod;
                   5008:   int modcovmax =1;
                   5009:   int mobilavrange, mob;
                   5010:   double age;
                   5011: 
                   5012:   modcovmax=2*cptcoveff;/* Max number of modalities. We suppose 
                   5013:                           a covariate has 2 modalities */
                   5014:   if (cptcovn<1) modcovmax=1; /* At least 1 pass */
                   5015: 
                   5016:   if(mobilav==1||mobilav ==3 ||mobilav==5 ||mobilav== 7){
                   5017:     if(mobilav==1) mobilavrange=5; /* default */
                   5018:     else mobilavrange=mobilav;
                   5019:     for (age=bage; age<=fage; age++)
                   5020:       for (i=1; i<=nlstate;i++)
                   5021:        for (cptcod=1;cptcod<=modcovmax;cptcod++)
                   5022:          mobaverage[(int)age][i][cptcod]=probs[(int)age][i][cptcod];
                   5023:     /* We keep the original values on the extreme ages bage, fage and for 
                   5024:        fage+1 and bage-1 we use a 3 terms moving average; for fage+2 bage+2
                   5025:        we use a 5 terms etc. until the borders are no more concerned. 
                   5026:     */ 
                   5027:     for (mob=3;mob <=mobilavrange;mob=mob+2){
                   5028:       for (age=bage+(mob-1)/2; age<=fage-(mob-1)/2; age++){
                   5029:        for (i=1; i<=nlstate;i++){
                   5030:          for (cptcod=1;cptcod<=modcovmax;cptcod++){
                   5031:            mobaverage[(int)age][i][cptcod] =probs[(int)age][i][cptcod];
                   5032:              for (cpt=1;cpt<=(mob-1)/2;cpt++){
                   5033:                mobaverage[(int)age][i][cptcod] +=probs[(int)age-cpt][i][cptcod];
                   5034:                mobaverage[(int)age][i][cptcod] +=probs[(int)age+cpt][i][cptcod];
                   5035:              }
                   5036:            mobaverage[(int)age][i][cptcod]=mobaverage[(int)age][i][cptcod]/mob;
                   5037:          }
                   5038:        }
                   5039:       }/* end age */
                   5040:     }/* end mob */
                   5041:   }else return -1;
                   5042:   return 0;
                   5043: }/* End movingaverage */
                   5044: 
                   5045: 
                   5046: /************** Forecasting ******************/
1.169     brouard  5047: 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  5048:   /* proj1, year, month, day of starting projection 
                   5049:      agemin, agemax range of age
                   5050:      dateprev1 dateprev2 range of dates during which prevalence is computed
                   5051:      anproj2 year of en of projection (same day and month as proj1).
                   5052:   */
1.164     brouard  5053:   int yearp, stepsize, hstepm, nhstepm, j, k, cptcod, i, h, i1;
1.126     brouard  5054:   double agec; /* generic age */
                   5055:   double agelim, ppij, yp,yp1,yp2,jprojmean,mprojmean,anprojmean;
                   5056:   double *popeffectif,*popcount;
                   5057:   double ***p3mat;
                   5058:   double ***mobaverage;
                   5059:   char fileresf[FILENAMELENGTH];
                   5060: 
                   5061:   agelim=AGESUP;
                   5062:   prevalence(probs, ageminpar, agemax, s, agev, nlstate, imx, Tvar, nbcode, ncodemax, mint, anint, dateprev1, dateprev2, firstpass, lastpass);
                   5063:  
1.201   ! brouard  5064:   strcpy(fileresf,"F_"); 
        !          5065:   strcat(fileresf,fileresu);
1.126     brouard  5066:   if((ficresf=fopen(fileresf,"w"))==NULL) {
                   5067:     printf("Problem with forecast resultfile: %s\n", fileresf);
                   5068:     fprintf(ficlog,"Problem with forecast resultfile: %s\n", fileresf);
                   5069:   }
                   5070:   printf("Computing forecasting: result on file '%s' \n", fileresf);
                   5071:   fprintf(ficlog,"Computing forecasting: result on file '%s' \n", fileresf);
                   5072: 
                   5073:   if (cptcoveff==0) ncodemax[cptcoveff]=1;
                   5074: 
                   5075:   if (mobilav!=0) {
                   5076:     mobaverage= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
                   5077:     if (movingaverage(probs, ageminpar, fage, mobaverage,mobilav)!=0){
                   5078:       fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav);
                   5079:       printf(" Error in movingaverage mobilav=%d\n",mobilav);
                   5080:     }
                   5081:   }
                   5082: 
                   5083:   stepsize=(int) (stepm+YEARM-1)/YEARM;
                   5084:   if (stepm<=12) stepsize=1;
                   5085:   if(estepm < stepm){
                   5086:     printf ("Problem %d lower than %d\n",estepm, stepm);
                   5087:   }
                   5088:   else  hstepm=estepm;   
                   5089: 
                   5090:   hstepm=hstepm/stepm; 
                   5091:   yp1=modf(dateintmean,&yp);/* extracts integral of datemean in yp  and
                   5092:                                fractional in yp1 */
                   5093:   anprojmean=yp;
                   5094:   yp2=modf((yp1*12),&yp);
                   5095:   mprojmean=yp;
                   5096:   yp1=modf((yp2*30.5),&yp);
                   5097:   jprojmean=yp;
                   5098:   if(jprojmean==0) jprojmean=1;
                   5099:   if(mprojmean==0) jprojmean=1;
                   5100: 
                   5101:   i1=cptcoveff;
                   5102:   if (cptcovn < 1){i1=1;}
                   5103:   
                   5104:   fprintf(ficresf,"# Mean day of interviews %.lf/%.lf/%.lf (%.2f) between %.2f and %.2f \n",jprojmean,mprojmean,anprojmean,dateintmean,dateprev1,dateprev2); 
                   5105:   
                   5106:   fprintf(ficresf,"#****** Routine prevforecast **\n");
                   5107: 
                   5108: /*           if (h==(int)(YEARM*yearp)){ */
                   5109:   for(cptcov=1, k=0;cptcov<=i1;cptcov++){
                   5110:     for(cptcod=1;cptcod<=ncodemax[cptcoveff];cptcod++){
                   5111:       k=k+1;
                   5112:       fprintf(ficresf,"\n#******");
                   5113:       for(j=1;j<=cptcoveff;j++) {
1.198     brouard  5114:        fprintf(ficresf," V%d=%d, hpijx=probability over h years, hp.jx is weighted by observed prev ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
1.126     brouard  5115:       }
                   5116:       fprintf(ficresf,"******\n");
                   5117:       fprintf(ficresf,"# Covariate valuofcovar yearproj age");
                   5118:       for(j=1; j<=nlstate+ndeath;j++){ 
                   5119:        for(i=1; i<=nlstate;i++)              
                   5120:           fprintf(ficresf," p%d%d",i,j);
                   5121:        fprintf(ficresf," p.%d",j);
                   5122:       }
                   5123:       for (yearp=0; yearp<=(anproj2-anproj1);yearp +=stepsize) { 
                   5124:        fprintf(ficresf,"\n");
                   5125:        fprintf(ficresf,"\n# Forecasting at date %.lf/%.lf/%.lf ",jproj1,mproj1,anproj1+yearp);   
                   5126: 
                   5127:        for (agec=fage; agec>=(ageminpar-1); agec--){ 
                   5128:          nhstepm=(int) rint((agelim-agec)*YEARM/stepm); 
                   5129:          nhstepm = nhstepm/hstepm; 
                   5130:          p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   5131:          oldm=oldms;savm=savms;
                   5132:          hpxij(p3mat,nhstepm,agec,hstepm,p,nlstate,stepm,oldm,savm, k);  
                   5133:        
                   5134:          for (h=0; h<=nhstepm; h++){
                   5135:            if (h*hstepm/YEARM*stepm ==yearp) {
                   5136:               fprintf(ficresf,"\n");
                   5137:               for(j=1;j<=cptcoveff;j++) 
1.198     brouard  5138:                 fprintf(ficresf,"%d %d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
1.126     brouard  5139:              fprintf(ficresf,"%.f %.f ",anproj1+yearp,agec+h*hstepm/YEARM*stepm);
                   5140:            } 
                   5141:            for(j=1; j<=nlstate+ndeath;j++) {
                   5142:              ppij=0.;
                   5143:              for(i=1; i<=nlstate;i++) {
                   5144:                if (mobilav==1) 
                   5145:                  ppij=ppij+p3mat[i][j][h]*mobaverage[(int)agec][i][cptcod];
                   5146:                else {
                   5147:                  ppij=ppij+p3mat[i][j][h]*probs[(int)(agec)][i][cptcod];
                   5148:                }
                   5149:                if (h*hstepm/YEARM*stepm== yearp) {
                   5150:                  fprintf(ficresf," %.3f", p3mat[i][j][h]);
                   5151:                }
                   5152:              } /* end i */
                   5153:              if (h*hstepm/YEARM*stepm==yearp) {
                   5154:                fprintf(ficresf," %.3f", ppij);
                   5155:              }
                   5156:            }/* end j */
                   5157:          } /* end h */
                   5158:          free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   5159:        } /* end agec */
                   5160:       } /* end yearp */
                   5161:     } /* end cptcod */
                   5162:   } /* end  cptcov */
                   5163:        
                   5164:   if (mobilav!=0) free_ma3x(mobaverage,1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
                   5165: 
                   5166:   fclose(ficresf);
                   5167: }
                   5168: 
                   5169: /************** Forecasting *****not tested NB*************/
1.169     brouard  5170: 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  5171:   
                   5172:   int cpt, stepsize, hstepm, nhstepm, j,k,c, cptcod, i,h;
                   5173:   int *popage;
                   5174:   double calagedatem, agelim, kk1, kk2;
                   5175:   double *popeffectif,*popcount;
                   5176:   double ***p3mat,***tabpop,***tabpopprev;
                   5177:   double ***mobaverage;
                   5178:   char filerespop[FILENAMELENGTH];
                   5179: 
                   5180:   tabpop= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
                   5181:   tabpopprev= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
                   5182:   agelim=AGESUP;
                   5183:   calagedatem=(anpyram+mpyram/12.+jpyram/365.-dateintmean)*YEARM;
                   5184:   
                   5185:   prevalence(probs, ageminpar, agemax, s, agev, nlstate, imx, Tvar, nbcode, ncodemax, mint, anint, dateprev1, dateprev2, firstpass, lastpass);
                   5186:   
                   5187:   
1.201   ! brouard  5188:   strcpy(filerespop,"POP_"); 
        !          5189:   strcat(filerespop,fileresu);
1.126     brouard  5190:   if((ficrespop=fopen(filerespop,"w"))==NULL) {
                   5191:     printf("Problem with forecast resultfile: %s\n", filerespop);
                   5192:     fprintf(ficlog,"Problem with forecast resultfile: %s\n", filerespop);
                   5193:   }
                   5194:   printf("Computing forecasting: result on file '%s' \n", filerespop);
                   5195:   fprintf(ficlog,"Computing forecasting: result on file '%s' \n", filerespop);
                   5196: 
                   5197:   if (cptcoveff==0) ncodemax[cptcoveff]=1;
                   5198: 
                   5199:   if (mobilav!=0) {
                   5200:     mobaverage= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
                   5201:     if (movingaverage(probs, ageminpar, fage, mobaverage,mobilav)!=0){
                   5202:       fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav);
                   5203:       printf(" Error in movingaverage mobilav=%d\n",mobilav);
                   5204:     }
                   5205:   }
                   5206: 
                   5207:   stepsize=(int) (stepm+YEARM-1)/YEARM;
                   5208:   if (stepm<=12) stepsize=1;
                   5209:   
                   5210:   agelim=AGESUP;
                   5211:   
                   5212:   hstepm=1;
                   5213:   hstepm=hstepm/stepm; 
                   5214:   
                   5215:   if (popforecast==1) {
                   5216:     if((ficpop=fopen(popfile,"r"))==NULL) {
                   5217:       printf("Problem with population file : %s\n",popfile);exit(0);
                   5218:       fprintf(ficlog,"Problem with population file : %s\n",popfile);exit(0);
                   5219:     } 
                   5220:     popage=ivector(0,AGESUP);
                   5221:     popeffectif=vector(0,AGESUP);
                   5222:     popcount=vector(0,AGESUP);
                   5223:     
                   5224:     i=1;   
                   5225:     while ((c=fscanf(ficpop,"%d %lf\n",&popage[i],&popcount[i])) != EOF) i=i+1;
                   5226:    
                   5227:     imx=i;
                   5228:     for (i=1; i<imx;i++) popeffectif[popage[i]]=popcount[i];
                   5229:   }
                   5230: 
                   5231:   for(cptcov=1,k=0;cptcov<=i2;cptcov++){
                   5232:    for(cptcod=1;cptcod<=ncodemax[cptcoveff];cptcod++){
                   5233:       k=k+1;
                   5234:       fprintf(ficrespop,"\n#******");
                   5235:       for(j=1;j<=cptcoveff;j++) {
1.198     brouard  5236:        fprintf(ficrespop," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
1.126     brouard  5237:       }
                   5238:       fprintf(ficrespop,"******\n");
                   5239:       fprintf(ficrespop,"# Age");
                   5240:       for(j=1; j<=nlstate+ndeath;j++) fprintf(ficrespop," P.%d",j);
                   5241:       if (popforecast==1)  fprintf(ficrespop," [Population]");
                   5242:       
                   5243:       for (cpt=0; cpt<=0;cpt++) { 
                   5244:        fprintf(ficrespop,"\n\n# Forecasting at date %.lf/%.lf/%.lf ",jpyram,mpyram,anpyram+cpt);   
                   5245:        
                   5246:        for (agedeb=(fage-((int)calagedatem %12/12.)); agedeb>=(ageminpar-((int)calagedatem %12)/12.); agedeb--){ 
                   5247:          nhstepm=(int) rint((agelim-agedeb)*YEARM/stepm); 
                   5248:          nhstepm = nhstepm/hstepm; 
                   5249:          
                   5250:          p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   5251:          oldm=oldms;savm=savms;
                   5252:          hpxij(p3mat,nhstepm,agedeb,hstepm,p,nlstate,stepm,oldm,savm, k);  
                   5253:        
                   5254:          for (h=0; h<=nhstepm; h++){
                   5255:            if (h==(int) (calagedatem+YEARM*cpt)) {
                   5256:              fprintf(ficrespop,"\n %3.f ",agedeb+h*hstepm/YEARM*stepm);
                   5257:            } 
                   5258:            for(j=1; j<=nlstate+ndeath;j++) {
                   5259:              kk1=0.;kk2=0;
                   5260:              for(i=1; i<=nlstate;i++) {              
                   5261:                if (mobilav==1) 
                   5262:                  kk1=kk1+p3mat[i][j][h]*mobaverage[(int)agedeb+1][i][cptcod];
                   5263:                else {
                   5264:                  kk1=kk1+p3mat[i][j][h]*probs[(int)(agedeb+1)][i][cptcod];
                   5265:                }
                   5266:              }
                   5267:              if (h==(int)(calagedatem+12*cpt)){
                   5268:                tabpop[(int)(agedeb)][j][cptcod]=kk1;
                   5269:                  /*fprintf(ficrespop," %.3f", kk1);
                   5270:                    if (popforecast==1) fprintf(ficrespop," [%.f]", kk1*popeffectif[(int)agedeb+1]);*/
                   5271:              }
                   5272:            }
                   5273:            for(i=1; i<=nlstate;i++){
                   5274:              kk1=0.;
                   5275:                for(j=1; j<=nlstate;j++){
                   5276:                  kk1= kk1+tabpop[(int)(agedeb)][j][cptcod]; 
                   5277:                }
                   5278:                  tabpopprev[(int)(agedeb)][i][cptcod]=tabpop[(int)(agedeb)][i][cptcod]/kk1*popeffectif[(int)(agedeb+(calagedatem+12*cpt)*hstepm/YEARM*stepm-1)];
                   5279:            }
                   5280: 
                   5281:            if (h==(int)(calagedatem+12*cpt)) for(j=1; j<=nlstate;j++) 
                   5282:              fprintf(ficrespop," %15.2f",tabpopprev[(int)(agedeb+1)][j][cptcod]);
                   5283:          }
                   5284:          free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   5285:        }
                   5286:       }
                   5287:  
                   5288:   /******/
                   5289: 
                   5290:       for (cpt=1; cpt<=(anpyram1-anpyram);cpt++) { 
                   5291:        fprintf(ficrespop,"\n\n# Forecasting at date %.lf/%.lf/%.lf ",jpyram,mpyram,anpyram+cpt);   
                   5292:        for (agedeb=(fage-((int)calagedatem %12/12.)); agedeb>=(ageminpar-((int)calagedatem %12)/12.); agedeb--){ 
                   5293:          nhstepm=(int) rint((agelim-agedeb)*YEARM/stepm); 
                   5294:          nhstepm = nhstepm/hstepm; 
                   5295:          
                   5296:          p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   5297:          oldm=oldms;savm=savms;
                   5298:          hpxij(p3mat,nhstepm,agedeb,hstepm,p,nlstate,stepm,oldm,savm, k);  
                   5299:          for (h=0; h<=nhstepm; h++){
                   5300:            if (h==(int) (calagedatem+YEARM*cpt)) {
                   5301:              fprintf(ficresf,"\n %3.f ",agedeb+h*hstepm/YEARM*stepm);
                   5302:            } 
                   5303:            for(j=1; j<=nlstate+ndeath;j++) {
                   5304:              kk1=0.;kk2=0;
                   5305:              for(i=1; i<=nlstate;i++) {              
                   5306:                kk1=kk1+p3mat[i][j][h]*tabpopprev[(int)agedeb+1][i][cptcod];    
                   5307:              }
                   5308:              if (h==(int)(calagedatem+12*cpt)) fprintf(ficresf," %15.2f", kk1);        
                   5309:            }
                   5310:          }
                   5311:          free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   5312:        }
                   5313:       }
                   5314:    } 
                   5315:   }
                   5316:  
                   5317:   if (mobilav!=0) free_ma3x(mobaverage,1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
                   5318: 
                   5319:   if (popforecast==1) {
                   5320:     free_ivector(popage,0,AGESUP);
                   5321:     free_vector(popeffectif,0,AGESUP);
                   5322:     free_vector(popcount,0,AGESUP);
                   5323:   }
                   5324:   free_ma3x(tabpop,1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
                   5325:   free_ma3x(tabpopprev,1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
                   5326:   fclose(ficrespop);
                   5327: } /* End of popforecast */
                   5328: 
                   5329: int fileappend(FILE *fichier, char *optionfich)
                   5330: {
                   5331:   if((fichier=fopen(optionfich,"a"))==NULL) {
                   5332:     printf("Problem with file: %s\n", optionfich);
                   5333:     fprintf(ficlog,"Problem with file: %s\n", optionfich);
                   5334:     return (0);
                   5335:   }
                   5336:   fflush(fichier);
                   5337:   return (1);
                   5338: }
                   5339: 
                   5340: 
                   5341: /**************** function prwizard **********************/
                   5342: void prwizard(int ncovmodel, int nlstate, int ndeath,  char model[], FILE *ficparo)
                   5343: {
                   5344: 
                   5345:   /* Wizard to print covariance matrix template */
                   5346: 
1.164     brouard  5347:   char ca[32], cb[32];
                   5348:   int i,j, k, li, lj, lk, ll, jj, npar, itimes;
1.126     brouard  5349:   int numlinepar;
                   5350: 
                   5351:   printf("# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
                   5352:   fprintf(ficparo,"# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
                   5353:   for(i=1; i <=nlstate; i++){
                   5354:     jj=0;
                   5355:     for(j=1; j <=nlstate+ndeath; j++){
                   5356:       if(j==i) continue;
                   5357:       jj++;
                   5358:       /*ca[0]= k+'a'-1;ca[1]='\0';*/
                   5359:       printf("%1d%1d",i,j);
                   5360:       fprintf(ficparo,"%1d%1d",i,j);
                   5361:       for(k=1; k<=ncovmodel;k++){
                   5362:        /*        printf(" %lf",param[i][j][k]); */
                   5363:        /*        fprintf(ficparo," %lf",param[i][j][k]); */
                   5364:        printf(" 0.");
                   5365:        fprintf(ficparo," 0.");
                   5366:       }
                   5367:       printf("\n");
                   5368:       fprintf(ficparo,"\n");
                   5369:     }
                   5370:   }
                   5371:   printf("# Scales (for hessian or gradient estimation)\n");
                   5372:   fprintf(ficparo,"# Scales (for hessian or gradient estimation)\n");
                   5373:   npar= (nlstate+ndeath-1)*nlstate*ncovmodel; /* Number of parameters*/ 
                   5374:   for(i=1; i <=nlstate; i++){
                   5375:     jj=0;
                   5376:     for(j=1; j <=nlstate+ndeath; j++){
                   5377:       if(j==i) continue;
                   5378:       jj++;
                   5379:       fprintf(ficparo,"%1d%1d",i,j);
                   5380:       printf("%1d%1d",i,j);
                   5381:       fflush(stdout);
                   5382:       for(k=1; k<=ncovmodel;k++){
                   5383:        /*      printf(" %le",delti3[i][j][k]); */
                   5384:        /*      fprintf(ficparo," %le",delti3[i][j][k]); */
                   5385:        printf(" 0.");
                   5386:        fprintf(ficparo," 0.");
                   5387:       }
                   5388:       numlinepar++;
                   5389:       printf("\n");
                   5390:       fprintf(ficparo,"\n");
                   5391:     }
                   5392:   }
                   5393:   printf("# Covariance matrix\n");
                   5394: /* # 121 Var(a12)\n\ */
                   5395: /* # 122 Cov(b12,a12) Var(b12)\n\ */
                   5396: /* # 131 Cov(a13,a12) Cov(a13,b12, Var(a13)\n\ */
                   5397: /* # 132 Cov(b13,a12) Cov(b13,b12, Cov(b13,a13) Var(b13)\n\ */
                   5398: /* # 212 Cov(a21,a12) Cov(a21,b12, Cov(a21,a13) Cov(a21,b13) Var(a21)\n\ */
                   5399: /* # 212 Cov(b21,a12) Cov(b21,b12, Cov(b21,a13) Cov(b21,b13) Cov(b21,a21) Var(b21)\n\ */
                   5400: /* # 232 Cov(a23,a12) Cov(a23,b12, Cov(a23,a13) Cov(a23,b13) Cov(a23,a21) Cov(a23,b21) Var(a23)\n\ */
                   5401: /* # 232 Cov(b23,a12) Cov(b23,b12) ... Var (b23)\n" */
                   5402:   fflush(stdout);
                   5403:   fprintf(ficparo,"# Covariance matrix\n");
                   5404:   /* # 121 Var(a12)\n\ */
                   5405:   /* # 122 Cov(b12,a12) Var(b12)\n\ */
                   5406:   /* #   ...\n\ */
                   5407:   /* # 232 Cov(b23,a12)  Cov(b23,b12) ... Var (b23)\n" */
                   5408:   
                   5409:   for(itimes=1;itimes<=2;itimes++){
                   5410:     jj=0;
                   5411:     for(i=1; i <=nlstate; i++){
                   5412:       for(j=1; j <=nlstate+ndeath; j++){
                   5413:        if(j==i) continue;
                   5414:        for(k=1; k<=ncovmodel;k++){
                   5415:          jj++;
                   5416:          ca[0]= k+'a'-1;ca[1]='\0';
                   5417:          if(itimes==1){
                   5418:            printf("#%1d%1d%d",i,j,k);
                   5419:            fprintf(ficparo,"#%1d%1d%d",i,j,k);
                   5420:          }else{
                   5421:            printf("%1d%1d%d",i,j,k);
                   5422:            fprintf(ficparo,"%1d%1d%d",i,j,k);
                   5423:            /*  printf(" %.5le",matcov[i][j]); */
                   5424:          }
                   5425:          ll=0;
                   5426:          for(li=1;li <=nlstate; li++){
                   5427:            for(lj=1;lj <=nlstate+ndeath; lj++){
                   5428:              if(lj==li) continue;
                   5429:              for(lk=1;lk<=ncovmodel;lk++){
                   5430:                ll++;
                   5431:                if(ll<=jj){
                   5432:                  cb[0]= lk +'a'-1;cb[1]='\0';
                   5433:                  if(ll<jj){
                   5434:                    if(itimes==1){
                   5435:                      printf(" Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
                   5436:                      fprintf(ficparo," Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
                   5437:                    }else{
                   5438:                      printf(" 0.");
                   5439:                      fprintf(ficparo," 0.");
                   5440:                    }
                   5441:                  }else{
                   5442:                    if(itimes==1){
                   5443:                      printf(" Var(%s%1d%1d)",ca,i,j);
                   5444:                      fprintf(ficparo," Var(%s%1d%1d)",ca,i,j);
                   5445:                    }else{
                   5446:                      printf(" 0.");
                   5447:                      fprintf(ficparo," 0.");
                   5448:                    }
                   5449:                  }
                   5450:                }
                   5451:              } /* end lk */
                   5452:            } /* end lj */
                   5453:          } /* end li */
                   5454:          printf("\n");
                   5455:          fprintf(ficparo,"\n");
                   5456:          numlinepar++;
                   5457:        } /* end k*/
                   5458:       } /*end j */
                   5459:     } /* end i */
                   5460:   } /* end itimes */
                   5461: 
                   5462: } /* end of prwizard */
                   5463: /******************* Gompertz Likelihood ******************************/
                   5464: double gompertz(double x[])
                   5465: { 
                   5466:   double A,B,L=0.0,sump=0.,num=0.;
                   5467:   int i,n=0; /* n is the size of the sample */
                   5468: 
                   5469:   for (i=0;i<=imx-1 ; i++) {
                   5470:     sump=sump+weight[i];
                   5471:     /*    sump=sump+1;*/
                   5472:     num=num+1;
                   5473:   }
                   5474:  
                   5475:  
                   5476:   /* for (i=0; i<=imx; i++) 
                   5477:      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]);*/
                   5478: 
                   5479:   for (i=1;i<=imx ; i++)
                   5480:     {
                   5481:       if (cens[i] == 1 && wav[i]>1)
                   5482:        A=-x[1]/(x[2])*(exp(x[2]*(agecens[i]-agegomp))-exp(x[2]*(ageexmed[i]-agegomp)));
                   5483:       
                   5484:       if (cens[i] == 0 && wav[i]>1)
                   5485:        A=-x[1]/(x[2])*(exp(x[2]*(agedc[i]-agegomp))-exp(x[2]*(ageexmed[i]-agegomp)))
                   5486:             +log(x[1]/YEARM)+x[2]*(agedc[i]-agegomp)+log(YEARM);  
                   5487:       
                   5488:       /*if (wav[i] > 1 && agecens[i] > 15) {*/ /* ??? */
                   5489:       if (wav[i] > 1 ) { /* ??? */
                   5490:        L=L+A*weight[i];
                   5491:        /*      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]);*/
                   5492:       }
                   5493:     }
                   5494: 
                   5495:  /*printf("x1=%2.9f x2=%2.9f x3=%2.9f L=%f\n",x[1],x[2],x[3],L);*/
                   5496:  
                   5497:   return -2*L*num/sump;
                   5498: }
                   5499: 
1.136     brouard  5500: #ifdef GSL
                   5501: /******************* Gompertz_f Likelihood ******************************/
                   5502: double gompertz_f(const gsl_vector *v, void *params)
                   5503: { 
                   5504:   double A,B,LL=0.0,sump=0.,num=0.;
                   5505:   double *x= (double *) v->data;
                   5506:   int i,n=0; /* n is the size of the sample */
                   5507: 
                   5508:   for (i=0;i<=imx-1 ; i++) {
                   5509:     sump=sump+weight[i];
                   5510:     /*    sump=sump+1;*/
                   5511:     num=num+1;
                   5512:   }
                   5513:  
                   5514:  
                   5515:   /* for (i=0; i<=imx; i++) 
                   5516:      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]);*/
                   5517:   printf("x[0]=%lf x[1]=%lf\n",x[0],x[1]);
                   5518:   for (i=1;i<=imx ; i++)
                   5519:     {
                   5520:       if (cens[i] == 1 && wav[i]>1)
                   5521:        A=-x[0]/(x[1])*(exp(x[1]*(agecens[i]-agegomp))-exp(x[1]*(ageexmed[i]-agegomp)));
                   5522:       
                   5523:       if (cens[i] == 0 && wav[i]>1)
                   5524:        A=-x[0]/(x[1])*(exp(x[1]*(agedc[i]-agegomp))-exp(x[1]*(ageexmed[i]-agegomp)))
                   5525:             +log(x[0]/YEARM)+x[1]*(agedc[i]-agegomp)+log(YEARM);  
                   5526:       
                   5527:       /*if (wav[i] > 1 && agecens[i] > 15) {*/ /* ??? */
                   5528:       if (wav[i] > 1 ) { /* ??? */
                   5529:        LL=LL+A*weight[i];
                   5530:        /*      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]);*/
                   5531:       }
                   5532:     }
                   5533: 
                   5534:  /*printf("x1=%2.9f x2=%2.9f x3=%2.9f L=%f\n",x[1],x[2],x[3],L);*/
                   5535:   printf("x[0]=%lf x[1]=%lf -2*LL*num/sump=%lf\n",x[0],x[1],-2*LL*num/sump);
                   5536:  
                   5537:   return -2*LL*num/sump;
                   5538: }
                   5539: #endif
                   5540: 
1.126     brouard  5541: /******************* Printing html file ***********/
1.201   ! brouard  5542: void printinghtmlmort(char fileresu[], char title[], char datafile[], int firstpass, \
1.126     brouard  5543:                  int lastpass, int stepm, int weightopt, char model[],\
                   5544:                  int imx,  double p[],double **matcov,double agemortsup){
                   5545:   int i,k;
                   5546: 
                   5547:   fprintf(fichtm,"<ul><li><h4>Result files </h4>\n Force of mortality. Parameters of the Gompertz fit (with confidence interval in brackets):<br>");
                   5548:   fprintf(fichtm,"  mu(age) =%lf*exp(%lf*(age-%d)) per year<br><br>",p[1],p[2],agegomp);
                   5549:   for (i=1;i<=2;i++) 
                   5550:     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]));
1.199     brouard  5551:   fprintf(fichtm,"<br><br><img src=\"graphmort.svg\">");
1.126     brouard  5552:   fprintf(fichtm,"</ul>");
                   5553: 
                   5554: fprintf(fichtm,"<ul><li><h4>Life table</h4>\n <br>");
                   5555: 
                   5556:  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>");
                   5557: 
                   5558:  for (k=agegomp;k<(agemortsup-2);k++) 
                   5559:    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]);
                   5560: 
                   5561:  
                   5562:   fflush(fichtm);
                   5563: }
                   5564: 
                   5565: /******************* Gnuplot file **************/
1.201   ! brouard  5566: void printinggnuplotmort(char fileresu[], char optionfilefiname[], double ageminpar, double agemaxpar, double fage , char pathc[], double p[]){
1.126     brouard  5567: 
                   5568:   char dirfileres[132],optfileres[132];
1.164     brouard  5569: 
1.126     brouard  5570:   int ng;
                   5571: 
                   5572: 
                   5573:   /*#ifdef windows */
                   5574:   fprintf(ficgp,"cd \"%s\" \n",pathc);
                   5575:     /*#endif */
                   5576: 
                   5577: 
                   5578:   strcpy(dirfileres,optionfilefiname);
                   5579:   strcpy(optfileres,"vpl");
1.199     brouard  5580:   fprintf(ficgp,"set out \"graphmort.svg\"\n "); 
1.126     brouard  5581:   fprintf(ficgp,"set xlabel \"Age\"\n set ylabel \"Force of mortality (per year)\" \n "); 
1.199     brouard  5582:   fprintf(ficgp, "set ter svg size 640, 480\n set log y\n"); 
1.145     brouard  5583:   /* fprintf(ficgp, "set size 0.65,0.65\n"); */
1.126     brouard  5584:   fprintf(ficgp,"plot [%d:100] %lf*exp(%lf*(x-%d))",agegomp,p[1],p[2],agegomp);
                   5585: 
                   5586: } 
                   5587: 
1.136     brouard  5588: int readdata(char datafile[], int firstobs, int lastobs, int *imax)
                   5589: {
1.126     brouard  5590: 
1.136     brouard  5591:   /*-------- data file ----------*/
                   5592:   FILE *fic;
                   5593:   char dummy[]="                         ";
1.164     brouard  5594:   int i=0, j=0, n=0;
1.136     brouard  5595:   int linei, month, year,iout;
                   5596:   char line[MAXLINE], linetmp[MAXLINE];
1.164     brouard  5597:   char stra[MAXLINE], strb[MAXLINE];
1.136     brouard  5598:   char *stratrunc;
                   5599:   int lstra;
1.126     brouard  5600: 
                   5601: 
1.136     brouard  5602:   if((fic=fopen(datafile,"r"))==NULL)    {
1.195     brouard  5603:     printf("Problem while opening datafile: %s\n", datafile);fflush(stdout);
                   5604:     fprintf(ficlog,"Problem while opening datafile: %s\n", datafile);fflush(ficlog);return 1;
1.136     brouard  5605:   }
1.126     brouard  5606: 
1.136     brouard  5607:   i=1;
                   5608:   linei=0;
                   5609:   while ((fgets(line, MAXLINE, fic) != NULL) &&((i >= firstobs) && (i <=lastobs))) {
                   5610:     linei=linei+1;
                   5611:     for(j=strlen(line); j>=0;j--){  /* Untabifies line */
                   5612:       if(line[j] == '\t')
                   5613:        line[j] = ' ';
                   5614:     }
                   5615:     for(j=strlen(line)-1; (line[j]==' ')||(line[j]==10)||(line[j]==13);j--){
                   5616:       ;
                   5617:     };
                   5618:     line[j+1]=0;  /* Trims blanks at end of line */
                   5619:     if(line[0]=='#'){
                   5620:       fprintf(ficlog,"Comment line\n%s\n",line);
                   5621:       printf("Comment line\n%s\n",line);
                   5622:       continue;
                   5623:     }
                   5624:     trimbb(linetmp,line); /* Trims multiple blanks in line */
1.164     brouard  5625:     strcpy(line, linetmp);
1.136     brouard  5626:   
1.126     brouard  5627: 
1.136     brouard  5628:     for (j=maxwav;j>=1;j--){
1.137     brouard  5629:       cutv(stra, strb, line, ' '); 
1.136     brouard  5630:       if(strb[0]=='.') { /* Missing status */
                   5631:        lval=-1;
                   5632:       }else{
                   5633:        errno=0;
                   5634:        lval=strtol(strb,&endptr,10); 
                   5635:       /*       if (errno == ERANGE && (lval == LONG_MAX || lval == LONG_MIN))*/
                   5636:        if( strb[0]=='\0' || (*endptr != '\0')){
1.141     brouard  5637:          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);
                   5638:          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  5639:          return 1;
                   5640:        }
                   5641:       }
                   5642:       s[j][i]=lval;
                   5643:       
                   5644:       strcpy(line,stra);
                   5645:       cutv(stra, strb,line,' ');
1.169     brouard  5646:       if( (iout=sscanf(strb,"%d/%d",&month, &year)) != 0){
1.136     brouard  5647:       }
1.169     brouard  5648:       else  if( (iout=sscanf(strb,"%s.",dummy)) != 0){
1.136     brouard  5649:        month=99;
                   5650:        year=9999;
                   5651:       }else{
1.141     brouard  5652:        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);
                   5653:        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  5654:        return 1;
                   5655:       }
                   5656:       anint[j][i]= (double) year; 
                   5657:       mint[j][i]= (double)month; 
                   5658:       strcpy(line,stra);
                   5659:     } /* ENd Waves */
                   5660:     
                   5661:     cutv(stra, strb,line,' '); 
1.169     brouard  5662:     if( (iout=sscanf(strb,"%d/%d",&month, &year)) != 0){
1.136     brouard  5663:     }
1.169     brouard  5664:     else  if( (iout=sscanf(strb,"%s.",dummy)) != 0){
1.136     brouard  5665:       month=99;
                   5666:       year=9999;
                   5667:     }else{
1.141     brouard  5668:       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);
                   5669:        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  5670:        return 1;
                   5671:     }
                   5672:     andc[i]=(double) year; 
                   5673:     moisdc[i]=(double) month; 
                   5674:     strcpy(line,stra);
                   5675:     
                   5676:     cutv(stra, strb,line,' '); 
1.169     brouard  5677:     if( (iout=sscanf(strb,"%d/%d",&month, &year)) != 0){
1.136     brouard  5678:     }
1.169     brouard  5679:     else  if( (iout=sscanf(strb,"%s.", dummy)) != 0){
1.136     brouard  5680:       month=99;
                   5681:       year=9999;
                   5682:     }else{
1.141     brouard  5683:       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);
                   5684:       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  5685:        return 1;
                   5686:     }
                   5687:     if (year==9999) {
1.141     brouard  5688:       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);
                   5689:       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  5690:        return 1;
1.126     brouard  5691: 
1.136     brouard  5692:     }
                   5693:     annais[i]=(double)(year);
                   5694:     moisnais[i]=(double)(month); 
                   5695:     strcpy(line,stra);
                   5696:     
                   5697:     cutv(stra, strb,line,' '); 
                   5698:     errno=0;
                   5699:     dval=strtod(strb,&endptr); 
                   5700:     if( strb[0]=='\0' || (*endptr != '\0')){
1.141     brouard  5701:       printf("Error reading data around '%f' at line number %d, \"%s\" for individual %d\nShould be a weight.  Exiting.\n",dval, i,line,linei);
                   5702:       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  5703:       fflush(ficlog);
                   5704:       return 1;
                   5705:     }
                   5706:     weight[i]=dval; 
                   5707:     strcpy(line,stra);
                   5708:     
                   5709:     for (j=ncovcol;j>=1;j--){
                   5710:       cutv(stra, strb,line,' '); 
                   5711:       if(strb[0]=='.') { /* Missing status */
                   5712:        lval=-1;
                   5713:       }else{
                   5714:        errno=0;
                   5715:        lval=strtol(strb,&endptr,10); 
                   5716:        if( strb[0]=='\0' || (*endptr != '\0')){
1.141     brouard  5717:          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);
                   5718:          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  5719:          return 1;
                   5720:        }
                   5721:       }
                   5722:       if(lval <-1 || lval >1){
1.141     brouard  5723:        printf("Error reading data around '%ld' at line number %d for individual %d, '%s'\n \
1.136     brouard  5724:  Should be a value of %d(nth) covariate (0 should be the value for the reference and 1\n \
                   5725:  for the alternative. IMaCh does not build design variables automatically, do it yourself.\n \
                   5726:  For example, for multinomial values like 1, 2 and 3,\n \
                   5727:  build V1=0 V2=0 for the reference value (1),\n \
                   5728:         V1=1 V2=0 for (2) \n \
                   5729:  and V1=0 V2=1 for (3). V1=1 V2=1 should not exist and the corresponding\n \
                   5730:  output of IMaCh is often meaningless.\n \
                   5731:  Exiting.\n",lval,linei, i,line,j);
1.141     brouard  5732:        fprintf(ficlog,"Error reading data around '%ld' at line number %d for individual %d, '%s'\n \
1.136     brouard  5733:  Should be a value of %d(nth) covariate (0 should be the value for the reference and 1\n \
                   5734:  for the alternative. IMaCh does not build design variables automatically, do it yourself.\n \
                   5735:  For example, for multinomial values like 1, 2 and 3,\n \
                   5736:  build V1=0 V2=0 for the reference value (1),\n \
                   5737:         V1=1 V2=0 for (2) \n \
                   5738:  and V1=0 V2=1 for (3). V1=1 V2=1 should not exist and the corresponding\n \
                   5739:  output of IMaCh is often meaningless.\n \
                   5740:  Exiting.\n",lval,linei, i,line,j);fflush(ficlog);
                   5741:        return 1;
                   5742:       }
                   5743:       covar[j][i]=(double)(lval);
                   5744:       strcpy(line,stra);
                   5745:     }  
                   5746:     lstra=strlen(stra);
                   5747:      
                   5748:     if(lstra > 9){ /* More than 2**32 or max of what printf can write with %ld */
                   5749:       stratrunc = &(stra[lstra-9]);
                   5750:       num[i]=atol(stratrunc);
                   5751:     }
                   5752:     else
                   5753:       num[i]=atol(stra);
                   5754:     /*if((s[2][i]==2) && (s[3][i]==-1)&&(s[4][i]==9)){
                   5755:       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;}*/
                   5756:     
                   5757:     i=i+1;
                   5758:   } /* End loop reading  data */
1.126     brouard  5759: 
1.136     brouard  5760:   *imax=i-1; /* Number of individuals */
                   5761:   fclose(fic);
                   5762:  
                   5763:   return (0);
1.164     brouard  5764:   /* endread: */
1.136     brouard  5765:     printf("Exiting readdata: ");
                   5766:     fclose(fic);
                   5767:     return (1);
1.126     brouard  5768: 
                   5769: 
                   5770: 
1.136     brouard  5771: }
1.145     brouard  5772: void removespace(char *str) {
                   5773:   char *p1 = str, *p2 = str;
                   5774:   do
                   5775:     while (*p2 == ' ')
                   5776:       p2++;
1.169     brouard  5777:   while (*p1++ == *p2++);
1.145     brouard  5778: }
                   5779: 
                   5780: int decodemodel ( char model[], int lastobs) /**< This routine decode the model and returns:
1.187     brouard  5781:    * Model  V1+V2+V3+V8+V7*V8+V5*V6+V8*age+V3*age+age*age
                   5782:    * - nagesqr = 1 if age*age in the model, otherwise 0.
                   5783:    * - cptcovt total number of covariates of the model nbocc(+)+1 = 8 excepting constant and age and age*age
                   5784:    * - cptcovn or number of covariates k of the models excluding age*products =6 and age*age
1.145     brouard  5785:    * - cptcovage number of covariates with age*products =2
                   5786:    * - cptcovs number of simple covariates
                   5787:    * - 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
                   5788:    *     which is a new column after the 9 (ncovcol) variables. 
                   5789:    * - if k is a product Vn*Vm covar[k][i] is filled with correct values for each individual
                   5790:    * - Tprod[l] gives the kth covariates of the product Vn*Vm l=1 to cptcovprod-cptcovage
                   5791:    *    Tprod[1]@2 {5, 6}: position of first product V7*V8 is 5, and second V5*V6 is 6.
                   5792:    * - Tvard[k]  p Tvard[1][1]@4 {7, 8, 5, 6} for V7*V8 and V5*V6 .
                   5793:  */
1.136     brouard  5794: {
1.145     brouard  5795:   int i, j, k, ks;
1.164     brouard  5796:   int  j1, k1, k2;
1.136     brouard  5797:   char modelsav[80];
1.145     brouard  5798:   char stra[80], strb[80], strc[80], strd[80],stre[80];
1.187     brouard  5799:   char *strpt;
1.136     brouard  5800: 
1.145     brouard  5801:   /*removespace(model);*/
1.136     brouard  5802:   if (strlen(model) >1){ /* If there is at least 1 covariate */
1.145     brouard  5803:     j=0, j1=0, k1=0, k2=-1, ks=0, cptcovn=0;
1.137     brouard  5804:     if (strstr(model,"AGE") !=0){
1.192     brouard  5805:       printf("Error. AGE must be in lower case 'age' model=1+age+%s. ",model);
                   5806:       fprintf(ficlog,"Error. AGE must be in lower case model=1+age+%s. ",model);fflush(ficlog);
1.136     brouard  5807:       return 1;
                   5808:     }
1.141     brouard  5809:     if (strstr(model,"v") !=0){
                   5810:       printf("Error. 'v' must be in upper case 'V' model=%s ",model);
                   5811:       fprintf(ficlog,"Error. 'v' must be in upper case model=%s ",model);fflush(ficlog);
                   5812:       return 1;
                   5813:     }
1.187     brouard  5814:     strcpy(modelsav,model); 
                   5815:     if ((strpt=strstr(model,"age*age")) !=0){
                   5816:       printf(" strpt=%s, model=%s\n",strpt, model);
                   5817:       if(strpt != model){
                   5818:       printf("Error in model: 'model=%s'; 'age*age' should in first place before other covariates\n \
1.192     brouard  5819:  'model=1+age+age*age+V1.' or 'model=1+age+age*age+V1+V1*age.', please swap as well as \n \
1.187     brouard  5820:  corresponding column of parameters.\n",model);
                   5821:       fprintf(ficlog,"Error in model: 'model=%s'; 'age*age' should in first place before other covariates\n \
1.192     brouard  5822:  'model=1+age+age*age+V1.' or 'model=1+age+age*age+V1+V1*age.', please swap as well as \n \
1.187     brouard  5823:  corresponding column of parameters.\n",model); fflush(ficlog);
                   5824:       return 1;
                   5825:     }
                   5826: 
                   5827:       nagesqr=1;
                   5828:       if (strstr(model,"+age*age") !=0)
                   5829:        substrchaine(modelsav, model, "+age*age");
                   5830:       else if (strstr(model,"age*age+") !=0)
                   5831:        substrchaine(modelsav, model, "age*age+");
                   5832:       else 
                   5833:        substrchaine(modelsav, model, "age*age");
                   5834:     }else
                   5835:       nagesqr=0;
                   5836:     if (strlen(modelsav) >1){
                   5837:       j=nbocc(modelsav,'+'); /**< j=Number of '+' */
                   5838:       j1=nbocc(modelsav,'*'); /**< j1=Number of '*' */
                   5839:       cptcovs=j+1-j1; /**<  Number of simple covariates V1+V1*age+V3 +V3*V4+age*age=> V1 + V3 =2  */
                   5840:       cptcovt= j+1; /* Number of total covariates in the model, not including
                   5841:                   * cst, age and age*age 
                   5842:                   * V1+V1*age+ V3 + V3*V4+age*age=> 4*/
                   5843:                   /* including age products which are counted in cptcovage.
                   5844:                  * but the covariates which are products must be treated 
                   5845:                  * separately: ncovn=4- 2=2 (V1+V3). */
                   5846:       cptcovprod=j1; /**< Number of products  V1*V2 +v3*age = 2 */
                   5847:       cptcovprodnoage=0; /**< Number of covariate products without age: V3*V4 =1  */
                   5848: 
                   5849:     
                   5850:       /*   Design
                   5851:        *  V1   V2   V3   V4  V5  V6  V7  V8  V9 Weight
                   5852:        *  <          ncovcol=8                >
                   5853:        * Model V2 + V1 + V3*age + V3 + V5*V6 + V7*V8 + V8*age + V8
                   5854:        *   k=  1    2      3       4     5       6      7        8
                   5855:        *  cptcovn number of covariates (not including constant and age ) = # of + plus 1 = 7+1=8
                   5856:        *  covar[k,i], value of kth covariate if not including age for individual i:
                   5857:        *       covar[1][i]= (V2), covar[4][i]=(V3), covar[8][i]=(V8)
                   5858:        *  Tvar[k] # of the kth covariate:  Tvar[1]=2  Tvar[4]=3 Tvar[8]=8
                   5859:        *       if multiplied by age: V3*age Tvar[3=V3*age]=3 (V3) Tvar[7]=8 and 
                   5860:        *  Tage[++cptcovage]=k
                   5861:        *       if products, new covar are created after ncovcol with k1
                   5862:        *  Tvar[k]=ncovcol+k1; # of the kth covariate product:  Tvar[5]=ncovcol+1=10  Tvar[6]=ncovcol+1=11
                   5863:        *  Tprod[k1]=k; Tprod[1]=5 Tprod[2]= 6; gives the position of the k1th product
                   5864:        *  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
                   5865:        *  Tvar[cptcovn+k2]=Tvard[k1][1];Tvar[cptcovn+k2+1]=Tvard[k1][2];
                   5866:        *  Tvar[8+1]=5;Tvar[8+2]=6;Tvar[8+3]=7;Tvar[8+4]=8 inverted
                   5867:        *  V1   V2   V3   V4  V5  V6  V7  V8  V9  V10  V11
                   5868:        *  <          ncovcol=8                >
                   5869:        *       Model V2 + V1 + V3*age + V3 + V5*V6 + V7*V8 + V8*age + V8    d1   d1   d2  d2
                   5870:        *          k=  1    2      3       4     5       6      7        8    9   10   11  12
                   5871:        *     Tvar[k]= 2    1      3       3    10      11      8        8    5    6    7   8
                   5872:        * p Tvar[1]@12={2,   1,     3,      3,   11,     10,     8,       8,   7,   8,   5,  6}
                   5873:        * p Tprod[1]@2={                         6, 5}
                   5874:        *p Tvard[1][1]@4= {7, 8, 5, 6}
                   5875:        * covar[k][i]= V2   V1      ?      V3    V5*V6?   V7*V8?  ?       V8   
                   5876:        *  cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*cov[2];
                   5877:        *How to reorganize?
                   5878:        * Model V1 + V2 + V3 + V8 + V5*V6 + V7*V8 + V3*age + V8*age
                   5879:        * Tvars {2,   1,     3,      3,   11,     10,     8,       8,   7,   8,   5,  6}
                   5880:        *       {2,   1,     4,      8,    5,      6,     3,       7}
                   5881:        * Struct []
                   5882:        */
1.145     brouard  5883: 
1.187     brouard  5884:       /* This loop fills the array Tvar from the string 'model'.*/
                   5885:       /* j is the number of + signs in the model V1+V2+V3 j=2 i=3 to 1 */
                   5886:       /*   modelsav=V2+V1+V4+age*V3 strb=age*V3 stra=V2+V1+V4  */
                   5887:       /*       k=4 (age*V3) Tvar[k=4]= 3 (from V3) Tage[cptcovage=1]=4 */
                   5888:       /*       k=3 V4 Tvar[k=3]= 4 (from V4) */
                   5889:       /*       k=2 V1 Tvar[k=2]= 1 (from V1) */
                   5890:       /*       k=1 Tvar[1]=2 (from V2) */
                   5891:       /*       k=5 Tvar[5] */
                   5892:       /* for (k=1; k<=cptcovn;k++) { */
1.198     brouard  5893:       /*       cov[2+k]=nbcode[Tvar[k]][codtabm(ij,Tvar[k])]; */
1.187     brouard  5894:       /*       } */
1.198     brouard  5895:       /* for (k=1; k<=cptcovage;k++) cov[2+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(ij,Tvar[Tage[k])]]*cov[2]; */
1.187     brouard  5896:       /*
                   5897:        * Treating invertedly V2+V1+V3*age+V2*V4 is as if written V2*V4 +V3*age + V1 + V2 */
                   5898:       for(k=cptcovt; k>=1;k--) /**< Number of covariates */
1.145     brouard  5899:         Tvar[k]=0;
1.187     brouard  5900:       cptcovage=0;
                   5901:       for(k=1; k<=cptcovt;k++){ /* Loop on total covariates of the model */
                   5902:        cutl(stra,strb,modelsav,'+'); /* keeps in strb after the first '+' 
                   5903:                                         modelsav==V2+V1+V4+V3*age strb=V3*age stra=V2+V1+V4 */ 
                   5904:        if (nbocc(modelsav,'+')==0) strcpy(strb,modelsav); /* and analyzes it */
                   5905:        /*      printf("i=%d a=%s b=%s sav=%s\n",i, stra,strb,modelsav);*/
                   5906:        /*scanf("%d",i);*/
                   5907:        if (strchr(strb,'*')) {  /**< Model includes a product V2+V1+V4+V3*age strb=V3*age */
                   5908:          cutl(strc,strd,strb,'*'); /**< strd*strc  Vm*Vn: strb=V3*age(input) strc=age strd=V3 ; V3*V2 strc=V2, strd=V3 */
                   5909:          if (strcmp(strc,"age")==0) { /**< Model includes age: Vn*age */
                   5910:            /* covar is not filled and then is empty */
                   5911:            cptcovprod--;
                   5912:            cutl(stre,strb,strd,'V'); /* strd=V3(input): stre="3" */
                   5913:            Tvar[k]=atoi(stre);  /* V2+V1+V4+V3*age Tvar[4]=3 ; V1+V2*age Tvar[2]=2; V1+V1*age Tvar[2]=1 */
                   5914:            cptcovage++; /* Sums the number of covariates which include age as a product */
                   5915:            Tage[cptcovage]=k;  /* Tvar[4]=3, Tage[1] = 4 or V1+V1*age Tvar[2]=1, Tage[1]=2 */
                   5916:            /*printf("stre=%s ", stre);*/
                   5917:          } else if (strcmp(strd,"age")==0) { /* or age*Vn */
                   5918:            cptcovprod--;
                   5919:            cutl(stre,strb,strc,'V');
                   5920:            Tvar[k]=atoi(stre);
                   5921:            cptcovage++;
                   5922:            Tage[cptcovage]=k;
                   5923:          } else {  /* Age is not in the model product V2+V1+V1*V4+V3*age+V3*V2  strb=V3*V2*/
                   5924:            /* loops on k1=1 (V3*V2) and k1=2 V4*V3 */
                   5925:            cptcovn++;
                   5926:            cptcovprodnoage++;k1++;
                   5927:            cutl(stre,strb,strc,'V'); /* strc= Vn, stre is n; strb=V3*V2 stre=3 strc=*/
                   5928:            Tvar[k]=ncovcol+k1; /* For model-covariate k tells which data-covariate to use but
                   5929:                                   because this model-covariate is a construction we invent a new column
                   5930:                                   ncovcol + k1
                   5931:                                   If already ncovcol=4 and model=V2+V1+V1*V4+age*V3+V3*V2
                   5932:                                   Tvar[3=V1*V4]=4+1 Tvar[5=V3*V2]=4 + 2= 6, etc */
                   5933:            cutl(strc,strb,strd,'V'); /* strd was Vm, strc is m */
                   5934:            Tprod[k1]=k;  /* Tprod[1]=3(=V1*V4) for V2+V1+V1*V4+age*V3+V3*V2  */
                   5935:            Tvard[k1][1] =atoi(strc); /* m 1 for V1*/
                   5936:            Tvard[k1][2] =atoi(stre); /* n 4 for V4*/
                   5937:            k2=k2+2;
                   5938:            Tvar[cptcovt+k2]=Tvard[k1][1]; /* Tvar[(cptcovt=4+k2=1)=5]= 1 (V1) */
                   5939:            Tvar[cptcovt+k2+1]=Tvard[k1][2];  /* Tvar[(cptcovt=4+(k2=1)+1)=6]= 4 (V4) */
                   5940:            for (i=1; i<=lastobs;i++){
                   5941:              /* Computes the new covariate which is a product of
                   5942:                 covar[n][i]* covar[m][i] and stores it at ncovol+k1 May not be defined */
                   5943:              covar[ncovcol+k1][i]=covar[atoi(stre)][i]*covar[atoi(strc)][i];
                   5944:            }
                   5945:          } /* End age is not in the model */
                   5946:        } /* End if model includes a product */
                   5947:        else { /* no more sum */
                   5948:          /*printf("d=%s c=%s b=%s\n", strd,strc,strb);*/
                   5949:          /*  scanf("%d",i);*/
                   5950:          cutl(strd,strc,strb,'V');
                   5951:          ks++; /**< Number of simple covariates */
1.145     brouard  5952:          cptcovn++;
1.187     brouard  5953:          Tvar[k]=atoi(strd);
                   5954:        }
                   5955:        strcpy(modelsav,stra);  /* modelsav=V2+V1+V4 stra=V2+V1+V4 */ 
                   5956:        /*printf("a=%s b=%s sav=%s\n", stra,strb,modelsav);
                   5957:          scanf("%d",i);*/
                   5958:       } /* end of loop + on total covariates */
                   5959:     } /* end if strlen(modelsave == 0) age*age might exist */
                   5960:   } /* end if strlen(model == 0) */
1.136     brouard  5961:   
                   5962:   /*The number n of Vn is stored in Tvar. cptcovage =number of age covariate. Tage gives the position of age. cptcovprod= number of products.
                   5963:     If model=V1+V1*age then Tvar[1]=1 Tvar[2]=1 cptcovage=1 Tage[1]=2 cptcovprod=0*/
                   5964: 
                   5965:   /* printf("tvar1=%d tvar2=%d tvar3=%d cptcovage=%d Tage=%d",Tvar[1],Tvar[2],Tvar[3],cptcovage,Tage[1]);
                   5966:   printf("cptcovprod=%d ", cptcovprod);
                   5967:   fprintf(ficlog,"cptcovprod=%d ", cptcovprod);
                   5968: 
                   5969:   scanf("%d ",i);*/
                   5970: 
                   5971: 
1.137     brouard  5972:   return (0); /* with covar[new additional covariate if product] and Tage if age */ 
1.164     brouard  5973:   /*endread:*/
1.136     brouard  5974:     printf("Exiting decodemodel: ");
                   5975:     return (1);
                   5976: }
                   5977: 
1.169     brouard  5978: int calandcheckages(int imx, int maxwav, double *agemin, double *agemax, int *nberr, int *nbwarn )
1.136     brouard  5979: {
                   5980:   int i, m;
                   5981: 
                   5982:   for (i=1; i<=imx; i++) {
                   5983:     for(m=2; (m<= maxwav); m++) {
                   5984:       if (((int)mint[m][i]== 99) && (s[m][i] <= nlstate)){
                   5985:        anint[m][i]=9999;
                   5986:        s[m][i]=-1;
                   5987:       }
                   5988:       if((int)moisdc[i]==99 && (int)andc[i]==9999 && s[m][i]>nlstate){
1.169     brouard  5989:        *nberr = *nberr + 1;
                   5990:        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);
                   5991:        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  5992:        s[m][i]=-1;
                   5993:       }
                   5994:       if((int)moisdc[i]==99 && (int)andc[i]!=9999 && s[m][i]>nlstate){
1.169     brouard  5995:        (*nberr)++;
1.136     brouard  5996:        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]); 
                   5997:        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]); 
                   5998:        s[m][i]=-1; /* We prefer to skip it (and to skip it in version 0.8a1 too */
                   5999:       }
                   6000:     }
                   6001:   }
                   6002: 
                   6003:   for (i=1; i<=imx; i++)  {
                   6004:     agedc[i]=(moisdc[i]/12.+andc[i])-(moisnais[i]/12.+annais[i]);
                   6005:     for(m=firstpass; (m<= lastpass); m++){
                   6006:       if(s[m][i] >0 || s[m][i]==-2 || s[m][i]==-4 || s[m][i]==-5){
                   6007:        if (s[m][i] >= nlstate+1) {
1.169     brouard  6008:          if(agedc[i]>0){
                   6009:            if((int)moisdc[i]!=99 && (int)andc[i]!=9999){
1.136     brouard  6010:              agev[m][i]=agedc[i];
                   6011:          /*if(moisdc[i]==99 && andc[i]==9999) s[m][i]=-1;*/
1.169     brouard  6012:            }else {
1.136     brouard  6013:              if ((int)andc[i]!=9999){
                   6014:                nbwarn++;
                   6015:                printf("Warning negative age at death: %ld line:%d\n",num[i],i);
                   6016:                fprintf(ficlog,"Warning negative age at death: %ld line:%d\n",num[i],i);
                   6017:                agev[m][i]=-1;
                   6018:              }
                   6019:            }
1.169     brouard  6020:          } /* agedc > 0 */
1.136     brouard  6021:        }
                   6022:        else if(s[m][i] !=9){ /* Standard case, age in fractional
                   6023:                                 years but with the precision of a month */
                   6024:          agev[m][i]=(mint[m][i]/12.+1./24.+anint[m][i])-(moisnais[i]/12.+1./24.+annais[i]);
                   6025:          if((int)mint[m][i]==99 || (int)anint[m][i]==9999)
                   6026:            agev[m][i]=1;
                   6027:          else if(agev[m][i] < *agemin){ 
                   6028:            *agemin=agev[m][i];
                   6029:            printf(" Min anint[%d][%d]=%.2f annais[%d]=%.2f, agemin=%.2f\n",m,i,anint[m][i], i,annais[i], *agemin);
                   6030:          }
                   6031:          else if(agev[m][i] >*agemax){
                   6032:            *agemax=agev[m][i];
1.156     brouard  6033:            /* printf(" Max anint[%d][%d]=%.0f annais[%d]=%.0f, agemax=%.2f\n",m,i,anint[m][i], i,annais[i], *agemax);*/
1.136     brouard  6034:          }
                   6035:          /*agev[m][i]=anint[m][i]-annais[i];*/
                   6036:          /*     agev[m][i] = age[i]+2*m;*/
                   6037:        }
                   6038:        else { /* =9 */
                   6039:          agev[m][i]=1;
                   6040:          s[m][i]=-1;
                   6041:        }
                   6042:       }
                   6043:       else /*= 0 Unknown */
                   6044:        agev[m][i]=1;
                   6045:     }
                   6046:     
                   6047:   }
                   6048:   for (i=1; i<=imx; i++)  {
                   6049:     for(m=firstpass; (m<=lastpass); m++){
                   6050:       if (s[m][i] > (nlstate+ndeath)) {
1.169     brouard  6051:        (*nberr)++;
1.136     brouard  6052:        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);     
                   6053:        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);     
                   6054:        return 1;
                   6055:       }
                   6056:     }
                   6057:   }
                   6058: 
                   6059:   /*for (i=1; i<=imx; i++){
                   6060:   for (m=firstpass; (m<lastpass); m++){
                   6061:      printf("%ld %d %.lf %d %d\n", num[i],(covar[1][i]),agev[m][i],s[m][i],s[m+1][i]);
                   6062: }
                   6063: 
                   6064: }*/
                   6065: 
                   6066: 
1.139     brouard  6067:   printf("Total number of individuals= %d, Agemin = %.2f, Agemax= %.2f\n\n", imx, *agemin, *agemax);
                   6068:   fprintf(ficlog,"Total number of individuals= %d, Agemin = %.2f, Agemax= %.2f\n\n", imx, *agemin, *agemax); 
1.136     brouard  6069: 
                   6070:   return (0);
1.164     brouard  6071:  /* endread:*/
1.136     brouard  6072:     printf("Exiting calandcheckages: ");
                   6073:     return (1);
                   6074: }
                   6075: 
1.172     brouard  6076: #if defined(_MSC_VER)
                   6077: /*printf("Visual C++ compiler: %s \n;", _MSC_FULL_VER);*/
                   6078: /*fprintf(ficlog, "Visual C++ compiler: %s \n;", _MSC_FULL_VER);*/
                   6079: //#include "stdafx.h"
                   6080: //#include <stdio.h>
                   6081: //#include <tchar.h>
                   6082: //#include <windows.h>
                   6083: //#include <iostream>
                   6084: typedef BOOL(WINAPI *LPFN_ISWOW64PROCESS) (HANDLE, PBOOL);
                   6085: 
                   6086: LPFN_ISWOW64PROCESS fnIsWow64Process;
                   6087: 
                   6088: BOOL IsWow64()
                   6089: {
                   6090:        BOOL bIsWow64 = FALSE;
                   6091: 
                   6092:        //typedef BOOL (APIENTRY *LPFN_ISWOW64PROCESS)
                   6093:        //  (HANDLE, PBOOL);
                   6094: 
                   6095:        //LPFN_ISWOW64PROCESS fnIsWow64Process;
                   6096: 
                   6097:        HMODULE module = GetModuleHandle(_T("kernel32"));
                   6098:        const char funcName[] = "IsWow64Process";
                   6099:        fnIsWow64Process = (LPFN_ISWOW64PROCESS)
                   6100:                GetProcAddress(module, funcName);
                   6101: 
                   6102:        if (NULL != fnIsWow64Process)
                   6103:        {
                   6104:                if (!fnIsWow64Process(GetCurrentProcess(),
                   6105:                        &bIsWow64))
                   6106:                        //throw std::exception("Unknown error");
                   6107:                        printf("Unknown error\n");
                   6108:        }
                   6109:        return bIsWow64 != FALSE;
                   6110: }
                   6111: #endif
1.177     brouard  6112: 
1.191     brouard  6113: void syscompilerinfo(int logged)
1.167     brouard  6114:  {
                   6115:    /* #include "syscompilerinfo.h"*/
1.185     brouard  6116:    /* command line Intel compiler 32bit windows, XP compatible:*/
                   6117:    /* /GS /W3 /Gy
                   6118:       /Zc:wchar_t /Zi /O2 /Fd"Release\vc120.pdb" /D "WIN32" /D "NDEBUG" /D
                   6119:       "_CONSOLE" /D "_LIB" /D "_USING_V110_SDK71_" /D "_UNICODE" /D
                   6120:       "UNICODE" /Qipo /Zc:forScope /Gd /Oi /MT /Fa"Release\" /EHsc /nologo
1.186     brouard  6121:       /Fo"Release\" /Qprof-dir "Release\" /Fp"Release\IMaCh.pch"
                   6122:    */ 
                   6123:    /* 64 bits */
1.185     brouard  6124:    /*
                   6125:      /GS /W3 /Gy
                   6126:      /Zc:wchar_t /Zi /O2 /Fd"x64\Release\vc120.pdb" /D "WIN32" /D "NDEBUG"
                   6127:      /D "_CONSOLE" /D "_LIB" /D "_UNICODE" /D "UNICODE" /Qipo /Zc:forScope
                   6128:      /Oi /MD /Fa"x64\Release\" /EHsc /nologo /Fo"x64\Release\" /Qprof-dir
                   6129:      "x64\Release\" /Fp"x64\Release\IMaCh.pch" */
                   6130:    /* Optimization are useless and O3 is slower than O2 */
                   6131:    /*
                   6132:      /GS /W3 /Gy /Zc:wchar_t /Zi /O3 /Fd"x64\Release\vc120.pdb" /D "WIN32" 
                   6133:      /D "NDEBUG" /D "_CONSOLE" /D "_LIB" /D "_UNICODE" /D "UNICODE" /Qipo 
                   6134:      /Zc:forScope /Oi /MD /Fa"x64\Release\" /EHsc /nologo /Qparallel 
                   6135:      /Fo"x64\Release\" /Qprof-dir "x64\Release\" /Fp"x64\Release\IMaCh.pch" 
                   6136:    */
1.186     brouard  6137:    /* Link is */ /* /OUT:"visual studio
1.185     brouard  6138:       2013\Projects\IMaCh\Release\IMaCh.exe" /MANIFEST /NXCOMPAT
                   6139:       /PDB:"visual studio
                   6140:       2013\Projects\IMaCh\Release\IMaCh.pdb" /DYNAMICBASE
                   6141:       "kernel32.lib" "user32.lib" "gdi32.lib" "winspool.lib"
                   6142:       "comdlg32.lib" "advapi32.lib" "shell32.lib" "ole32.lib"
                   6143:       "oleaut32.lib" "uuid.lib" "odbc32.lib" "odbccp32.lib"
                   6144:       /MACHINE:X86 /OPT:REF /SAFESEH /INCREMENTAL:NO
                   6145:       /SUBSYSTEM:CONSOLE",5.01" /MANIFESTUAC:"level='asInvoker'
                   6146:       uiAccess='false'"
                   6147:       /ManifestFile:"Release\IMaCh.exe.intermediate.manifest" /OPT:ICF
                   6148:       /NOLOGO /TLBID:1
                   6149:    */
1.177     brouard  6150: #if defined __INTEL_COMPILER
1.178     brouard  6151: #if defined(__GNUC__)
                   6152:        struct utsname sysInfo;  /* For Intel on Linux and OS/X */
                   6153: #endif
1.177     brouard  6154: #elif defined(__GNUC__) 
1.179     brouard  6155: #ifndef  __APPLE__
1.174     brouard  6156: #include <gnu/libc-version.h>  /* Only on gnu */
1.179     brouard  6157: #endif
1.177     brouard  6158:    struct utsname sysInfo;
1.178     brouard  6159:    int cross = CROSS;
                   6160:    if (cross){
                   6161:           printf("Cross-");
1.191     brouard  6162:           if(logged) fprintf(ficlog, "Cross-");
1.178     brouard  6163:    }
1.174     brouard  6164: #endif
                   6165: 
1.171     brouard  6166: #include <stdint.h>
1.178     brouard  6167: 
1.191     brouard  6168:    printf("Compiled with:");if(logged)fprintf(ficlog,"Compiled with:");
1.169     brouard  6169: #if defined(__clang__)
1.191     brouard  6170:    printf(" Clang/LLVM");if(logged)fprintf(ficlog," Clang/LLVM");      /* Clang/LLVM. ---------------------------------------------- */
1.169     brouard  6171: #endif
                   6172: #if defined(__ICC) || defined(__INTEL_COMPILER)
1.191     brouard  6173:    printf(" Intel ICC/ICPC");if(logged)fprintf(ficlog," Intel ICC/ICPC");/* Intel ICC/ICPC. ------------------------------------------ */
1.169     brouard  6174: #endif
                   6175: #if defined(__GNUC__) || defined(__GNUG__)
1.191     brouard  6176:    printf(" GNU GCC/G++");if(logged)fprintf(ficlog," GNU GCC/G++");/* GNU GCC/G++. --------------------------------------------- */
1.169     brouard  6177: #endif
                   6178: #if defined(__HP_cc) || defined(__HP_aCC)
1.191     brouard  6179:    printf(" Hewlett-Packard C/aC++");if(logged)fprintf(fcilog," Hewlett-Packard C/aC++"); /* Hewlett-Packard C/aC++. ---------------------------------- */
1.169     brouard  6180: #endif
                   6181: #if defined(__IBMC__) || defined(__IBMCPP__)
1.191     brouard  6182:    printf(" IBM XL C/C++"); if(logged) fprintf(ficlog," IBM XL C/C++");/* IBM XL C/C++. -------------------------------------------- */
1.169     brouard  6183: #endif
                   6184: #if defined(_MSC_VER)
1.191     brouard  6185:    printf(" Microsoft Visual Studio");if(logged)fprintf(ficlog," Microsoft Visual Studio");/* Microsoft Visual Studio. --------------------------------- */
1.169     brouard  6186: #endif
                   6187: #if defined(__PGI)
1.191     brouard  6188:    printf(" Portland Group PGCC/PGCPP");if(logged) fprintf(ficlog," Portland Group PGCC/PGCPP");/* Portland Group PGCC/PGCPP. ------------------------------- */
1.169     brouard  6189: #endif
                   6190: #if defined(__SUNPRO_C) || defined(__SUNPRO_CC)
1.191     brouard  6191:    printf(" Oracle Solaris Studio");if(logged)fprintf(ficlog," Oracle Solaris Studio\n");/* Oracle Solaris Studio. ----------------------------------- */
1.167     brouard  6192: #endif
1.191     brouard  6193:    printf(" for "); if (logged) fprintf(ficlog, " for ");
1.169     brouard  6194:    
1.167     brouard  6195: // http://stackoverflow.com/questions/4605842/how-to-identify-platform-compiler-from-preprocessor-macros
                   6196: #ifdef _WIN32 // note the underscore: without it, it's not msdn official!
                   6197:     // Windows (x64 and x86)
1.191     brouard  6198:    printf("Windows (x64 and x86) ");if(logged) fprintf(ficlog,"Windows (x64 and x86) ");
1.167     brouard  6199: #elif __unix__ // all unices, not all compilers
                   6200:     // Unix
1.191     brouard  6201:    printf("Unix ");if(logged) fprintf(ficlog,"Unix ");
1.167     brouard  6202: #elif __linux__
                   6203:     // linux
1.191     brouard  6204:    printf("linux ");if(logged) fprintf(ficlog,"linux ");
1.167     brouard  6205: #elif __APPLE__
1.174     brouard  6206:     // Mac OS, not sure if this is covered by __posix__ and/or __unix__ though..
1.191     brouard  6207:    printf("Mac OS ");if(logged) fprintf(ficlog,"Mac OS ");
1.167     brouard  6208: #endif
                   6209: 
                   6210: /*  __MINGW32__          */
                   6211: /*  __CYGWIN__  */
                   6212: /* __MINGW64__  */
                   6213: // http://msdn.microsoft.com/en-us/library/b0084kay.aspx
                   6214: /* _MSC_VER  //the Visual C++ compiler is 17.00.51106.1, the _MSC_VER macro evaluates to 1700. Type cl /?  */
                   6215: /* _MSC_FULL_VER //the Visual C++ compiler is 15.00.20706.01, the _MSC_FULL_VER macro evaluates to 150020706 */
                   6216: /* _WIN64  // Defined for applications for Win64. */
                   6217: /* _M_X64 // Defined for compilations that target x64 processors. */
                   6218: /* _DEBUG // Defined when you compile with /LDd, /MDd, and /MTd. */
1.171     brouard  6219: 
1.167     brouard  6220: #if UINTPTR_MAX == 0xffffffff
1.191     brouard  6221:    printf(" 32-bit"); if(logged) fprintf(ficlog," 32-bit");/* 32-bit */
1.167     brouard  6222: #elif UINTPTR_MAX == 0xffffffffffffffff
1.191     brouard  6223:    printf(" 64-bit"); if(logged) fprintf(ficlog," 64-bit");/* 64-bit */
1.167     brouard  6224: #else
1.191     brouard  6225:    printf(" wtf-bit"); if(logged) fprintf(ficlog," wtf-bit");/* wtf */
1.167     brouard  6226: #endif
                   6227: 
1.169     brouard  6228: #if defined(__GNUC__)
                   6229: # if defined(__GNUC_PATCHLEVEL__)
                   6230: #  define __GNUC_VERSION__ (__GNUC__ * 10000 \
                   6231:                             + __GNUC_MINOR__ * 100 \
                   6232:                             + __GNUC_PATCHLEVEL__)
                   6233: # else
                   6234: #  define __GNUC_VERSION__ (__GNUC__ * 10000 \
                   6235:                             + __GNUC_MINOR__ * 100)
                   6236: # endif
1.174     brouard  6237:    printf(" using GNU C version %d.\n", __GNUC_VERSION__);
1.191     brouard  6238:    if(logged) fprintf(ficlog, " using GNU C version %d.\n", __GNUC_VERSION__);
1.176     brouard  6239: 
                   6240:    if (uname(&sysInfo) != -1) {
                   6241:      printf("Running on: %s %s %s %s %s\n",sysInfo.sysname, sysInfo.nodename, sysInfo.release, sysInfo.version, sysInfo.machine);
1.191     brouard  6242:         if(logged) fprintf(ficlog,"Running on: %s %s %s %s %s\n ",sysInfo.sysname, sysInfo.nodename, sysInfo.release, sysInfo.version, sysInfo.machine);
1.176     brouard  6243:    }
                   6244:    else
                   6245:       perror("uname() error");
1.179     brouard  6246:    //#ifndef __INTEL_COMPILER 
                   6247: #if !defined (__INTEL_COMPILER) && !defined(__APPLE__)
1.174     brouard  6248:    printf("GNU libc version: %s\n", gnu_get_libc_version()); 
1.191     brouard  6249:    if(logged) fprintf(ficlog,"GNU libc version: %s\n", gnu_get_libc_version());
1.177     brouard  6250: #endif
1.169     brouard  6251: #endif
1.172     brouard  6252: 
                   6253:    //   void main()
                   6254:    //   {
1.169     brouard  6255: #if defined(_MSC_VER)
1.174     brouard  6256:    if (IsWow64()){
1.191     brouard  6257:           printf("\nThe program (probably compiled for 32bit) is running under WOW64 (64bit) emulation.\n");
                   6258:           if (logged) fprintf(ficlog, "\nThe program (probably compiled for 32bit) is running under WOW64 (64bit) emulation.\n");
1.174     brouard  6259:    }
                   6260:    else{
1.191     brouard  6261:           printf("\nThe program is not running under WOW64 (i.e probably on a 64bit Windows).\n");
                   6262:           if (logged) fprintf(ficlog, "\nThe programm is not running under WOW64 (i.e probably on a 64bit Windows).\n");
1.174     brouard  6263:    }
1.172     brouard  6264:    //     printf("\nPress Enter to continue...");
                   6265:    //     getchar();
                   6266:    //   }
                   6267: 
1.169     brouard  6268: #endif
                   6269:    
1.167     brouard  6270: 
                   6271:  }
1.136     brouard  6272: 
1.180     brouard  6273: int prevalence_limit(double *p, double **prlim, double ageminpar, double agemaxpar){
                   6274:   /*--------------- Prevalence limit  (period or stable prevalence) --------------*/
                   6275:   int i, j, k, i1 ;
                   6276:   double ftolpl = 1.e-10;
                   6277:   double age, agebase, agelim;
                   6278: 
1.201   ! brouard  6279:     strcpy(filerespl,"PL_");
        !          6280:     strcat(filerespl,fileresu);
1.180     brouard  6281:     if((ficrespl=fopen(filerespl,"w"))==NULL) {
                   6282:       printf("Problem with period (stable) prevalence resultfile: %s\n", filerespl);return 1;
                   6283:       fprintf(ficlog,"Problem with period (stable) prevalence resultfile: %s\n", filerespl);return 1;
                   6284:     }
                   6285:     printf("Computing period (stable) prevalence: result on file '%s' \n", filerespl);
                   6286:     fprintf(ficlog,"Computing period (stable) prevalence: result on file '%s' \n", filerespl);
                   6287:     pstamp(ficrespl);
                   6288:     fprintf(ficrespl,"# Period (stable) prevalence \n");
                   6289:     fprintf(ficrespl,"#Age ");
                   6290:     for(i=1; i<=nlstate;i++) fprintf(ficrespl,"%d-%d ",i,i);
                   6291:     fprintf(ficrespl,"\n");
                   6292:   
                   6293:     /* prlim=matrix(1,nlstate,1,nlstate);*/ /* back in main */
                   6294: 
                   6295:     agebase=ageminpar;
                   6296:     agelim=agemaxpar;
                   6297: 
                   6298:     i1=pow(2,cptcoveff);
                   6299:     if (cptcovn < 1){i1=1;}
                   6300: 
                   6301:     for(cptcov=1,k=0;cptcov<=i1;cptcov++){
                   6302:     /* for(cptcov=1,k=0;cptcov<=1;cptcov++){ */
                   6303:       //for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){
                   6304:        k=k+1;
                   6305:        /* to clean */
1.198     brouard  6306:        //printf("cptcov=%d cptcod=%d codtab=%d\n",cptcov, cptcod,codtabm(cptcod,cptcov));
1.200     brouard  6307:        fprintf(ficrespl,"#******");
                   6308:        printf("#******");
                   6309:        fprintf(ficlog,"#******");
1.180     brouard  6310:        for(j=1;j<=cptcoveff;j++) {
1.198     brouard  6311:          fprintf(ficrespl," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
                   6312:          printf(" V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
                   6313:          fprintf(ficlog," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
1.180     brouard  6314:        }
                   6315:        fprintf(ficrespl,"******\n");
                   6316:        printf("******\n");
                   6317:        fprintf(ficlog,"******\n");
                   6318: 
                   6319:        fprintf(ficrespl,"#Age ");
                   6320:        for(j=1;j<=cptcoveff;j++) {
1.200     brouard  6321:          fprintf(ficrespl,"V%d %d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
1.180     brouard  6322:        }
                   6323:        for(i=1; i<=nlstate;i++) fprintf(ficrespl,"%d-%d ",i,i);
                   6324:        fprintf(ficrespl,"\n");
                   6325:        
                   6326:        for (age=agebase; age<=agelim; age++){
                   6327:        /* for (age=agebase; age<=agebase; age++){ */
                   6328:          prevalim(prlim, nlstate, p, age, oldm, savm,ftolpl,k);
                   6329:          fprintf(ficrespl,"%.0f ",age );
                   6330:          for(j=1;j<=cptcoveff;j++)
1.198     brouard  6331:            fprintf(ficrespl,"%d %d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
1.180     brouard  6332:          for(i=1; i<=nlstate;i++)
                   6333:            fprintf(ficrespl," %.5f", prlim[i][i]);
                   6334:          fprintf(ficrespl,"\n");
                   6335:        } /* Age */
                   6336:        /* was end of cptcod */
                   6337:     } /* cptcov */
1.184     brouard  6338:        return 0;
1.180     brouard  6339: }
                   6340: 
                   6341: int hPijx(double *p, int bage, int fage){
                   6342:     /*------------- h Pij x at various ages ------------*/
                   6343: 
                   6344:   int stepsize;
                   6345:   int agelim;
                   6346:   int hstepm;
                   6347:   int nhstepm;
                   6348:   int h, i, i1, j, k;
                   6349: 
                   6350:   double agedeb;
                   6351:   double ***p3mat;
                   6352: 
1.201   ! brouard  6353:     strcpy(filerespij,"PIJ_");  strcat(filerespij,fileresu);
1.180     brouard  6354:     if((ficrespij=fopen(filerespij,"w"))==NULL) {
                   6355:       printf("Problem with Pij resultfile: %s\n", filerespij); return 1;
                   6356:       fprintf(ficlog,"Problem with Pij resultfile: %s\n", filerespij); return 1;
                   6357:     }
                   6358:     printf("Computing pij: result on file '%s' \n", filerespij);
                   6359:     fprintf(ficlog,"Computing pij: result on file '%s' \n", filerespij);
                   6360:   
                   6361:     stepsize=(int) (stepm+YEARM-1)/YEARM;
                   6362:     /*if (stepm<=24) stepsize=2;*/
                   6363: 
                   6364:     agelim=AGESUP;
                   6365:     hstepm=stepsize*YEARM; /* Every year of age */
                   6366:     hstepm=hstepm/stepm; /* Typically 2 years, = 2/6 months = 4 */ 
                   6367: 
                   6368:     /* hstepm=1;   aff par mois*/
                   6369:     pstamp(ficrespij);
                   6370:     fprintf(ficrespij,"#****** h Pij x Probability to be in state j at age x+h being in i at x ");
                   6371:     i1= pow(2,cptcoveff);
1.183     brouard  6372:    /* for(cptcov=1,k=0;cptcov<=i1;cptcov++){ */
                   6373:    /*    /\*for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){*\/ */
                   6374:    /*          k=k+1;  */
                   6375:     for (k=1; k <= (int) pow(2,cptcoveff); k++){
                   6376:       fprintf(ficrespij,"\n#****** ");
                   6377:       for(j=1;j<=cptcoveff;j++) 
1.198     brouard  6378:        fprintf(ficrespij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
1.183     brouard  6379:       fprintf(ficrespij,"******\n");
                   6380:       
                   6381:       for (agedeb=fage; agedeb>=bage; agedeb--){ /* If stepm=6 months */
                   6382:        nhstepm=(int) rint((agelim-agedeb)*YEARM/stepm); /* Typically 20 years = 20*12/6=40 */ 
                   6383:        nhstepm = nhstepm/hstepm; /* Typically 40/4=10 */
                   6384:        
                   6385:        /*        nhstepm=nhstepm*YEARM; aff par mois*/
1.180     brouard  6386:        
1.183     brouard  6387:        p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   6388:        oldm=oldms;savm=savms;
                   6389:        hpxij(p3mat,nhstepm,agedeb,hstepm,p,nlstate,stepm,oldm,savm, k);  
                   6390:        fprintf(ficrespij,"# Cov Agex agex+h hpijx with i,j=");
                   6391:        for(i=1; i<=nlstate;i++)
                   6392:          for(j=1; j<=nlstate+ndeath;j++)
                   6393:            fprintf(ficrespij," %1d-%1d",i,j);
                   6394:        fprintf(ficrespij,"\n");
                   6395:        for (h=0; h<=nhstepm; h++){
                   6396:          /*agedebphstep = agedeb + h*hstepm/YEARM*stepm;*/
                   6397:          fprintf(ficrespij,"%d %3.f %3.f",k, agedeb, agedeb + h*hstepm/YEARM*stepm );
1.180     brouard  6398:          for(i=1; i<=nlstate;i++)
                   6399:            for(j=1; j<=nlstate+ndeath;j++)
1.183     brouard  6400:              fprintf(ficrespij," %.5f", p3mat[i][j][h]);
1.180     brouard  6401:          fprintf(ficrespij,"\n");
                   6402:        }
1.183     brouard  6403:        free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   6404:        fprintf(ficrespij,"\n");
                   6405:       }
1.180     brouard  6406:       /*}*/
                   6407:     }
1.184     brouard  6408:        return 0;
1.180     brouard  6409: }
                   6410: 
                   6411: 
1.136     brouard  6412: /***********************************************/
                   6413: /**************** Main Program *****************/
                   6414: /***********************************************/
                   6415: 
                   6416: int main(int argc, char *argv[])
                   6417: {
                   6418: #ifdef GSL
                   6419:   const gsl_multimin_fminimizer_type *T;
                   6420:   size_t iteri = 0, it;
                   6421:   int rval = GSL_CONTINUE;
                   6422:   int status = GSL_SUCCESS;
                   6423:   double ssval;
                   6424: #endif
                   6425:   int movingaverage(double ***probs, double bage,double fage, double ***mobaverage, int mobilav);
1.164     brouard  6426:   int i,j, k, n=MAXN,iter=0,m,size=100, cptcod;
                   6427: 
                   6428:   int jj, ll, li, lj, lk;
1.136     brouard  6429:   int numlinepar=0; /* Current linenumber of parameter file */
1.197     brouard  6430:   int num_filled;
1.136     brouard  6431:   int itimes;
                   6432:   int NDIM=2;
                   6433:   int vpopbased=0;
                   6434: 
1.164     brouard  6435:   char ca[32], cb[32];
1.136     brouard  6436:   /*  FILE *fichtm; *//* Html File */
                   6437:   /* FILE *ficgp;*/ /*Gnuplot File */
                   6438:   struct stat info;
1.191     brouard  6439:   double agedeb=0.;
1.194     brouard  6440: 
                   6441:   double ageminpar=AGEOVERFLOW,agemin=AGEOVERFLOW, agemaxpar=-AGEOVERFLOW, agemax=-AGEOVERFLOW;
1.136     brouard  6442: 
1.165     brouard  6443:   double fret;
1.191     brouard  6444:   double dum=0.; /* Dummy variable */
1.136     brouard  6445:   double ***p3mat;
                   6446:   double ***mobaverage;
1.164     brouard  6447: 
                   6448:   char line[MAXLINE];
1.197     brouard  6449:   char path[MAXLINE],pathc[MAXLINE],pathcd[MAXLINE],pathtot[MAXLINE];
                   6450: 
                   6451:   char model[MAXLINE], modeltemp[MAXLINE];
1.136     brouard  6452:   char pathr[MAXLINE], pathimach[MAXLINE]; 
1.164     brouard  6453:   char *tok, *val; /* pathtot */
1.136     brouard  6454:   int firstobs=1, lastobs=10;
1.195     brouard  6455:   int c,  h , cpt, c2;
1.191     brouard  6456:   int jl=0;
                   6457:   int i1, j1, jk, stepsize=0;
1.194     brouard  6458:   int count=0;
                   6459: 
1.164     brouard  6460:   int *tab; 
1.136     brouard  6461:   int mobilavproj=0 , prevfcast=0 ; /* moving average of prev, If prevfcast=1 prevalence projection */
                   6462:   int mobilav=0,popforecast=0;
1.191     brouard  6463:   int hstepm=0, nhstepm=0;
1.136     brouard  6464:   int agemortsup;
                   6465:   float  sumlpop=0.;
                   6466:   double jprev1=1, mprev1=1,anprev1=2000,jprev2=1, mprev2=1,anprev2=2000;
                   6467:   double jpyram=1, mpyram=1,anpyram=2000,jpyram1=1, mpyram1=1,anpyram1=2000;
                   6468: 
1.191     brouard  6469:   double bage=0, fage=110., age, agelim=0., agebase=0.;
1.136     brouard  6470:   double ftolpl=FTOL;
                   6471:   double **prlim;
                   6472:   double ***param; /* Matrix of parameters */
                   6473:   double  *p;
                   6474:   double **matcov; /* Matrix of covariance */
                   6475:   double ***delti3; /* Scale */
                   6476:   double *delti; /* Scale */
                   6477:   double ***eij, ***vareij;
                   6478:   double **varpl; /* Variances of prevalence limits by age */
                   6479:   double *epj, vepp;
1.164     brouard  6480: 
1.136     brouard  6481:   double dateprev1, dateprev2,jproj1=1,mproj1=1,anproj1=2000,jproj2=1,mproj2=1,anproj2=2000;
                   6482:   double **ximort;
1.145     brouard  6483:   char *alph[]={"a","a","b","c","d","e"}, str[4]="1234";
1.136     brouard  6484:   int *dcwave;
                   6485: 
1.164     brouard  6486:   char z[1]="c";
1.136     brouard  6487: 
                   6488:   /*char  *strt;*/
                   6489:   char strtend[80];
1.126     brouard  6490: 
1.164     brouard  6491: 
1.126     brouard  6492: /*   setlocale (LC_ALL, ""); */
                   6493: /*   bindtextdomain (PACKAGE, LOCALEDIR); */
                   6494: /*   textdomain (PACKAGE); */
                   6495: /*   setlocale (LC_CTYPE, ""); */
                   6496: /*   setlocale (LC_MESSAGES, ""); */
                   6497: 
                   6498:   /*   gettimeofday(&start_time, (struct timezone*)0); */ /* at first time */
1.157     brouard  6499:   rstart_time = time(NULL);  
                   6500:   /*  (void) gettimeofday(&start_time,&tzp);*/
                   6501:   start_time = *localtime(&rstart_time);
1.126     brouard  6502:   curr_time=start_time;
1.157     brouard  6503:   /*tml = *localtime(&start_time.tm_sec);*/
                   6504:   /* strcpy(strstart,asctime(&tml)); */
                   6505:   strcpy(strstart,asctime(&start_time));
1.126     brouard  6506: 
                   6507: /*  printf("Localtime (at start)=%s",strstart); */
1.157     brouard  6508: /*  tp.tm_sec = tp.tm_sec +86400; */
                   6509: /*  tm = *localtime(&start_time.tm_sec); */
1.126     brouard  6510: /*   tmg.tm_year=tmg.tm_year +dsign*dyear; */
                   6511: /*   tmg.tm_mon=tmg.tm_mon +dsign*dmonth; */
                   6512: /*   tmg.tm_hour=tmg.tm_hour + 1; */
1.157     brouard  6513: /*   tp.tm_sec = mktime(&tmg); */
1.126     brouard  6514: /*   strt=asctime(&tmg); */
                   6515: /*   printf("Time(after) =%s",strstart);  */
                   6516: /*  (void) time (&time_value);
                   6517: *  printf("time=%d,t-=%d\n",time_value,time_value-86400);
                   6518: *  tm = *localtime(&time_value);
                   6519: *  strstart=asctime(&tm);
                   6520: *  printf("tim_value=%d,asctime=%s\n",time_value,strstart); 
                   6521: */
                   6522: 
                   6523:   nberr=0; /* Number of errors and warnings */
                   6524:   nbwarn=0;
1.184     brouard  6525: #ifdef WIN32
                   6526:   _getcwd(pathcd, size);
                   6527: #else
1.126     brouard  6528:   getcwd(pathcd, size);
1.184     brouard  6529: #endif
1.191     brouard  6530:   syscompilerinfo(0);
1.196     brouard  6531:   printf("\nIMaCh version %s, %s\n%s",version, copyright, fullversion);
1.126     brouard  6532:   if(argc <=1){
                   6533:     printf("\nEnter the parameter file name: ");
                   6534:     fgets(pathr,FILENAMELENGTH,stdin);
                   6535:     i=strlen(pathr);
                   6536:     if(pathr[i-1]=='\n')
                   6537:       pathr[i-1]='\0';
1.156     brouard  6538:     i=strlen(pathr);
                   6539:     if(pathr[i-1]==' ') /* This may happen when dragging on oS/X! */
                   6540:       pathr[i-1]='\0';
1.126     brouard  6541:    for (tok = pathr; tok != NULL; ){
                   6542:       printf("Pathr |%s|\n",pathr);
                   6543:       while ((val = strsep(&tok, "\"" )) != NULL && *val == '\0');
                   6544:       printf("val= |%s| pathr=%s\n",val,pathr);
                   6545:       strcpy (pathtot, val);
                   6546:       if(pathr[0] == '\0') break; /* Dirty */
                   6547:     }
                   6548:   }
                   6549:   else{
                   6550:     strcpy(pathtot,argv[1]);
                   6551:   }
                   6552:   /*if(getcwd(pathcd, MAXLINE)!= NULL)printf ("Error pathcd\n");*/
                   6553:   /*cygwin_split_path(pathtot,path,optionfile);
                   6554:     printf("pathtot=%s, path=%s, optionfile=%s\n",pathtot,path,optionfile);*/
                   6555:   /* cutv(path,optionfile,pathtot,'\\');*/
                   6556: 
                   6557:   /* Split argv[0], imach program to get pathimach */
                   6558:   printf("\nargv[0]=%s argv[1]=%s, \n",argv[0],argv[1]);
                   6559:   split(argv[0],pathimach,optionfile,optionfilext,optionfilefiname);
                   6560:   printf("\nargv[0]=%s pathimach=%s, \noptionfile=%s \noptionfilext=%s \noptionfilefiname=%s\n",argv[0],pathimach,optionfile,optionfilext,optionfilefiname);
                   6561:  /*   strcpy(pathimach,argv[0]); */
                   6562:   /* Split argv[1]=pathtot, parameter file name to get path, optionfile, extension and name */
                   6563:   split(pathtot,path,optionfile,optionfilext,optionfilefiname);
                   6564:   printf("\npathtot=%s,\npath=%s,\noptionfile=%s \noptionfilext=%s \noptionfilefiname=%s\n",pathtot,path,optionfile,optionfilext,optionfilefiname);
1.184     brouard  6565: #ifdef WIN32
                   6566:   _chdir(path); /* Can be a relative path */
                   6567:   if(_getcwd(pathcd,MAXLINE) > 0) /* So pathcd is the full path */
                   6568: #else
1.126     brouard  6569:   chdir(path); /* Can be a relative path */
1.184     brouard  6570:   if (getcwd(pathcd, MAXLINE) > 0) /* So pathcd is the full path */
                   6571: #endif
                   6572:   printf("Current directory %s!\n",pathcd);
1.126     brouard  6573:   strcpy(command,"mkdir ");
                   6574:   strcat(command,optionfilefiname);
                   6575:   if((outcmd=system(command)) != 0){
1.169     brouard  6576:     printf("Directory already exists (or can't create it) %s%s, err=%d\n",path,optionfilefiname,outcmd);
1.126     brouard  6577:     /* fprintf(ficlog,"Problem creating directory %s%s\n",path,optionfilefiname); */
                   6578:     /* fclose(ficlog); */
                   6579: /*     exit(1); */
                   6580:   }
                   6581: /*   if((imk=mkdir(optionfilefiname))<0){ */
                   6582: /*     perror("mkdir"); */
                   6583: /*   } */
                   6584: 
                   6585:   /*-------- arguments in the command line --------*/
                   6586: 
1.186     brouard  6587:   /* Main Log file */
1.126     brouard  6588:   strcat(filelog, optionfilefiname);
                   6589:   strcat(filelog,".log");    /* */
                   6590:   if((ficlog=fopen(filelog,"w"))==NULL)    {
                   6591:     printf("Problem with logfile %s\n",filelog);
                   6592:     goto end;
                   6593:   }
                   6594:   fprintf(ficlog,"Log filename:%s\n",filelog);
1.197     brouard  6595:   fprintf(ficlog,"Version %s %s",version,fullversion);
1.126     brouard  6596:   fprintf(ficlog,"\nEnter the parameter file name: \n");
                   6597:   fprintf(ficlog,"pathimach=%s\npathtot=%s\n\
                   6598:  path=%s \n\
                   6599:  optionfile=%s\n\
                   6600:  optionfilext=%s\n\
1.156     brouard  6601:  optionfilefiname='%s'\n",pathimach,pathtot,path,optionfile,optionfilext,optionfilefiname);
1.126     brouard  6602: 
1.197     brouard  6603:   syscompilerinfo(1);
1.167     brouard  6604: 
1.126     brouard  6605:   printf("Local time (at start):%s",strstart);
                   6606:   fprintf(ficlog,"Local time (at start): %s",strstart);
                   6607:   fflush(ficlog);
                   6608: /*   (void) gettimeofday(&curr_time,&tzp); */
1.157     brouard  6609: /*   printf("Elapsed time %d\n", asc_diff_time(curr_time.tm_sec-start_time.tm_sec,tmpout)); */
1.126     brouard  6610: 
                   6611:   /* */
                   6612:   strcpy(fileres,"r");
                   6613:   strcat(fileres, optionfilefiname);
1.201   ! brouard  6614:   strcat(fileresu, optionfilefiname); /* Without r in front */
1.126     brouard  6615:   strcat(fileres,".txt");    /* Other files have txt extension */
1.201   ! brouard  6616:   strcat(fileresu,".txt");    /* Other files have txt extension */
1.126     brouard  6617: 
1.186     brouard  6618:   /* Main ---------arguments file --------*/
1.126     brouard  6619: 
                   6620:   if((ficpar=fopen(optionfile,"r"))==NULL)    {
1.155     brouard  6621:     printf("Problem with optionfile '%s' with errno='%s'\n",optionfile,strerror(errno));
                   6622:     fprintf(ficlog,"Problem with optionfile '%s' with errno='%s'\n",optionfile,strerror(errno));
1.126     brouard  6623:     fflush(ficlog);
1.149     brouard  6624:     /* goto end; */
                   6625:     exit(70); 
1.126     brouard  6626:   }
                   6627: 
                   6628: 
                   6629: 
                   6630:   strcpy(filereso,"o");
1.201   ! brouard  6631:   strcat(filereso,fileresu);
1.126     brouard  6632:   if((ficparo=fopen(filereso,"w"))==NULL) { /* opened on subdirectory */
                   6633:     printf("Problem with Output resultfile: %s\n", filereso);
                   6634:     fprintf(ficlog,"Problem with Output resultfile: %s\n", filereso);
                   6635:     fflush(ficlog);
                   6636:     goto end;
                   6637:   }
                   6638: 
                   6639:   /* Reads comments: lines beginning with '#' */
                   6640:   numlinepar=0;
1.197     brouard  6641: 
                   6642:     /* First parameter line */
                   6643:   while(fgets(line, MAXLINE, ficpar)) {
                   6644:     /* If line starts with a # it is a comment */
                   6645:     if (line[0] == '#') {
                   6646:       numlinepar++;
                   6647:       fputs(line,stdout);
                   6648:       fputs(line,ficparo);
                   6649:       fputs(line,ficlog);
                   6650:       continue;
                   6651:     }else
                   6652:       break;
                   6653:   }
                   6654:   if((num_filled=sscanf(line,"title=%s datafile=%s lastobs=%d firstpass=%d lastpass=%d\n", \
                   6655:                        title, datafile, &lastobs, &firstpass,&lastpass)) !=EOF){
                   6656:     if (num_filled != 5) {
                   6657:       printf("Should be 5 parameters\n");
                   6658:     }
1.126     brouard  6659:     numlinepar++;
1.197     brouard  6660:     printf("title=%s datafile=%s lastobs=%d firstpass=%d lastpass=%d\n", title, datafile, lastobs, firstpass,lastpass);
                   6661:   }
                   6662:   /* Second parameter line */
                   6663:   while(fgets(line, MAXLINE, ficpar)) {
                   6664:     /* If line starts with a # it is a comment */
                   6665:     if (line[0] == '#') {
                   6666:       numlinepar++;
                   6667:       fputs(line,stdout);
                   6668:       fputs(line,ficparo);
                   6669:       fputs(line,ficlog);
                   6670:       continue;
                   6671:     }else
                   6672:       break;
                   6673:   }
                   6674:   if((num_filled=sscanf(line,"ftol=%lf stepm=%d ncovcol=%d nlstate=%d ndeath=%d maxwav=%d mle=%d weight=%d\n", \
                   6675:                        &ftol, &stepm, &ncovcol, &nlstate, &ndeath, &maxwav, &mle, &weightopt)) !=EOF){
                   6676:     if (num_filled != 8) {
                   6677:       printf("Not 8\n");
                   6678:     }
                   6679:     printf("ftol=%e stepm=%d ncovcol=%d nlstate=%d ndeath=%d maxwav=%d mle=%d weight=%d\n",ftol, stepm, ncovcol, nlstate,ndeath, maxwav, mle, weightopt);
1.126     brouard  6680:   }
                   6681: 
1.197     brouard  6682:   /* Third parameter line */
                   6683:   while(fgets(line, MAXLINE, ficpar)) {
                   6684:     /* If line starts with a # it is a comment */
                   6685:     if (line[0] == '#') {
                   6686:       numlinepar++;
                   6687:       fputs(line,stdout);
                   6688:       fputs(line,ficparo);
                   6689:       fputs(line,ficlog);
                   6690:       continue;
                   6691:     }else
                   6692:       break;
                   6693:   }
1.201   ! brouard  6694:   if((num_filled=sscanf(line,"model=1+age%[^.\n]", model)) !=EOF){
        !          6695:     if (num_filled == 0)
        !          6696:             model[0]='\0';
        !          6697:     else if (num_filled != 1){
1.197     brouard  6698:       printf("ERROR %d: Model should be at minimum 'model=1+age.' %s\n",num_filled, line);
                   6699:       fprintf(ficlog,"ERROR %d: Model should be at minimum 'model=1+age.' %s\n",num_filled, line);
                   6700:       model[0]='\0';
                   6701:       goto end;
                   6702:     }
                   6703:     else{
                   6704:       if (model[0]=='+'){
                   6705:        for(i=1; i<=strlen(model);i++)
                   6706:          modeltemp[i-1]=model[i];
1.201   ! brouard  6707:        strcpy(model,modeltemp); 
1.197     brouard  6708:       }
                   6709:     }
1.199     brouard  6710:     /* printf(" model=1+age%s modeltemp= %s, model=%s\n",model, modeltemp, model);fflush(stdout); */
1.197     brouard  6711:   }
                   6712:   /* 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); */
                   6713:   /* numlinepar=numlinepar+3; /\* In general *\/ */
                   6714:   /* 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); */
1.187     brouard  6715:   if(model[strlen(model)-1]=='.') /* Suppressing leading dot in the model */
                   6716:     model[strlen(model)-1]='\0';
1.197     brouard  6717:   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);
                   6718:   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  6719:   fflush(ficlog);
1.190     brouard  6720:   /* if(model[0]=='#'|| model[0]== '\0'){ */
                   6721:   if(model[0]=='#'){
1.187     brouard  6722:     printf("Error in 'model' line: model should start with 'model=1+age+' and end with '.' \n \
                   6723:  'model=1+age+.' or 'model=1+age+V1.' or 'model=1+age+age*age+V1+V1*age.' or \n \
                   6724:  'model=1+age+V1+V2.' or 'model=1+age+V1+V2+V1*V2.' etc. \n");         \
                   6725:     if(mle != -1){
                   6726:       printf("Fix the model line and run imach with mle=-1 to get a correct template of the parameter file.\n");
                   6727:       exit(1);
                   6728:     }
                   6729:   }
1.126     brouard  6730:   while((c=getc(ficpar))=='#' && c!= EOF){
                   6731:     ungetc(c,ficpar);
                   6732:     fgets(line, MAXLINE, ficpar);
                   6733:     numlinepar++;
1.195     brouard  6734:     if(line[1]=='q'){ /* This #q will quit imach (the answer is q) */
                   6735:       z[0]=line[1];
                   6736:     }
                   6737:     /* printf("****line [1] = %c \n",line[1]); */
1.141     brouard  6738:     fputs(line, stdout);
                   6739:     //puts(line);
1.126     brouard  6740:     fputs(line,ficparo);
                   6741:     fputs(line,ficlog);
                   6742:   }
                   6743:   ungetc(c,ficpar);
                   6744: 
                   6745:    
1.145     brouard  6746:   covar=matrix(0,NCOVMAX,1,n);  /**< used in readdata */
1.136     brouard  6747:   cptcovn=0; /*Number of covariates, i.e. number of '+' in model statement plus one, indepently of n in Vn*/
                   6748:   /* v1+v2+v3+v2*v4+v5*age makes cptcovn = 5
                   6749:      v1+v2*age+v2*v3 makes cptcovn = 3
                   6750:   */
                   6751:   if (strlen(model)>1) 
1.187     brouard  6752:     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  6753:   else
1.187     brouard  6754:     ncovmodel=2; /* Constant and age */
1.133     brouard  6755:   nforce= (nlstate+ndeath-1)*nlstate; /* Number of forces ij from state i to j */
                   6756:   npar= nforce*ncovmodel; /* Number of parameters like aij*/
1.131     brouard  6757:   if(npar >MAXPARM || nlstate >NLSTATEMAX || ndeath >NDEATHMAX || ncovmodel>NCOVMAX){
                   6758:     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);
                   6759:     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);
                   6760:     fflush(stdout);
                   6761:     fclose (ficlog);
                   6762:     goto end;
                   6763:   }
1.126     brouard  6764:   delti3= ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel);
                   6765:   delti=delti3[1][1];
                   6766:   /*delti=vector(1,npar); *//* Scale of each paramater (output from hesscov)*/
                   6767:   if(mle==-1){ /* Print a wizard for help writing covariance matrix */
                   6768:     prwizard(ncovmodel, nlstate, ndeath, model, ficparo);
1.191     brouard  6769:     printf(" You chose mle=-1, look at file %s for a template of covariance matrix \n",filereso);
                   6770:     fprintf(ficlog," You chose mle=-1, look at file %s for a template of covariance matrix \n",filereso);
1.126     brouard  6771:     free_ma3x(delti3,1,nlstate,1, nlstate+ndeath-1,1,ncovmodel); 
                   6772:     fclose (ficparo);
                   6773:     fclose (ficlog);
                   6774:     goto end;
                   6775:     exit(0);
                   6776:   }
1.186     brouard  6777:   else if(mle==-3) { /* Main Wizard */
1.126     brouard  6778:     prwizard(ncovmodel, nlstate, ndeath, model, ficparo);
1.192     brouard  6779:     printf(" You chose mle=-3, look at file %s for a template of covariance matrix \n",filereso);
                   6780:     fprintf(ficlog," You chose mle=-3, look at file %s for a template of covariance matrix \n",filereso);
1.126     brouard  6781:     param= ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel);
                   6782:     matcov=matrix(1,npar,1,npar);
                   6783:   }
                   6784:   else{
1.145     brouard  6785:     /* Read guessed parameters */
1.126     brouard  6786:     /* Reads comments: lines beginning with '#' */
                   6787:     while((c=getc(ficpar))=='#' && c!= EOF){
                   6788:       ungetc(c,ficpar);
                   6789:       fgets(line, MAXLINE, ficpar);
                   6790:       numlinepar++;
1.141     brouard  6791:       fputs(line,stdout);
1.126     brouard  6792:       fputs(line,ficparo);
                   6793:       fputs(line,ficlog);
                   6794:     }
                   6795:     ungetc(c,ficpar);
                   6796:     
                   6797:     param= ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel);
                   6798:     for(i=1; i <=nlstate; i++){
                   6799:       j=0;
                   6800:       for(jj=1; jj <=nlstate+ndeath; jj++){
                   6801:        if(jj==i) continue;
                   6802:        j++;
                   6803:        fscanf(ficpar,"%1d%1d",&i1,&j1);
1.193     brouard  6804:        if ((i1 != i) || (j1 != jj)){
1.126     brouard  6805:          printf("Error in line parameters number %d, %1d%1d instead of %1d%1d \n \
                   6806: It might be a problem of design; if ncovcol and the model are correct\n \
                   6807: run imach with mle=-1 to get a correct template of the parameter file.\n",numlinepar, i,j, i1, j1);
                   6808:          exit(1);
                   6809:        }
                   6810:        fprintf(ficparo,"%1d%1d",i1,j1);
                   6811:        if(mle==1)
1.193     brouard  6812:          printf("%1d%1d",i,jj);
                   6813:        fprintf(ficlog,"%1d%1d",i,jj);
1.126     brouard  6814:        for(k=1; k<=ncovmodel;k++){
                   6815:          fscanf(ficpar," %lf",&param[i][j][k]);
                   6816:          if(mle==1){
                   6817:            printf(" %lf",param[i][j][k]);
                   6818:            fprintf(ficlog," %lf",param[i][j][k]);
                   6819:          }
                   6820:          else
                   6821:            fprintf(ficlog," %lf",param[i][j][k]);
                   6822:          fprintf(ficparo," %lf",param[i][j][k]);
                   6823:        }
                   6824:        fscanf(ficpar,"\n");
                   6825:        numlinepar++;
                   6826:        if(mle==1)
                   6827:          printf("\n");
                   6828:        fprintf(ficlog,"\n");
                   6829:        fprintf(ficparo,"\n");
                   6830:       }
                   6831:     }  
                   6832:     fflush(ficlog);
                   6833: 
1.145     brouard  6834:     /* Reads scales values */
1.126     brouard  6835:     p=param[1][1];
                   6836:     
                   6837:     /* Reads comments: lines beginning with '#' */
                   6838:     while((c=getc(ficpar))=='#' && c!= EOF){
                   6839:       ungetc(c,ficpar);
                   6840:       fgets(line, MAXLINE, ficpar);
                   6841:       numlinepar++;
1.141     brouard  6842:       fputs(line,stdout);
1.126     brouard  6843:       fputs(line,ficparo);
                   6844:       fputs(line,ficlog);
                   6845:     }
                   6846:     ungetc(c,ficpar);
                   6847: 
                   6848:     for(i=1; i <=nlstate; i++){
                   6849:       for(j=1; j <=nlstate+ndeath-1; j++){
                   6850:        fscanf(ficpar,"%1d%1d",&i1,&j1);
1.164     brouard  6851:        if ( (i1-i) * (j1-j) != 0){
1.126     brouard  6852:          printf("Error in line parameters number %d, %1d%1d instead of %1d%1d \n",numlinepar, i,j, i1, j1);
                   6853:          exit(1);
                   6854:        }
                   6855:        printf("%1d%1d",i,j);
                   6856:        fprintf(ficparo,"%1d%1d",i1,j1);
                   6857:        fprintf(ficlog,"%1d%1d",i1,j1);
                   6858:        for(k=1; k<=ncovmodel;k++){
                   6859:          fscanf(ficpar,"%le",&delti3[i][j][k]);
                   6860:          printf(" %le",delti3[i][j][k]);
                   6861:          fprintf(ficparo," %le",delti3[i][j][k]);
                   6862:          fprintf(ficlog," %le",delti3[i][j][k]);
                   6863:        }
                   6864:        fscanf(ficpar,"\n");
                   6865:        numlinepar++;
                   6866:        printf("\n");
                   6867:        fprintf(ficparo,"\n");
                   6868:        fprintf(ficlog,"\n");
                   6869:       }
                   6870:     }
                   6871:     fflush(ficlog);
                   6872: 
1.145     brouard  6873:     /* Reads covariance matrix */
1.126     brouard  6874:     delti=delti3[1][1];
                   6875: 
                   6876: 
                   6877:     /* free_ma3x(delti3,1,nlstate,1,nlstate+ndeath-1,1,ncovmodel); */ /* Hasn't to to freed here otherwise delti is no more allocated */
                   6878:   
                   6879:     /* Reads comments: lines beginning with '#' */
                   6880:     while((c=getc(ficpar))=='#' && c!= EOF){
                   6881:       ungetc(c,ficpar);
                   6882:       fgets(line, MAXLINE, ficpar);
                   6883:       numlinepar++;
1.141     brouard  6884:       fputs(line,stdout);
1.126     brouard  6885:       fputs(line,ficparo);
                   6886:       fputs(line,ficlog);
                   6887:     }
                   6888:     ungetc(c,ficpar);
                   6889:   
                   6890:     matcov=matrix(1,npar,1,npar);
1.131     brouard  6891:     for(i=1; i <=npar; i++)
                   6892:       for(j=1; j <=npar; j++) matcov[i][j]=0.;
                   6893:       
1.194     brouard  6894:     /* Scans npar lines */
1.126     brouard  6895:     for(i=1; i <=npar; i++){
1.194     brouard  6896:       count=fscanf(ficpar,"%1d%1d%1d",&i1,&j1,&jk);
                   6897:       if(count != 3){
                   6898:        printf("Error! Error in parameter file %s at line %d after line starting with %1d%1d%1d\n\
                   6899: This is probably because your covariance matrix doesn't \n  contain exactly %d lines corresponding to your model line '1+age+%s'.\n\
                   6900: Please run with mle=-1 to get a correct covariance matrix.\n",optionfile,numlinepar, i1,j1,jk, npar, model);
                   6901:        fprintf(ficlog,"Error! Error in parameter file %s at line %d after line starting with %1d%1d%1d\n\
                   6902: This is probably because your covariance matrix doesn't \n  contain exactly %d lines corresponding to your model line '1+age+%s'.\n\
                   6903: Please run with mle=-1 to get a correct covariance matrix.\n",optionfile,numlinepar, i1,j1,jk, npar, model);
                   6904:        exit(1);
                   6905:       }else
1.126     brouard  6906:       if(mle==1)
1.194     brouard  6907:        printf("%1d%1d%1d",i1,j1,jk);
                   6908:       fprintf(ficlog,"%1d%1d%1d",i1,j1,jk);
                   6909:       fprintf(ficparo,"%1d%1d%1d",i1,j1,jk);
1.126     brouard  6910:       for(j=1; j <=i; j++){
                   6911:        fscanf(ficpar," %le",&matcov[i][j]);
                   6912:        if(mle==1){
                   6913:          printf(" %.5le",matcov[i][j]);
                   6914:        }
                   6915:        fprintf(ficlog," %.5le",matcov[i][j]);
                   6916:        fprintf(ficparo," %.5le",matcov[i][j]);
                   6917:       }
                   6918:       fscanf(ficpar,"\n");
                   6919:       numlinepar++;
                   6920:       if(mle==1)
                   6921:        printf("\n");
                   6922:       fprintf(ficlog,"\n");
                   6923:       fprintf(ficparo,"\n");
                   6924:     }
1.194     brouard  6925:     /* End of read covariance matrix npar lines */
1.126     brouard  6926:     for(i=1; i <=npar; i++)
                   6927:       for(j=i+1;j<=npar;j++)
                   6928:        matcov[i][j]=matcov[j][i];
                   6929:     
                   6930:     if(mle==1)
                   6931:       printf("\n");
                   6932:     fprintf(ficlog,"\n");
                   6933:     
                   6934:     fflush(ficlog);
                   6935:     
                   6936:     /*-------- Rewriting parameter file ----------*/
                   6937:     strcpy(rfileres,"r");    /* "Rparameterfile */
                   6938:     strcat(rfileres,optionfilefiname);    /* Parameter file first name*/
                   6939:     strcat(rfileres,".");    /* */
                   6940:     strcat(rfileres,optionfilext);    /* Other files have txt extension */
                   6941:     if((ficres =fopen(rfileres,"w"))==NULL) {
1.201   ! brouard  6942:       printf("Problem writing new parameter file: %s\n", rfileres);goto end;
        !          6943:       fprintf(ficlog,"Problem writing new parameter file: %s\n", rfileres);goto end;
1.126     brouard  6944:     }
                   6945:     fprintf(ficres,"#%s\n",version);
                   6946:   }    /* End of mle != -3 */
                   6947: 
1.186     brouard  6948:   /*  Main data
                   6949:    */
1.126     brouard  6950:   n= lastobs;
                   6951:   num=lvector(1,n);
                   6952:   moisnais=vector(1,n);
                   6953:   annais=vector(1,n);
                   6954:   moisdc=vector(1,n);
                   6955:   andc=vector(1,n);
                   6956:   agedc=vector(1,n);
                   6957:   cod=ivector(1,n);
                   6958:   weight=vector(1,n);
                   6959:   for(i=1;i<=n;i++) weight[i]=1.0; /* Equal weights, 1 by default */
                   6960:   mint=matrix(1,maxwav,1,n);
                   6961:   anint=matrix(1,maxwav,1,n);
1.131     brouard  6962:   s=imatrix(1,maxwav+1,1,n); /* s[i][j] health state for wave i and individual j */ 
1.126     brouard  6963:   tab=ivector(1,NCOVMAX);
1.144     brouard  6964:   ncodemax=ivector(1,NCOVMAX); /* Number of code per covariate; if O and 1 only, 2**ncov; V1+V2+V3+V4=>16 */
1.192     brouard  6965:   ncodemaxwundef=ivector(1,NCOVMAX); /* Number of code per covariate; if - 1 O and 1 only, 2**ncov; V1+V2+V3+V4=>16 */
1.126     brouard  6966: 
1.136     brouard  6967:   /* Reads data from file datafile */
                   6968:   if (readdata(datafile, firstobs, lastobs, &imx)==1)
                   6969:     goto end;
                   6970: 
                   6971:   /* Calculation of the number of parameters from char model */
1.137     brouard  6972:     /*    modelsav=V2+V1+V4+age*V3 strb=age*V3 stra=V2+V1+V4 
                   6973:        k=4 (age*V3) Tvar[k=4]= 3 (from V3) Tag[cptcovage=1]=4
                   6974:        k=3 V4 Tvar[k=3]= 4 (from V4)
                   6975:        k=2 V1 Tvar[k=2]= 1 (from V1)
                   6976:        k=1 Tvar[1]=2 (from V2)
                   6977:     */
                   6978:   Tvar=ivector(1,NCOVMAX); /* Was 15 changed to NCOVMAX. */
                   6979:   /*  V2+V1+V4+age*V3 is a model with 4 covariates (3 plus signs). 
                   6980:       For each model-covariate stores the data-covariate id. Tvar[1]=2, Tvar[2]=1, Tvar[3]=4, 
                   6981:       Tvar[4=age*V3] is 3 and 'age' is recorded in Tage.
                   6982:   */
                   6983:   /* For model-covariate k tells which data-covariate to use but
                   6984:     because this model-covariate is a construction we invent a new column
                   6985:     ncovcol + k1
                   6986:     If already ncovcol=4 and model=V2+V1+V1*V4+age*V3
                   6987:     Tvar[3=V1*V4]=4+1 etc */
1.145     brouard  6988:   Tprod=ivector(1,NCOVMAX); /* Gives the position of a product */
1.137     brouard  6989:   /* Tprod[k1=1]=3(=V1*V4) for V2+V1+V1*V4+age*V3
                   6990:      if  V2+V1+V1*V4+age*V3+V3*V2   TProd[k1=2]=5 (V3*V2)
                   6991:   */
1.145     brouard  6992:   Tvaraff=ivector(1,NCOVMAX); /* Unclear */
                   6993:   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  6994:                            * For V3*V2 (in V2+V1+V1*V4+age*V3+V3*V2), V3*V2 position is 2nd. 
                   6995:                            * Tvard[k1=2][1]=3 (V3) Tvard[k1=2][2]=2(V2) */
1.145     brouard  6996:   Tage=ivector(1,NCOVMAX); /* Gives the covariate id of covariates associated with age: V2 + V1 + age*V4 + V3*age
1.137     brouard  6997:                         4 covariates (3 plus signs)
                   6998:                         Tage[1=V3*age]= 4; Tage[2=age*V4] = 3
                   6999:                      */  
1.136     brouard  7000: 
1.186     brouard  7001: /* Main decodemodel */
                   7002: 
1.187     brouard  7003: 
1.136     brouard  7004:   if(decodemodel(model, lastobs) == 1)
                   7005:     goto end;
                   7006: 
1.137     brouard  7007:   if((double)(lastobs-imx)/(double)imx > 1.10){
                   7008:     nbwarn++;
                   7009:     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); 
                   7010:     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); 
                   7011:   }
1.136     brouard  7012:     /*  if(mle==1){*/
1.137     brouard  7013:   if (weightopt != 1) { /* Maximisation without weights. We can have weights different from 1 but want no weight*/
                   7014:     for(i=1;i<=imx;i++) weight[i]=1.0; /* changed to imx */
1.136     brouard  7015:   }
                   7016: 
                   7017:     /*-calculation of age at interview from date of interview and age at death -*/
                   7018:   agev=matrix(1,maxwav,1,imx);
                   7019: 
                   7020:   if(calandcheckages(imx, maxwav, &agemin, &agemax, &nberr, &nbwarn) == 1)
                   7021:     goto end;
                   7022: 
1.126     brouard  7023: 
1.136     brouard  7024:   agegomp=(int)agemin;
                   7025:   free_vector(moisnais,1,n);
                   7026:   free_vector(annais,1,n);
1.126     brouard  7027:   /* free_matrix(mint,1,maxwav,1,n);
                   7028:      free_matrix(anint,1,maxwav,1,n);*/
                   7029:   free_vector(moisdc,1,n);
                   7030:   free_vector(andc,1,n);
1.145     brouard  7031:   /* */
                   7032:   
1.126     brouard  7033:   wav=ivector(1,imx);
                   7034:   dh=imatrix(1,lastpass-firstpass+1,1,imx);
                   7035:   bh=imatrix(1,lastpass-firstpass+1,1,imx);
                   7036:   mw=imatrix(1,lastpass-firstpass+1,1,imx);
                   7037:    
                   7038:   /* Concatenates waves */
                   7039:   concatwav(wav, dh, bh, mw, s, agedc, agev,  firstpass, lastpass, imx, nlstate, stepm);
1.145     brouard  7040:   /* */
                   7041:  
1.126     brouard  7042:   /* Routine tricode is to calculate cptcoveff (real number of unique covariates) and to associate covariable number and modality */
                   7043: 
                   7044:   nbcode=imatrix(0,NCOVMAX,0,NCOVMAX); 
                   7045:   ncodemax[1]=1;
1.145     brouard  7046:   Ndum =ivector(-1,NCOVMAX);  
1.187     brouard  7047:   if (ncovmodel-nagesqr > 2 ) /* That is if covariate other than cst, age and age*age */
1.145     brouard  7048:     tricode(Tvar,nbcode,imx, Ndum); /**< Fills nbcode[Tvar[j]][l]; */
1.186     brouard  7049:   /* Nbcode gives the value of the lth modality of jth covariate, in
                   7050:      V2+V1*age, there are 3 covariates Tvar[2]=1 (V1).*/
                   7051:   /* 1 to ncodemax[j] is the maximum value of this jth covariate */
1.145     brouard  7052: 
1.200     brouard  7053:   /*  codtab=imatrix(1,100,1,10);*/ /* codtab[h,k]=( (h-1) - mod(k-1,2**(k-1) )/2**(k-1) */
1.198     brouard  7054:   /*printf(" codtab[1,1],codtab[100,10]=%d,%d\n", codtab[1][1],codtabm(100,10));*/
1.186     brouard  7055:   /* codtab gives the value 1 or 2 of the hth combination of k covariates (1 or 2).*/
1.145     brouard  7056:   h=0;
                   7057: 
                   7058: 
                   7059:   /*if (cptcovn > 0) */
1.126     brouard  7060:       
1.145     brouard  7061:  
1.126     brouard  7062:   m=pow(2,cptcoveff);
                   7063:  
1.144     brouard  7064:          /**< codtab(h,k)  k   = codtab[h,k]=( (h-1) - mod(k-1,2**(k-1) )/2**(k-1) + 1
1.186     brouard  7065:           * For k=4 covariates, h goes from 1 to 2**k
                   7066:           * codtabm(h,k)=  1 & (h-1) >> (k-1) ;
                   7067:           *     h\k   1     2     3     4
1.143     brouard  7068:           *______________________________  
                   7069:           *     1 i=1 1 i=1 1 i=1 1 i=1 1
                   7070:           *     2     2     1     1     1
                   7071:           *     3 i=2 1     2     1     1
                   7072:           *     4     2     2     1     1
                   7073:           *     5 i=3 1 i=2 1     2     1
                   7074:           *     6     2     1     2     1
                   7075:           *     7 i=4 1     2     2     1
                   7076:           *     8     2     2     2     1
1.197     brouard  7077:           *     9 i=5 1 i=3 1 i=2 1     2
                   7078:           *    10     2     1     1     2
                   7079:           *    11 i=6 1     2     1     2
                   7080:           *    12     2     2     1     2
                   7081:           *    13 i=7 1 i=4 1     2     2    
                   7082:           *    14     2     1     2     2
                   7083:           *    15 i=8 1     2     2     2
                   7084:           *    16     2     2     2     2
1.143     brouard  7085:           */
1.197     brouard  7086:   for(h=1; h <=100 ;h++){ 
                   7087:     /* printf("h=%2d ", h); */
1.200     brouard  7088:      /* for(k=1; k <=10; k++){ */
1.197     brouard  7089:        /* printf("k=%d %d ",k,codtabm(h,k)); */
1.200     brouard  7090:      /*   codtab[h][k]=codtabm(h,k); */
                   7091:      /* } */
1.197     brouard  7092:      /* printf("\n"); */
                   7093:   }
                   7094:   /* for(k=1;k<=cptcoveff; k++){ /\* scans any effective covariate *\/ */
                   7095:   /*   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 *\/  */
                   7096:   /*     for(j=1; j <= ncodemax[k]; j++){ /\* For each modality of this covariate ncodemax=2*\/ */
                   7097:   /*   for(cpt=1; cpt <=pow(2,k-1); cpt++){  /\* cpt=1 to 8/2**(3+1-1 or 3+1-3) =1 or 4 *\/  */
                   7098:   /*     h++; */
                   7099:   /*     if (h>m)  */
                   7100:   /*       h=1; */
                   7101:   /*     codtab[h][k]=j; */
                   7102:   /*     /\* codtab[12][3]=1; *\/ */
                   7103:   /*     /\*codtab[h][Tvar[k]]=j;*\/ */
                   7104:   /*     /\* 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]]); *\/ */
                   7105:   /*   }  */
                   7106:   /*     } */
                   7107:   /*   } */
                   7108:   /* }  */
1.126     brouard  7109:   /* printf("codtab[1][2]=%d codtab[2][2]=%d",codtab[1][2],codtab[2][2]); 
                   7110:      codtab[1][2]=1;codtab[2][2]=2; */
1.197     brouard  7111:   /* for(i=1; i <=m ;i++){  */
                   7112:   /*    for(k=1; k <=cptcovn; k++){ */
                   7113:   /*      printf("i=%d k=%d %d %d ",i,k,codtab[i][k], cptcoveff); */
                   7114:   /*    } */
                   7115:   /*    printf("\n"); */
                   7116:   /* } */
                   7117:   /*   scanf("%d",i);*/
1.145     brouard  7118: 
                   7119:  free_ivector(Ndum,-1,NCOVMAX);
                   7120: 
                   7121: 
1.126     brouard  7122:     
1.186     brouard  7123:   /* Initialisation of ----------- gnuplot -------------*/
1.126     brouard  7124:   strcpy(optionfilegnuplot,optionfilefiname);
                   7125:   if(mle==-3)
1.201   ! brouard  7126:     strcat(optionfilegnuplot,"-MORT_");
1.126     brouard  7127:   strcat(optionfilegnuplot,".gp");
                   7128: 
                   7129:   if((ficgp=fopen(optionfilegnuplot,"w"))==NULL) {
                   7130:     printf("Problem with file %s",optionfilegnuplot);
                   7131:   }
                   7132:   else{
                   7133:     fprintf(ficgp,"\n# %s\n", version); 
                   7134:     fprintf(ficgp,"# %s\n", optionfilegnuplot); 
1.141     brouard  7135:     //fprintf(ficgp,"set missing 'NaNq'\n");
                   7136:     fprintf(ficgp,"set datafile missing 'NaNq'\n");
1.126     brouard  7137:   }
                   7138:   /*  fclose(ficgp);*/
1.186     brouard  7139: 
                   7140: 
                   7141:   /* Initialisation of --------- index.htm --------*/
1.126     brouard  7142: 
                   7143:   strcpy(optionfilehtm,optionfilefiname); /* Main html file */
                   7144:   if(mle==-3)
1.201   ! brouard  7145:     strcat(optionfilehtm,"-MORT_");
1.126     brouard  7146:   strcat(optionfilehtm,".htm");
                   7147:   if((fichtm=fopen(optionfilehtm,"w"))==NULL)    {
1.131     brouard  7148:     printf("Problem with %s \n",optionfilehtm);
                   7149:     exit(0);
1.126     brouard  7150:   }
                   7151: 
                   7152:   strcpy(optionfilehtmcov,optionfilefiname); /* Only for matrix of covariance */
                   7153:   strcat(optionfilehtmcov,"-cov.htm");
                   7154:   if((fichtmcov=fopen(optionfilehtmcov,"w"))==NULL)    {
                   7155:     printf("Problem with %s \n",optionfilehtmcov), exit(0);
                   7156:   }
                   7157:   else{
                   7158:   fprintf(fichtmcov,"<html><head>\n<title>IMaCh Cov %s</title></head>\n <body><font size=\"2\">%s <br> %s</font> \
                   7159: <hr size=\"2\" color=\"#EC5E5E\"> \n\
                   7160: Title=%s <br>Datafile=%s Firstpass=%d Lastpass=%d Stepm=%d Weight=%d Model=%s<br>\n",\
                   7161:          optionfilehtmcov,version,fullversion,title,datafile,firstpass,lastpass,stepm, weightopt, model);
                   7162:   }
                   7163: 
                   7164:   fprintf(fichtm,"<html><head>\n<title>IMaCh %s</title></head>\n <body><font size=\"2\">%s <br> %s</font> \
                   7165: <hr size=\"2\" color=\"#EC5E5E\"> \n\
                   7166: Title=%s <br>Datafile=%s Firstpass=%d Lastpass=%d Stepm=%d Weight=%d Model=%s<br>\n\
                   7167: \n\
                   7168: <hr  size=\"2\" color=\"#EC5E5E\">\
                   7169:  <ul><li><h4>Parameter files</h4>\n\
                   7170:  - Parameter file: <a href=\"%s.%s\">%s.%s</a><br>\n\
                   7171:  - Copy of the parameter file: <a href=\"o%s\">o%s</a><br>\n\
                   7172:  - Log file of the run: <a href=\"%s\">%s</a><br>\n\
                   7173:  - Gnuplot file name: <a href=\"%s\">%s</a><br>\n\
                   7174:  - Date and time at start: %s</ul>\n",\
                   7175:          optionfilehtm,version,fullversion,title,datafile,firstpass,lastpass,stepm, weightopt, model,\
                   7176:          optionfilefiname,optionfilext,optionfilefiname,optionfilext,\
                   7177:          fileres,fileres,\
                   7178:          filelog,filelog,optionfilegnuplot,optionfilegnuplot,strstart);
                   7179:   fflush(fichtm);
                   7180: 
                   7181:   strcpy(pathr,path);
                   7182:   strcat(pathr,optionfilefiname);
1.184     brouard  7183: #ifdef WIN32
                   7184:   _chdir(optionfilefiname); /* Move to directory named optionfile */
                   7185: #else
1.126     brouard  7186:   chdir(optionfilefiname); /* Move to directory named optionfile */
1.184     brouard  7187: #endif
                   7188:          
1.126     brouard  7189:   
                   7190:   /* Calculates basic frequencies. Computes observed prevalence at single age
                   7191:      and prints on file fileres'p'. */
                   7192:   freqsummary(fileres, agemin, agemax, s, agev, nlstate, imx,Tvaraff,nbcode, ncodemax,mint,anint,strstart);
                   7193: 
                   7194:   fprintf(fichtm,"\n");
                   7195:   fprintf(fichtm,"<br>Total number of observations=%d <br>\n\
                   7196: Youngest age at first (selected) pass %.2f, oldest age %.2f<br>\n\
                   7197: Interval (in months) between two waves: Min=%d Max=%d Mean=%.2lf<br>\n",\
                   7198:          imx,agemin,agemax,jmin,jmax,jmean);
                   7199:   pmmij= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
                   7200:     oldms= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
                   7201:     newms= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
                   7202:     savms= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
                   7203:     oldm=oldms; newm=newms; savm=savms; /* Keeps fixed addresses to free */
                   7204:     
                   7205:    
                   7206:   /* For Powell, parameters are in a vector p[] starting at p[1]
                   7207:      so we point p on param[1][1] so that p[1] maps on param[1][1][1] */
                   7208:   p=param[1][1]; /* *(*(*(param +1)+1)+0) */
                   7209: 
                   7210:   globpr=0; /* To get the number ipmx of contributions and the sum of weights*/
1.186     brouard  7211:   /* For mortality only */
1.126     brouard  7212:   if (mle==-3){
1.136     brouard  7213:     ximort=matrix(1,NDIM,1,NDIM); 
1.186     brouard  7214:     /*     ximort=gsl_matrix_alloc(1,NDIM,1,NDIM); */
1.126     brouard  7215:     cens=ivector(1,n);
                   7216:     ageexmed=vector(1,n);
                   7217:     agecens=vector(1,n);
                   7218:     dcwave=ivector(1,n);
                   7219:  
                   7220:     for (i=1; i<=imx; i++){
                   7221:       dcwave[i]=-1;
                   7222:       for (m=firstpass; m<=lastpass; m++)
                   7223:        if (s[m][i]>nlstate) {
                   7224:          dcwave[i]=m;
                   7225:          /*    printf("i=%d j=%d s=%d dcwave=%d\n",i,j, s[j][i],dcwave[i]);*/
                   7226:          break;
                   7227:        }
                   7228:     }
                   7229: 
                   7230:     for (i=1; i<=imx; i++) {
                   7231:       if (wav[i]>0){
                   7232:        ageexmed[i]=agev[mw[1][i]][i];
                   7233:        j=wav[i];
                   7234:        agecens[i]=1.; 
                   7235: 
                   7236:        if (ageexmed[i]> 1 && wav[i] > 0){
                   7237:          agecens[i]=agev[mw[j][i]][i];
                   7238:          cens[i]= 1;
                   7239:        }else if (ageexmed[i]< 1) 
                   7240:          cens[i]= -1;
                   7241:        if (agedc[i]< AGESUP && agedc[i]>1 && dcwave[i]>firstpass && dcwave[i]<=lastpass)
                   7242:          cens[i]=0 ;
                   7243:       }
                   7244:       else cens[i]=-1;
                   7245:     }
                   7246:     
                   7247:     for (i=1;i<=NDIM;i++) {
                   7248:       for (j=1;j<=NDIM;j++)
                   7249:        ximort[i][j]=(i == j ? 1.0 : 0.0);
                   7250:     }
                   7251:     
1.145     brouard  7252:     /*p[1]=0.0268; p[NDIM]=0.083;*/
1.126     brouard  7253:     /*printf("%lf %lf", p[1], p[2]);*/
                   7254:     
                   7255:     
1.136     brouard  7256: #ifdef GSL
                   7257:     printf("GSL optimization\n");  fprintf(ficlog,"Powell\n");
1.162     brouard  7258: #else
1.126     brouard  7259:     printf("Powell\n");  fprintf(ficlog,"Powell\n");
1.136     brouard  7260: #endif
1.201   ! brouard  7261:     strcpy(filerespow,"POW-MORT_"); 
        !          7262:     strcat(filerespow,fileresu);
1.126     brouard  7263:     if((ficrespow=fopen(filerespow,"w"))==NULL) {
                   7264:       printf("Problem with resultfile: %s\n", filerespow);
                   7265:       fprintf(ficlog,"Problem with resultfile: %s\n", filerespow);
                   7266:     }
1.136     brouard  7267: #ifdef GSL
                   7268:     fprintf(ficrespow,"# GSL optimization\n# iter -2*LL");
1.162     brouard  7269: #else
1.126     brouard  7270:     fprintf(ficrespow,"# Powell\n# iter -2*LL");
1.136     brouard  7271: #endif
1.126     brouard  7272:     /*  for (i=1;i<=nlstate;i++)
                   7273:        for(j=1;j<=nlstate+ndeath;j++)
                   7274:        if(j!=i)fprintf(ficrespow," p%1d%1d",i,j);
                   7275:     */
                   7276:     fprintf(ficrespow,"\n");
1.136     brouard  7277: #ifdef GSL
                   7278:     /* gsl starts here */ 
                   7279:     T = gsl_multimin_fminimizer_nmsimplex;
                   7280:     gsl_multimin_fminimizer *sfm = NULL;
                   7281:     gsl_vector *ss, *x;
                   7282:     gsl_multimin_function minex_func;
                   7283: 
                   7284:     /* Initial vertex size vector */
                   7285:     ss = gsl_vector_alloc (NDIM);
                   7286:     
                   7287:     if (ss == NULL){
                   7288:       GSL_ERROR_VAL ("failed to allocate space for ss", GSL_ENOMEM, 0);
                   7289:     }
                   7290:     /* Set all step sizes to 1 */
                   7291:     gsl_vector_set_all (ss, 0.001);
                   7292: 
                   7293:     /* Starting point */
1.126     brouard  7294:     
1.136     brouard  7295:     x = gsl_vector_alloc (NDIM);
                   7296:     
                   7297:     if (x == NULL){
                   7298:       gsl_vector_free(ss);
                   7299:       GSL_ERROR_VAL ("failed to allocate space for x", GSL_ENOMEM, 0);
                   7300:     }
                   7301:   
                   7302:     /* Initialize method and iterate */
                   7303:     /*     p[1]=0.0268; p[NDIM]=0.083; */
1.186     brouard  7304:     /*     gsl_vector_set(x, 0, 0.0268); */
                   7305:     /*     gsl_vector_set(x, 1, 0.083); */
1.136     brouard  7306:     gsl_vector_set(x, 0, p[1]);
                   7307:     gsl_vector_set(x, 1, p[2]);
                   7308: 
                   7309:     minex_func.f = &gompertz_f;
                   7310:     minex_func.n = NDIM;
                   7311:     minex_func.params = (void *)&p; /* ??? */
                   7312:     
                   7313:     sfm = gsl_multimin_fminimizer_alloc (T, NDIM);
                   7314:     gsl_multimin_fminimizer_set (sfm, &minex_func, x, ss);
                   7315:     
                   7316:     printf("Iterations beginning .....\n\n");
                   7317:     printf("Iter. #    Intercept       Slope     -Log Likelihood     Simplex size\n");
                   7318: 
                   7319:     iteri=0;
                   7320:     while (rval == GSL_CONTINUE){
                   7321:       iteri++;
                   7322:       status = gsl_multimin_fminimizer_iterate(sfm);
                   7323:       
                   7324:       if (status) printf("error: %s\n", gsl_strerror (status));
                   7325:       fflush(0);
                   7326:       
                   7327:       if (status) 
                   7328:         break;
                   7329:       
                   7330:       rval = gsl_multimin_test_size (gsl_multimin_fminimizer_size (sfm), 1e-6);
                   7331:       ssval = gsl_multimin_fminimizer_size (sfm);
                   7332:       
                   7333:       if (rval == GSL_SUCCESS)
                   7334:         printf ("converged to a local maximum at\n");
                   7335:       
                   7336:       printf("%5d ", iteri);
                   7337:       for (it = 0; it < NDIM; it++){
                   7338:        printf ("%10.5f ", gsl_vector_get (sfm->x, it));
                   7339:       }
                   7340:       printf("f() = %-10.5f ssize = %.7f\n", sfm->fval, ssval);
                   7341:     }
                   7342:     
                   7343:     printf("\n\n Please note: Program should be run many times with varying starting points to detemine global maximum\n\n");
                   7344:     
                   7345:     gsl_vector_free(x); /* initial values */
                   7346:     gsl_vector_free(ss); /* inital step size */
                   7347:     for (it=0; it<NDIM; it++){
                   7348:       p[it+1]=gsl_vector_get(sfm->x,it);
                   7349:       fprintf(ficrespow," %.12lf", p[it]);
                   7350:     }
                   7351:     gsl_multimin_fminimizer_free (sfm); /* p *(sfm.x.data) et p *(sfm.x.data+1)  */
                   7352: #endif
                   7353: #ifdef POWELL
                   7354:      powell(p,ximort,NDIM,ftol,&iter,&fret,gompertz);
                   7355: #endif  
1.126     brouard  7356:     fclose(ficrespow);
                   7357:     
                   7358:     hesscov(matcov, p, NDIM, delti, 1e-4, gompertz); 
                   7359: 
                   7360:     for(i=1; i <=NDIM; i++)
                   7361:       for(j=i+1;j<=NDIM;j++)
                   7362:        matcov[i][j]=matcov[j][i];
                   7363:     
                   7364:     printf("\nCovariance matrix\n ");
                   7365:     for(i=1; i <=NDIM; i++) {
                   7366:       for(j=1;j<=NDIM;j++){ 
                   7367:        printf("%f ",matcov[i][j]);
                   7368:       }
                   7369:       printf("\n ");
                   7370:     }
                   7371:     
                   7372:     printf("iter=%d MLE=%f Eq=%lf*exp(%lf*(age-%d))\n",iter,-gompertz(p),p[1],p[2],agegomp);
1.193     brouard  7373:     for (i=1;i<=NDIM;i++) {
1.126     brouard  7374:       printf("%f [%f ; %f]\n",p[i],p[i]-2*sqrt(matcov[i][i]),p[i]+2*sqrt(matcov[i][i]));
1.193     brouard  7375:       fprintf(ficlog,"%f [%f ; %f]\n",p[i],p[i]-2*sqrt(matcov[i][i]),p[i]+2*sqrt(matcov[i][i]));
                   7376:     }
1.126     brouard  7377:     lsurv=vector(1,AGESUP);
                   7378:     lpop=vector(1,AGESUP);
                   7379:     tpop=vector(1,AGESUP);
                   7380:     lsurv[agegomp]=100000;
                   7381:     
                   7382:     for (k=agegomp;k<=AGESUP;k++) {
                   7383:       agemortsup=k;
                   7384:       if (p[1]*exp(p[2]*(k-agegomp))>1) break;
                   7385:     }
                   7386:     
                   7387:     for (k=agegomp;k<agemortsup;k++)
                   7388:       lsurv[k+1]=lsurv[k]-lsurv[k]*(p[1]*exp(p[2]*(k-agegomp)));
                   7389:     
                   7390:     for (k=agegomp;k<agemortsup;k++){
                   7391:       lpop[k]=(lsurv[k]+lsurv[k+1])/2.;
                   7392:       sumlpop=sumlpop+lpop[k];
                   7393:     }
                   7394:     
                   7395:     tpop[agegomp]=sumlpop;
                   7396:     for (k=agegomp;k<(agemortsup-3);k++){
                   7397:       /*  tpop[k+1]=2;*/
                   7398:       tpop[k+1]=tpop[k]-lpop[k];
                   7399:     }
                   7400:     
                   7401:     
                   7402:     printf("\nAge   lx     qx    dx    Lx     Tx     e(x)\n");
                   7403:     for (k=agegomp;k<(agemortsup-2);k++) 
                   7404:       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]);
                   7405:     
                   7406:     
                   7407:     replace_back_to_slash(pathc,pathcd); /* Even gnuplot wants a / */
1.194     brouard  7408:     if(ageminpar == AGEOVERFLOW ||agemaxpar == AGEOVERFLOW){
                   7409:        printf("Warning! Error in gnuplot file with ageminpar %f or agemaxpar %f overflow\n\
                   7410: This is probably because your parameter file doesn't \n  contain the exact number of lines (or columns) corresponding to your model line.\n\
                   7411: Please run with mle=-1 to get a correct covariance matrix.\n",ageminpar,agemaxpar);
                   7412:        fprintf(ficlog,"Warning! Error in gnuplot file with ageminpar %f or agemaxpar %f overflow\n\
                   7413: This is probably because your parameter file doesn't \n  contain the exact number of lines (or columns) corresponding to your model line.\n\
                   7414: Please run with mle=-1 to get a correct covariance matrix.\n",ageminpar,agemaxpar);
                   7415:     }else
1.201   ! brouard  7416:       printinggnuplotmort(fileresu, optionfilefiname,ageminpar,agemaxpar,fage, pathc,p);
        !          7417:     printinghtmlmort(fileresu,title,datafile, firstpass, lastpass, \
1.126     brouard  7418:                     stepm, weightopt,\
                   7419:                     model,imx,p,matcov,agemortsup);
                   7420:     
                   7421:     free_vector(lsurv,1,AGESUP);
                   7422:     free_vector(lpop,1,AGESUP);
                   7423:     free_vector(tpop,1,AGESUP);
1.136     brouard  7424: #ifdef GSL
                   7425:     free_ivector(cens,1,n);
                   7426:     free_vector(agecens,1,n);
                   7427:     free_ivector(dcwave,1,n);
                   7428:     free_matrix(ximort,1,NDIM,1,NDIM);
                   7429: #endif
1.186     brouard  7430:   } /* Endof if mle==-3 mortality only */
                   7431:   /* Standard maximisation */
1.126     brouard  7432:   else{ /* For mle >=1 */
1.132     brouard  7433:     globpr=0;/* debug */
1.186     brouard  7434:     /* Computes likelihood for initial parameters */
1.132     brouard  7435:     likelione(ficres, p, npar, nlstate, &globpr, &ipmx, &sw, &fretone, funcone); /* Prints the contributions to the likelihood */
1.126     brouard  7436:     printf("First Likeli=%12.6f ipmx=%ld sw=%12.6f",fretone,ipmx,sw);
                   7437:     for (k=1; k<=npar;k++)
                   7438:       printf(" %d %8.5f",k,p[k]);
                   7439:     printf("\n");
1.186     brouard  7440:     globpr=1; /* again, to print the contributions */
1.126     brouard  7441:     likelione(ficres, p, npar, nlstate, &globpr, &ipmx, &sw, &fretone, funcone); /* Prints the contributions to the likelihood */
                   7442:     printf("Second Likeli=%12.6f ipmx=%ld sw=%12.6f",fretone,ipmx,sw);
                   7443:     for (k=1; k<=npar;k++)
                   7444:       printf(" %d %8.5f",k,p[k]);
                   7445:     printf("\n");
1.186     brouard  7446:     if(mle>=1){ /* Could be 1 or 2, Real Maximisation */
1.126     brouard  7447:       mlikeli(ficres,p, npar, ncovmodel, nlstate, ftol, func);
                   7448:     }
                   7449:     
                   7450:     /*--------- results files --------------*/
1.192     brouard  7451:     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  7452:     
                   7453:     
                   7454:     fprintf(ficres,"# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
                   7455:     printf("# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
                   7456:     fprintf(ficlog,"# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
                   7457:     for(i=1,jk=1; i <=nlstate; i++){
                   7458:       for(k=1; k <=(nlstate+ndeath); k++){
                   7459:        if (k != i) {
                   7460:          printf("%d%d ",i,k);
                   7461:          fprintf(ficlog,"%d%d ",i,k);
                   7462:          fprintf(ficres,"%1d%1d ",i,k);
                   7463:          for(j=1; j <=ncovmodel; j++){
1.190     brouard  7464:            printf("%12.7f ",p[jk]);
                   7465:            fprintf(ficlog,"%12.7f ",p[jk]);
                   7466:            fprintf(ficres,"%12.7f ",p[jk]);
1.126     brouard  7467:            jk++; 
                   7468:          }
                   7469:          printf("\n");
                   7470:          fprintf(ficlog,"\n");
                   7471:          fprintf(ficres,"\n");
                   7472:        }
                   7473:       }
                   7474:     }
                   7475:     if(mle!=0){
                   7476:       /* Computing hessian and covariance matrix */
                   7477:       ftolhess=ftol; /* Usually correct */
                   7478:       hesscov(matcov, p, npar, delti, ftolhess, func);
                   7479:     }
1.197     brouard  7480:     printf("Parameters and 95%% confidence intervals\n W is simply the result of the division of the parameter by the square root of covariance of the parameter.\n And Wald-based confidence intervals plus and minus 1.96 * W .\n But be careful that parameters are highly correlated because incidence of disability is highly correlated to incidence of recovery.\n It might be better to visualize the covariance matrix. See the page 'Matrix of variance-covariance of one-step probabilities' and its graphs.\n");
                   7481:     fprintf(ficlog, "Parameters, Wald tests and Wald-based confidence intervals\n W is simply the result of the division of the parameter by the square root of covariance of the parameter.\n And Wald-based confidence intervals plus and minus 1.96 * W \n  It might be better to visualize the covariance matrix. See the page 'Matrix of variance-covariance of one-step probabilities' and its graphs.\n");
1.193     brouard  7482:     for(i=1,jk=1; i <=nlstate; i++){
                   7483:       for(k=1; k <=(nlstate+ndeath); k++){
                   7484:        if (k != i) {
                   7485:          printf("%d%d ",i,k);
                   7486:          fprintf(ficlog,"%d%d ",i,k);
                   7487:          for(j=1; j <=ncovmodel; j++){
1.197     brouard  7488:            printf("%12.7f W=%8.3f CI=[%12.7f ; %12.7f] ",p[jk], p[jk]/sqrt(matcov[jk][jk]), p[jk]-1.96*sqrt(matcov[jk][jk]),p[jk]+1.96*sqrt(matcov[jk][jk]));
                   7489:            fprintf(ficlog,"%12.7f W=%8.3f CI=[%12.7f ; %12.7f] ",p[jk], p[jk]/sqrt(matcov[jk][jk]), p[jk]-1.96*sqrt(matcov[jk][jk]),p[jk]+1.96*sqrt(matcov[jk][jk]));
1.193     brouard  7490:            jk++; 
                   7491:          }
                   7492:          printf("\n");
                   7493:          fprintf(ficlog,"\n");
                   7494:        }
                   7495:       }
                   7496:     }
                   7497: 
1.126     brouard  7498:     fprintf(ficres,"# Scales (for hessian or gradient estimation)\n");
                   7499:     printf("# Scales (for hessian or gradient estimation)\n");
                   7500:     fprintf(ficlog,"# Scales (for hessian or gradient estimation)\n");
                   7501:     for(i=1,jk=1; i <=nlstate; i++){
                   7502:       for(j=1; j <=nlstate+ndeath; j++){
                   7503:        if (j!=i) {
                   7504:          fprintf(ficres,"%1d%1d",i,j);
                   7505:          printf("%1d%1d",i,j);
                   7506:          fprintf(ficlog,"%1d%1d",i,j);
                   7507:          for(k=1; k<=ncovmodel;k++){
                   7508:            printf(" %.5e",delti[jk]);
                   7509:            fprintf(ficlog," %.5e",delti[jk]);
                   7510:            fprintf(ficres," %.5e",delti[jk]);
                   7511:            jk++;
                   7512:          }
                   7513:          printf("\n");
                   7514:          fprintf(ficlog,"\n");
                   7515:          fprintf(ficres,"\n");
                   7516:        }
                   7517:       }
                   7518:     }
                   7519:     
                   7520:     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");
                   7521:     if(mle>=1)
                   7522:       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");
                   7523:     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");
                   7524:     /* # 121 Var(a12)\n\ */
                   7525:     /* # 122 Cov(b12,a12) Var(b12)\n\ */
                   7526:     /* # 131 Cov(a13,a12) Cov(a13,b12, Var(a13)\n\ */
                   7527:     /* # 132 Cov(b13,a12) Cov(b13,b12, Cov(b13,a13) Var(b13)\n\ */
                   7528:     /* # 212 Cov(a21,a12) Cov(a21,b12, Cov(a21,a13) Cov(a21,b13) Var(a21)\n\ */
                   7529:     /* # 212 Cov(b21,a12) Cov(b21,b12, Cov(b21,a13) Cov(b21,b13) Cov(b21,a21) Var(b21)\n\ */
                   7530:     /* # 232 Cov(a23,a12) Cov(a23,b12, Cov(a23,a13) Cov(a23,b13) Cov(a23,a21) Cov(a23,b21) Var(a23)\n\ */
                   7531:     /* # 232 Cov(b23,a12) Cov(b23,b12) ... Var (b23)\n" */
                   7532:     
                   7533:     
                   7534:     /* Just to have a covariance matrix which will be more understandable
                   7535:        even is we still don't want to manage dictionary of variables
                   7536:     */
                   7537:     for(itimes=1;itimes<=2;itimes++){
                   7538:       jj=0;
                   7539:       for(i=1; i <=nlstate; i++){
                   7540:        for(j=1; j <=nlstate+ndeath; j++){
                   7541:          if(j==i) continue;
                   7542:          for(k=1; k<=ncovmodel;k++){
                   7543:            jj++;
                   7544:            ca[0]= k+'a'-1;ca[1]='\0';
                   7545:            if(itimes==1){
                   7546:              if(mle>=1)
                   7547:                printf("#%1d%1d%d",i,j,k);
                   7548:              fprintf(ficlog,"#%1d%1d%d",i,j,k);
                   7549:              fprintf(ficres,"#%1d%1d%d",i,j,k);
                   7550:            }else{
                   7551:              if(mle>=1)
                   7552:                printf("%1d%1d%d",i,j,k);
                   7553:              fprintf(ficlog,"%1d%1d%d",i,j,k);
                   7554:              fprintf(ficres,"%1d%1d%d",i,j,k);
                   7555:            }
                   7556:            ll=0;
                   7557:            for(li=1;li <=nlstate; li++){
                   7558:              for(lj=1;lj <=nlstate+ndeath; lj++){
                   7559:                if(lj==li) continue;
                   7560:                for(lk=1;lk<=ncovmodel;lk++){
                   7561:                  ll++;
                   7562:                  if(ll<=jj){
                   7563:                    cb[0]= lk +'a'-1;cb[1]='\0';
                   7564:                    if(ll<jj){
                   7565:                      if(itimes==1){
                   7566:                        if(mle>=1)
                   7567:                          printf(" Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
                   7568:                        fprintf(ficlog," Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
                   7569:                        fprintf(ficres," Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
                   7570:                      }else{
                   7571:                        if(mle>=1)
                   7572:                          printf(" %.5e",matcov[jj][ll]); 
                   7573:                        fprintf(ficlog," %.5e",matcov[jj][ll]); 
                   7574:                        fprintf(ficres," %.5e",matcov[jj][ll]); 
                   7575:                      }
                   7576:                    }else{
                   7577:                      if(itimes==1){
                   7578:                        if(mle>=1)
                   7579:                          printf(" Var(%s%1d%1d)",ca,i,j);
                   7580:                        fprintf(ficlog," Var(%s%1d%1d)",ca,i,j);
                   7581:                        fprintf(ficres," Var(%s%1d%1d)",ca,i,j);
                   7582:                      }else{
                   7583:                        if(mle>=1)
                   7584:                          printf(" %.5e",matcov[jj][ll]); 
                   7585:                        fprintf(ficlog," %.5e",matcov[jj][ll]); 
                   7586:                        fprintf(ficres," %.5e",matcov[jj][ll]); 
                   7587:                      }
                   7588:                    }
                   7589:                  }
                   7590:                } /* end lk */
                   7591:              } /* end lj */
                   7592:            } /* end li */
                   7593:            if(mle>=1)
                   7594:              printf("\n");
                   7595:            fprintf(ficlog,"\n");
                   7596:            fprintf(ficres,"\n");
                   7597:            numlinepar++;
                   7598:          } /* end k*/
                   7599:        } /*end j */
                   7600:       } /* end i */
                   7601:     } /* end itimes */
                   7602:     
                   7603:     fflush(ficlog);
                   7604:     fflush(ficres);
                   7605:     
                   7606:     while((c=getc(ficpar))=='#' && c!= EOF){
                   7607:       ungetc(c,ficpar);
                   7608:       fgets(line, MAXLINE, ficpar);
1.141     brouard  7609:       fputs(line,stdout);
1.126     brouard  7610:       fputs(line,ficparo);
                   7611:     }
                   7612:     ungetc(c,ficpar);
                   7613:     
                   7614:     estepm=0;
                   7615:     fscanf(ficpar,"agemin=%lf agemax=%lf bage=%lf fage=%lf estepm=%d\n",&ageminpar,&agemaxpar, &bage, &fage, &estepm);
                   7616:     if (estepm==0 || estepm < stepm) estepm=stepm;
                   7617:     if (fage <= 2) {
                   7618:       bage = ageminpar;
                   7619:       fage = agemaxpar;
                   7620:     }
                   7621:     
                   7622:     fprintf(ficres,"# agemin agemax for life expectancy, bage fage (if mle==0 ie no data nor Max likelihood).\n");
                   7623:     fprintf(ficres,"agemin=%.0f agemax=%.0f bage=%.0f fage=%.0f estepm=%d\n",ageminpar,agemaxpar,bage,fage, estepm);
                   7624:     fprintf(ficparo,"agemin=%.0f agemax=%.0f bage=%.0f fage=%.0f estepm=%d\n",ageminpar,agemaxpar,bage,fage, estepm);
1.186     brouard  7625: 
                   7626:     /* Other stuffs, more or less useful */    
1.126     brouard  7627:     while((c=getc(ficpar))=='#' && c!= EOF){
                   7628:       ungetc(c,ficpar);
                   7629:       fgets(line, MAXLINE, ficpar);
1.141     brouard  7630:       fputs(line,stdout);
1.126     brouard  7631:       fputs(line,ficparo);
                   7632:     }
                   7633:     ungetc(c,ficpar);
                   7634:     
                   7635:     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);
                   7636:     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);
                   7637:     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);
                   7638:     printf("begin-prev-date=%.lf/%.lf/%.lf end-prev-date=%.lf/%.lf/%.lf mov_average=%d\n",jprev1, mprev1,anprev1,jprev2, mprev2,anprev2,mobilav);
                   7639:     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);
                   7640:     
                   7641:     while((c=getc(ficpar))=='#' && c!= EOF){
                   7642:       ungetc(c,ficpar);
                   7643:       fgets(line, MAXLINE, ficpar);
1.141     brouard  7644:       fputs(line,stdout);
1.126     brouard  7645:       fputs(line,ficparo);
                   7646:     }
                   7647:     ungetc(c,ficpar);
                   7648:     
                   7649:     
                   7650:     dateprev1=anprev1+(mprev1-1)/12.+(jprev1-1)/365.;
                   7651:     dateprev2=anprev2+(mprev2-1)/12.+(jprev2-1)/365.;
                   7652:     
                   7653:     fscanf(ficpar,"pop_based=%d\n",&popbased);
1.193     brouard  7654:     fprintf(ficlog,"pop_based=%d\n",popbased);
1.126     brouard  7655:     fprintf(ficparo,"pop_based=%d\n",popbased);   
                   7656:     fprintf(ficres,"pop_based=%d\n",popbased);   
                   7657:     
                   7658:     while((c=getc(ficpar))=='#' && c!= EOF){
                   7659:       ungetc(c,ficpar);
                   7660:       fgets(line, MAXLINE, ficpar);
1.141     brouard  7661:       fputs(line,stdout);
1.126     brouard  7662:       fputs(line,ficparo);
                   7663:     }
                   7664:     ungetc(c,ficpar);
                   7665:     
                   7666:     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);
                   7667:     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);
                   7668:     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);
                   7669:     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);
                   7670:     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);
                   7671:     /* day and month of proj2 are not used but only year anproj2.*/
                   7672:     
                   7673:     
                   7674:     
1.145     brouard  7675:      /* freqsummary(fileres, agemin, agemax, s, agev, nlstate, imx,Tvaraff,nbcode, ncodemax,mint,anint); */
                   7676:     /* ,dateprev1,dateprev2,jprev1, mprev1,anprev1,jprev2, mprev2,anprev2); */
1.126     brouard  7677:     
                   7678:     replace_back_to_slash(pathc,pathcd); /* Even gnuplot wants a / */
1.194     brouard  7679:     if(ageminpar == AGEOVERFLOW ||agemaxpar == -AGEOVERFLOW){
                   7680:        printf("Warning! Error in gnuplot file with ageminpar %f or agemaxpar %f overflow\n\
                   7681: This is probably because your parameter file doesn't \n  contain the exact number of lines (or columns) corresponding to your model line.\n\
                   7682: Please run with mle=-1 to get a correct covariance matrix.\n",ageminpar,agemaxpar);
                   7683:        fprintf(ficlog,"Warning! Error in gnuplot file with ageminpar %f or agemaxpar %f overflow\n\
                   7684: This is probably because your parameter file doesn't \n  contain the exact number of lines (or columns) corresponding to your model line.\n\
                   7685: Please run with mle=-1 to get a correct covariance matrix.\n",ageminpar,agemaxpar);
                   7686:     }else
1.201   ! brouard  7687:       printinggnuplot(fileresu, optionfilefiname,ageminpar,agemaxpar,fage, pathc,p);
1.126     brouard  7688:     
1.201   ! brouard  7689:     printinghtml(fileresu,title,datafile, firstpass, lastpass, stepm, weightopt,\
1.126     brouard  7690:                 model,imx,jmin,jmax,jmean,rfileres,popforecast,estepm,\
                   7691:                 jprev1,mprev1,anprev1,jprev2,mprev2,anprev2);
                   7692:       
                   7693:    /*------------ free_vector  -------------*/
                   7694:    /*  chdir(path); */
                   7695:  
                   7696:     free_ivector(wav,1,imx);
                   7697:     free_imatrix(dh,1,lastpass-firstpass+1,1,imx);
                   7698:     free_imatrix(bh,1,lastpass-firstpass+1,1,imx);
                   7699:     free_imatrix(mw,1,lastpass-firstpass+1,1,imx);   
                   7700:     free_lvector(num,1,n);
                   7701:     free_vector(agedc,1,n);
                   7702:     /*free_matrix(covar,0,NCOVMAX,1,n);*/
                   7703:     /*free_matrix(covar,1,NCOVMAX,1,n);*/
                   7704:     fclose(ficparo);
                   7705:     fclose(ficres);
                   7706: 
                   7707: 
1.186     brouard  7708:     /* Other results (useful)*/
                   7709: 
                   7710: 
1.126     brouard  7711:     /*--------------- Prevalence limit  (period or stable prevalence) --------------*/
1.180     brouard  7712:     /*#include "prevlim.h"*/  /* Use ficrespl, ficlog */
                   7713:     prlim=matrix(1,nlstate,1,nlstate);
                   7714:     prevalence_limit(p, prlim,  ageminpar, agemaxpar);
1.126     brouard  7715:     fclose(ficrespl);
                   7716: 
1.145     brouard  7717: #ifdef FREEEXIT2
                   7718: #include "freeexit2.h"
                   7719: #endif
                   7720: 
1.126     brouard  7721:     /*------------- h Pij x at various ages ------------*/
1.180     brouard  7722:     /*#include "hpijx.h"*/
                   7723:     hPijx(p, bage, fage);
1.145     brouard  7724:     fclose(ficrespij);
1.126     brouard  7725: 
1.145     brouard  7726:   /*-------------- Variance of one-step probabilities---*/
                   7727:     k=1;
1.126     brouard  7728:     varprob(optionfilefiname, matcov, p, delti, nlstate, bage, fage,k,Tvar,nbcode, ncodemax,strstart);
                   7729: 
                   7730: 
                   7731:     probs= ma3x(1,AGESUP,1,NCOVMAX, 1,NCOVMAX);
                   7732:     for(i=1;i<=AGESUP;i++)
                   7733:       for(j=1;j<=NCOVMAX;j++)
                   7734:        for(k=1;k<=NCOVMAX;k++)
                   7735:          probs[i][j][k]=0.;
                   7736: 
                   7737:     /*---------- Forecasting ------------------*/
                   7738:     /*if((stepm == 1) && (strcmp(model,".")==0)){*/
                   7739:     if(prevfcast==1){
                   7740:       /*    if(stepm ==1){*/
1.201   ! brouard  7741:       prevforecast(fileresu, anproj1, mproj1, jproj1, agemin, agemax, dateprev1, dateprev2, mobilavproj, bage, fage, firstpass, lastpass, anproj2, p, cptcoveff);
1.126     brouard  7742:       /* (popforecast==1) populforecast(fileres, anpyram,mpyram,jpyram, agemin,agemax, dateprev1, dateprev2,mobilav, agedeb, fage, popforecast, popfile, anpyram1,p, i1);*/
                   7743:       /*      }  */
                   7744:       /*      else{ */
                   7745:       /*        erreur=108; */
                   7746:       /*        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); */
                   7747:       /*        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); */
                   7748:       /*      } */
                   7749:     }
1.186     brouard  7750:  
                   7751:     /* ------ Other prevalence ratios------------ */
1.126     brouard  7752: 
1.127     brouard  7753:     /* Computes prevalence between agemin (i.e minimal age computed) and no more ageminpar */
                   7754: 
                   7755:     prevalence(probs, agemin, agemax, s, agev, nlstate, imx, Tvar, nbcode, ncodemax, mint, anint, dateprev1, dateprev2, firstpass, lastpass);
                   7756:     /*  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",\
                   7757:        ageminpar, agemax, s[lastpass][imx], agev[lastpass][imx], nlstate, imx, mint[lastpass][imx],anint[lastpass][imx], dateprev1, dateprev2, firstpass, lastpass);
                   7758:     */
1.126     brouard  7759: 
1.127     brouard  7760:     if (mobilav!=0) {
                   7761:       mobaverage= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
                   7762:       if (movingaverage(probs, bage, fage, mobaverage,mobilav)!=0){
                   7763:        fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav);
                   7764:        printf(" Error in movingaverage mobilav=%d\n",mobilav);
                   7765:       }
1.126     brouard  7766:     }
                   7767: 
                   7768: 
1.127     brouard  7769:     /*---------- Health expectancies, no variances ------------*/
                   7770: 
1.201   ! brouard  7771:     strcpy(filerese,"E_");
        !          7772:     strcat(filerese,fileresu);
1.126     brouard  7773:     if((ficreseij=fopen(filerese,"w"))==NULL) {
                   7774:       printf("Problem with Health Exp. resultfile: %s\n", filerese); exit(0);
                   7775:       fprintf(ficlog,"Problem with Health Exp. resultfile: %s\n", filerese); exit(0);
                   7776:     }
                   7777:     printf("Computing Health Expectancies: result on file '%s' \n", filerese);
                   7778:     fprintf(ficlog,"Computing Health Expectancies: result on file '%s' \n", filerese);
1.145     brouard  7779:     /*for(cptcov=1,k=0;cptcov<=i1;cptcov++){
                   7780:       for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){*/
                   7781:           
                   7782:     for (k=1; k <= (int) pow(2,cptcoveff); k++){
1.127     brouard  7783:        fprintf(ficreseij,"\n#****** ");
                   7784:        for(j=1;j<=cptcoveff;j++) {
1.200     brouard  7785:          fprintf(ficreseij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
1.127     brouard  7786:        }
                   7787:        fprintf(ficreseij,"******\n");
                   7788: 
                   7789:        eij=ma3x(1,nlstate,1,nlstate,(int) bage, (int) fage);
                   7790:        oldm=oldms;savm=savms;
                   7791:        evsij(eij, p, nlstate, stepm, (int) bage, (int)fage, oldm, savm, k, estepm, strstart);  
                   7792:       
                   7793:        free_ma3x(eij,1,nlstate,1,nlstate,(int) bage, (int)fage);
1.145     brouard  7794:       /*}*/
1.127     brouard  7795:     }
                   7796:     fclose(ficreseij);
                   7797: 
                   7798: 
                   7799:     /*---------- Health expectancies and variances ------------*/
                   7800: 
                   7801: 
1.201   ! brouard  7802:     strcpy(filerest,"T_");
        !          7803:     strcat(filerest,fileresu);
1.127     brouard  7804:     if((ficrest=fopen(filerest,"w"))==NULL) {
                   7805:       printf("Problem with total LE resultfile: %s\n", filerest);goto end;
                   7806:       fprintf(ficlog,"Problem with total LE resultfile: %s\n", filerest);goto end;
                   7807:     }
                   7808:     printf("Computing Total Life expectancies with their standard errors: file '%s' \n", filerest); 
                   7809:     fprintf(ficlog,"Computing Total Life expectancies with their standard errors: file '%s' \n", filerest); 
                   7810: 
1.126     brouard  7811: 
1.201   ! brouard  7812:     strcpy(fileresstde,"STDE_");
        !          7813:     strcat(fileresstde,fileresu);
1.126     brouard  7814:     if((ficresstdeij=fopen(fileresstde,"w"))==NULL) {
                   7815:       printf("Problem with Health Exp. and std errors resultfile: %s\n", fileresstde); exit(0);
                   7816:       fprintf(ficlog,"Problem with Health Exp. and std errors resultfile: %s\n", fileresstde); exit(0);
                   7817:     }
                   7818:     printf("Computing Health Expectancies and standard errors: result on file '%s' \n", fileresstde);
                   7819:     fprintf(ficlog,"Computing Health Expectancies and standard errors: result on file '%s' \n", fileresstde);
                   7820: 
1.201   ! brouard  7821:     strcpy(filerescve,"CVE_");
        !          7822:     strcat(filerescve,fileresu);
1.126     brouard  7823:     if((ficrescveij=fopen(filerescve,"w"))==NULL) {
                   7824:       printf("Problem with Covar. Health Exp. resultfile: %s\n", filerescve); exit(0);
                   7825:       fprintf(ficlog,"Problem with Covar. Health Exp. resultfile: %s\n", filerescve); exit(0);
                   7826:     }
                   7827:     printf("Computing Covar. of Health Expectancies: result on file '%s' \n", filerescve);
                   7828:     fprintf(ficlog,"Computing Covar. of Health Expectancies: result on file '%s' \n", filerescve);
                   7829: 
1.201   ! brouard  7830:     strcpy(fileresv,"V_");
        !          7831:     strcat(fileresv,fileresu);
1.126     brouard  7832:     if((ficresvij=fopen(fileresv,"w"))==NULL) {
                   7833:       printf("Problem with variance resultfile: %s\n", fileresv);exit(0);
                   7834:       fprintf(ficlog,"Problem with variance resultfile: %s\n", fileresv);exit(0);
                   7835:     }
                   7836:     printf("Computing Variance-covariance of DFLEs: file '%s' \n", fileresv);
                   7837:     fprintf(ficlog,"Computing Variance-covariance of DFLEs: file '%s' \n", fileresv);
                   7838: 
1.145     brouard  7839:     /*for(cptcov=1,k=0;cptcov<=i1;cptcov++){
                   7840:       for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){*/
                   7841:           
                   7842:     for (k=1; k <= (int) pow(2,cptcoveff); k++){
                   7843:        fprintf(ficrest,"\n#****** ");
1.126     brouard  7844:        for(j=1;j<=cptcoveff;j++) 
1.200     brouard  7845:          fprintf(ficrest,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
1.126     brouard  7846:        fprintf(ficrest,"******\n");
                   7847: 
                   7848:        fprintf(ficresstdeij,"\n#****** ");
                   7849:        fprintf(ficrescveij,"\n#****** ");
                   7850:        for(j=1;j<=cptcoveff;j++) {
1.200     brouard  7851:          fprintf(ficresstdeij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
                   7852:          fprintf(ficrescveij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
1.126     brouard  7853:        }
                   7854:        fprintf(ficresstdeij,"******\n");
                   7855:        fprintf(ficrescveij,"******\n");
                   7856: 
                   7857:        fprintf(ficresvij,"\n#****** ");
                   7858:        for(j=1;j<=cptcoveff;j++) 
1.200     brouard  7859:          fprintf(ficresvij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
1.126     brouard  7860:        fprintf(ficresvij,"******\n");
                   7861: 
                   7862:        eij=ma3x(1,nlstate,1,nlstate,(int) bage, (int) fage);
                   7863:        oldm=oldms;savm=savms;
1.127     brouard  7864:        cvevsij(eij, p, nlstate, stepm, (int) bage, (int)fage, oldm, savm, k, estepm, delti, matcov, strstart);  
1.145     brouard  7865:        /*
                   7866:         */
                   7867:        /* goto endfree; */
1.126     brouard  7868:  
                   7869:        vareij=ma3x(1,nlstate,1,nlstate,(int) bage, (int) fage);
                   7870:        pstamp(ficrest);
1.145     brouard  7871: 
                   7872: 
1.128     brouard  7873:        for(vpopbased=0; vpopbased <= popbased; vpopbased++){ /* Done for vpopbased=0 and vpopbased=1 if popbased==1*/
1.199     brouard  7874:          oldm=oldms;savm=savms; /* ZZ Segmentation fault */
1.161     brouard  7875:          cptcod= 0; /* To be deleted */
                   7876:          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  7877:          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  7878:          if(vpopbased==1)
                   7879:            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);
                   7880:          else
                   7881:            fprintf(ficrest,"the age specific period (stable) prevalences in each health state \n");
1.201   ! brouard  7882:          fprintf(ficrest,"# Age popbased mobilav e.. (std) ");
1.128     brouard  7883:          for (i=1;i<=nlstate;i++) fprintf(ficrest,"e.%d (std) ",i);
                   7884:          fprintf(ficrest,"\n");
1.199     brouard  7885:          /* printf("Which p?\n"); for(i=1;i<=npar;i++)printf("p[i=%d]=%lf,",i,p[i]);printf("\n"); */
1.128     brouard  7886:          epj=vector(1,nlstate+1);
                   7887:          for(age=bage; age <=fage ;age++){
1.199     brouard  7888:            prevalim(prlim, nlstate, p, age, oldm, savm,ftolpl,k); /*ZZ Is it the correct prevalim */
1.128     brouard  7889:            if (vpopbased==1) {
                   7890:              if(mobilav ==0){
                   7891:                for(i=1; i<=nlstate;i++)
                   7892:                  prlim[i][i]=probs[(int)age][i][k];
                   7893:              }else{ /* mobilav */ 
                   7894:                for(i=1; i<=nlstate;i++)
                   7895:                  prlim[i][i]=mobaverage[(int)age][i][k];
                   7896:              }
1.126     brouard  7897:            }
                   7898:        
1.201   ! brouard  7899:            fprintf(ficrest," %4.0f %d %d",age, vpopbased, mobilav);
1.199     brouard  7900:            /* printf(" age %4.0f ",age); */
1.128     brouard  7901:            for(j=1, epj[nlstate+1]=0.;j <=nlstate;j++){
                   7902:              for(i=1, epj[j]=0.;i <=nlstate;i++) {
                   7903:                epj[j] += prlim[i][i]*eij[i][j][(int)age];
1.199     brouard  7904:                /*ZZZ  printf("%lf %lf ", prlim[i][i] ,eij[i][j][(int)age]);*/
                   7905:                /* printf("%lf %lf ", prlim[i][i] ,eij[i][j][(int)age]); */
1.128     brouard  7906:              }
                   7907:              epj[nlstate+1] +=epj[j];
1.126     brouard  7908:            }
1.199     brouard  7909:            /* printf(" age %4.0f \n",age); */
1.126     brouard  7910: 
1.128     brouard  7911:            for(i=1, vepp=0.;i <=nlstate;i++)
                   7912:              for(j=1;j <=nlstate;j++)
                   7913:                vepp += vareij[i][j][(int)age];
                   7914:            fprintf(ficrest," %7.3f (%7.3f)", epj[nlstate+1],sqrt(vepp));
                   7915:            for(j=1;j <=nlstate;j++){
                   7916:              fprintf(ficrest," %7.3f (%7.3f)", epj[j],sqrt(vareij[j][j][(int)age]));
                   7917:            }
                   7918:            fprintf(ficrest,"\n");
1.126     brouard  7919:          }
                   7920:        }
                   7921:        free_ma3x(eij,1,nlstate,1,nlstate,(int) bage, (int)fage);
                   7922:        free_ma3x(vareij,1,nlstate,1,nlstate,(int) bage, (int)fage);
                   7923:        free_vector(epj,1,nlstate+1);
1.145     brouard  7924:       /*}*/
1.126     brouard  7925:     }
                   7926:     free_vector(weight,1,n);
1.145     brouard  7927:     free_imatrix(Tvard,1,NCOVMAX,1,2);
1.126     brouard  7928:     free_imatrix(s,1,maxwav+1,1,n);
                   7929:     free_matrix(anint,1,maxwav,1,n); 
                   7930:     free_matrix(mint,1,maxwav,1,n);
                   7931:     free_ivector(cod,1,n);
                   7932:     free_ivector(tab,1,NCOVMAX);
                   7933:     fclose(ficresstdeij);
                   7934:     fclose(ficrescveij);
                   7935:     fclose(ficresvij);
                   7936:     fclose(ficrest);
                   7937:     fclose(ficpar);
                   7938:   
                   7939:     /*------- Variance of period (stable) prevalence------*/   
                   7940: 
1.201   ! brouard  7941:     strcpy(fileresvpl,"VPL_");
        !          7942:     strcat(fileresvpl,fileresu);
1.126     brouard  7943:     if((ficresvpl=fopen(fileresvpl,"w"))==NULL) {
                   7944:       printf("Problem with variance of period (stable) prevalence  resultfile: %s\n", fileresvpl);
                   7945:       exit(0);
                   7946:     }
                   7947:     printf("Computing Variance-covariance of period (stable) prevalence: file '%s' \n", fileresvpl);
                   7948: 
1.145     brouard  7949:     /*for(cptcov=1,k=0;cptcov<=i1;cptcov++){
                   7950:       for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){*/
                   7951:           
                   7952:     for (k=1; k <= (int) pow(2,cptcoveff); k++){
                   7953:        fprintf(ficresvpl,"\n#****** ");
1.126     brouard  7954:        for(j=1;j<=cptcoveff;j++) 
1.200     brouard  7955:          fprintf(ficresvpl,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
1.126     brouard  7956:        fprintf(ficresvpl,"******\n");
                   7957:       
                   7958:        varpl=matrix(1,nlstate,(int) bage, (int) fage);
                   7959:        oldm=oldms;savm=savms;
                   7960:        varprevlim(fileres, varpl, matcov, p, delti, nlstate, stepm, (int) bage, (int) fage, oldm, savm, prlim, ftolpl,k,strstart);
                   7961:        free_matrix(varpl,1,nlstate,(int) bage, (int)fage);
1.145     brouard  7962:       /*}*/
1.126     brouard  7963:     }
                   7964: 
                   7965:     fclose(ficresvpl);
                   7966: 
                   7967:     /*---------- End : free ----------------*/
                   7968:     if (mobilav!=0) free_ma3x(mobaverage,1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
                   7969:     free_ma3x(probs,1,AGESUP,1,NCOVMAX, 1,NCOVMAX);
                   7970:   }  /* mle==-3 arrives here for freeing */
1.164     brouard  7971:  /* endfree:*/
1.141     brouard  7972:     free_matrix(prlim,1,nlstate,1,nlstate); /*here or after loop ? */
1.126     brouard  7973:     free_matrix(pmmij,1,nlstate+ndeath,1,nlstate+ndeath);
                   7974:     free_matrix(oldms, 1,nlstate+ndeath,1,nlstate+ndeath);
                   7975:     free_matrix(newms, 1,nlstate+ndeath,1,nlstate+ndeath);
                   7976:     free_matrix(savms, 1,nlstate+ndeath,1,nlstate+ndeath);
                   7977:     free_matrix(covar,0,NCOVMAX,1,n);
                   7978:     free_matrix(matcov,1,npar,1,npar);
                   7979:     /*free_vector(delti,1,npar);*/
                   7980:     free_ma3x(delti3,1,nlstate,1, nlstate+ndeath-1,1,ncovmodel); 
                   7981:     free_matrix(agev,1,maxwav,1,imx);
                   7982:     free_ma3x(param,1,nlstate,1, nlstate+ndeath-1,1,ncovmodel);
                   7983: 
1.145     brouard  7984:     free_ivector(ncodemax,1,NCOVMAX);
1.192     brouard  7985:     free_ivector(ncodemaxwundef,1,NCOVMAX);
1.145     brouard  7986:     free_ivector(Tvar,1,NCOVMAX);
                   7987:     free_ivector(Tprod,1,NCOVMAX);
                   7988:     free_ivector(Tvaraff,1,NCOVMAX);
                   7989:     free_ivector(Tage,1,NCOVMAX);
1.126     brouard  7990: 
                   7991:     free_imatrix(nbcode,0,NCOVMAX,0,NCOVMAX);
1.200     brouard  7992:     /* free_imatrix(codtab,1,100,1,10); */
1.126     brouard  7993:   fflush(fichtm);
                   7994:   fflush(ficgp);
                   7995:   
                   7996: 
                   7997:   if((nberr >0) || (nbwarn>0)){
                   7998:     printf("End of Imach with %d errors and/or %d warnings\n",nberr,nbwarn);
                   7999:     fprintf(ficlog,"End of Imach with %d errors and/or warnings %d\n",nberr,nbwarn);
                   8000:   }else{
                   8001:     printf("End of Imach\n");
                   8002:     fprintf(ficlog,"End of Imach\n");
                   8003:   }
                   8004:   printf("See log file on %s\n",filelog);
                   8005:   /*  gettimeofday(&end_time, (struct timezone*)0);*/  /* after time */
1.157     brouard  8006:   /*(void) gettimeofday(&end_time,&tzp);*/
                   8007:   rend_time = time(NULL);  
                   8008:   end_time = *localtime(&rend_time);
                   8009:   /* tml = *localtime(&end_time.tm_sec); */
                   8010:   strcpy(strtend,asctime(&end_time));
1.126     brouard  8011:   printf("Local time at start %s\nLocal time at end   %s",strstart, strtend); 
                   8012:   fprintf(ficlog,"Local time at start %s\nLocal time at end   %s\n",strstart, strtend); 
1.157     brouard  8013:   printf("Total time used %s\n", asc_diff_time(rend_time -rstart_time,tmpout));
1.126     brouard  8014: 
1.157     brouard  8015:   printf("Total time was %.0lf Sec.\n", difftime(rend_time,rstart_time));
                   8016:   fprintf(ficlog,"Total time used %s\n", asc_diff_time(rend_time -rstart_time,tmpout));
                   8017:   fprintf(ficlog,"Total time was %.0lf Sec.\n", difftime(rend_time,rstart_time));
1.126     brouard  8018:   /*  printf("Total time was %d uSec.\n", total_usecs);*/
                   8019: /*   if(fileappend(fichtm,optionfilehtm)){ */
                   8020:   fprintf(fichtm,"<br>Local time at start %s<br>Local time at end   %s<br>\n</body></html>",strstart, strtend);
                   8021:   fclose(fichtm);
                   8022:   fprintf(fichtmcov,"<br>Local time at start %s<br>Local time at end   %s<br>\n</body></html>",strstart, strtend);
                   8023:   fclose(fichtmcov);
                   8024:   fclose(ficgp);
                   8025:   fclose(ficlog);
                   8026:   /*------ End -----------*/
                   8027: 
                   8028: 
                   8029:    printf("Before Current directory %s!\n",pathcd);
1.184     brouard  8030: #ifdef WIN32
                   8031:    if (_chdir(pathcd) != 0)
                   8032:           printf("Can't move to directory %s!\n",path);
                   8033:    if(_getcwd(pathcd,MAXLINE) > 0)
                   8034: #else
1.126     brouard  8035:    if(chdir(pathcd) != 0)
1.184     brouard  8036:           printf("Can't move to directory %s!\n", path);
                   8037:    if (getcwd(pathcd, MAXLINE) > 0)
                   8038: #endif 
1.126     brouard  8039:     printf("Current directory %s!\n",pathcd);
                   8040:   /*strcat(plotcmd,CHARSEPARATOR);*/
                   8041:   sprintf(plotcmd,"gnuplot");
1.157     brouard  8042: #ifdef _WIN32
1.126     brouard  8043:   sprintf(plotcmd,"\"%sgnuplot.exe\"",pathimach);
                   8044: #endif
                   8045:   if(!stat(plotcmd,&info)){
1.158     brouard  8046:     printf("Error or gnuplot program not found: '%s'\n",plotcmd);fflush(stdout);
1.126     brouard  8047:     if(!stat(getenv("GNUPLOTBIN"),&info)){
1.158     brouard  8048:       printf("Error or gnuplot program not found: '%s' Environment GNUPLOTBIN not set.\n",plotcmd);fflush(stdout);
1.126     brouard  8049:     }else
                   8050:       strcpy(pplotcmd,plotcmd);
1.157     brouard  8051: #ifdef __unix
1.126     brouard  8052:     strcpy(plotcmd,GNUPLOTPROGRAM);
                   8053:     if(!stat(plotcmd,&info)){
1.158     brouard  8054:       printf("Error gnuplot program not found: '%s'\n",plotcmd);fflush(stdout);
1.126     brouard  8055:     }else
                   8056:       strcpy(pplotcmd,plotcmd);
                   8057: #endif
                   8058:   }else
                   8059:     strcpy(pplotcmd,plotcmd);
                   8060:   
                   8061:   sprintf(plotcmd,"%s %s",pplotcmd, optionfilegnuplot);
1.158     brouard  8062:   printf("Starting graphs with: '%s'\n",plotcmd);fflush(stdout);
1.126     brouard  8063: 
                   8064:   if((outcmd=system(plotcmd)) != 0){
1.158     brouard  8065:     printf("gnuplot command might not be in your path: '%s', err=%d\n", plotcmd, outcmd);
1.154     brouard  8066:     printf("\n Trying if gnuplot resides on the same directory that IMaCh\n");
1.152     brouard  8067:     sprintf(plotcmd,"%sgnuplot %s", pathimach, optionfilegnuplot);
1.150     brouard  8068:     if((outcmd=system(plotcmd)) != 0)
1.153     brouard  8069:       printf("\n Still a problem with gnuplot command %s, err=%d\n", plotcmd, outcmd);
1.126     brouard  8070:   }
1.158     brouard  8071:   printf(" Successful, please wait...");
1.126     brouard  8072:   while (z[0] != 'q') {
                   8073:     /* chdir(path); */
1.154     brouard  8074:     printf("\nType e to edit results with your browser, g to graph again and q for exit: ");
1.126     brouard  8075:     scanf("%s",z);
                   8076: /*     if (z[0] == 'c') system("./imach"); */
                   8077:     if (z[0] == 'e') {
1.158     brouard  8078: #ifdef __APPLE__
1.152     brouard  8079:       sprintf(pplotcmd, "open %s", optionfilehtm);
1.157     brouard  8080: #elif __linux
                   8081:       sprintf(pplotcmd, "xdg-open %s", optionfilehtm);
1.153     brouard  8082: #else
1.152     brouard  8083:       sprintf(pplotcmd, "%s", optionfilehtm);
1.153     brouard  8084: #endif
                   8085:       printf("Starting browser with: %s",pplotcmd);fflush(stdout);
                   8086:       system(pplotcmd);
1.126     brouard  8087:     }
                   8088:     else if (z[0] == 'g') system(plotcmd);
                   8089:     else if (z[0] == 'q') exit(0);
                   8090:   }
                   8091:   end:
                   8092:   while (z[0] != 'q') {
1.195     brouard  8093:     printf("\nType  q for exiting: "); fflush(stdout);
1.126     brouard  8094:     scanf("%s",z);
                   8095:   }
                   8096: }

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