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

1.199   ! brouard     1: /* $Id: imach.c,v 1.198 2015/09/03 07:14:39 brouard Exp $
1.126     brouard     2:   $State: Exp $
1.163     brouard     3:   $Log: imach.c,v $
1.199   ! brouard     4:   Revision 1.198  2015/09/03 07:14:39  brouard
        !             5:   Summary: 0.98q5 Flavia
        !             6: 
1.198     brouard     7:   Revision 1.197  2015/09/01 18:24:39  brouard
                      8:   *** empty log message ***
                      9: 
1.197     brouard    10:   Revision 1.196  2015/08/18 23:17:52  brouard
                     11:   Summary: 0.98q5
                     12: 
1.196     brouard    13:   Revision 1.195  2015/08/18 16:28:39  brouard
                     14:   Summary: Adding a hack for testing purpose
                     15: 
                     16:   After reading the title, ftol and model lines, if the comment line has
                     17:   a q, starting with #q, the answer at the end of the run is quit. It
                     18:   permits to run test files in batch with ctest. The former workaround was
                     19:   $ echo q | imach foo.imach
                     20: 
1.195     brouard    21:   Revision 1.194  2015/08/18 13:32:00  brouard
                     22:   Summary:  Adding error when the covariance matrix doesn't contain the exact number of lines required by the model line.
                     23: 
1.194     brouard    24:   Revision 1.193  2015/08/04 07:17:42  brouard
                     25:   Summary: 0.98q4
                     26: 
1.193     brouard    27:   Revision 1.192  2015/07/16 16:49:02  brouard
                     28:   Summary: Fixing some outputs
                     29: 
1.192     brouard    30:   Revision 1.191  2015/07/14 10:00:33  brouard
                     31:   Summary: Some fixes
                     32: 
1.191     brouard    33:   Revision 1.190  2015/05/05 08:51:13  brouard
                     34:   Summary: Adding digits in output parameters (7 digits instead of 6)
                     35: 
                     36:   Fix 1+age+.
                     37: 
1.190     brouard    38:   Revision 1.189  2015/04/30 14:45:16  brouard
                     39:   Summary: 0.98q2
                     40: 
1.189     brouard    41:   Revision 1.188  2015/04/30 08:27:53  brouard
                     42:   *** empty log message ***
                     43: 
1.188     brouard    44:   Revision 1.187  2015/04/29 09:11:15  brouard
                     45:   *** empty log message ***
                     46: 
1.187     brouard    47:   Revision 1.186  2015/04/23 12:01:52  brouard
                     48:   Summary: V1*age is working now, version 0.98q1
                     49: 
                     50:   Some codes had been disabled in order to simplify and Vn*age was
                     51:   working in the optimization phase, ie, giving correct MLE parameters,
                     52:   but, as usual, outputs were not correct and program core dumped.
                     53: 
1.186     brouard    54:   Revision 1.185  2015/03/11 13:26:42  brouard
                     55:   Summary: Inclusion of compile and links command line for Intel Compiler
                     56: 
1.185     brouard    57:   Revision 1.184  2015/03/11 11:52:39  brouard
                     58:   Summary: Back from Windows 8. Intel Compiler
                     59: 
1.184     brouard    60:   Revision 1.183  2015/03/10 20:34:32  brouard
                     61:   Summary: 0.98q0, trying with directest, mnbrak fixed
                     62: 
                     63:   We use directest instead of original Powell test; probably no
                     64:   incidence on the results, but better justifications;
                     65:   We fixed Numerical Recipes mnbrak routine which was wrong and gave
                     66:   wrong results.
                     67: 
1.183     brouard    68:   Revision 1.182  2015/02/12 08:19:57  brouard
                     69:   Summary: Trying to keep directest which seems simpler and more general
                     70:   Author: Nicolas Brouard
                     71: 
1.182     brouard    72:   Revision 1.181  2015/02/11 23:22:24  brouard
                     73:   Summary: Comments on Powell added
                     74: 
                     75:   Author:
                     76: 
1.181     brouard    77:   Revision 1.180  2015/02/11 17:33:45  brouard
                     78:   Summary: Finishing move from main to function (hpijx and prevalence_limit)
                     79: 
1.180     brouard    80:   Revision 1.179  2015/01/04 09:57:06  brouard
                     81:   Summary: back to OS/X
                     82: 
1.179     brouard    83:   Revision 1.178  2015/01/04 09:35:48  brouard
                     84:   *** empty log message ***
                     85: 
1.178     brouard    86:   Revision 1.177  2015/01/03 18:40:56  brouard
                     87:   Summary: Still testing ilc32 on OSX
                     88: 
1.177     brouard    89:   Revision 1.176  2015/01/03 16:45:04  brouard
                     90:   *** empty log message ***
                     91: 
1.176     brouard    92:   Revision 1.175  2015/01/03 16:33:42  brouard
                     93:   *** empty log message ***
                     94: 
1.175     brouard    95:   Revision 1.174  2015/01/03 16:15:49  brouard
                     96:   Summary: Still in cross-compilation
                     97: 
1.174     brouard    98:   Revision 1.173  2015/01/03 12:06:26  brouard
                     99:   Summary: trying to detect cross-compilation
                    100: 
1.173     brouard   101:   Revision 1.172  2014/12/27 12:07:47  brouard
                    102:   Summary: Back from Visual Studio and Intel, options for compiling for Windows XP
                    103: 
1.172     brouard   104:   Revision 1.171  2014/12/23 13:26:59  brouard
                    105:   Summary: Back from Visual C
                    106: 
                    107:   Still problem with utsname.h on Windows
                    108: 
1.171     brouard   109:   Revision 1.170  2014/12/23 11:17:12  brouard
                    110:   Summary: Cleaning some \%% back to %%
                    111: 
                    112:   The escape was mandatory for a specific compiler (which one?), but too many warnings.
                    113: 
1.170     brouard   114:   Revision 1.169  2014/12/22 23:08:31  brouard
                    115:   Summary: 0.98p
                    116: 
                    117:   Outputs some informations on compiler used, OS etc. Testing on different platforms.
                    118: 
1.169     brouard   119:   Revision 1.168  2014/12/22 15:17:42  brouard
1.170     brouard   120:   Summary: update
1.169     brouard   121: 
1.168     brouard   122:   Revision 1.167  2014/12/22 13:50:56  brouard
                    123:   Summary: Testing uname and compiler version and if compiled 32 or 64
                    124: 
                    125:   Testing on Linux 64
                    126: 
1.167     brouard   127:   Revision 1.166  2014/12/22 11:40:47  brouard
                    128:   *** empty log message ***
                    129: 
1.166     brouard   130:   Revision 1.165  2014/12/16 11:20:36  brouard
                    131:   Summary: After compiling on Visual C
                    132: 
                    133:   * imach.c (Module): Merging 1.61 to 1.162
                    134: 
1.165     brouard   135:   Revision 1.164  2014/12/16 10:52:11  brouard
                    136:   Summary: Merging with Visual C after suppressing some warnings for unused variables. Also fixing Saito's bug 0.98Xn
                    137: 
                    138:   * imach.c (Module): Merging 1.61 to 1.162
                    139: 
1.164     brouard   140:   Revision 1.163  2014/12/16 10:30:11  brouard
                    141:   * imach.c (Module): Merging 1.61 to 1.162
                    142: 
1.163     brouard   143:   Revision 1.162  2014/09/25 11:43:39  brouard
                    144:   Summary: temporary backup 0.99!
                    145: 
1.162     brouard   146:   Revision 1.1  2014/09/16 11:06:58  brouard
                    147:   Summary: With some code (wrong) for nlopt
                    148: 
                    149:   Author:
                    150: 
                    151:   Revision 1.161  2014/09/15 20:41:41  brouard
                    152:   Summary: Problem with macro SQR on Intel compiler
                    153: 
1.161     brouard   154:   Revision 1.160  2014/09/02 09:24:05  brouard
                    155:   *** empty log message ***
                    156: 
1.160     brouard   157:   Revision 1.159  2014/09/01 10:34:10  brouard
                    158:   Summary: WIN32
                    159:   Author: Brouard
                    160: 
1.159     brouard   161:   Revision 1.158  2014/08/27 17:11:51  brouard
                    162:   *** empty log message ***
                    163: 
1.158     brouard   164:   Revision 1.157  2014/08/27 16:26:55  brouard
                    165:   Summary: Preparing windows Visual studio version
                    166:   Author: Brouard
                    167: 
                    168:   In order to compile on Visual studio, time.h is now correct and time_t
                    169:   and tm struct should be used. difftime should be used but sometimes I
                    170:   just make the differences in raw time format (time(&now).
                    171:   Trying to suppress #ifdef LINUX
                    172:   Add xdg-open for __linux in order to open default browser.
                    173: 
1.157     brouard   174:   Revision 1.156  2014/08/25 20:10:10  brouard
                    175:   *** empty log message ***
                    176: 
1.156     brouard   177:   Revision 1.155  2014/08/25 18:32:34  brouard
                    178:   Summary: New compile, minor changes
                    179:   Author: Brouard
                    180: 
1.155     brouard   181:   Revision 1.154  2014/06/20 17:32:08  brouard
                    182:   Summary: Outputs now all graphs of convergence to period prevalence
                    183: 
1.154     brouard   184:   Revision 1.153  2014/06/20 16:45:46  brouard
                    185:   Summary: If 3 live state, convergence to period prevalence on same graph
                    186:   Author: Brouard
                    187: 
1.153     brouard   188:   Revision 1.152  2014/06/18 17:54:09  brouard
                    189:   Summary: open browser, use gnuplot on same dir than imach if not found in the path
                    190: 
1.152     brouard   191:   Revision 1.151  2014/06/18 16:43:30  brouard
                    192:   *** empty log message ***
                    193: 
1.151     brouard   194:   Revision 1.150  2014/06/18 16:42:35  brouard
                    195:   Summary: If gnuplot is not in the path try on same directory than imach binary (OSX)
                    196:   Author: brouard
                    197: 
1.150     brouard   198:   Revision 1.149  2014/06/18 15:51:14  brouard
                    199:   Summary: Some fixes in parameter files errors
                    200:   Author: Nicolas Brouard
                    201: 
1.149     brouard   202:   Revision 1.148  2014/06/17 17:38:48  brouard
                    203:   Summary: Nothing new
                    204:   Author: Brouard
                    205: 
                    206:   Just a new packaging for OS/X version 0.98nS
                    207: 
1.148     brouard   208:   Revision 1.147  2014/06/16 10:33:11  brouard
                    209:   *** empty log message ***
                    210: 
1.147     brouard   211:   Revision 1.146  2014/06/16 10:20:28  brouard
                    212:   Summary: Merge
                    213:   Author: Brouard
                    214: 
                    215:   Merge, before building revised version.
                    216: 
1.146     brouard   217:   Revision 1.145  2014/06/10 21:23:15  brouard
                    218:   Summary: Debugging with valgrind
                    219:   Author: Nicolas Brouard
                    220: 
                    221:   Lot of changes in order to output the results with some covariates
                    222:   After the Edimburgh REVES conference 2014, it seems mandatory to
                    223:   improve the code.
                    224:   No more memory valgrind error but a lot has to be done in order to
                    225:   continue the work of splitting the code into subroutines.
                    226:   Also, decodemodel has been improved. Tricode is still not
                    227:   optimal. nbcode should be improved. Documentation has been added in
                    228:   the source code.
                    229: 
1.144     brouard   230:   Revision 1.143  2014/01/26 09:45:38  brouard
                    231:   Summary: Version 0.98nR (to be improved, but gives same optimization results as 0.98k. Nice, promising
                    232: 
                    233:   * imach.c (Module): Trying to merge old staffs together while being at Tokyo. Not tested...
                    234:   (Module): Version 0.98nR Running ok, but output format still only works for three covariates.
                    235: 
1.143     brouard   236:   Revision 1.142  2014/01/26 03:57:36  brouard
                    237:   Summary: gnuplot changed plot w l 1 has to be changed to plot w l lt 2
                    238: 
                    239:   * imach.c (Module): Trying to merge old staffs together while being at Tokyo. Not tested...
                    240: 
1.142     brouard   241:   Revision 1.141  2014/01/26 02:42:01  brouard
                    242:   * imach.c (Module): Trying to merge old staffs together while being at Tokyo. Not tested...
                    243: 
1.141     brouard   244:   Revision 1.140  2011/09/02 10:37:54  brouard
                    245:   Summary: times.h is ok with mingw32 now.
                    246: 
1.140     brouard   247:   Revision 1.139  2010/06/14 07:50:17  brouard
                    248:   After the theft of my laptop, I probably lost some lines of codes which were not uploaded to the CVS tree.
                    249:   I remember having already fixed agemin agemax which are pointers now but not cvs saved.
                    250: 
1.139     brouard   251:   Revision 1.138  2010/04/30 18:19:40  brouard
                    252:   *** empty log message ***
                    253: 
1.138     brouard   254:   Revision 1.137  2010/04/29 18:11:38  brouard
                    255:   (Module): Checking covariates for more complex models
                    256:   than V1+V2. A lot of change to be done. Unstable.
                    257: 
1.137     brouard   258:   Revision 1.136  2010/04/26 20:30:53  brouard
                    259:   (Module): merging some libgsl code. Fixing computation
                    260:   of likelione (using inter/intrapolation if mle = 0) in order to
                    261:   get same likelihood as if mle=1.
                    262:   Some cleaning of code and comments added.
                    263: 
1.136     brouard   264:   Revision 1.135  2009/10/29 15:33:14  brouard
                    265:   (Module): Now imach stops if date of birth, at least year of birth, is not given. Some cleaning of the code.
                    266: 
1.135     brouard   267:   Revision 1.134  2009/10/29 13:18:53  brouard
                    268:   (Module): Now imach stops if date of birth, at least year of birth, is not given. Some cleaning of the code.
                    269: 
1.134     brouard   270:   Revision 1.133  2009/07/06 10:21:25  brouard
                    271:   just nforces
                    272: 
1.133     brouard   273:   Revision 1.132  2009/07/06 08:22:05  brouard
                    274:   Many tings
                    275: 
1.132     brouard   276:   Revision 1.131  2009/06/20 16:22:47  brouard
                    277:   Some dimensions resccaled
                    278: 
1.131     brouard   279:   Revision 1.130  2009/05/26 06:44:34  brouard
                    280:   (Module): Max Covariate is now set to 20 instead of 8. A
                    281:   lot of cleaning with variables initialized to 0. Trying to make
                    282:   V2+V3*age+V1+V4 strb=V3*age+V1+V4 working better.
                    283: 
1.130     brouard   284:   Revision 1.129  2007/08/31 13:49:27  lievre
                    285:   Modification of the way of exiting when the covariate is not binary in order to see on the window the error message before exiting
                    286: 
1.129     lievre    287:   Revision 1.128  2006/06/30 13:02:05  brouard
                    288:   (Module): Clarifications on computing e.j
                    289: 
1.128     brouard   290:   Revision 1.127  2006/04/28 18:11:50  brouard
                    291:   (Module): Yes the sum of survivors was wrong since
                    292:   imach-114 because nhstepm was no more computed in the age
                    293:   loop. Now we define nhstepma in the age loop.
                    294:   (Module): In order to speed up (in case of numerous covariates) we
                    295:   compute health expectancies (without variances) in a first step
                    296:   and then all the health expectancies with variances or standard
                    297:   deviation (needs data from the Hessian matrices) which slows the
                    298:   computation.
                    299:   In the future we should be able to stop the program is only health
                    300:   expectancies and graph are needed without standard deviations.
                    301: 
1.127     brouard   302:   Revision 1.126  2006/04/28 17:23:28  brouard
                    303:   (Module): Yes the sum of survivors was wrong since
                    304:   imach-114 because nhstepm was no more computed in the age
                    305:   loop. Now we define nhstepma in the age loop.
                    306:   Version 0.98h
                    307: 
1.126     brouard   308:   Revision 1.125  2006/04/04 15:20:31  lievre
                    309:   Errors in calculation of health expectancies. Age was not initialized.
                    310:   Forecasting file added.
                    311: 
                    312:   Revision 1.124  2006/03/22 17:13:53  lievre
                    313:   Parameters are printed with %lf instead of %f (more numbers after the comma).
                    314:   The log-likelihood is printed in the log file
                    315: 
                    316:   Revision 1.123  2006/03/20 10:52:43  brouard
                    317:   * imach.c (Module): <title> changed, corresponds to .htm file
                    318:   name. <head> headers where missing.
                    319: 
                    320:   * imach.c (Module): Weights can have a decimal point as for
                    321:   English (a comma might work with a correct LC_NUMERIC environment,
                    322:   otherwise the weight is truncated).
                    323:   Modification of warning when the covariates values are not 0 or
                    324:   1.
                    325:   Version 0.98g
                    326: 
                    327:   Revision 1.122  2006/03/20 09:45:41  brouard
                    328:   (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.121  2006/03/16 17:45:01  lievre
                    336:   * imach.c (Module): Comments concerning covariates added
                    337: 
                    338:   * imach.c (Module): refinements in the computation of lli if
                    339:   status=-2 in order to have more reliable computation if stepm is
                    340:   not 1 month. Version 0.98f
                    341: 
                    342:   Revision 1.120  2006/03/16 15:10:38  lievre
                    343:   (Module): refinements in the computation of lli if
                    344:   status=-2 in order to have more reliable computation if stepm is
                    345:   not 1 month. Version 0.98f
                    346: 
                    347:   Revision 1.119  2006/03/15 17:42:26  brouard
                    348:   (Module): Bug if status = -2, the loglikelihood was
                    349:   computed as likelihood omitting the logarithm. Version O.98e
                    350: 
                    351:   Revision 1.118  2006/03/14 18:20:07  brouard
                    352:   (Module): varevsij Comments added explaining the second
                    353:   table of variances if popbased=1 .
                    354:   (Module): Covariances of eij, ekl added, graphs fixed, new html link.
                    355:   (Module): Function pstamp added
                    356:   (Module): Version 0.98d
                    357: 
                    358:   Revision 1.117  2006/03/14 17:16:22  brouard
                    359:   (Module): varevsij Comments added explaining the second
                    360:   table of variances if popbased=1 .
                    361:   (Module): Covariances of eij, ekl added, graphs fixed, new html link.
                    362:   (Module): Function pstamp added
                    363:   (Module): Version 0.98d
                    364: 
                    365:   Revision 1.116  2006/03/06 10:29:27  brouard
                    366:   (Module): Variance-covariance wrong links and
                    367:   varian-covariance of ej. is needed (Saito).
                    368: 
                    369:   Revision 1.115  2006/02/27 12:17:45  brouard
                    370:   (Module): One freematrix added in mlikeli! 0.98c
                    371: 
                    372:   Revision 1.114  2006/02/26 12:57:58  brouard
                    373:   (Module): Some improvements in processing parameter
                    374:   filename with strsep.
                    375: 
                    376:   Revision 1.113  2006/02/24 14:20:24  brouard
                    377:   (Module): Memory leaks checks with valgrind and:
                    378:   datafile was not closed, some imatrix were not freed and on matrix
                    379:   allocation too.
                    380: 
                    381:   Revision 1.112  2006/01/30 09:55:26  brouard
                    382:   (Module): Back to gnuplot.exe instead of wgnuplot.exe
                    383: 
                    384:   Revision 1.111  2006/01/25 20:38:18  brouard
                    385:   (Module): Lots of cleaning and bugs added (Gompertz)
                    386:   (Module): Comments can be added in data file. Missing date values
                    387:   can be a simple dot '.'.
                    388: 
                    389:   Revision 1.110  2006/01/25 00:51:50  brouard
                    390:   (Module): Lots of cleaning and bugs added (Gompertz)
                    391: 
                    392:   Revision 1.109  2006/01/24 19:37:15  brouard
                    393:   (Module): Comments (lines starting with a #) are allowed in data.
                    394: 
                    395:   Revision 1.108  2006/01/19 18:05:42  lievre
                    396:   Gnuplot problem appeared...
                    397:   To be fixed
                    398: 
                    399:   Revision 1.107  2006/01/19 16:20:37  brouard
                    400:   Test existence of gnuplot in imach path
                    401: 
                    402:   Revision 1.106  2006/01/19 13:24:36  brouard
                    403:   Some cleaning and links added in html output
                    404: 
                    405:   Revision 1.105  2006/01/05 20:23:19  lievre
                    406:   *** empty log message ***
                    407: 
                    408:   Revision 1.104  2005/09/30 16:11:43  lievre
                    409:   (Module): sump fixed, loop imx fixed, and simplifications.
                    410:   (Module): If the status is missing at the last wave but we know
                    411:   that the person is alive, then we can code his/her status as -2
                    412:   (instead of missing=-1 in earlier versions) and his/her
                    413:   contributions to the likelihood is 1 - Prob of dying from last
                    414:   health status (= 1-p13= p11+p12 in the easiest case of somebody in
                    415:   the healthy state at last known wave). Version is 0.98
                    416: 
                    417:   Revision 1.103  2005/09/30 15:54:49  lievre
                    418:   (Module): sump fixed, loop imx fixed, and simplifications.
                    419: 
                    420:   Revision 1.102  2004/09/15 17:31:30  brouard
                    421:   Add the possibility to read data file including tab characters.
                    422: 
                    423:   Revision 1.101  2004/09/15 10:38:38  brouard
                    424:   Fix on curr_time
                    425: 
                    426:   Revision 1.100  2004/07/12 18:29:06  brouard
                    427:   Add version for Mac OS X. Just define UNIX in Makefile
                    428: 
                    429:   Revision 1.99  2004/06/05 08:57:40  brouard
                    430:   *** empty log message ***
                    431: 
                    432:   Revision 1.98  2004/05/16 15:05:56  brouard
                    433:   New version 0.97 . First attempt to estimate force of mortality
                    434:   directly from the data i.e. without the need of knowing the health
                    435:   state at each age, but using a Gompertz model: log u =a + b*age .
                    436:   This is the basic analysis of mortality and should be done before any
                    437:   other analysis, in order to test if the mortality estimated from the
                    438:   cross-longitudinal survey is different from the mortality estimated
                    439:   from other sources like vital statistic data.
                    440: 
                    441:   The same imach parameter file can be used but the option for mle should be -3.
                    442: 
1.133     brouard   443:   Agnès, who wrote this part of the code, tried to keep most of the
1.126     brouard   444:   former routines in order to include the new code within the former code.
                    445: 
                    446:   The output is very simple: only an estimate of the intercept and of
                    447:   the slope with 95% confident intervals.
                    448: 
                    449:   Current limitations:
                    450:   A) Even if you enter covariates, i.e. with the
                    451:   model= V1+V2 equation for example, the programm does only estimate a unique global model without covariates.
                    452:   B) There is no computation of Life Expectancy nor Life Table.
                    453: 
                    454:   Revision 1.97  2004/02/20 13:25:42  lievre
                    455:   Version 0.96d. Population forecasting command line is (temporarily)
                    456:   suppressed.
                    457: 
                    458:   Revision 1.96  2003/07/15 15:38:55  brouard
                    459:   * imach.c (Repository): Errors in subdirf, 2, 3 while printing tmpout is
                    460:   rewritten within the same printf. Workaround: many printfs.
                    461: 
                    462:   Revision 1.95  2003/07/08 07:54:34  brouard
                    463:   * imach.c (Repository):
                    464:   (Repository): Using imachwizard code to output a more meaningful covariance
                    465:   matrix (cov(a12,c31) instead of numbers.
                    466: 
                    467:   Revision 1.94  2003/06/27 13:00:02  brouard
                    468:   Just cleaning
                    469: 
                    470:   Revision 1.93  2003/06/25 16:33:55  brouard
                    471:   (Module): On windows (cygwin) function asctime_r doesn't
                    472:   exist so I changed back to asctime which exists.
                    473:   (Module): Version 0.96b
                    474: 
                    475:   Revision 1.92  2003/06/25 16:30:45  brouard
                    476:   (Module): On windows (cygwin) function asctime_r doesn't
                    477:   exist so I changed back to asctime which exists.
                    478: 
                    479:   Revision 1.91  2003/06/25 15:30:29  brouard
                    480:   * imach.c (Repository): Duplicated warning errors corrected.
                    481:   (Repository): Elapsed time after each iteration is now output. It
                    482:   helps to forecast when convergence will be reached. Elapsed time
                    483:   is stamped in powell.  We created a new html file for the graphs
                    484:   concerning matrix of covariance. It has extension -cov.htm.
                    485: 
                    486:   Revision 1.90  2003/06/24 12:34:15  brouard
                    487:   (Module): Some bugs corrected for windows. Also, when
                    488:   mle=-1 a template is output in file "or"mypar.txt with the design
                    489:   of the covariance matrix to be input.
                    490: 
                    491:   Revision 1.89  2003/06/24 12:30:52  brouard
                    492:   (Module): Some bugs corrected for windows. Also, when
                    493:   mle=-1 a template is output in file "or"mypar.txt with the design
                    494:   of the covariance matrix to be input.
                    495: 
                    496:   Revision 1.88  2003/06/23 17:54:56  brouard
                    497:   * 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.
                    498: 
                    499:   Revision 1.87  2003/06/18 12:26:01  brouard
                    500:   Version 0.96
                    501: 
                    502:   Revision 1.86  2003/06/17 20:04:08  brouard
                    503:   (Module): Change position of html and gnuplot routines and added
                    504:   routine fileappend.
                    505: 
                    506:   Revision 1.85  2003/06/17 13:12:43  brouard
                    507:   * imach.c (Repository): Check when date of death was earlier that
                    508:   current date of interview. It may happen when the death was just
                    509:   prior to the death. In this case, dh was negative and likelihood
                    510:   was wrong (infinity). We still send an "Error" but patch by
                    511:   assuming that the date of death was just one stepm after the
                    512:   interview.
                    513:   (Repository): Because some people have very long ID (first column)
                    514:   we changed int to long in num[] and we added a new lvector for
                    515:   memory allocation. But we also truncated to 8 characters (left
                    516:   truncation)
                    517:   (Repository): No more line truncation errors.
                    518: 
                    519:   Revision 1.84  2003/06/13 21:44:43  brouard
                    520:   * imach.c (Repository): Replace "freqsummary" at a correct
                    521:   place. It differs from routine "prevalence" which may be called
                    522:   many times. Probs is memory consuming and must be used with
                    523:   parcimony.
                    524:   Version 0.95a3 (should output exactly the same maximization than 0.8a2)
                    525: 
                    526:   Revision 1.83  2003/06/10 13:39:11  lievre
                    527:   *** empty log message ***
                    528: 
                    529:   Revision 1.82  2003/06/05 15:57:20  brouard
                    530:   Add log in  imach.c and  fullversion number is now printed.
                    531: 
                    532: */
                    533: /*
                    534:    Interpolated Markov Chain
                    535: 
                    536:   Short summary of the programme:
                    537:   
                    538:   This program computes Healthy Life Expectancies from
                    539:   cross-longitudinal data. Cross-longitudinal data consist in: -1- a
                    540:   first survey ("cross") where individuals from different ages are
                    541:   interviewed on their health status or degree of disability (in the
                    542:   case of a health survey which is our main interest) -2- at least a
                    543:   second wave of interviews ("longitudinal") which measure each change
                    544:   (if any) in individual health status.  Health expectancies are
                    545:   computed from the time spent in each health state according to a
                    546:   model. More health states you consider, more time is necessary to reach the
                    547:   Maximum Likelihood of the parameters involved in the model.  The
                    548:   simplest model is the multinomial logistic model where pij is the
                    549:   probability to be observed in state j at the second wave
                    550:   conditional to be observed in state i at the first wave. Therefore
                    551:   the model is: log(pij/pii)= aij + bij*age+ cij*sex + etc , where
                    552:   'age' is age and 'sex' is a covariate. If you want to have a more
                    553:   complex model than "constant and age", you should modify the program
                    554:   where the markup *Covariates have to be included here again* invites
                    555:   you to do it.  More covariates you add, slower the
                    556:   convergence.
                    557: 
                    558:   The advantage of this computer programme, compared to a simple
                    559:   multinomial logistic model, is clear when the delay between waves is not
                    560:   identical for each individual. Also, if a individual missed an
                    561:   intermediate interview, the information is lost, but taken into
                    562:   account using an interpolation or extrapolation.  
                    563: 
                    564:   hPijx is the probability to be observed in state i at age x+h
                    565:   conditional to the observed state i at age x. The delay 'h' can be
                    566:   split into an exact number (nh*stepm) of unobserved intermediate
                    567:   states. This elementary transition (by month, quarter,
                    568:   semester or year) is modelled as a multinomial logistic.  The hPx
                    569:   matrix is simply the matrix product of nh*stepm elementary matrices
                    570:   and the contribution of each individual to the likelihood is simply
                    571:   hPijx.
                    572: 
                    573:   Also this programme outputs the covariance matrix of the parameters but also
                    574:   of the life expectancies. It also computes the period (stable) prevalence. 
                    575:   
1.133     brouard   576:   Authors: Nicolas Brouard (brouard@ined.fr) and Agnès Lièvre (lievre@ined.fr).
                    577:            Institut national d'études démographiques, Paris.
1.126     brouard   578:   This software have been partly granted by Euro-REVES, a concerted action
                    579:   from the European Union.
                    580:   It is copyrighted identically to a GNU software product, ie programme and
                    581:   software can be distributed freely for non commercial use. Latest version
                    582:   can be accessed at http://euroreves.ined.fr/imach .
                    583: 
                    584:   Help to debug: LD_PRELOAD=/usr/local/lib/libnjamd.so ./imach foo.imach
                    585:   or better on gdb : set env LD_PRELOAD=/usr/local/lib/libnjamd.so
                    586:   
                    587:   **********************************************************************/
                    588: /*
                    589:   main
                    590:   read parameterfile
                    591:   read datafile
                    592:   concatwav
                    593:   freqsummary
                    594:   if (mle >= 1)
                    595:     mlikeli
                    596:   print results files
                    597:   if mle==1 
                    598:      computes hessian
                    599:   read end of parameter file: agemin, agemax, bage, fage, estepm
                    600:       begin-prev-date,...
                    601:   open gnuplot file
                    602:   open html file
1.145     brouard   603:   period (stable) prevalence      | pl_nom    1-1 2-2 etc by covariate
                    604:    for age prevalim()             | #****** V1=0  V2=1  V3=1  V4=0 ******
                    605:                                   | 65 1 0 2 1 3 1 4 0  0.96326 0.03674
                    606:     freexexit2 possible for memory heap.
                    607: 
                    608:   h Pij x                         | pij_nom  ficrestpij
                    609:    # Cov Agex agex+h hpijx with i,j= 1-1 1-2     1-3     2-1     2-2     2-3
                    610:        1  85   85    1.00000             0.00000 0.00000 0.00000 1.00000 0.00000
                    611:        1  85   86    0.68299             0.22291 0.09410 0.71093 0.00000 0.28907
                    612: 
                    613:        1  65   99    0.00364             0.00322 0.99314 0.00350 0.00310 0.99340
                    614:        1  65  100    0.00214             0.00204 0.99581 0.00206 0.00196 0.99597
                    615:   variance of p one-step probabilities varprob  | prob_nom   ficresprob #One-step probabilities and stand. devi in ()
                    616:    Standard deviation of one-step probabilities | probcor_nom   ficresprobcor #One-step probabilities and correlation matrix
                    617:    Matrix of variance covariance of one-step probabilities |  probcov_nom ficresprobcov #One-step probabilities and covariance matrix
                    618: 
1.126     brouard   619:   forecasting if prevfcast==1 prevforecast call prevalence()
                    620:   health expectancies
                    621:   Variance-covariance of DFLE
                    622:   prevalence()
                    623:    movingaverage()
                    624:   varevsij() 
                    625:   if popbased==1 varevsij(,popbased)
                    626:   total life expectancies
                    627:   Variance of period (stable) prevalence
                    628:  end
                    629: */
                    630: 
1.187     brouard   631: /* #define DEBUG */
                    632: /* #define DEBUGBRENT */
1.165     brouard   633: #define POWELL /* Instead of NLOPT */
1.192     brouard   634: #define POWELLF1F3 /* Skip test */
1.186     brouard   635: /* #define POWELLORIGINAL /\* Don't use Directest to decide new direction but original Powell test *\/ */
                    636: /* #define MNBRAKORIGINAL /\* Don't use mnbrak fix *\/ */
1.126     brouard   637: 
                    638: #include <math.h>
                    639: #include <stdio.h>
                    640: #include <stdlib.h>
                    641: #include <string.h>
1.159     brouard   642: 
                    643: #ifdef _WIN32
                    644: #include <io.h>
1.172     brouard   645: #include <windows.h>
                    646: #include <tchar.h>
1.159     brouard   647: #else
1.126     brouard   648: #include <unistd.h>
1.159     brouard   649: #endif
1.126     brouard   650: 
                    651: #include <limits.h>
                    652: #include <sys/types.h>
1.171     brouard   653: 
                    654: #if defined(__GNUC__)
                    655: #include <sys/utsname.h> /* Doesn't work on Windows */
                    656: #endif
                    657: 
1.126     brouard   658: #include <sys/stat.h>
                    659: #include <errno.h>
1.159     brouard   660: /* extern int errno; */
1.126     brouard   661: 
1.157     brouard   662: /* #ifdef LINUX */
                    663: /* #include <time.h> */
                    664: /* #include "timeval.h" */
                    665: /* #else */
                    666: /* #include <sys/time.h> */
                    667: /* #endif */
                    668: 
1.126     brouard   669: #include <time.h>
                    670: 
1.136     brouard   671: #ifdef GSL
                    672: #include <gsl/gsl_errno.h>
                    673: #include <gsl/gsl_multimin.h>
                    674: #endif
                    675: 
1.167     brouard   676: 
1.162     brouard   677: #ifdef NLOPT
                    678: #include <nlopt.h>
                    679: typedef struct {
                    680:   double (* function)(double [] );
                    681: } myfunc_data ;
                    682: #endif
                    683: 
1.126     brouard   684: /* #include <libintl.h> */
                    685: /* #define _(String) gettext (String) */
                    686: 
1.141     brouard   687: #define MAXLINE 1024 /* Was 256. Overflow with 312 with 2 states and 4 covariates. Should be ok */
1.126     brouard   688: 
                    689: #define GNUPLOTPROGRAM "gnuplot"
                    690: /*#define GNUPLOTPROGRAM "..\\gp37mgw\\wgnuplot"*/
                    691: #define FILENAMELENGTH 132
                    692: 
                    693: #define        GLOCK_ERROR_NOPATH              -1      /* empty path */
                    694: #define        GLOCK_ERROR_GETCWD              -2      /* cannot get cwd */
                    695: 
1.144     brouard   696: #define MAXPARM 128 /**< Maximum number of parameters for the optimization */
                    697: #define NPARMAX 64 /**< (nlstate+ndeath-1)*nlstate*ncovmodel */
1.126     brouard   698: 
                    699: #define NINTERVMAX 8
1.144     brouard   700: #define NLSTATEMAX 8 /**< Maximum number of live states (for func) */
                    701: #define NDEATHMAX 8 /**< Maximum number of dead states (for func) */
                    702: #define NCOVMAX 20 /**< Maximum number of covariates, including generated covariates V1*V2 */
1.197     brouard   703: #define codtabm(h,k)  (1 & (h-1) >> (k-1))+1
1.126     brouard   704: #define MAXN 20000
1.144     brouard   705: #define YEARM 12. /**< Number of months per year */
1.126     brouard   706: #define AGESUP 130
                    707: #define AGEBASE 40
1.194     brouard   708: #define AGEOVERFLOW 1.e20
1.164     brouard   709: #define AGEGOMP 10 /**< Minimal age for Gompertz adjustment */
1.157     brouard   710: #ifdef _WIN32
                    711: #define DIRSEPARATOR '\\'
                    712: #define CHARSEPARATOR "\\"
                    713: #define ODIRSEPARATOR '/'
                    714: #else
1.126     brouard   715: #define DIRSEPARATOR '/'
                    716: #define CHARSEPARATOR "/"
                    717: #define ODIRSEPARATOR '\\'
                    718: #endif
                    719: 
1.199   ! brouard   720: /* $Id: imach.c,v 1.198 2015/09/03 07:14:39 brouard Exp $ */
1.126     brouard   721: /* $State: Exp $ */
1.196     brouard   722: #include "version.h"
                    723: char version[]=__IMACH_VERSION__;
1.197     brouard   724: 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.199   ! brouard   725: char fullversion[]="$Revision: 1.198 $ $Date: 2015/09/03 07:14:39 $"; 
1.126     brouard   726: char strstart[80];
                    727: char optionfilext[10], optionfilefiname[FILENAMELENGTH];
1.130     brouard   728: int erreur=0, nberr=0, nbwarn=0; /* Error number, number of errors number of warnings  */
1.187     brouard   729: int nagesqr=0, nforce=0; /* nagesqr=1 if model is including age*age, number of forces */
1.145     brouard   730: /* Number of covariates model=V2+V1+ V3*age+V2*V4 */
                    731: int cptcovn=0; /**< cptcovn number of covariates added in the model (excepting constant and age and age*product) */
                    732: int cptcovt=0; /**< cptcovt number of covariates added in the model (excepting constant and age) */
                    733: int cptcovs=0; /**< cptcovs number of simple covariates V2+V1 =2 */
                    734: int cptcovage=0; /**< Number of covariates with age: V3*age only =1 */
                    735: int cptcovprodnoage=0; /**< Number of covariate products without age */   
                    736: int cptcoveff=0; /* Total number of covariates to vary for printing results */
                    737: int cptcov=0; /* Working variable */
1.126     brouard   738: int npar=NPARMAX;
                    739: int nlstate=2; /* Number of live states */
                    740: int ndeath=1; /* Number of dead states */
1.130     brouard   741: int ncovmodel=0, ncovcol=0;     /* Total number of covariables including constant a12*1 +b12*x ncovmodel=2 */
1.126     brouard   742: int popbased=0;
                    743: 
                    744: int *wav; /* Number of waves for this individuual 0 is possible */
1.130     brouard   745: int maxwav=0; /* Maxim number of waves */
                    746: int jmin=0, jmax=0; /* min, max spacing between 2 waves */
                    747: int ijmin=0, ijmax=0; /* Individuals having jmin and jmax */ 
                    748: int gipmx=0, gsw=0; /* Global variables on the number of contributions 
1.126     brouard   749:                   to the likelihood and the sum of weights (done by funcone)*/
1.130     brouard   750: int mle=1, weightopt=0;
1.126     brouard   751: int **mw; /* mw[mi][i] is number of the mi wave for this individual */
                    752: int **dh; /* dh[mi][i] is number of steps between mi,mi+1 for this individual */
                    753: int **bh; /* bh[mi][i] is the bias (+ or -) for this individual if the delay between
                    754:           * wave mi and wave mi+1 is not an exact multiple of stepm. */
1.162     brouard   755: int countcallfunc=0;  /* Count the number of calls to func */
1.130     brouard   756: double jmean=1; /* Mean space between 2 waves */
1.145     brouard   757: double **matprod2(); /* test */
1.126     brouard   758: double **oldm, **newm, **savm; /* Working pointers to matrices */
                    759: double **oldms, **newms, **savms; /* Fixed working pointers to matrices */
1.136     brouard   760: /*FILE *fic ; */ /* Used in readdata only */
                    761: FILE *ficpar, *ficparo,*ficres, *ficresp, *ficrespl, *ficrespij, *ficrest,*ficresf,*ficrespop;
1.126     brouard   762: FILE *ficlog, *ficrespow;
1.130     brouard   763: int globpr=0; /* Global variable for printing or not */
1.126     brouard   764: double fretone; /* Only one call to likelihood */
1.130     brouard   765: long ipmx=0; /* Number of contributions */
1.126     brouard   766: double sw; /* Sum of weights */
                    767: char filerespow[FILENAMELENGTH];
                    768: char fileresilk[FILENAMELENGTH]; /* File of individual contributions to the likelihood */
                    769: FILE *ficresilk;
                    770: FILE *ficgp,*ficresprob,*ficpop, *ficresprobcov, *ficresprobcor;
                    771: FILE *ficresprobmorprev;
                    772: FILE *fichtm, *fichtmcov; /* Html File */
                    773: FILE *ficreseij;
                    774: char filerese[FILENAMELENGTH];
                    775: FILE *ficresstdeij;
                    776: char fileresstde[FILENAMELENGTH];
                    777: FILE *ficrescveij;
                    778: char filerescve[FILENAMELENGTH];
                    779: FILE  *ficresvij;
                    780: char fileresv[FILENAMELENGTH];
                    781: FILE  *ficresvpl;
                    782: char fileresvpl[FILENAMELENGTH];
                    783: char title[MAXLINE];
                    784: char optionfile[FILENAMELENGTH], datafile[FILENAMELENGTH],  filerespl[FILENAMELENGTH];
                    785: char plotcmd[FILENAMELENGTH], pplotcmd[FILENAMELENGTH];
                    786: char tmpout[FILENAMELENGTH],  tmpout2[FILENAMELENGTH]; 
                    787: char command[FILENAMELENGTH];
                    788: int  outcmd=0;
                    789: 
                    790: char fileres[FILENAMELENGTH], filerespij[FILENAMELENGTH], filereso[FILENAMELENGTH], rfileres[FILENAMELENGTH];
                    791: 
                    792: char filelog[FILENAMELENGTH]; /* Log file */
                    793: char filerest[FILENAMELENGTH];
                    794: char fileregp[FILENAMELENGTH];
                    795: char popfile[FILENAMELENGTH];
                    796: 
                    797: char optionfilegnuplot[FILENAMELENGTH], optionfilehtm[FILENAMELENGTH], optionfilehtmcov[FILENAMELENGTH] ;
                    798: 
1.157     brouard   799: /* struct timeval start_time, end_time, curr_time, last_time, forecast_time; */
                    800: /* struct timezone tzp; */
                    801: /* extern int gettimeofday(); */
                    802: struct tm tml, *gmtime(), *localtime();
                    803: 
                    804: extern time_t time();
                    805: 
                    806: struct tm start_time, end_time, curr_time, last_time, forecast_time;
                    807: time_t  rstart_time, rend_time, rcurr_time, rlast_time, rforecast_time; /* raw time */
                    808: struct tm tm;
                    809: 
1.126     brouard   810: char strcurr[80], strfor[80];
                    811: 
                    812: char *endptr;
                    813: long lval;
                    814: double dval;
                    815: 
                    816: #define NR_END 1
                    817: #define FREE_ARG char*
                    818: #define FTOL 1.0e-10
                    819: 
                    820: #define NRANSI 
                    821: #define ITMAX 200 
                    822: 
                    823: #define TOL 2.0e-4 
                    824: 
                    825: #define CGOLD 0.3819660 
                    826: #define ZEPS 1.0e-10 
                    827: #define SHFT(a,b,c,d) (a)=(b);(b)=(c);(c)=(d); 
                    828: 
                    829: #define GOLD 1.618034 
                    830: #define GLIMIT 100.0 
                    831: #define TINY 1.0e-20 
                    832: 
                    833: static double maxarg1,maxarg2;
                    834: #define FMAX(a,b) (maxarg1=(a),maxarg2=(b),(maxarg1)>(maxarg2)? (maxarg1):(maxarg2))
                    835: #define FMIN(a,b) (maxarg1=(a),maxarg2=(b),(maxarg1)<(maxarg2)? (maxarg1):(maxarg2))
                    836:   
                    837: #define SIGN(a,b) ((b)>0.0 ? fabs(a) : -fabs(a))
                    838: #define rint(a) floor(a+0.5)
1.166     brouard   839: /* http://www.thphys.uni-heidelberg.de/~robbers/cmbeasy/doc/html/myutils_8h-source.html */
1.183     brouard   840: #define mytinydouble 1.0e-16
1.166     brouard   841: /* #define DEQUAL(a,b) (fabs((a)-(b))<mytinydouble) */
                    842: /* http://www.thphys.uni-heidelberg.de/~robbers/cmbeasy/doc/html/mynrutils_8h-source.html */
                    843: /* static double dsqrarg; */
                    844: /* #define DSQR(a) (DEQUAL((dsqrarg=(a)),0.0) ? 0.0 : dsqrarg*dsqrarg) */
1.126     brouard   845: static double sqrarg;
                    846: #define SQR(a) ((sqrarg=(a)) == 0.0 ? 0.0 :sqrarg*sqrarg)
                    847: #define SWAP(a,b) {temp=(a);(a)=(b);(b)=temp;} 
                    848: int agegomp= AGEGOMP;
                    849: 
                    850: int imx; 
                    851: int stepm=1;
                    852: /* Stepm, step in month: minimum step interpolation*/
                    853: 
                    854: int estepm;
                    855: /* Estepm, step in month to interpolate survival function in order to approximate Life Expectancy*/
                    856: 
                    857: int m,nb;
                    858: long *num;
1.197     brouard   859: int firstpass=0, lastpass=4,*cod, *cens;
1.192     brouard   860: int *ncodemax;  /* ncodemax[j]= Number of modalities of the j th
                    861:                   covariate for which somebody answered excluding 
                    862:                   undefined. Usually 2: 0 and 1. */
                    863: int *ncodemaxwundef;  /* ncodemax[j]= Number of modalities of the j th
                    864:                             covariate for which somebody answered including 
                    865:                             undefined. Usually 3: -1, 0 and 1. */
1.126     brouard   866: double **agev,*moisnais, *annais, *moisdc, *andc,**mint, **anint;
                    867: double **pmmij, ***probs;
                    868: double *ageexmed,*agecens;
                    869: double dateintmean=0;
                    870: 
                    871: double *weight;
                    872: int **s; /* Status */
1.141     brouard   873: double *agedc;
1.145     brouard   874: double  **covar; /**< covar[j,i], value of jth covariate for individual i,
1.141     brouard   875:                  * covar=matrix(0,NCOVMAX,1,n); 
1.187     brouard   876:                  * cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*age; */
1.141     brouard   877: double  idx; 
                    878: int **nbcode, *Tvar; /**< model=V2 => Tvar[1]= 2 */
1.197     brouard   879: int *Tage;
1.145     brouard   880: int *Ndum; /** Freq of modality (tricode */
1.141     brouard   881: int **codtab; /**< codtab=imatrix(1,100,1,10); */
                    882: int **Tvard, *Tprod, cptcovprod, *Tvaraff;
1.126     brouard   883: double *lsurv, *lpop, *tpop;
                    884: 
1.143     brouard   885: double ftol=FTOL; /**< Tolerance for computing Max Likelihood */
                    886: double ftolhess; /**< Tolerance for computing hessian */
1.126     brouard   887: 
                    888: /**************** split *************************/
                    889: static int split( char *path, char *dirc, char *name, char *ext, char *finame )
                    890: {
                    891:   /* From a file name with (full) path (either Unix or Windows) we extract the directory (dirc)
                    892:      the name of the file (name), its extension only (ext) and its first part of the name (finame)
                    893:   */ 
                    894:   char *ss;                            /* pointer */
1.186     brouard   895:   int  l1=0, l2=0;                             /* length counters */
1.126     brouard   896: 
                    897:   l1 = strlen(path );                  /* length of path */
                    898:   if ( l1 == 0 ) return( GLOCK_ERROR_NOPATH );
                    899:   ss= strrchr( path, DIRSEPARATOR );           /* find last / */
                    900:   if ( ss == NULL ) {                  /* no directory, so determine current directory */
                    901:     strcpy( name, path );              /* we got the fullname name because no directory */
                    902:     /*if(strrchr(path, ODIRSEPARATOR )==NULL)
                    903:       printf("Warning you should use %s as a separator\n",DIRSEPARATOR);*/
                    904:     /* get current working directory */
                    905:     /*    extern  char* getcwd ( char *buf , int len);*/
1.184     brouard   906: #ifdef WIN32
                    907:     if (_getcwd( dirc, FILENAME_MAX ) == NULL ) {
                    908: #else
                    909:        if (getcwd(dirc, FILENAME_MAX) == NULL) {
                    910: #endif
1.126     brouard   911:       return( GLOCK_ERROR_GETCWD );
                    912:     }
                    913:     /* got dirc from getcwd*/
                    914:     printf(" DIRC = %s \n",dirc);
                    915:   } else {                             /* strip direcotry from path */
                    916:     ss++;                              /* after this, the filename */
                    917:     l2 = strlen( ss );                 /* length of filename */
                    918:     if ( l2 == 0 ) return( GLOCK_ERROR_NOPATH );
                    919:     strcpy( name, ss );                /* save file name */
                    920:     strncpy( dirc, path, l1 - l2 );    /* now the directory */
1.186     brouard   921:     dirc[l1-l2] = '\0';                        /* add zero */
1.126     brouard   922:     printf(" DIRC2 = %s \n",dirc);
                    923:   }
                    924:   /* We add a separator at the end of dirc if not exists */
                    925:   l1 = strlen( dirc );                 /* length of directory */
                    926:   if( dirc[l1-1] != DIRSEPARATOR ){
                    927:     dirc[l1] =  DIRSEPARATOR;
                    928:     dirc[l1+1] = 0; 
                    929:     printf(" DIRC3 = %s \n",dirc);
                    930:   }
                    931:   ss = strrchr( name, '.' );           /* find last / */
                    932:   if (ss >0){
                    933:     ss++;
                    934:     strcpy(ext,ss);                    /* save extension */
                    935:     l1= strlen( name);
                    936:     l2= strlen(ss)+1;
                    937:     strncpy( finame, name, l1-l2);
                    938:     finame[l1-l2]= 0;
                    939:   }
                    940: 
                    941:   return( 0 );                         /* we're done */
                    942: }
                    943: 
                    944: 
                    945: /******************************************/
                    946: 
                    947: void replace_back_to_slash(char *s, char*t)
                    948: {
                    949:   int i;
                    950:   int lg=0;
                    951:   i=0;
                    952:   lg=strlen(t);
                    953:   for(i=0; i<= lg; i++) {
                    954:     (s[i] = t[i]);
                    955:     if (t[i]== '\\') s[i]='/';
                    956:   }
                    957: }
                    958: 
1.132     brouard   959: char *trimbb(char *out, char *in)
1.137     brouard   960: { /* Trim multiple blanks in line but keeps first blanks if line starts with blanks */
1.132     brouard   961:   char *s;
                    962:   s=out;
                    963:   while (*in != '\0'){
1.137     brouard   964:     while( *in == ' ' && *(in+1) == ' '){ /* && *(in+1) != '\0'){*/
1.132     brouard   965:       in++;
                    966:     }
                    967:     *out++ = *in++;
                    968:   }
                    969:   *out='\0';
                    970:   return s;
                    971: }
                    972: 
1.187     brouard   973: /* char *substrchaine(char *out, char *in, char *chain) */
                    974: /* { */
                    975: /*   /\* Substract chain 'chain' from 'in', return and output 'out' *\/ */
                    976: /*   char *s, *t; */
                    977: /*   t=in;s=out; */
                    978: /*   while ((*in != *chain) && (*in != '\0')){ */
                    979: /*     *out++ = *in++; */
                    980: /*   } */
                    981: 
                    982: /*   /\* *in matches *chain *\/ */
                    983: /*   while ((*in++ == *chain++) && (*in != '\0')){ */
                    984: /*     printf("*in = %c, *out= %c *chain= %c \n", *in, *out, *chain);  */
                    985: /*   } */
                    986: /*   in--; chain--; */
                    987: /*   while ( (*in != '\0')){ */
                    988: /*     printf("Bef *in = %c, *out= %c *chain= %c \n", *in, *out, *chain);  */
                    989: /*     *out++ = *in++; */
                    990: /*     printf("Aft *in = %c, *out= %c *chain= %c \n", *in, *out, *chain);  */
                    991: /*   } */
                    992: /*   *out='\0'; */
                    993: /*   out=s; */
                    994: /*   return out; */
                    995: /* } */
                    996: char *substrchaine(char *out, char *in, char *chain)
                    997: {
                    998:   /* Substract chain 'chain' from 'in', return and output 'out' */
                    999:   /* in="V1+V1*age+age*age+V2", chain="age*age" */
                   1000: 
                   1001:   char *strloc;
                   1002: 
                   1003:   strcpy (out, in); 
                   1004:   strloc = strstr(out, chain); /* strloc points to out at age*age+V2 */
                   1005:   printf("Bef strloc=%s chain=%s out=%s \n", strloc, chain, out);
                   1006:   if(strloc != NULL){ 
                   1007:     /* will affect out */ /* strloc+strlenc(chain)=+V2 */ /* Will also work in Unicode */
                   1008:     memmove(strloc,strloc+strlen(chain), strlen(strloc+strlen(chain))+1);
                   1009:     /* strcpy (strloc, strloc +strlen(chain));*/
                   1010:   }
                   1011:   printf("Aft strloc=%s chain=%s in=%s out=%s \n", strloc, chain, in, out);
                   1012:   return out;
                   1013: }
                   1014: 
                   1015: 
1.145     brouard  1016: char *cutl(char *blocc, char *alocc, char *in, char occ)
                   1017: {
1.187     brouard  1018:   /* cuts string in into blocc and alocc where blocc ends before FIRST occurence of char 'occ' 
1.145     brouard  1019:      and alocc starts after first occurence of char 'occ' : ex cutv(blocc,alocc,"abcdef2ghi2j",'2')
1.187     brouard  1020:      gives blocc="abcdef" and alocc="ghi2j".
1.145     brouard  1021:      If occ is not found blocc is null and alocc is equal to in. Returns blocc
                   1022:   */
1.160     brouard  1023:   char *s, *t;
1.145     brouard  1024:   t=in;s=in;
                   1025:   while ((*in != occ) && (*in != '\0')){
                   1026:     *alocc++ = *in++;
                   1027:   }
                   1028:   if( *in == occ){
                   1029:     *(alocc)='\0';
                   1030:     s=++in;
                   1031:   }
                   1032:  
                   1033:   if (s == t) {/* occ not found */
                   1034:     *(alocc-(in-s))='\0';
                   1035:     in=s;
                   1036:   }
                   1037:   while ( *in != '\0'){
                   1038:     *blocc++ = *in++;
                   1039:   }
                   1040: 
                   1041:   *blocc='\0';
                   1042:   return t;
                   1043: }
1.137     brouard  1044: char *cutv(char *blocc, char *alocc, char *in, char occ)
                   1045: {
1.187     brouard  1046:   /* cuts string in into blocc and alocc where blocc ends before LAST occurence of char 'occ' 
1.137     brouard  1047:      and alocc starts after last occurence of char 'occ' : ex cutv(blocc,alocc,"abcdef2ghi2j",'2')
                   1048:      gives blocc="abcdef2ghi" and alocc="j".
                   1049:      If occ is not found blocc is null and alocc is equal to in. Returns alocc
                   1050:   */
                   1051:   char *s, *t;
                   1052:   t=in;s=in;
                   1053:   while (*in != '\0'){
                   1054:     while( *in == occ){
                   1055:       *blocc++ = *in++;
                   1056:       s=in;
                   1057:     }
                   1058:     *blocc++ = *in++;
                   1059:   }
                   1060:   if (s == t) /* occ not found */
                   1061:     *(blocc-(in-s))='\0';
                   1062:   else
                   1063:     *(blocc-(in-s)-1)='\0';
                   1064:   in=s;
                   1065:   while ( *in != '\0'){
                   1066:     *alocc++ = *in++;
                   1067:   }
                   1068: 
                   1069:   *alocc='\0';
                   1070:   return s;
                   1071: }
                   1072: 
1.126     brouard  1073: int nbocc(char *s, char occ)
                   1074: {
                   1075:   int i,j=0;
                   1076:   int lg=20;
                   1077:   i=0;
                   1078:   lg=strlen(s);
                   1079:   for(i=0; i<= lg; i++) {
                   1080:   if  (s[i] == occ ) j++;
                   1081:   }
                   1082:   return j;
                   1083: }
                   1084: 
1.137     brouard  1085: /* void cutv(char *u,char *v, char*t, char occ) */
                   1086: /* { */
                   1087: /*   /\* cuts string t into u and v where u ends before last occurence of char 'occ'  */
                   1088: /*      and v starts after last occurence of char 'occ' : ex cutv(u,v,"abcdef2ghi2j",'2') */
                   1089: /*      gives u="abcdef2ghi" and v="j" *\/ */
                   1090: /*   int i,lg,j,p=0; */
                   1091: /*   i=0; */
                   1092: /*   lg=strlen(t); */
                   1093: /*   for(j=0; j<=lg-1; j++) { */
                   1094: /*     if((t[j]!= occ) && (t[j+1]== occ)) p=j+1; */
                   1095: /*   } */
1.126     brouard  1096: 
1.137     brouard  1097: /*   for(j=0; j<p; j++) { */
                   1098: /*     (u[j] = t[j]); */
                   1099: /*   } */
                   1100: /*      u[p]='\0'; */
1.126     brouard  1101: 
1.137     brouard  1102: /*    for(j=0; j<= lg; j++) { */
                   1103: /*     if (j>=(p+1))(v[j-p-1] = t[j]); */
                   1104: /*   } */
                   1105: /* } */
1.126     brouard  1106: 
1.160     brouard  1107: #ifdef _WIN32
                   1108: char * strsep(char **pp, const char *delim)
                   1109: {
                   1110:   char *p, *q;
                   1111:          
                   1112:   if ((p = *pp) == NULL)
                   1113:     return 0;
                   1114:   if ((q = strpbrk (p, delim)) != NULL)
                   1115:   {
                   1116:     *pp = q + 1;
                   1117:     *q = '\0';
                   1118:   }
                   1119:   else
                   1120:     *pp = 0;
                   1121:   return p;
                   1122: }
                   1123: #endif
                   1124: 
1.126     brouard  1125: /********************** nrerror ********************/
                   1126: 
                   1127: void nrerror(char error_text[])
                   1128: {
                   1129:   fprintf(stderr,"ERREUR ...\n");
                   1130:   fprintf(stderr,"%s\n",error_text);
                   1131:   exit(EXIT_FAILURE);
                   1132: }
                   1133: /*********************** vector *******************/
                   1134: double *vector(int nl, int nh)
                   1135: {
                   1136:   double *v;
                   1137:   v=(double *) malloc((size_t)((nh-nl+1+NR_END)*sizeof(double)));
                   1138:   if (!v) nrerror("allocation failure in vector");
                   1139:   return v-nl+NR_END;
                   1140: }
                   1141: 
                   1142: /************************ free vector ******************/
                   1143: void free_vector(double*v, int nl, int nh)
                   1144: {
                   1145:   free((FREE_ARG)(v+nl-NR_END));
                   1146: }
                   1147: 
                   1148: /************************ivector *******************************/
                   1149: int *ivector(long nl,long nh)
                   1150: {
                   1151:   int *v;
                   1152:   v=(int *) malloc((size_t)((nh-nl+1+NR_END)*sizeof(int)));
                   1153:   if (!v) nrerror("allocation failure in ivector");
                   1154:   return v-nl+NR_END;
                   1155: }
                   1156: 
                   1157: /******************free ivector **************************/
                   1158: void free_ivector(int *v, long nl, long nh)
                   1159: {
                   1160:   free((FREE_ARG)(v+nl-NR_END));
                   1161: }
                   1162: 
                   1163: /************************lvector *******************************/
                   1164: long *lvector(long nl,long nh)
                   1165: {
                   1166:   long *v;
                   1167:   v=(long *) malloc((size_t)((nh-nl+1+NR_END)*sizeof(long)));
                   1168:   if (!v) nrerror("allocation failure in ivector");
                   1169:   return v-nl+NR_END;
                   1170: }
                   1171: 
                   1172: /******************free lvector **************************/
                   1173: void free_lvector(long *v, long nl, long nh)
                   1174: {
                   1175:   free((FREE_ARG)(v+nl-NR_END));
                   1176: }
                   1177: 
                   1178: /******************* imatrix *******************************/
                   1179: int **imatrix(long nrl, long nrh, long ncl, long nch) 
                   1180:      /* allocate a int matrix with subscript range m[nrl..nrh][ncl..nch] */ 
                   1181: { 
                   1182:   long i, nrow=nrh-nrl+1,ncol=nch-ncl+1; 
                   1183:   int **m; 
                   1184:   
                   1185:   /* allocate pointers to rows */ 
                   1186:   m=(int **) malloc((size_t)((nrow+NR_END)*sizeof(int*))); 
                   1187:   if (!m) nrerror("allocation failure 1 in matrix()"); 
                   1188:   m += NR_END; 
                   1189:   m -= nrl; 
                   1190:   
                   1191:   
                   1192:   /* allocate rows and set pointers to them */ 
                   1193:   m[nrl]=(int *) malloc((size_t)((nrow*ncol+NR_END)*sizeof(int))); 
                   1194:   if (!m[nrl]) nrerror("allocation failure 2 in matrix()"); 
                   1195:   m[nrl] += NR_END; 
                   1196:   m[nrl] -= ncl; 
                   1197:   
                   1198:   for(i=nrl+1;i<=nrh;i++) m[i]=m[i-1]+ncol; 
                   1199:   
                   1200:   /* return pointer to array of pointers to rows */ 
                   1201:   return m; 
                   1202: } 
                   1203: 
                   1204: /****************** free_imatrix *************************/
                   1205: void free_imatrix(m,nrl,nrh,ncl,nch)
                   1206:       int **m;
                   1207:       long nch,ncl,nrh,nrl; 
                   1208:      /* free an int matrix allocated by imatrix() */ 
                   1209: { 
                   1210:   free((FREE_ARG) (m[nrl]+ncl-NR_END)); 
                   1211:   free((FREE_ARG) (m+nrl-NR_END)); 
                   1212: } 
                   1213: 
                   1214: /******************* matrix *******************************/
                   1215: double **matrix(long nrl, long nrh, long ncl, long nch)
                   1216: {
                   1217:   long i, nrow=nrh-nrl+1, ncol=nch-ncl+1;
                   1218:   double **m;
                   1219: 
                   1220:   m=(double **) malloc((size_t)((nrow+NR_END)*sizeof(double*)));
                   1221:   if (!m) nrerror("allocation failure 1 in matrix()");
                   1222:   m += NR_END;
                   1223:   m -= nrl;
                   1224: 
                   1225:   m[nrl]=(double *) malloc((size_t)((nrow*ncol+NR_END)*sizeof(double)));
                   1226:   if (!m[nrl]) nrerror("allocation failure 2 in matrix()");
                   1227:   m[nrl] += NR_END;
                   1228:   m[nrl] -= ncl;
                   1229: 
                   1230:   for (i=nrl+1; i<=nrh; i++) m[i]=m[i-1]+ncol;
                   1231:   return m;
1.145     brouard  1232:   /* print *(*(m+1)+70) or print m[1][70]; print m+1 or print &(m[1]) or &(m[1][0])
                   1233: m[i] = address of ith row of the table. &(m[i]) is its value which is another adress
                   1234: that of m[i][0]. In order to get the value p m[i][0] but it is unitialized.
1.126     brouard  1235:    */
                   1236: }
                   1237: 
                   1238: /*************************free matrix ************************/
                   1239: void free_matrix(double **m, long nrl, long nrh, long ncl, long nch)
                   1240: {
                   1241:   free((FREE_ARG)(m[nrl]+ncl-NR_END));
                   1242:   free((FREE_ARG)(m+nrl-NR_END));
                   1243: }
                   1244: 
                   1245: /******************* ma3x *******************************/
                   1246: double ***ma3x(long nrl, long nrh, long ncl, long nch, long nll, long nlh)
                   1247: {
                   1248:   long i, j, nrow=nrh-nrl+1, ncol=nch-ncl+1, nlay=nlh-nll+1;
                   1249:   double ***m;
                   1250: 
                   1251:   m=(double ***) malloc((size_t)((nrow+NR_END)*sizeof(double*)));
                   1252:   if (!m) nrerror("allocation failure 1 in matrix()");
                   1253:   m += NR_END;
                   1254:   m -= nrl;
                   1255: 
                   1256:   m[nrl]=(double **) malloc((size_t)((nrow*ncol+NR_END)*sizeof(double)));
                   1257:   if (!m[nrl]) nrerror("allocation failure 2 in matrix()");
                   1258:   m[nrl] += NR_END;
                   1259:   m[nrl] -= ncl;
                   1260: 
                   1261:   for (i=nrl+1; i<=nrh; i++) m[i]=m[i-1]+ncol;
                   1262: 
                   1263:   m[nrl][ncl]=(double *) malloc((size_t)((nrow*ncol*nlay+NR_END)*sizeof(double)));
                   1264:   if (!m[nrl][ncl]) nrerror("allocation failure 3 in matrix()");
                   1265:   m[nrl][ncl] += NR_END;
                   1266:   m[nrl][ncl] -= nll;
                   1267:   for (j=ncl+1; j<=nch; j++) 
                   1268:     m[nrl][j]=m[nrl][j-1]+nlay;
                   1269:   
                   1270:   for (i=nrl+1; i<=nrh; i++) {
                   1271:     m[i][ncl]=m[i-1l][ncl]+ncol*nlay;
                   1272:     for (j=ncl+1; j<=nch; j++) 
                   1273:       m[i][j]=m[i][j-1]+nlay;
                   1274:   }
                   1275:   return m; 
                   1276:   /*  gdb: p *(m+1) <=> p m[1] and p (m+1) <=> p (m+1) <=> p &(m[1])
                   1277:            &(m[i][j][k]) <=> *((*(m+i) + j)+k)
                   1278:   */
                   1279: }
                   1280: 
                   1281: /*************************free ma3x ************************/
                   1282: void free_ma3x(double ***m, long nrl, long nrh, long ncl, long nch,long nll, long nlh)
                   1283: {
                   1284:   free((FREE_ARG)(m[nrl][ncl]+ nll-NR_END));
                   1285:   free((FREE_ARG)(m[nrl]+ncl-NR_END));
                   1286:   free((FREE_ARG)(m+nrl-NR_END));
                   1287: }
                   1288: 
                   1289: /*************** function subdirf ***********/
                   1290: char *subdirf(char fileres[])
                   1291: {
                   1292:   /* Caution optionfilefiname is hidden */
                   1293:   strcpy(tmpout,optionfilefiname);
                   1294:   strcat(tmpout,"/"); /* Add to the right */
                   1295:   strcat(tmpout,fileres);
                   1296:   return tmpout;
                   1297: }
                   1298: 
                   1299: /*************** function subdirf2 ***********/
                   1300: char *subdirf2(char fileres[], char *preop)
                   1301: {
                   1302:   
                   1303:   /* Caution optionfilefiname is hidden */
                   1304:   strcpy(tmpout,optionfilefiname);
                   1305:   strcat(tmpout,"/");
                   1306:   strcat(tmpout,preop);
                   1307:   strcat(tmpout,fileres);
                   1308:   return tmpout;
                   1309: }
                   1310: 
                   1311: /*************** function subdirf3 ***********/
                   1312: char *subdirf3(char fileres[], char *preop, char *preop2)
                   1313: {
                   1314:   
                   1315:   /* Caution optionfilefiname is hidden */
                   1316:   strcpy(tmpout,optionfilefiname);
                   1317:   strcat(tmpout,"/");
                   1318:   strcat(tmpout,preop);
                   1319:   strcat(tmpout,preop2);
                   1320:   strcat(tmpout,fileres);
                   1321:   return tmpout;
                   1322: }
                   1323: 
1.162     brouard  1324: char *asc_diff_time(long time_sec, char ascdiff[])
                   1325: {
                   1326:   long sec_left, days, hours, minutes;
                   1327:   days = (time_sec) / (60*60*24);
                   1328:   sec_left = (time_sec) % (60*60*24);
                   1329:   hours = (sec_left) / (60*60) ;
                   1330:   sec_left = (sec_left) %(60*60);
                   1331:   minutes = (sec_left) /60;
                   1332:   sec_left = (sec_left) % (60);
                   1333:   sprintf(ascdiff,"%ld day(s) %ld hour(s) %ld minute(s) %ld second(s)",days, hours, minutes, sec_left);  
                   1334:   return ascdiff;
                   1335: }
                   1336: 
1.126     brouard  1337: /***************** f1dim *************************/
                   1338: extern int ncom; 
                   1339: extern double *pcom,*xicom;
                   1340: extern double (*nrfunc)(double []); 
                   1341:  
                   1342: double f1dim(double x) 
                   1343: { 
                   1344:   int j; 
                   1345:   double f;
                   1346:   double *xt; 
                   1347:  
                   1348:   xt=vector(1,ncom); 
                   1349:   for (j=1;j<=ncom;j++) xt[j]=pcom[j]+x*xicom[j]; 
                   1350:   f=(*nrfunc)(xt); 
                   1351:   free_vector(xt,1,ncom); 
                   1352:   return f; 
                   1353: } 
                   1354: 
                   1355: /*****************brent *************************/
                   1356: double brent(double ax, double bx, double cx, double (*f)(double), double tol,         double *xmin) 
1.187     brouard  1357: {
                   1358:   /* Given a function f, and given a bracketing triplet of abscissas ax, bx, cx (such that bx is
                   1359:    * between ax and cx, and f(bx) is less than both f(ax) and f(cx) ), this routine isolates
                   1360:    * the minimum to a fractional precision of about tol using Brent’s method. The abscissa of
                   1361:    * the minimum is returned as xmin, and the minimum function value is returned as brent , the
                   1362:    * returned function value. 
                   1363:   */
1.126     brouard  1364:   int iter; 
                   1365:   double a,b,d,etemp;
1.159     brouard  1366:   double fu=0,fv,fw,fx;
1.164     brouard  1367:   double ftemp=0.;
1.126     brouard  1368:   double p,q,r,tol1,tol2,u,v,w,x,xm; 
                   1369:   double e=0.0; 
                   1370:  
                   1371:   a=(ax < cx ? ax : cx); 
                   1372:   b=(ax > cx ? ax : cx); 
                   1373:   x=w=v=bx; 
                   1374:   fw=fv=fx=(*f)(x); 
                   1375:   for (iter=1;iter<=ITMAX;iter++) { 
                   1376:     xm=0.5*(a+b); 
                   1377:     tol2=2.0*(tol1=tol*fabs(x)+ZEPS); 
                   1378:     /*         if (2.0*fabs(fp-(*fret)) <= ftol*(fabs(fp)+fabs(*fret)))*/
                   1379:     printf(".");fflush(stdout);
                   1380:     fprintf(ficlog,".");fflush(ficlog);
1.162     brouard  1381: #ifdef DEBUGBRENT
1.126     brouard  1382:     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);
                   1383:     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);
                   1384:     /*         if ((fabs(x-xm) <= (tol2-0.5*(b-a)))||(2.0*fabs(fu-ftemp) <= ftol*1.e-2*(fabs(fu)+fabs(ftemp)))) { */
                   1385: #endif
                   1386:     if (fabs(x-xm) <= (tol2-0.5*(b-a))){ 
                   1387:       *xmin=x; 
                   1388:       return fx; 
                   1389:     } 
                   1390:     ftemp=fu;
                   1391:     if (fabs(e) > tol1) { 
                   1392:       r=(x-w)*(fx-fv); 
                   1393:       q=(x-v)*(fx-fw); 
                   1394:       p=(x-v)*q-(x-w)*r; 
                   1395:       q=2.0*(q-r); 
                   1396:       if (q > 0.0) p = -p; 
                   1397:       q=fabs(q); 
                   1398:       etemp=e; 
                   1399:       e=d; 
                   1400:       if (fabs(p) >= fabs(0.5*q*etemp) || p <= q*(a-x) || p >= q*(b-x)) 
                   1401:        d=CGOLD*(e=(x >= xm ? a-x : b-x)); 
                   1402:       else { 
                   1403:        d=p/q; 
                   1404:        u=x+d; 
                   1405:        if (u-a < tol2 || b-u < tol2) 
                   1406:          d=SIGN(tol1,xm-x); 
                   1407:       } 
                   1408:     } else { 
                   1409:       d=CGOLD*(e=(x >= xm ? a-x : b-x)); 
                   1410:     } 
                   1411:     u=(fabs(d) >= tol1 ? x+d : x+SIGN(tol1,d)); 
                   1412:     fu=(*f)(u); 
                   1413:     if (fu <= fx) { 
                   1414:       if (u >= x) a=x; else b=x; 
                   1415:       SHFT(v,w,x,u) 
1.183     brouard  1416:       SHFT(fv,fw,fx,fu) 
                   1417:     } else { 
                   1418:       if (u < x) a=u; else b=u; 
                   1419:       if (fu <= fw || w == x) { 
                   1420:        v=w; 
                   1421:        w=u; 
                   1422:        fv=fw; 
                   1423:        fw=fu; 
                   1424:       } else if (fu <= fv || v == x || v == w) { 
                   1425:        v=u; 
                   1426:        fv=fu; 
                   1427:       } 
                   1428:     } 
1.126     brouard  1429:   } 
                   1430:   nrerror("Too many iterations in brent"); 
                   1431:   *xmin=x; 
                   1432:   return fx; 
                   1433: } 
                   1434: 
                   1435: /****************** mnbrak ***********************/
                   1436: 
                   1437: void mnbrak(double *ax, double *bx, double *cx, double *fa, double *fb, double *fc, 
                   1438:            double (*func)(double)) 
1.183     brouard  1439: { /* Given a function func , and given distinct initial points ax and bx , this routine searches in
                   1440: the downhill direction (defined by the function as evaluated at the initial points) and returns
                   1441: new points ax , bx , cx that bracket a minimum of the function. Also returned are the function
                   1442: values at the three points, fa, fb , and fc such that fa > fb and fb < fc.
                   1443:    */
1.126     brouard  1444:   double ulim,u,r,q, dum;
                   1445:   double fu; 
1.187     brouard  1446: 
                   1447:   double scale=10.;
                   1448:   int iterscale=0;
                   1449: 
                   1450:   *fa=(*func)(*ax); /*  xta[j]=pcom[j]+(*ax)*xicom[j]; fa=f(xta[j])*/
                   1451:   *fb=(*func)(*bx); /*  xtb[j]=pcom[j]+(*bx)*xicom[j]; fb=f(xtb[j]) */
                   1452: 
                   1453: 
                   1454:   /* while(*fb != *fb){ /\* *ax should be ok, reducing distance to *ax *\/ */
                   1455:   /*   printf("Warning mnbrak *fb = %lf, *bx=%lf *ax=%lf *fa==%lf iter=%d\n",*fb, *bx, *ax, *fa, iterscale++); */
                   1456:   /*   *bx = *ax - (*ax - *bx)/scale; */
                   1457:   /*   *fb=(*func)(*bx);  /\*  xtb[j]=pcom[j]+(*bx)*xicom[j]; fb=f(xtb[j]) *\/ */
                   1458:   /* } */
                   1459: 
1.126     brouard  1460:   if (*fb > *fa) { 
                   1461:     SHFT(dum,*ax,*bx,dum) 
1.183     brouard  1462:     SHFT(dum,*fb,*fa,dum) 
                   1463:   } 
1.126     brouard  1464:   *cx=(*bx)+GOLD*(*bx-*ax); 
                   1465:   *fc=(*func)(*cx); 
1.183     brouard  1466: #ifdef DEBUG
                   1467:   printf("mnbrak0 *fb=%.12e *fc=%.12e\n",*fb,*fc);
                   1468:   fprintf(ficlog,"mnbrak0 *fb=%.12e *fc=%.12e\n",*fb,*fc);
                   1469: #endif
                   1470:   while (*fb > *fc) { /* Declining a,b,c with fa> fb > fc */
1.126     brouard  1471:     r=(*bx-*ax)*(*fb-*fc); 
                   1472:     q=(*bx-*cx)*(*fb-*fa); 
                   1473:     u=(*bx)-((*bx-*cx)*q-(*bx-*ax)*r)/ 
1.183     brouard  1474:       (2.0*SIGN(FMAX(fabs(q-r),TINY),q-r)); /* Minimum abscissa of a parabolic estimated from (a,fa), (b,fb) and (c,fc). */
                   1475:     ulim=(*bx)+GLIMIT*(*cx-*bx); /* Maximum abscissa where function should be evaluated */
                   1476:     if ((*bx-u)*(u-*cx) > 0.0) { /* if u_p is between b and c */
1.126     brouard  1477:       fu=(*func)(u); 
1.163     brouard  1478: #ifdef DEBUG
                   1479:       /* f(x)=A(x-u)**2+f(u) */
                   1480:       double A, fparabu; 
                   1481:       A= (*fb - *fa)/(*bx-*ax)/(*bx+*ax-2*u);
                   1482:       fparabu= *fa - A*(*ax-u)*(*ax-u);
                   1483:       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);
                   1484:       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  1485:       /* And thus,it can be that fu > *fc even if fparabu < *fc */
                   1486:       /* mnbrak (*ax=7.666299858533, *fa=299039.693133272231), (*bx=8.595447774979, *fb=298976.598289369489),
                   1487:         (*cx=10.098840694817, *fc=298946.631474258087),  (*u=9.852501168332, fu=298948.773013752128, fparabu=298945.434711494134) */
                   1488:       /* In that case, there is no bracket in the output! Routine is wrong with many consequences.*/
1.163     brouard  1489: #endif 
1.184     brouard  1490: #ifdef MNBRAKORIGINAL
1.183     brouard  1491: #else
1.191     brouard  1492: /*       if (fu > *fc) { */
                   1493: /* #ifdef DEBUG */
                   1494: /*       printf("mnbrak4  fu > fc \n"); */
                   1495: /*       fprintf(ficlog, "mnbrak4 fu > fc\n"); */
                   1496: /* #endif */
                   1497: /*     /\* 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 *\\/  *\/ */
                   1498: /*     /\* SHFT(*fa,*fc,fu,*fc) /\\* (b, u, c) is a bracket while test fb > fc will be fu > fc  will exit *\\/ *\/ */
                   1499: /*     dum=u; /\* Shifting c and u *\/ */
                   1500: /*     u = *cx; */
                   1501: /*     *cx = dum; */
                   1502: /*     dum = fu; */
                   1503: /*     fu = *fc; */
                   1504: /*     *fc =dum; */
                   1505: /*       } else { /\* end *\/ */
                   1506: /* #ifdef DEBUG */
                   1507: /*       printf("mnbrak3  fu < fc \n"); */
                   1508: /*       fprintf(ficlog, "mnbrak3 fu < fc\n"); */
                   1509: /* #endif */
                   1510: /*     dum=u; /\* Shifting c and u *\/ */
                   1511: /*     u = *cx; */
                   1512: /*     *cx = dum; */
                   1513: /*     dum = fu; */
                   1514: /*     fu = *fc; */
                   1515: /*     *fc =dum; */
                   1516: /*       } */
1.183     brouard  1517: #ifdef DEBUG
1.191     brouard  1518:       printf("mnbrak34  fu < or >= fc \n");
                   1519:       fprintf(ficlog, "mnbrak34 fu < fc\n");
1.183     brouard  1520: #endif
1.191     brouard  1521:       dum=u; /* Shifting c and u */
                   1522:       u = *cx;
                   1523:       *cx = dum;
                   1524:       dum = fu;
                   1525:       fu = *fc;
                   1526:       *fc =dum;
1.183     brouard  1527: #endif
1.162     brouard  1528:     } else if ((*cx-u)*(u-ulim) > 0.0) { /* u is after c but before ulim */
1.183     brouard  1529: #ifdef DEBUG
                   1530:       printf("mnbrak2  u after c but before ulim\n");
                   1531:       fprintf(ficlog, "mnbrak2 u after c but before ulim\n");
                   1532: #endif
1.126     brouard  1533:       fu=(*func)(u); 
                   1534:       if (fu < *fc) { 
1.183     brouard  1535: #ifdef DEBUG
                   1536:       printf("mnbrak2  u after c but before ulim AND fu < fc\n");
                   1537:       fprintf(ficlog, "mnbrak2 u after c but before ulim AND fu <fc \n");
                   1538: #endif
1.126     brouard  1539:        SHFT(*bx,*cx,u,*cx+GOLD*(*cx-*bx)) 
1.183     brouard  1540:        SHFT(*fb,*fc,fu,(*func)(u)) 
                   1541:       } 
1.162     brouard  1542:     } else if ((u-ulim)*(ulim-*cx) >= 0.0) { /* u outside ulim (verifying that ulim is beyond c) */
1.183     brouard  1543: #ifdef DEBUG
                   1544:       printf("mnbrak2  u outside ulim (verifying that ulim is beyond c)\n");
                   1545:       fprintf(ficlog, "mnbrak2 u outside ulim (verifying that ulim is beyond c)\n");
                   1546: #endif
1.126     brouard  1547:       u=ulim; 
                   1548:       fu=(*func)(u); 
1.183     brouard  1549:     } else { /* u could be left to b (if r > q parabola has a maximum) */
                   1550: #ifdef DEBUG
                   1551:       printf("mnbrak2  u could be left to b (if r > q parabola has a maximum)\n");
                   1552:       fprintf(ficlog, "mnbrak2  u could be left to b (if r > q parabola has a maximum)\n");
                   1553: #endif
1.126     brouard  1554:       u=(*cx)+GOLD*(*cx-*bx); 
                   1555:       fu=(*func)(u); 
1.183     brouard  1556:     } /* end tests */
1.126     brouard  1557:     SHFT(*ax,*bx,*cx,u) 
1.183     brouard  1558:     SHFT(*fa,*fb,*fc,fu) 
                   1559: #ifdef DEBUG
                   1560:       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);
                   1561:       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);
                   1562: #endif
                   1563:   } /* 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  1564: } 
                   1565: 
                   1566: /*************** linmin ************************/
1.162     brouard  1567: /* Given an n -dimensional point p[1..n] and an n -dimensional direction xi[1..n] , moves and
                   1568: resets p to where the function func(p) takes on a minimum along the direction xi from p ,
                   1569: and replaces xi by the actual vector displacement that p was moved. Also returns as fret
                   1570: the value of func at the returned location p . This is actually all accomplished by calling the
                   1571: routines mnbrak and brent .*/
1.126     brouard  1572: int ncom; 
                   1573: double *pcom,*xicom;
                   1574: double (*nrfunc)(double []); 
                   1575:  
                   1576: void linmin(double p[], double xi[], int n, double *fret,double (*func)(double [])) 
                   1577: { 
                   1578:   double brent(double ax, double bx, double cx, 
                   1579:               double (*f)(double), double tol, double *xmin); 
                   1580:   double f1dim(double x); 
                   1581:   void mnbrak(double *ax, double *bx, double *cx, double *fa, double *fb, 
                   1582:              double *fc, double (*func)(double)); 
                   1583:   int j; 
                   1584:   double xx,xmin,bx,ax; 
                   1585:   double fx,fb,fa;
1.187     brouard  1586: 
                   1587:   double scale=10., axs, xxs, xxss; /* Scale added for infinity */
1.126     brouard  1588:  
                   1589:   ncom=n; 
                   1590:   pcom=vector(1,n); 
                   1591:   xicom=vector(1,n); 
                   1592:   nrfunc=func; 
                   1593:   for (j=1;j<=n;j++) { 
                   1594:     pcom[j]=p[j]; 
                   1595:     xicom[j]=xi[j]; 
                   1596:   } 
1.187     brouard  1597: 
1.192     brouard  1598:   /* axs=0.0; */
                   1599:   /* xxss=1; /\* 1 and using scale *\/ */
1.187     brouard  1600:   xxs=1;
1.192     brouard  1601:   /* do{ */
1.187     brouard  1602:     ax=0.;
                   1603:     xx= xxs;
                   1604:     mnbrak(&ax,&xx,&bx,&fa,&fx,&fb,f1dim);  /* Outputs: xtx[j]=pcom[j]+(*xx)*xicom[j]; fx=f(xtx[j]) */
                   1605:     /* brackets with inputs ax=0 and xx=1, but points, pcom=p, and directions values, xicom=xi, are sent via f1dim(x) */
                   1606:     /* 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))   */
                   1607:     /* Outputs: fa=f(p(j)) and fx=f(p(j) + xxs * xi(j) ) and f(bx)= f(p(j)+ bx* xi(j)) */
                   1608:     /* Given input ax=axs and xx=xxs, xx might be too far from ax to get a finite f(xx) */
                   1609:     /* Searches on line, outputs (ax, xx, bx) such that fx < min(fa and fb) */
                   1610:     /* 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  1611:   /*   if (fx != fx){ */
                   1612:   /*   xxs=xxs/scale; /\* Trying a smaller xx, closer to initial ax=0 *\/ */
                   1613:   /*   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); */
                   1614:   /*   } */
                   1615:   /* }while(fx != fx); */
1.187     brouard  1616: 
1.191     brouard  1617: #ifdef DEBUGLINMIN
                   1618:   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);
                   1619: #endif
1.187     brouard  1620:   *fret=brent(ax,xx,bx,f1dim,TOL,&xmin); /* Giving a bracketting triplet (ax, xx, bx), find a minimum, xmin, according to f1dim, *fret(xmin),*/
                   1621:   /* fa = f(p[j] + ax * xi[j]), fx = f(p[j] + xx * xi[j]), fb = f(p[j] + bx * xi[j]) */
                   1622:   /* fmin = f(p[j] + xmin * xi[j]) */
                   1623:   /* P+lambda n in that direction (lambdamin), with TOL between abscisses */
                   1624:   /* f1dim(xmin): for (j=1;j<=ncom;j++) xt[j]=pcom[j]+xmin*xicom[j]; */
1.126     brouard  1625: #ifdef DEBUG
                   1626:   printf("retour brent fret=%.12e xmin=%.12e\n",*fret,xmin);
                   1627:   fprintf(ficlog,"retour brent fret=%.12e xmin=%.12e\n",*fret,xmin);
                   1628: #endif
1.191     brouard  1629: #ifdef DEBUGLINMIN
                   1630:   printf("linmin end ");
                   1631: #endif
1.126     brouard  1632:   for (j=1;j<=n;j++) { 
1.188     brouard  1633:     /* printf(" before xi[%d]=%12.8f", j,xi[j]); */
1.187     brouard  1634:     xi[j] *= xmin; /* xi rescaled by xmin: if xmin=-1.237 and xi=(1,0,...,0) xi=(-1.237,0,...,0) */
1.189     brouard  1635:     /* if(xxs <1.0) */
                   1636:     /*   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  1637:     p[j] += xi[j]; /* Parameters values are updated accordingly */
1.126     brouard  1638:   } 
1.189     brouard  1639:   /* printf("\n"); */
1.191     brouard  1640: #ifdef DEBUGLINMIN
                   1641:   printf("Comparing last *frec(xmin=%12.8f)=%12.8f from Brent and frec(0.)=%12.8f \n", xmin, *fret, (*func)(p));
                   1642:   for (j=1;j<=n;j++) { 
                   1643:     printf(" xi[%d]= %12.7f p[%d]= %12.7f",j,xi[j],j,p[j]);
                   1644:     if(j % ncovmodel == 0)
                   1645:       printf("\n");
                   1646:   }
                   1647: #endif
1.126     brouard  1648:   free_vector(xicom,1,n); 
                   1649:   free_vector(pcom,1,n); 
                   1650: } 
                   1651: 
                   1652: 
                   1653: /*************** powell ************************/
1.162     brouard  1654: /*
                   1655: Minimization of a function func of n variables. Input consists of an initial starting point
                   1656: p[1..n] ; an initial matrix xi[1..n][1..n] , whose columns contain the initial set of di-
                   1657: rections (usually the n unit vectors); and ftol , the fractional tolerance in the function value
                   1658: such that failure to decrease by more than this amount on one iteration signals doneness. On
                   1659: output, p is set to the best point found, xi is the then-current direction set, fret is the returned
                   1660: function value at p , and iter is the number of iterations taken. The routine linmin is used.
                   1661:  */
1.126     brouard  1662: void powell(double p[], double **xi, int n, double ftol, int *iter, double *fret, 
                   1663:            double (*func)(double [])) 
                   1664: { 
                   1665:   void linmin(double p[], double xi[], int n, double *fret, 
                   1666:              double (*func)(double [])); 
                   1667:   int i,ibig,j; 
                   1668:   double del,t,*pt,*ptt,*xit;
1.181     brouard  1669:   double directest;
1.126     brouard  1670:   double fp,fptt;
                   1671:   double *xits;
                   1672:   int niterf, itmp;
                   1673: 
                   1674:   pt=vector(1,n); 
                   1675:   ptt=vector(1,n); 
                   1676:   xit=vector(1,n); 
                   1677:   xits=vector(1,n); 
                   1678:   *fret=(*func)(p); 
                   1679:   for (j=1;j<=n;j++) pt[j]=p[j]; 
1.157     brouard  1680:     rcurr_time = time(NULL);  
1.126     brouard  1681:   for (*iter=1;;++(*iter)) { 
1.187     brouard  1682:     fp=(*fret); /* From former iteration or initial value */
1.126     brouard  1683:     ibig=0; 
                   1684:     del=0.0; 
1.157     brouard  1685:     rlast_time=rcurr_time;
                   1686:     /* (void) gettimeofday(&curr_time,&tzp); */
                   1687:     rcurr_time = time(NULL);  
                   1688:     curr_time = *localtime(&rcurr_time);
                   1689:     printf("\nPowell iter=%d -2*LL=%.12f %ld sec. %ld sec.",*iter,*fret, rcurr_time-rlast_time, rcurr_time-rstart_time);fflush(stdout);
                   1690:     fprintf(ficlog,"\nPowell iter=%d -2*LL=%.12f %ld sec. %ld sec.",*iter,*fret,rcurr_time-rlast_time, rcurr_time-rstart_time); fflush(ficlog);
                   1691: /*     fprintf(ficrespow,"%d %.12f %ld",*iter,*fret,curr_time.tm_sec-start_time.tm_sec); */
1.192     brouard  1692:     for (i=1;i<=n;i++) {
1.126     brouard  1693:       printf(" %d %.12f",i, p[i]);
                   1694:       fprintf(ficlog," %d %.12lf",i, p[i]);
                   1695:       fprintf(ficrespow," %.12lf", p[i]);
                   1696:     }
                   1697:     printf("\n");
                   1698:     fprintf(ficlog,"\n");
                   1699:     fprintf(ficrespow,"\n");fflush(ficrespow);
                   1700:     if(*iter <=3){
1.157     brouard  1701:       tml = *localtime(&rcurr_time);
                   1702:       strcpy(strcurr,asctime(&tml));
                   1703:       rforecast_time=rcurr_time; 
1.126     brouard  1704:       itmp = strlen(strcurr);
                   1705:       if(strcurr[itmp-1]=='\n')  /* Windows outputs with a new line */
                   1706:        strcurr[itmp-1]='\0';
1.162     brouard  1707:       printf("\nConsidering the time needed for the last iteration #%d: %ld seconds,\n",*iter,rcurr_time-rlast_time);
1.157     brouard  1708:       fprintf(ficlog,"\nConsidering the time needed for this last iteration #%d: %ld seconds,\n",*iter,rcurr_time-rlast_time);
1.126     brouard  1709:       for(niterf=10;niterf<=30;niterf+=10){
1.157     brouard  1710:        rforecast_time=rcurr_time+(niterf-*iter)*(rcurr_time-rlast_time);
                   1711:        forecast_time = *localtime(&rforecast_time);
                   1712:        strcpy(strfor,asctime(&forecast_time));
1.126     brouard  1713:        itmp = strlen(strfor);
                   1714:        if(strfor[itmp-1]=='\n')
                   1715:        strfor[itmp-1]='\0';
1.157     brouard  1716:        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);
                   1717:        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  1718:       }
                   1719:     }
1.187     brouard  1720:     for (i=1;i<=n;i++) { /* For each direction i */
                   1721:       for (j=1;j<=n;j++) xit[j]=xi[j][i]; /* Directions stored from previous iteration with previous scales */
1.126     brouard  1722:       fptt=(*fret); 
                   1723: #ifdef DEBUG
1.164     brouard  1724:          printf("fret=%lf, %lf, %lf \n", *fret, *fret, *fret);
                   1725:          fprintf(ficlog, "fret=%lf, %lf, %lf \n", *fret, *fret, *fret);
1.126     brouard  1726: #endif
1.187     brouard  1727:          printf("%d",i);fflush(stdout); /* print direction (parameter) i */
1.126     brouard  1728:       fprintf(ficlog,"%d",i);fflush(ficlog);
1.188     brouard  1729:       linmin(p,xit,n,fret,func); /* Point p[n]. xit[n] has been loaded for direction i as input.*/
                   1730:                                    /* Outputs are fret(new point p) p is updated and xit rescaled */
                   1731:       if (fabs(fptt-(*fret)) > del) { /* We are keeping the max gain on each of the n directions */
                   1732:        /* because that direction will be replaced unless the gain del is small */
                   1733:        /* in comparison with the 'probable' gain, mu^2, with the last average direction. */
                   1734:        /* Unless the n directions are conjugate some gain in the determinant may be obtained */
                   1735:        /* with the new direction. */
1.126     brouard  1736:        del=fabs(fptt-(*fret)); 
                   1737:        ibig=i; 
                   1738:       } 
                   1739: #ifdef DEBUG
                   1740:       printf("%d %.12e",i,(*fret));
                   1741:       fprintf(ficlog,"%d %.12e",i,(*fret));
                   1742:       for (j=1;j<=n;j++) {
                   1743:        xits[j]=FMAX(fabs(p[j]-pt[j]),1.e-5);
                   1744:        printf(" x(%d)=%.12e",j,xit[j]);
                   1745:        fprintf(ficlog," x(%d)=%.12e",j,xit[j]);
                   1746:       }
                   1747:       for(j=1;j<=n;j++) {
1.162     brouard  1748:        printf(" p(%d)=%.12e",j,p[j]);
                   1749:        fprintf(ficlog," p(%d)=%.12e",j,p[j]);
1.126     brouard  1750:       }
                   1751:       printf("\n");
                   1752:       fprintf(ficlog,"\n");
                   1753: #endif
1.187     brouard  1754:     } /* end loop on each direction i */
                   1755:     /* Convergence test will use last linmin estimation (fret) and compare former iteration (fp) */ 
1.188     brouard  1756:     /* But p and xit have been updated at the end of linmin, *fret corresponds to new p, xit  */
1.187     brouard  1757:     /* New value of last point Pn is not computed, P(n-1) */
1.182     brouard  1758:     if (2.0*fabs(fp-(*fret)) <= ftol*(fabs(fp)+fabs(*fret))) { /* Did we reach enough precision? */
1.188     brouard  1759:       /* We could compare with a chi^2. chisquare(0.95,ddl=1)=3.84 */
                   1760:       /* By adding age*age in a model, the new -2LL should be lower and the difference follows a */
                   1761:       /* a chisquare statistics with 1 degree. To be significant at the 95% level, it should have */
                   1762:       /* decreased of more than 3.84  */
                   1763:       /* By adding age*age and V1*age the gain (-2LL) should be more than 5.99 (ddl=2) */
                   1764:       /* By using V1+V2+V3, the gain should be  7.82, compared with basic 1+age. */
                   1765:       /* By adding 10 parameters more the gain should be 18.31 */
                   1766: 
                   1767:       /* Starting the program with initial values given by a former maximization will simply change */
                   1768:       /* the scales of the directions and the directions, because the are reset to canonical directions */
                   1769:       /* Thus the first calls to linmin will give new points and better maximizations until fp-(*fret) is */
                   1770:       /* under the tolerance value. If the tolerance is very small 1.e-9, it could last long.  */
1.126     brouard  1771: #ifdef DEBUG
                   1772:       int k[2],l;
                   1773:       k[0]=1;
                   1774:       k[1]=-1;
                   1775:       printf("Max: %.12e",(*func)(p));
                   1776:       fprintf(ficlog,"Max: %.12e",(*func)(p));
                   1777:       for (j=1;j<=n;j++) {
                   1778:        printf(" %.12e",p[j]);
                   1779:        fprintf(ficlog," %.12e",p[j]);
                   1780:       }
                   1781:       printf("\n");
                   1782:       fprintf(ficlog,"\n");
                   1783:       for(l=0;l<=1;l++) {
                   1784:        for (j=1;j<=n;j++) {
                   1785:          ptt[j]=p[j]+(p[j]-pt[j])*k[l];
                   1786:          printf("l=%d j=%d ptt=%.12e, xits=%.12e, p=%.12e, xit=%.12e", l,j,ptt[j],xits[j],p[j],xit[j]);
                   1787:          fprintf(ficlog,"l=%d j=%d ptt=%.12e, xits=%.12e, p=%.12e, xit=%.12e", l,j,ptt[j],xits[j],p[j],xit[j]);
                   1788:        }
                   1789:        printf("func(ptt)=%.12e, deriv=%.12e\n",(*func)(ptt),(ptt[j]-p[j])/((*func)(ptt)-(*func)(p)));
                   1790:        fprintf(ficlog,"func(ptt)=%.12e, deriv=%.12e\n",(*func)(ptt),(ptt[j]-p[j])/((*func)(ptt)-(*func)(p)));
                   1791:       }
                   1792: #endif
                   1793: 
                   1794: 
                   1795:       free_vector(xit,1,n); 
                   1796:       free_vector(xits,1,n); 
                   1797:       free_vector(ptt,1,n); 
                   1798:       free_vector(pt,1,n); 
                   1799:       return; 
1.192     brouard  1800:     } /* enough precision */ 
1.126     brouard  1801:     if (*iter == ITMAX) nrerror("powell exceeding maximum iterations."); 
1.181     brouard  1802:     for (j=1;j<=n;j++) { /* Computes the extrapolated point P_0 + 2 (P_n-P_0) */
1.126     brouard  1803:       ptt[j]=2.0*p[j]-pt[j]; 
                   1804:       xit[j]=p[j]-pt[j]; 
                   1805:       pt[j]=p[j]; 
                   1806:     } 
1.181     brouard  1807:     fptt=(*func)(ptt); /* f_3 */
1.192     brouard  1808: #ifdef POWELLF1F3
                   1809: #else
1.161     brouard  1810:     if (fptt < fp) { /* If extrapolated point is better, decide if we keep that new direction or not */
1.192     brouard  1811: #endif
1.162     brouard  1812:       /* (x1 f1=fp), (x2 f2=*fret), (x3 f3=fptt), (xm fm) */
1.161     brouard  1813:       /* From x1 (P0) distance of x2 is at h and x3 is 2h */
1.162     brouard  1814:       /* Let f"(x2) be the 2nd derivative equal everywhere.  */
                   1815:       /* Then the parabolic through (x1,f1), (x2,f2) and (x3,f3) */
                   1816:       /* will reach at f3 = fm + h^2/2 f"m  ; f" = (f1 -2f2 +f3 ) / h**2 */
1.181     brouard  1817:       /* Conditional for using this new direction is that mu^2 = (f1-2f2+f3)^2 /2 < del */
1.161     brouard  1818:       /* t=2.0*(fp-2.0*(*fret)+fptt)*SQR(fp-(*fret)-del)-del*SQR(fp-fptt); */
1.183     brouard  1819: #ifdef NRCORIGINAL
                   1820:       t=2.0*(fp-2.0*(*fret)+fptt)*SQR(fp-(*fret)-del)- del*SQR(fp-fptt); /* Original Numerical Recipes in C*/
                   1821: #else
                   1822:       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  1823:       t= t- del*SQR(fp-fptt);
1.183     brouard  1824: #endif
1.182     brouard  1825:       directest = fp-2.0*(*fret)+fptt - 2.0 * del; /* If del was big enough we change it for a new direction */
1.161     brouard  1826: #ifdef DEBUG
1.181     brouard  1827:       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);
                   1828:       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  1829:       printf("t3= %.12lf, t4= %.12lf, t3*= %.12lf, t4*= %.12lf\n",SQR(fp-(*fret)-del),SQR(fp-fptt),
                   1830:             (fp-(*fret)-del)*(fp-(*fret)-del),(fp-fptt)*(fp-fptt));
                   1831:       fprintf(ficlog,"t3= %.12lf, t4= %.12lf, t3*= %.12lf, t4*= %.12lf\n",SQR(fp-(*fret)-del),SQR(fp-fptt),
                   1832:             (fp-(*fret)-del)*(fp-(*fret)-del),(fp-fptt)*(fp-fptt));
                   1833:       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);
                   1834:       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);
                   1835: #endif
1.183     brouard  1836: #ifdef POWELLORIGINAL
                   1837:       if (t < 0.0) { /* Then we use it for new direction */
                   1838: #else
1.182     brouard  1839:       if (directest*t < 0.0) { /* Contradiction between both tests */
1.192     brouard  1840:        printf("directest= %.12lf, t= %.12lf, f1= %.12lf,f2= %.12lf,f3= %.12lf, del= %.12lf\n",directest, t, fp,(*fret),fptt,del);
                   1841:         printf("f1-2f2+f3= %.12lf, f1-f2-del= %.12lf, f1-f3= %.12lf\n",fp-2.0*(*fret)+fptt, fp -(*fret) -del, fp-fptt);
                   1842:         fprintf(ficlog,"directest= %.12lf, t= %.12lf, f1= %.12lf,f2= %.12lf,f3= %.12lf, del= %.12lf\n",directest, t, fp,(*fret),fptt, del);
                   1843:         fprintf(ficlog,"f1-2f2+f3= %.12lf, f1-f2-del= %.12lf, f1-f3= %.12lf\n",fp-2.0*(*fret)+fptt, fp -(*fret) -del, fp-fptt);
                   1844:       } 
1.181     brouard  1845:       if (directest < 0.0) { /* Then we use it for new direction */
                   1846: #endif
1.191     brouard  1847: #ifdef DEBUGLINMIN
                   1848:        printf("Before linmin in direction P%d-P0\n",n);
                   1849:        for (j=1;j<=n;j++) { 
                   1850:          printf("Before xit[%d]= %12.7f p[%d]= %12.7f",j,xit[j],j,p[j]);
                   1851:          if(j % ncovmodel == 0)
                   1852:            printf("\n");
                   1853:        }
                   1854: #endif
1.187     brouard  1855:        linmin(p,xit,n,fret,func); /* computes minimum on the extrapolated direction: changes p and rescales xit.*/
1.191     brouard  1856: #ifdef DEBUGLINMIN
                   1857:        for (j=1;j<=n;j++) { 
                   1858:          printf("After 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.126     brouard  1863:        for (j=1;j<=n;j++) { 
1.181     brouard  1864:          xi[j][ibig]=xi[j][n]; /* Replace direction with biggest decrease by last direction n */
                   1865:          xi[j][n]=xit[j];      /* and this nth direction by the by the average p_0 p_n */
1.126     brouard  1866:        }
1.181     brouard  1867:        printf("Gaining to use new average direction of P0 P%d instead of biggest increase direction %d :\n",n,ibig);
                   1868:        fprintf(ficlog,"Gaining to use new average direction of P0 P%d instead of biggest increase direction %d :\n",n,ibig);
1.161     brouard  1869: 
1.126     brouard  1870: #ifdef DEBUG
1.164     brouard  1871:        printf("Direction changed  last moved %d in place of ibig=%d, new last is the average:\n",n,ibig);
                   1872:        fprintf(ficlog,"Direction changed  last moved %d in place of ibig=%d, new last is the average:\n",n,ibig);
1.126     brouard  1873:        for(j=1;j<=n;j++){
                   1874:          printf(" %.12e",xit[j]);
                   1875:          fprintf(ficlog," %.12e",xit[j]);
                   1876:        }
                   1877:        printf("\n");
                   1878:        fprintf(ficlog,"\n");
                   1879: #endif
1.192     brouard  1880:       } /* end of t or directest negative */
                   1881: #ifdef POWELLF1F3
                   1882: #else
1.162     brouard  1883:     } /* end if (fptt < fp)  */
1.192     brouard  1884: #endif
                   1885:   } /* loop iteration */ 
1.126     brouard  1886: } 
                   1887: 
                   1888: /**** Prevalence limit (stable or period prevalence)  ****************/
                   1889: 
                   1890: double **prevalim(double **prlim, int nlstate, double x[], double age, double **oldm, double **savm, double ftolpl, int ij)
                   1891: {
                   1892:   /* Computes the prevalence limit in each live state at age x by left multiplying the unit
                   1893:      matrix by transitions matrix until convergence is reached */
1.169     brouard  1894:   
1.126     brouard  1895:   int i, ii,j,k;
                   1896:   double min, max, maxmin, maxmax,sumnew=0.;
1.145     brouard  1897:   /* double **matprod2(); */ /* test */
1.131     brouard  1898:   double **out, cov[NCOVMAX+1], **pmij();
1.126     brouard  1899:   double **newm;
                   1900:   double agefin, delaymax=50 ; /* Max number of years to converge */
1.169     brouard  1901:   
1.126     brouard  1902:   for (ii=1;ii<=nlstate+ndeath;ii++)
                   1903:     for (j=1;j<=nlstate+ndeath;j++){
                   1904:       oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   1905:     }
1.169     brouard  1906:   
                   1907:   cov[1]=1.;
                   1908:   
                   1909:   /* Even if hstepm = 1, at least one multiplication by the unit matrix */
1.126     brouard  1910:   for(agefin=age-stepm/YEARM; agefin>=age-delaymax; agefin=agefin-stepm/YEARM){
                   1911:     newm=savm;
                   1912:     /* Covariates have to be included here again */
1.138     brouard  1913:     cov[2]=agefin;
1.187     brouard  1914:     if(nagesqr==1)
                   1915:       cov[3]= agefin*agefin;;
1.138     brouard  1916:     for (k=1; k<=cptcovn;k++) {
1.198     brouard  1917:       cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(ij,Tvar[k])];
                   1918:       /* 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  1919:     }
1.186     brouard  1920:     /*wrong? for (k=1; k<=cptcovage;k++) cov[2+Tage[k]]=cov[2+Tage[k]]*cov[2]; */
1.198     brouard  1921:     for (k=1; k<=cptcovage;k++) cov[2+nagesqr+Tage[k]]=nbcode[Tvar[k]][codtabm(ij,Tvar[k])]*cov[2];
1.186     brouard  1922:     for (k=1; k<=cptcovprod;k++) /* Useless */
1.198     brouard  1923:       cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,Tvard[k][1])] * nbcode[Tvard[k][2]][codtabm(ij,Tvard[k][2])];
1.138     brouard  1924:     
                   1925:     /*printf("ij=%d cptcovprod=%d tvar=%d ", ij, cptcovprod, Tvar[1]);*/
                   1926:     /*printf("ij=%d cov[3]=%lf cov[4]=%lf \n",ij, cov[3],cov[4]);*/
                   1927:     /*printf("ij=%d cov[3]=%lf \n",ij, cov[3]);*/
1.145     brouard  1928:     /* savm=pmij(pmmij,cov,ncovmodel,x,nlstate); */
                   1929:     /* out=matprod2(newm, pmij(pmmij,cov,ncovmodel,x,nlstate),1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, oldm); /\* Bug Valgrind *\/ */
1.142     brouard  1930:     out=matprod2(newm, pmij(pmmij,cov,ncovmodel,x,nlstate),1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, oldm); /* Bug Valgrind */
1.138     brouard  1931:     
1.126     brouard  1932:     savm=oldm;
                   1933:     oldm=newm;
                   1934:     maxmax=0.;
                   1935:     for(j=1;j<=nlstate;j++){
                   1936:       min=1.;
                   1937:       max=0.;
                   1938:       for(i=1; i<=nlstate; i++) {
                   1939:        sumnew=0;
                   1940:        for(k=1; k<=ndeath; k++) sumnew+=newm[i][nlstate+k];
                   1941:        prlim[i][j]= newm[i][j]/(1-sumnew);
1.145     brouard  1942:         /*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  1943:        max=FMAX(max,prlim[i][j]);
                   1944:        min=FMIN(min,prlim[i][j]);
                   1945:       }
                   1946:       maxmin=max-min;
                   1947:       maxmax=FMAX(maxmax,maxmin);
1.169     brouard  1948:     } /* j loop */
1.126     brouard  1949:     if(maxmax < ftolpl){
                   1950:       return prlim;
                   1951:     }
1.169     brouard  1952:   } /* age loop */
                   1953:   return prlim; /* should not reach here */
1.126     brouard  1954: }
                   1955: 
                   1956: /*************** transition probabilities ***************/ 
                   1957: 
                   1958: double **pmij(double **ps, double *cov, int ncovmodel, double *x, int nlstate )
                   1959: {
1.138     brouard  1960:   /* According to parameters values stored in x and the covariate's values stored in cov,
                   1961:      computes the probability to be observed in state j being in state i by appying the
                   1962:      model to the ncovmodel covariates (including constant and age).
                   1963:      lnpijopii=ln(pij/pii)= aij+bij*age+cij*v1+dij*v2+... = sum_nc=1^ncovmodel xij(nc)*cov[nc]
                   1964:      and, according on how parameters are entered, the position of the coefficient xij(nc) of the
                   1965:      ncth covariate in the global vector x is given by the formula:
                   1966:      j<i nc+((i-1)*(nlstate+ndeath-1)+j-1)*ncovmodel
                   1967:      j>=i nc + ((i-1)*(nlstate+ndeath-1)+(j-2))*ncovmodel
                   1968:      Computes ln(pij/pii) (lnpijopii), deduces pij/pii by exponentiation,
                   1969:      sums on j different of i to get 1-pii/pii, deduces pii, and then all pij.
                   1970:      Outputs ps[i][j] the probability to be observed in j being in j according to
                   1971:      the values of the covariates cov[nc] and corresponding parameter values x[nc+shiftij]
                   1972:   */
                   1973:   double s1, lnpijopii;
1.126     brouard  1974:   /*double t34;*/
1.164     brouard  1975:   int i,j, nc, ii, jj;
1.126     brouard  1976: 
                   1977:     for(i=1; i<= nlstate; i++){
                   1978:       for(j=1; j<i;j++){
1.138     brouard  1979:        for (nc=1, lnpijopii=0.;nc <=ncovmodel; nc++){
                   1980:          /*lnpijopii += param[i][j][nc]*cov[nc];*/
                   1981:          lnpijopii += x[nc+((i-1)*(nlstate+ndeath-1)+j-1)*ncovmodel]*cov[nc];
                   1982: /*      printf("Int j<i s1=%.17e, lnpijopii=%.17e\n",s1,lnpijopii); */
1.126     brouard  1983:        }
1.138     brouard  1984:        ps[i][j]=lnpijopii; /* In fact ln(pij/pii) */
                   1985: /*     printf("s1=%.17e, lnpijopii=%.17e\n",s1,lnpijopii); */
1.126     brouard  1986:       }
                   1987:       for(j=i+1; j<=nlstate+ndeath;j++){
1.138     brouard  1988:        for (nc=1, lnpijopii=0.;nc <=ncovmodel; nc++){
                   1989:          /*lnpijopii += x[(i-1)*nlstate*ncovmodel+(j-2)*ncovmodel+nc+(i-1)*(ndeath-1)*ncovmodel]*cov[nc];*/
                   1990:          lnpijopii += x[nc + ((i-1)*(nlstate+ndeath-1)+(j-2))*ncovmodel]*cov[nc];
                   1991: /*       printf("Int j>i s1=%.17e, lnpijopii=%.17e %lx %lx\n",s1,lnpijopii,s1,lnpijopii); */
1.126     brouard  1992:        }
1.138     brouard  1993:        ps[i][j]=lnpijopii; /* In fact ln(pij/pii) */
1.126     brouard  1994:       }
                   1995:     }
                   1996:     
                   1997:     for(i=1; i<= nlstate; i++){
                   1998:       s1=0;
1.131     brouard  1999:       for(j=1; j<i; j++){
1.138     brouard  2000:        s1+=exp(ps[i][j]); /* In fact sums pij/pii */
1.131     brouard  2001:        /*printf("debug1 %d %d ps=%lf exp(ps)=%lf s1+=%lf\n",i,j,ps[i][j],exp(ps[i][j]),s1); */
                   2002:       }
                   2003:       for(j=i+1; j<=nlstate+ndeath; j++){
1.138     brouard  2004:        s1+=exp(ps[i][j]); /* In fact sums pij/pii */
1.131     brouard  2005:        /*printf("debug2 %d %d ps=%lf exp(ps)=%lf s1+=%lf\n",i,j,ps[i][j],exp(ps[i][j]),s1); */
                   2006:       }
1.138     brouard  2007:       /* s1= sum_{j<>i} pij/pii=(1-pii)/pii and thus pii is known from s1 */
1.126     brouard  2008:       ps[i][i]=1./(s1+1.);
1.138     brouard  2009:       /* Computing other pijs */
1.126     brouard  2010:       for(j=1; j<i; j++)
                   2011:        ps[i][j]= exp(ps[i][j])*ps[i][i];
                   2012:       for(j=i+1; j<=nlstate+ndeath; j++)
                   2013:        ps[i][j]= exp(ps[i][j])*ps[i][i];
                   2014:       /* ps[i][nlstate+1]=1.-s1- ps[i][i];*/ /* Sum should be 1 */
                   2015:     } /* end i */
                   2016:     
                   2017:     for(ii=nlstate+1; ii<= nlstate+ndeath; ii++){
                   2018:       for(jj=1; jj<= nlstate+ndeath; jj++){
                   2019:        ps[ii][jj]=0;
                   2020:        ps[ii][ii]=1;
                   2021:       }
                   2022:     }
                   2023:     
1.145     brouard  2024:     
                   2025:     /* for(ii=1; ii<= nlstate+ndeath; ii++){ */
                   2026:     /*   for(jj=1; jj<= nlstate+ndeath; jj++){ */
                   2027:     /*         printf(" pmij  ps[%d][%d]=%lf ",ii,jj,ps[ii][jj]); */
                   2028:     /*   } */
                   2029:     /*   printf("\n "); */
                   2030:     /* } */
                   2031:     /* printf("\n ");printf("%lf ",cov[2]);*/
                   2032:     /*
1.126     brouard  2033:       for(i=1; i<= npar; i++) printf("%f ",x[i]);
                   2034:       goto end;*/
                   2035:     return ps;
                   2036: }
                   2037: 
                   2038: /**************** Product of 2 matrices ******************/
                   2039: 
1.145     brouard  2040: double **matprod2(double **out, double **in,int nrl, int nrh, int ncl, int nch, int ncolol, int ncoloh, double **b)
1.126     brouard  2041: {
                   2042:   /* Computes the matrix product of in(1,nrh-nrl+1)(1,nch-ncl+1) times
                   2043:      b(1,nch-ncl+1)(1,ncoloh-ncolol+1) into out(...) */
                   2044:   /* in, b, out are matrice of pointers which should have been initialized 
                   2045:      before: only the contents of out is modified. The function returns
                   2046:      a pointer to pointers identical to out */
1.145     brouard  2047:   int i, j, k;
1.126     brouard  2048:   for(i=nrl; i<= nrh; i++)
1.145     brouard  2049:     for(k=ncolol; k<=ncoloh; k++){
                   2050:       out[i][k]=0.;
                   2051:       for(j=ncl; j<=nch; j++)
                   2052:        out[i][k] +=in[i][j]*b[j][k];
                   2053:     }
1.126     brouard  2054:   return out;
                   2055: }
                   2056: 
                   2057: 
                   2058: /************* Higher Matrix Product ***************/
                   2059: 
                   2060: double ***hpxij(double ***po, int nhstepm, double age, int hstepm, double *x, int nlstate, int stepm, double **oldm, double **savm, int ij )
                   2061: {
                   2062:   /* Computes the transition matrix starting at age 'age' over 
                   2063:      'nhstepm*hstepm*stepm' months (i.e. until
                   2064:      age (in years)  age+nhstepm*hstepm*stepm/12) by multiplying 
                   2065:      nhstepm*hstepm matrices. 
                   2066:      Output is stored in matrix po[i][j][h] for h every 'hstepm' step 
                   2067:      (typically every 2 years instead of every month which is too big 
                   2068:      for the memory).
                   2069:      Model is determined by parameters x and covariates have to be 
                   2070:      included manually here. 
                   2071: 
                   2072:      */
                   2073: 
                   2074:   int i, j, d, h, k;
1.131     brouard  2075:   double **out, cov[NCOVMAX+1];
1.126     brouard  2076:   double **newm;
1.187     brouard  2077:   double agexact;
1.126     brouard  2078: 
                   2079:   /* Hstepm could be zero and should return the unit matrix */
                   2080:   for (i=1;i<=nlstate+ndeath;i++)
                   2081:     for (j=1;j<=nlstate+ndeath;j++){
                   2082:       oldm[i][j]=(i==j ? 1.0 : 0.0);
                   2083:       po[i][j][0]=(i==j ? 1.0 : 0.0);
                   2084:     }
                   2085:   /* Even if hstepm = 1, at least one multiplication by the unit matrix */
                   2086:   for(h=1; h <=nhstepm; h++){
                   2087:     for(d=1; d <=hstepm; d++){
                   2088:       newm=savm;
                   2089:       /* Covariates have to be included here again */
                   2090:       cov[1]=1.;
1.187     brouard  2091:       agexact=age+((h-1)*hstepm + (d-1))*stepm/YEARM;
                   2092:       cov[2]=agexact;
                   2093:       if(nagesqr==1)
                   2094:        cov[3]= agexact*agexact;
1.131     brouard  2095:       for (k=1; k<=cptcovn;k++) 
1.198     brouard  2096:        cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(ij,Tvar[k])];
1.186     brouard  2097:       for (k=1; k<=cptcovage;k++) /* Should start at cptcovn+1 */
                   2098:        /* cov[2+Tage[k]]=cov[2+Tage[k]]*cov[2]; */
1.198     brouard  2099:        cov[2+nagesqr+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(ij,Tvar[Tage[k]])]*cov[2];
1.145     brouard  2100:       for (k=1; k<=cptcovprod;k++) /* Useless because included in cptcovn */
1.198     brouard  2101:        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  2102: 
                   2103: 
                   2104:       /*printf("hxi cptcov=%d cptcode=%d\n",cptcov,cptcode);*/
                   2105:       /*printf("h=%d d=%d age=%f cov=%f\n",h,d,age,cov[2]);*/
                   2106:       out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, 
                   2107:                   pmij(pmmij,cov,ncovmodel,x,nlstate));
                   2108:       savm=oldm;
                   2109:       oldm=newm;
                   2110:     }
                   2111:     for(i=1; i<=nlstate+ndeath; i++)
                   2112:       for(j=1;j<=nlstate+ndeath;j++) {
                   2113:        po[i][j][h]=newm[i][j];
1.128     brouard  2114:        /*if(h==nhstepm) printf("po[%d][%d][%d]=%f ",i,j,h,po[i][j][h]);*/
1.126     brouard  2115:       }
1.128     brouard  2116:     /*printf("h=%d ",h);*/
1.126     brouard  2117:   } /* end h */
1.128     brouard  2118: /*     printf("\n H=%d \n",h); */
1.126     brouard  2119:   return po;
                   2120: }
                   2121: 
1.162     brouard  2122: #ifdef NLOPT
                   2123:   double  myfunc(unsigned n, const double *p1, double *grad, void *pd){
                   2124:   double fret;
                   2125:   double *xt;
                   2126:   int j;
                   2127:   myfunc_data *d2 = (myfunc_data *) pd;
                   2128: /* xt = (p1-1); */
                   2129:   xt=vector(1,n); 
                   2130:   for (j=1;j<=n;j++)   xt[j]=p1[j-1]; /* xt[1]=p1[0] */
                   2131: 
                   2132:   fret=(d2->function)(xt); /*  p xt[1]@8 is fine */
                   2133:   /* fret=(*func)(xt); /\*  p xt[1]@8 is fine *\/ */
                   2134:   printf("Function = %.12lf ",fret);
                   2135:   for (j=1;j<=n;j++) printf(" %d %.8lf", j, xt[j]); 
                   2136:   printf("\n");
                   2137:  free_vector(xt,1,n);
                   2138:   return fret;
                   2139: }
                   2140: #endif
1.126     brouard  2141: 
                   2142: /*************** log-likelihood *************/
                   2143: double func( double *x)
                   2144: {
                   2145:   int i, ii, j, k, mi, d, kk;
1.131     brouard  2146:   double l, ll[NLSTATEMAX+1], cov[NCOVMAX+1];
1.126     brouard  2147:   double **out;
                   2148:   double sw; /* Sum of weights */
                   2149:   double lli; /* Individual log likelihood */
                   2150:   int s1, s2;
                   2151:   double bbh, survp;
                   2152:   long ipmx;
1.187     brouard  2153:   double agexact;
1.126     brouard  2154:   /*extern weight */
                   2155:   /* We are differentiating ll according to initial status */
                   2156:   /*  for (i=1;i<=npar;i++) printf("%f ", x[i]);*/
                   2157:   /*for(i=1;i<imx;i++) 
                   2158:     printf(" %d\n",s[4][i]);
                   2159:   */
1.162     brouard  2160: 
                   2161:   ++countcallfunc;
                   2162: 
1.126     brouard  2163:   cov[1]=1.;
                   2164: 
                   2165:   for(k=1; k<=nlstate; k++) ll[k]=0.;
                   2166: 
                   2167:   if(mle==1){
                   2168:     for (i=1,ipmx=0, sw=0.; i<=imx; i++){
1.138     brouard  2169:       /* Computes the values of the ncovmodel covariates of the model
                   2170:         depending if the covariates are fixed or variying (age dependent) and stores them in cov[]
                   2171:         Then computes with function pmij which return a matrix p[i][j] giving the elementary probability
                   2172:         to be observed in j being in i according to the model.
                   2173:        */
1.145     brouard  2174:       for (k=1; k<=cptcovn;k++){ /* Simple and product covariates without age* products */
1.187     brouard  2175:          cov[2+nagesqr+k]=covar[Tvar[k]][i];
1.145     brouard  2176:       }
1.137     brouard  2177:       /* In model V2+V1*V4+age*V3+V3*V2 Tvar[1] is V2, Tvar[2=V1*V4] 
1.138     brouard  2178:         is 6, Tvar[3=age*V3] should not be computed because of age Tvar[4=V3*V2] 
1.137     brouard  2179:         has been calculated etc */
1.126     brouard  2180:       for(mi=1; mi<= wav[i]-1; mi++){
                   2181:        for (ii=1;ii<=nlstate+ndeath;ii++)
                   2182:          for (j=1;j<=nlstate+ndeath;j++){
                   2183:            oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   2184:            savm[ii][j]=(ii==j ? 1.0 : 0.0);
                   2185:          }
                   2186:        for(d=0; d<dh[mi][i]; d++){
                   2187:          newm=savm;
1.187     brouard  2188:          agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;
                   2189:          cov[2]=agexact;
                   2190:          if(nagesqr==1)
                   2191:            cov[3]= agexact*agexact;
1.126     brouard  2192:          for (kk=1; kk<=cptcovage;kk++) {
1.187     brouard  2193:            cov[Tage[kk]+2+nagesqr]=covar[Tvar[Tage[kk]]][i]*agexact; /* Tage[kk] gives the data-covariate associated with age */
1.126     brouard  2194:          }
                   2195:          out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
                   2196:                       1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
                   2197:          savm=oldm;
                   2198:          oldm=newm;
                   2199:        } /* end mult */
                   2200:       
                   2201:        /*lli=log(out[s[mw[mi][i]][i]][s[mw[mi+1][i]][i]]);*/ /* Original formula */
                   2202:        /* But now since version 0.9 we anticipate for bias at large stepm.
                   2203:         * If stepm is larger than one month (smallest stepm) and if the exact delay 
                   2204:         * (in months) between two waves is not a multiple of stepm, we rounded to 
                   2205:         * the nearest (and in case of equal distance, to the lowest) interval but now
                   2206:         * we keep into memory the bias bh[mi][i] and also the previous matrix product
                   2207:         * (i.e to dh[mi][i]-1) saved in 'savm'. Then we inter(extra)polate the
                   2208:         * probability in order to take into account the bias as a fraction of the way
                   2209:         * from savm to out if bh is negative or even beyond if bh is positive. bh varies
                   2210:         * -stepm/2 to stepm/2 .
                   2211:         * For stepm=1 the results are the same as for previous versions of Imach.
                   2212:         * For stepm > 1 the results are less biased than in previous versions. 
                   2213:         */
                   2214:        s1=s[mw[mi][i]][i];
                   2215:        s2=s[mw[mi+1][i]][i];
                   2216:        bbh=(double)bh[mi][i]/(double)stepm; 
                   2217:        /* bias bh is positive if real duration
                   2218:         * is higher than the multiple of stepm and negative otherwise.
                   2219:         */
                   2220:        /* lli= (savm[s1][s2]>1.e-8 ?(1.+bbh)*log(out[s1][s2])- bbh*log(savm[s1][s2]):log((1.+bbh)*out[s1][s2]));*/
                   2221:        if( s2 > nlstate){ 
                   2222:          /* i.e. if s2 is a death state and if the date of death is known 
                   2223:             then the contribution to the likelihood is the probability to 
                   2224:             die between last step unit time and current  step unit time, 
                   2225:             which is also equal to probability to die before dh 
                   2226:             minus probability to die before dh-stepm . 
                   2227:             In version up to 0.92 likelihood was computed
                   2228:        as if date of death was unknown. Death was treated as any other
                   2229:        health state: the date of the interview describes the actual state
                   2230:        and not the date of a change in health state. The former idea was
                   2231:        to consider that at each interview the state was recorded
                   2232:        (healthy, disable or death) and IMaCh was corrected; but when we
                   2233:        introduced the exact date of death then we should have modified
                   2234:        the contribution of an exact death to the likelihood. This new
                   2235:        contribution is smaller and very dependent of the step unit
                   2236:        stepm. It is no more the probability to die between last interview
                   2237:        and month of death but the probability to survive from last
                   2238:        interview up to one month before death multiplied by the
                   2239:        probability to die within a month. Thanks to Chris
                   2240:        Jackson for correcting this bug.  Former versions increased
                   2241:        mortality artificially. The bad side is that we add another loop
                   2242:        which slows down the processing. The difference can be up to 10%
                   2243:        lower mortality.
                   2244:          */
1.183     brouard  2245:        /* If, at the beginning of the maximization mostly, the
                   2246:           cumulative probability or probability to be dead is
                   2247:           constant (ie = 1) over time d, the difference is equal to
                   2248:           0.  out[s1][3] = savm[s1][3]: probability, being at state
                   2249:           s1 at precedent wave, to be dead a month before current
                   2250:           wave is equal to probability, being at state s1 at
                   2251:           precedent wave, to be dead at mont of the current
                   2252:           wave. Then the observed probability (that this person died)
                   2253:           is null according to current estimated parameter. In fact,
                   2254:           it should be very low but not zero otherwise the log go to
                   2255:           infinity.
                   2256:        */
                   2257: /* #ifdef INFINITYORIGINAL */
                   2258: /*         lli=log(out[s1][s2] - savm[s1][s2]); */
                   2259: /* #else */
                   2260: /*       if ((out[s1][s2] - savm[s1][s2]) < mytinydouble)  */
                   2261: /*         lli=log(mytinydouble); */
                   2262: /*       else */
                   2263: /*         lli=log(out[s1][s2] - savm[s1][s2]); */
                   2264: /* #endif */
                   2265:            lli=log(out[s1][s2] - savm[s1][s2]);
1.126     brouard  2266: 
                   2267:        } else if  (s2==-2) {
                   2268:          for (j=1,survp=0. ; j<=nlstate; j++) 
                   2269:            survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j];
                   2270:          /*survp += out[s1][j]; */
                   2271:          lli= log(survp);
                   2272:        }
                   2273:        
                   2274:        else if  (s2==-4) { 
                   2275:          for (j=3,survp=0. ; j<=nlstate; j++)  
                   2276:            survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j];
                   2277:          lli= log(survp); 
                   2278:        } 
                   2279: 
                   2280:        else if  (s2==-5) { 
                   2281:          for (j=1,survp=0. ; j<=2; j++)  
                   2282:            survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j];
                   2283:          lli= log(survp); 
                   2284:        } 
                   2285:        
                   2286:        else{
                   2287:          lli= log((1.+bbh)*out[s1][s2]- bbh*savm[s1][s2]); /* linear interpolation */
                   2288:          /*  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 */
                   2289:        } 
                   2290:        /*lli=(1.+bbh)*log(out[s1][s2])- bbh*log(savm[s1][s2]);*/
                   2291:        /*if(lli ==000.0)*/
                   2292:        /*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); */
                   2293:        ipmx +=1;
                   2294:        sw += weight[i];
                   2295:        ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
1.183     brouard  2296:        /* if (lli < log(mytinydouble)){ */
                   2297:        /*   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); */
                   2298:        /*   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]); */
                   2299:        /* } */
1.126     brouard  2300:       } /* end of wave */
                   2301:     } /* end of individual */
                   2302:   }  else if(mle==2){
                   2303:     for (i=1,ipmx=0, sw=0.; i<=imx; i++){
1.187     brouard  2304:       for (k=1; k<=cptcovn;k++) cov[2+nagesqr+k]=covar[Tvar[k]][i];
1.126     brouard  2305:       for(mi=1; mi<= wav[i]-1; mi++){
                   2306:        for (ii=1;ii<=nlstate+ndeath;ii++)
                   2307:          for (j=1;j<=nlstate+ndeath;j++){
                   2308:            oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   2309:            savm[ii][j]=(ii==j ? 1.0 : 0.0);
                   2310:          }
                   2311:        for(d=0; d<=dh[mi][i]; d++){
                   2312:          newm=savm;
1.187     brouard  2313:          agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;
                   2314:          cov[2]=agexact;
                   2315:          if(nagesqr==1)
                   2316:            cov[3]= agexact*agexact;
1.126     brouard  2317:          for (kk=1; kk<=cptcovage;kk++) {
1.187     brouard  2318:            cov[Tage[kk]+2+nagesqr]=covar[Tvar[Tage[kk]]][i]*agexact;
1.126     brouard  2319:          }
                   2320:          out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
                   2321:                       1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
                   2322:          savm=oldm;
                   2323:          oldm=newm;
                   2324:        } /* end mult */
                   2325:       
                   2326:        s1=s[mw[mi][i]][i];
                   2327:        s2=s[mw[mi+1][i]][i];
                   2328:        bbh=(double)bh[mi][i]/(double)stepm; 
                   2329:        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 */
                   2330:        ipmx +=1;
                   2331:        sw += weight[i];
                   2332:        ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
                   2333:       } /* end of wave */
                   2334:     } /* end of individual */
                   2335:   }  else if(mle==3){  /* exponential inter-extrapolation */
                   2336:     for (i=1,ipmx=0, sw=0.; i<=imx; i++){
1.187     brouard  2337:       for (k=1; k<=cptcovn;k++) cov[2+nagesqr+k]=covar[Tvar[k]][i];
1.126     brouard  2338:       for(mi=1; mi<= wav[i]-1; mi++){
                   2339:        for (ii=1;ii<=nlstate+ndeath;ii++)
                   2340:          for (j=1;j<=nlstate+ndeath;j++){
                   2341:            oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   2342:            savm[ii][j]=(ii==j ? 1.0 : 0.0);
                   2343:          }
                   2344:        for(d=0; d<dh[mi][i]; d++){
                   2345:          newm=savm;
1.187     brouard  2346:          agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;
                   2347:          cov[2]=agexact;
                   2348:          if(nagesqr==1)
                   2349:            cov[3]= agexact*agexact;
1.126     brouard  2350:          for (kk=1; kk<=cptcovage;kk++) {
1.187     brouard  2351:            cov[Tage[kk]+2+nagesqr]=covar[Tvar[Tage[kk]]][i]*agexact;
1.126     brouard  2352:          }
                   2353:          out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
                   2354:                       1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
                   2355:          savm=oldm;
                   2356:          oldm=newm;
                   2357:        } /* end mult */
                   2358:       
                   2359:        s1=s[mw[mi][i]][i];
                   2360:        s2=s[mw[mi+1][i]][i];
                   2361:        bbh=(double)bh[mi][i]/(double)stepm; 
                   2362:        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 */
                   2363:        ipmx +=1;
                   2364:        sw += weight[i];
                   2365:        ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
                   2366:       } /* end of wave */
                   2367:     } /* end of individual */
                   2368:   }else if (mle==4){  /* ml=4 no inter-extrapolation */
                   2369:     for (i=1,ipmx=0, sw=0.; i<=imx; i++){
1.187     brouard  2370:       for (k=1; k<=cptcovn;k++) cov[2+nagesqr+k]=covar[Tvar[k]][i];
1.126     brouard  2371:       for(mi=1; mi<= wav[i]-1; mi++){
                   2372:        for (ii=1;ii<=nlstate+ndeath;ii++)
                   2373:          for (j=1;j<=nlstate+ndeath;j++){
                   2374:            oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   2375:            savm[ii][j]=(ii==j ? 1.0 : 0.0);
                   2376:          }
                   2377:        for(d=0; d<dh[mi][i]; d++){
                   2378:          newm=savm;
1.187     brouard  2379:          agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;
                   2380:          cov[2]=agexact;
                   2381:          if(nagesqr==1)
                   2382:            cov[3]= agexact*agexact;
1.126     brouard  2383:          for (kk=1; kk<=cptcovage;kk++) {
1.187     brouard  2384:            cov[Tage[kk]+2+nagesqr]=covar[Tvar[Tage[kk]]][i]*agexact;
1.126     brouard  2385:          }
                   2386:        
                   2387:          out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
                   2388:                       1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
                   2389:          savm=oldm;
                   2390:          oldm=newm;
                   2391:        } /* end mult */
                   2392:       
                   2393:        s1=s[mw[mi][i]][i];
                   2394:        s2=s[mw[mi+1][i]][i];
                   2395:        if( s2 > nlstate){ 
                   2396:          lli=log(out[s1][s2] - savm[s1][s2]);
                   2397:        }else{
                   2398:          lli=log(out[s[mw[mi][i]][i]][s[mw[mi+1][i]][i]]); /* Original formula */
                   2399:        }
                   2400:        ipmx +=1;
                   2401:        sw += weight[i];
                   2402:        ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
                   2403: /*     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]); */
                   2404:       } /* end of wave */
                   2405:     } /* end of individual */
                   2406:   }else{  /* ml=5 no inter-extrapolation no jackson =0.8a */
                   2407:     for (i=1,ipmx=0, sw=0.; i<=imx; i++){
1.187     brouard  2408:       for (k=1; k<=cptcovn;k++) cov[2+nagesqr+k]=covar[Tvar[k]][i];
1.126     brouard  2409:       for(mi=1; mi<= wav[i]-1; mi++){
                   2410:        for (ii=1;ii<=nlstate+ndeath;ii++)
                   2411:          for (j=1;j<=nlstate+ndeath;j++){
                   2412:            oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   2413:            savm[ii][j]=(ii==j ? 1.0 : 0.0);
                   2414:          }
                   2415:        for(d=0; d<dh[mi][i]; d++){
                   2416:          newm=savm;
1.187     brouard  2417:          agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;
                   2418:          cov[2]=agexact;
                   2419:          if(nagesqr==1)
                   2420:            cov[3]= agexact*agexact;
1.126     brouard  2421:          for (kk=1; kk<=cptcovage;kk++) {
1.187     brouard  2422:            cov[Tage[kk]+2+nagesqr]=covar[Tvar[Tage[kk]]][i]*agexact;
1.126     brouard  2423:          }
                   2424:        
                   2425:          out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
                   2426:                       1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
                   2427:          savm=oldm;
                   2428:          oldm=newm;
                   2429:        } /* end mult */
                   2430:       
                   2431:        s1=s[mw[mi][i]][i];
                   2432:        s2=s[mw[mi+1][i]][i];
                   2433:        lli=log(out[s[mw[mi][i]][i]][s[mw[mi+1][i]][i]]); /* Original formula */
                   2434:        ipmx +=1;
                   2435:        sw += weight[i];
                   2436:        ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
                   2437:        /*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]);*/
                   2438:       } /* end of wave */
                   2439:     } /* end of individual */
                   2440:   } /* End of if */
                   2441:   for(k=1,l=0.; k<=nlstate; k++) l += ll[k];
                   2442:   /* printf("l1=%f l2=%f ",ll[1],ll[2]); */
                   2443:   l= l*ipmx/sw; /* To get the same order of magnitude as if weight=1 for every body */
                   2444:   return -l;
                   2445: }
                   2446: 
                   2447: /*************** log-likelihood *************/
                   2448: double funcone( double *x)
                   2449: {
                   2450:   /* Same as likeli but slower because of a lot of printf and if */
                   2451:   int i, ii, j, k, mi, d, kk;
1.131     brouard  2452:   double l, ll[NLSTATEMAX+1], cov[NCOVMAX+1];
1.126     brouard  2453:   double **out;
                   2454:   double lli; /* Individual log likelihood */
                   2455:   double llt;
                   2456:   int s1, s2;
                   2457:   double bbh, survp;
1.187     brouard  2458:   double agexact;
1.126     brouard  2459:   /*extern weight */
                   2460:   /* We are differentiating ll according to initial status */
                   2461:   /*  for (i=1;i<=npar;i++) printf("%f ", x[i]);*/
                   2462:   /*for(i=1;i<imx;i++) 
                   2463:     printf(" %d\n",s[4][i]);
                   2464:   */
                   2465:   cov[1]=1.;
                   2466: 
                   2467:   for(k=1; k<=nlstate; k++) ll[k]=0.;
                   2468: 
                   2469:   for (i=1,ipmx=0, sw=0.; i<=imx; i++){
1.187     brouard  2470:     for (k=1; k<=cptcovn;k++) cov[2+nagesqr+k]=covar[Tvar[k]][i];
1.126     brouard  2471:     for(mi=1; mi<= wav[i]-1; mi++){
                   2472:       for (ii=1;ii<=nlstate+ndeath;ii++)
                   2473:        for (j=1;j<=nlstate+ndeath;j++){
                   2474:          oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   2475:          savm[ii][j]=(ii==j ? 1.0 : 0.0);
                   2476:        }
                   2477:       for(d=0; d<dh[mi][i]; d++){
                   2478:        newm=savm;
1.187     brouard  2479:        agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;
                   2480:        cov[2]=agexact;
                   2481:        if(nagesqr==1)
                   2482:          cov[3]= agexact*agexact;
1.126     brouard  2483:        for (kk=1; kk<=cptcovage;kk++) {
1.187     brouard  2484:          cov[Tage[kk]+2+nagesqr]=covar[Tvar[Tage[kk]]][i]*agexact;
1.126     brouard  2485:        }
1.187     brouard  2486: 
1.145     brouard  2487:        /* savm=pmij(pmmij,cov,ncovmodel,x,nlstate); */
1.126     brouard  2488:        out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
                   2489:                     1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
1.145     brouard  2490:        /* out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath, */
                   2491:        /*           1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate)); */
1.126     brouard  2492:        savm=oldm;
                   2493:        oldm=newm;
                   2494:       } /* end mult */
                   2495:       
                   2496:       s1=s[mw[mi][i]][i];
                   2497:       s2=s[mw[mi+1][i]][i];
                   2498:       bbh=(double)bh[mi][i]/(double)stepm; 
                   2499:       /* bias is positive if real duration
                   2500:        * is higher than the multiple of stepm and negative otherwise.
                   2501:        */
                   2502:       if( s2 > nlstate && (mle <5) ){  /* Jackson */
                   2503:        lli=log(out[s1][s2] - savm[s1][s2]);
                   2504:       } else if  (s2==-2) {
                   2505:        for (j=1,survp=0. ; j<=nlstate; j++) 
                   2506:          survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j];
                   2507:        lli= log(survp);
                   2508:       }else if (mle==1){
                   2509:        lli= log((1.+bbh)*out[s1][s2]- bbh*savm[s1][s2]); /* linear interpolation */
                   2510:       } else if(mle==2){
                   2511:        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 */
                   2512:       } else if(mle==3){  /* exponential inter-extrapolation */
                   2513:        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 */
                   2514:       } else if (mle==4){  /* mle=4 no inter-extrapolation */
                   2515:        lli=log(out[s1][s2]); /* Original formula */
1.136     brouard  2516:       } else{  /* mle=0 back to 1 */
                   2517:        lli= log((1.+bbh)*out[s1][s2]- bbh*savm[s1][s2]); /* linear interpolation */
                   2518:        /*lli=log(out[s1][s2]); */ /* Original formula */
1.126     brouard  2519:       } /* End of if */
                   2520:       ipmx +=1;
                   2521:       sw += weight[i];
                   2522:       ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
1.132     brouard  2523:       /*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  2524:       if(globpr){
1.141     brouard  2525:        fprintf(ficresilk,"%9ld %6d %2d %2d %1d %1d %3d %11.6f %8.4f\
1.126     brouard  2526:  %11.6f %11.6f %11.6f ", \
                   2527:                num[i],i,s1,s2,mi,mw[mi][i],dh[mi][i],exp(lli),weight[i],
                   2528:                2*weight[i]*lli,out[s1][s2],savm[s1][s2]);
                   2529:        for(k=1,llt=0.,l=0.; k<=nlstate; k++){
                   2530:          llt +=ll[k]*gipmx/gsw;
                   2531:          fprintf(ficresilk," %10.6f",-ll[k]*gipmx/gsw);
                   2532:        }
                   2533:        fprintf(ficresilk," %10.6f\n", -llt);
                   2534:       }
                   2535:     } /* end of wave */
                   2536:   } /* end of individual */
                   2537:   for(k=1,l=0.; k<=nlstate; k++) l += ll[k];
                   2538:   /* printf("l1=%f l2=%f ",ll[1],ll[2]); */
                   2539:   l= l*ipmx/sw; /* To get the same order of magnitude as if weight=1 for every body */
                   2540:   if(globpr==0){ /* First time we count the contributions and weights */
                   2541:     gipmx=ipmx;
                   2542:     gsw=sw;
                   2543:   }
                   2544:   return -l;
                   2545: }
                   2546: 
                   2547: 
                   2548: /*************** function likelione ***********/
                   2549: void likelione(FILE *ficres,double p[], int npar, int nlstate, int *globpri, long *ipmx, double *sw, double *fretone, double (*funcone)(double []))
                   2550: {
                   2551:   /* This routine should help understanding what is done with 
                   2552:      the selection of individuals/waves and
                   2553:      to check the exact contribution to the likelihood.
                   2554:      Plotting could be done.
                   2555:    */
                   2556:   int k;
                   2557: 
                   2558:   if(*globpri !=0){ /* Just counts and sums, no printings */
                   2559:     strcpy(fileresilk,"ilk"); 
                   2560:     strcat(fileresilk,fileres);
                   2561:     if((ficresilk=fopen(fileresilk,"w"))==NULL) {
                   2562:       printf("Problem with resultfile: %s\n", fileresilk);
                   2563:       fprintf(ficlog,"Problem with resultfile: %s\n", fileresilk);
                   2564:     }
                   2565:     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");
                   2566:     fprintf(ficresilk, "#num_i i s1 s2 mi mw dh likeli weight 2wlli out sav ");
                   2567:     /*         i,s1,s2,mi,mw[mi][i],dh[mi][i],exp(lli),weight[i],2*weight[i]*lli,out[s1][s2],savm[s1][s2]); */
                   2568:     for(k=1; k<=nlstate; k++) 
                   2569:       fprintf(ficresilk," -2*gipw/gsw*weight*ll[%d]++",k);
                   2570:     fprintf(ficresilk," -2*gipw/gsw*weight*ll(total)\n");
                   2571:   }
                   2572: 
                   2573:   *fretone=(*funcone)(p);
                   2574:   if(*globpri !=0){
                   2575:     fclose(ficresilk);
                   2576:     fprintf(fichtm,"\n<br>File of contributions to the likelihood: <a href=\"%s\">%s</a><br>\n",subdirf(fileresilk),subdirf(fileresilk));
                   2577:     fflush(fichtm); 
                   2578:   } 
                   2579:   return;
                   2580: }
                   2581: 
                   2582: 
                   2583: /*********** Maximum Likelihood Estimation ***************/
                   2584: 
                   2585: void mlikeli(FILE *ficres,double p[], int npar, int ncovmodel, int nlstate, double ftol, double (*func)(double []))
                   2586: {
1.165     brouard  2587:   int i,j, iter=0;
1.126     brouard  2588:   double **xi;
                   2589:   double fret;
                   2590:   double fretone; /* Only one call to likelihood */
                   2591:   /*  char filerespow[FILENAMELENGTH];*/
1.162     brouard  2592: 
                   2593: #ifdef NLOPT
                   2594:   int creturn;
                   2595:   nlopt_opt opt;
                   2596:   /* double lb[9] = { -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL }; /\* lower bounds *\/ */
                   2597:   double *lb;
                   2598:   double minf; /* the minimum objective value, upon return */
                   2599:   double * p1; /* Shifted parameters from 0 instead of 1 */
                   2600:   myfunc_data dinst, *d = &dinst;
                   2601: #endif
                   2602: 
                   2603: 
1.126     brouard  2604:   xi=matrix(1,npar,1,npar);
                   2605:   for (i=1;i<=npar;i++)
                   2606:     for (j=1;j<=npar;j++)
                   2607:       xi[i][j]=(i==j ? 1.0 : 0.0);
                   2608:   printf("Powell\n");  fprintf(ficlog,"Powell\n");
                   2609:   strcpy(filerespow,"pow"); 
                   2610:   strcat(filerespow,fileres);
                   2611:   if((ficrespow=fopen(filerespow,"w"))==NULL) {
                   2612:     printf("Problem with resultfile: %s\n", filerespow);
                   2613:     fprintf(ficlog,"Problem with resultfile: %s\n", filerespow);
                   2614:   }
                   2615:   fprintf(ficrespow,"# Powell\n# iter -2*LL");
                   2616:   for (i=1;i<=nlstate;i++)
                   2617:     for(j=1;j<=nlstate+ndeath;j++)
                   2618:       if(j!=i)fprintf(ficrespow," p%1d%1d",i,j);
                   2619:   fprintf(ficrespow,"\n");
1.162     brouard  2620: #ifdef POWELL
1.126     brouard  2621:   powell(p,xi,npar,ftol,&iter,&fret,func);
1.162     brouard  2622: #endif
1.126     brouard  2623: 
1.162     brouard  2624: #ifdef NLOPT
                   2625: #ifdef NEWUOA
                   2626:   opt = nlopt_create(NLOPT_LN_NEWUOA,npar);
                   2627: #else
                   2628:   opt = nlopt_create(NLOPT_LN_BOBYQA,npar);
                   2629: #endif
                   2630:   lb=vector(0,npar-1);
                   2631:   for (i=0;i<npar;i++) lb[i]= -HUGE_VAL;
                   2632:   nlopt_set_lower_bounds(opt, lb);
                   2633:   nlopt_set_initial_step1(opt, 0.1);
                   2634:   
                   2635:   p1= (p+1); /*  p *(p+1)@8 and p *(p1)@8 are equal p1[0]=p[1] */
                   2636:   d->function = func;
                   2637:   printf(" Func %.12lf \n",myfunc(npar,p1,NULL,d));
                   2638:   nlopt_set_min_objective(opt, myfunc, d);
                   2639:   nlopt_set_xtol_rel(opt, ftol);
                   2640:   if ((creturn=nlopt_optimize(opt, p1, &minf)) < 0) {
                   2641:     printf("nlopt failed! %d\n",creturn); 
                   2642:   }
                   2643:   else {
                   2644:     printf("found minimum after %d evaluations (NLOPT=%d)\n", countcallfunc ,NLOPT);
                   2645:     printf("found minimum at f(%g,%g) = %0.10g\n", p[0], p[1], minf);
                   2646:     iter=1; /* not equal */
                   2647:   }
                   2648:   nlopt_destroy(opt);
                   2649: #endif
1.126     brouard  2650:   free_matrix(xi,1,npar,1,npar);
                   2651:   fclose(ficrespow);
1.180     brouard  2652:   printf("#Number of iterations & function calls = %d & %d, -2 Log likelihood = %.12f\n",iter, countcallfunc,func(p));
                   2653:   fprintf(ficlog,"#Number of iterations & function calls = %d & %d, -2 Log likelihood = %.12f\n",iter, countcallfunc,func(p));
                   2654:   fprintf(ficres,"#Number of iterations & function calls = %d & %d, -2 Log likelihood = %.12f\n",iter, countcallfunc,func(p));
1.126     brouard  2655: 
                   2656: }
                   2657: 
                   2658: /**** Computes Hessian and covariance matrix ***/
                   2659: void hesscov(double **matcov, double p[], int npar, double delti[], double ftolhess, double (*func)(double []))
                   2660: {
                   2661:   double  **a,**y,*x,pd;
                   2662:   double **hess;
1.164     brouard  2663:   int i, j;
1.126     brouard  2664:   int *indx;
                   2665: 
                   2666:   double hessii(double p[], double delta, int theta, double delti[],double (*func)(double []),int npar);
                   2667:   double hessij(double p[], double delti[], int i, int j,double (*func)(double []),int npar);
                   2668:   void lubksb(double **a, int npar, int *indx, double b[]) ;
                   2669:   void ludcmp(double **a, int npar, int *indx, double *d) ;
                   2670:   double gompertz(double p[]);
                   2671:   hess=matrix(1,npar,1,npar);
                   2672: 
                   2673:   printf("\nCalculation of the hessian matrix. Wait...\n");
                   2674:   fprintf(ficlog,"\nCalculation of the hessian matrix. Wait...\n");
                   2675:   for (i=1;i<=npar;i++){
                   2676:     printf("%d",i);fflush(stdout);
                   2677:     fprintf(ficlog,"%d",i);fflush(ficlog);
                   2678:    
                   2679:      hess[i][i]=hessii(p,ftolhess,i,delti,func,npar);
                   2680:     
                   2681:     /*  printf(" %f ",p[i]);
                   2682:        printf(" %lf %lf %lf",hess[i][i],ftolhess,delti[i]);*/
                   2683:   }
                   2684:   
                   2685:   for (i=1;i<=npar;i++) {
                   2686:     for (j=1;j<=npar;j++)  {
                   2687:       if (j>i) { 
                   2688:        printf(".%d%d",i,j);fflush(stdout);
                   2689:        fprintf(ficlog,".%d%d",i,j);fflush(ficlog);
                   2690:        hess[i][j]=hessij(p,delti,i,j,func,npar);
                   2691:        
                   2692:        hess[j][i]=hess[i][j];    
                   2693:        /*printf(" %lf ",hess[i][j]);*/
                   2694:       }
                   2695:     }
                   2696:   }
                   2697:   printf("\n");
                   2698:   fprintf(ficlog,"\n");
                   2699: 
                   2700:   printf("\nInverting the hessian to get the covariance matrix. Wait...\n");
                   2701:   fprintf(ficlog,"\nInverting the hessian to get the covariance matrix. Wait...\n");
                   2702:   
                   2703:   a=matrix(1,npar,1,npar);
                   2704:   y=matrix(1,npar,1,npar);
                   2705:   x=vector(1,npar);
                   2706:   indx=ivector(1,npar);
                   2707:   for (i=1;i<=npar;i++)
                   2708:     for (j=1;j<=npar;j++) a[i][j]=hess[i][j];
                   2709:   ludcmp(a,npar,indx,&pd);
                   2710: 
                   2711:   for (j=1;j<=npar;j++) {
                   2712:     for (i=1;i<=npar;i++) x[i]=0;
                   2713:     x[j]=1;
                   2714:     lubksb(a,npar,indx,x);
                   2715:     for (i=1;i<=npar;i++){ 
                   2716:       matcov[i][j]=x[i];
                   2717:     }
                   2718:   }
                   2719: 
                   2720:   printf("\n#Hessian matrix#\n");
                   2721:   fprintf(ficlog,"\n#Hessian matrix#\n");
                   2722:   for (i=1;i<=npar;i++) { 
                   2723:     for (j=1;j<=npar;j++) { 
                   2724:       printf("%.3e ",hess[i][j]);
                   2725:       fprintf(ficlog,"%.3e ",hess[i][j]);
                   2726:     }
                   2727:     printf("\n");
                   2728:     fprintf(ficlog,"\n");
                   2729:   }
                   2730: 
                   2731:   /* Recompute Inverse */
                   2732:   for (i=1;i<=npar;i++)
                   2733:     for (j=1;j<=npar;j++) a[i][j]=matcov[i][j];
                   2734:   ludcmp(a,npar,indx,&pd);
                   2735: 
                   2736:   /*  printf("\n#Hessian matrix recomputed#\n");
                   2737: 
                   2738:   for (j=1;j<=npar;j++) {
                   2739:     for (i=1;i<=npar;i++) x[i]=0;
                   2740:     x[j]=1;
                   2741:     lubksb(a,npar,indx,x);
                   2742:     for (i=1;i<=npar;i++){ 
                   2743:       y[i][j]=x[i];
                   2744:       printf("%.3e ",y[i][j]);
                   2745:       fprintf(ficlog,"%.3e ",y[i][j]);
                   2746:     }
                   2747:     printf("\n");
                   2748:     fprintf(ficlog,"\n");
                   2749:   }
                   2750:   */
                   2751: 
                   2752:   free_matrix(a,1,npar,1,npar);
                   2753:   free_matrix(y,1,npar,1,npar);
                   2754:   free_vector(x,1,npar);
                   2755:   free_ivector(indx,1,npar);
                   2756:   free_matrix(hess,1,npar,1,npar);
                   2757: 
                   2758: 
                   2759: }
                   2760: 
                   2761: /*************** hessian matrix ****************/
                   2762: double hessii(double x[], double delta, int theta, double delti[], double (*func)(double []), int npar)
                   2763: {
                   2764:   int i;
                   2765:   int l=1, lmax=20;
                   2766:   double k1,k2;
1.132     brouard  2767:   double p2[MAXPARM+1]; /* identical to x */
1.126     brouard  2768:   double res;
                   2769:   double delt=0.0001, delts, nkhi=10.,nkhif=1., khi=1.e-4;
                   2770:   double fx;
                   2771:   int k=0,kmax=10;
                   2772:   double l1;
                   2773: 
                   2774:   fx=func(x);
                   2775:   for (i=1;i<=npar;i++) p2[i]=x[i];
1.145     brouard  2776:   for(l=0 ; l <=lmax; l++){  /* Enlarging the zone around the Maximum */
1.126     brouard  2777:     l1=pow(10,l);
                   2778:     delts=delt;
                   2779:     for(k=1 ; k <kmax; k=k+1){
                   2780:       delt = delta*(l1*k);
                   2781:       p2[theta]=x[theta] +delt;
1.145     brouard  2782:       k1=func(p2)-fx;   /* Might be negative if too close to the theoretical maximum */
1.126     brouard  2783:       p2[theta]=x[theta]-delt;
                   2784:       k2=func(p2)-fx;
                   2785:       /*res= (k1-2.0*fx+k2)/delt/delt; */
                   2786:       res= (k1+k2)/delt/delt/2.; /* Divided by because L and not 2*L */
                   2787:       
1.132     brouard  2788: #ifdef DEBUGHESS
1.126     brouard  2789:       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);
                   2790:       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);
                   2791: #endif
                   2792:       /*if(fabs(k1-2.0*fx+k2) <1.e-13){ */
                   2793:       if((k1 <khi/nkhi/2.) || (k2 <khi/nkhi/2.)){
                   2794:        k=kmax;
                   2795:       }
                   2796:       else if((k1 >khi/nkhif) || (k2 >khi/nkhif)){ /* Keeps lastvalue before 3.84/2 KHI2 5% 1d.f. */
1.164     brouard  2797:        k=kmax; l=lmax*10;
1.126     brouard  2798:       }
                   2799:       else if((k1 >khi/nkhi) || (k2 >khi/nkhi)){ 
                   2800:        delts=delt;
                   2801:       }
                   2802:     }
                   2803:   }
                   2804:   delti[theta]=delts;
                   2805:   return res; 
                   2806:   
                   2807: }
                   2808: 
                   2809: double hessij( double x[], double delti[], int thetai,int thetaj,double (*func)(double []),int npar)
                   2810: {
                   2811:   int i;
1.164     brouard  2812:   int l=1, lmax=20;
1.126     brouard  2813:   double k1,k2,k3,k4,res,fx;
1.132     brouard  2814:   double p2[MAXPARM+1];
1.126     brouard  2815:   int k;
                   2816: 
                   2817:   fx=func(x);
                   2818:   for (k=1; k<=2; k++) {
                   2819:     for (i=1;i<=npar;i++) p2[i]=x[i];
                   2820:     p2[thetai]=x[thetai]+delti[thetai]/k;
                   2821:     p2[thetaj]=x[thetaj]+delti[thetaj]/k;
                   2822:     k1=func(p2)-fx;
                   2823:   
                   2824:     p2[thetai]=x[thetai]+delti[thetai]/k;
                   2825:     p2[thetaj]=x[thetaj]-delti[thetaj]/k;
                   2826:     k2=func(p2)-fx;
                   2827:   
                   2828:     p2[thetai]=x[thetai]-delti[thetai]/k;
                   2829:     p2[thetaj]=x[thetaj]+delti[thetaj]/k;
                   2830:     k3=func(p2)-fx;
                   2831:   
                   2832:     p2[thetai]=x[thetai]-delti[thetai]/k;
                   2833:     p2[thetaj]=x[thetaj]-delti[thetaj]/k;
                   2834:     k4=func(p2)-fx;
                   2835:     res=(k1-k2-k3+k4)/4.0/delti[thetai]*k/delti[thetaj]*k/2.; /* Because of L not 2*L */
                   2836: #ifdef DEBUG
                   2837:     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);
                   2838:     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);
                   2839: #endif
                   2840:   }
                   2841:   return res;
                   2842: }
                   2843: 
                   2844: /************** Inverse of matrix **************/
                   2845: void ludcmp(double **a, int n, int *indx, double *d) 
                   2846: { 
                   2847:   int i,imax,j,k; 
                   2848:   double big,dum,sum,temp; 
                   2849:   double *vv; 
                   2850:  
                   2851:   vv=vector(1,n); 
                   2852:   *d=1.0; 
                   2853:   for (i=1;i<=n;i++) { 
                   2854:     big=0.0; 
                   2855:     for (j=1;j<=n;j++) 
                   2856:       if ((temp=fabs(a[i][j])) > big) big=temp; 
                   2857:     if (big == 0.0) nrerror("Singular matrix in routine ludcmp"); 
                   2858:     vv[i]=1.0/big; 
                   2859:   } 
                   2860:   for (j=1;j<=n;j++) { 
                   2861:     for (i=1;i<j;i++) { 
                   2862:       sum=a[i][j]; 
                   2863:       for (k=1;k<i;k++) sum -= a[i][k]*a[k][j]; 
                   2864:       a[i][j]=sum; 
                   2865:     } 
                   2866:     big=0.0; 
                   2867:     for (i=j;i<=n;i++) { 
                   2868:       sum=a[i][j]; 
                   2869:       for (k=1;k<j;k++) 
                   2870:        sum -= a[i][k]*a[k][j]; 
                   2871:       a[i][j]=sum; 
                   2872:       if ( (dum=vv[i]*fabs(sum)) >= big) { 
                   2873:        big=dum; 
                   2874:        imax=i; 
                   2875:       } 
                   2876:     } 
                   2877:     if (j != imax) { 
                   2878:       for (k=1;k<=n;k++) { 
                   2879:        dum=a[imax][k]; 
                   2880:        a[imax][k]=a[j][k]; 
                   2881:        a[j][k]=dum; 
                   2882:       } 
                   2883:       *d = -(*d); 
                   2884:       vv[imax]=vv[j]; 
                   2885:     } 
                   2886:     indx[j]=imax; 
                   2887:     if (a[j][j] == 0.0) a[j][j]=TINY; 
                   2888:     if (j != n) { 
                   2889:       dum=1.0/(a[j][j]); 
                   2890:       for (i=j+1;i<=n;i++) a[i][j] *= dum; 
                   2891:     } 
                   2892:   } 
                   2893:   free_vector(vv,1,n);  /* Doesn't work */
                   2894: ;
                   2895: } 
                   2896: 
                   2897: void lubksb(double **a, int n, int *indx, double b[]) 
                   2898: { 
                   2899:   int i,ii=0,ip,j; 
                   2900:   double sum; 
                   2901:  
                   2902:   for (i=1;i<=n;i++) { 
                   2903:     ip=indx[i]; 
                   2904:     sum=b[ip]; 
                   2905:     b[ip]=b[i]; 
                   2906:     if (ii) 
                   2907:       for (j=ii;j<=i-1;j++) sum -= a[i][j]*b[j]; 
                   2908:     else if (sum) ii=i; 
                   2909:     b[i]=sum; 
                   2910:   } 
                   2911:   for (i=n;i>=1;i--) { 
                   2912:     sum=b[i]; 
                   2913:     for (j=i+1;j<=n;j++) sum -= a[i][j]*b[j]; 
                   2914:     b[i]=sum/a[i][i]; 
                   2915:   } 
                   2916: } 
                   2917: 
                   2918: void pstamp(FILE *fichier)
                   2919: {
1.196     brouard  2920:   fprintf(fichier,"# %s.%s\n#IMaCh version %s, %s\n#%s\n# %s", optionfilefiname,optionfilext,version,copyright, fullversion, strstart);
1.126     brouard  2921: }
                   2922: 
                   2923: /************ Frequencies ********************/
                   2924: 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[])
                   2925: {  /* Some frequencies */
                   2926:   
1.164     brouard  2927:   int i, m, jk, j1, bool, z1,j;
1.126     brouard  2928:   int first;
                   2929:   double ***freq; /* Frequencies */
                   2930:   double *pp, **prop;
                   2931:   double pos,posprop, k2, dateintsum=0,k2cpt=0;
                   2932:   char fileresp[FILENAMELENGTH];
                   2933:   
                   2934:   pp=vector(1,nlstate);
                   2935:   prop=matrix(1,nlstate,iagemin,iagemax+3);
                   2936:   strcpy(fileresp,"p");
                   2937:   strcat(fileresp,fileres);
                   2938:   if((ficresp=fopen(fileresp,"w"))==NULL) {
                   2939:     printf("Problem with prevalence resultfile: %s\n", fileresp);
                   2940:     fprintf(ficlog,"Problem with prevalence resultfile: %s\n", fileresp);
                   2941:     exit(0);
                   2942:   }
                   2943:   freq= ma3x(-5,nlstate+ndeath,-5,nlstate+ndeath,iagemin,iagemax+3);
                   2944:   j1=0;
                   2945:   
                   2946:   j=cptcoveff;
                   2947:   if (cptcovn<1) {j=1;ncodemax[1]=1;}
                   2948: 
                   2949:   first=1;
                   2950: 
1.169     brouard  2951:   /* for(k1=1; k1<=j ; k1++){ */  /* Loop on covariates */
                   2952:   /*  for(i1=1; i1<=ncodemax[k1];i1++){ */ /* Now it is 2 */
                   2953:   /*    j1++; */
1.145     brouard  2954:   for (j1 = 1; j1 <= (int) pow(2,cptcoveff); j1++){
1.126     brouard  2955:       /*printf("cptcoveff=%d Tvaraff=%d", cptcoveff,Tvaraff[1]);
                   2956:        scanf("%d", i);*/
                   2957:       for (i=-5; i<=nlstate+ndeath; i++)  
                   2958:        for (jk=-5; jk<=nlstate+ndeath; jk++)  
                   2959:          for(m=iagemin; m <= iagemax+3; m++)
                   2960:            freq[i][jk][m]=0;
1.143     brouard  2961:       
                   2962:       for (i=1; i<=nlstate; i++)  
                   2963:        for(m=iagemin; m <= iagemax+3; m++)
                   2964:          prop[i][m]=0;
1.126     brouard  2965:       
                   2966:       dateintsum=0;
                   2967:       k2cpt=0;
                   2968:       for (i=1; i<=imx; i++) {
                   2969:        bool=1;
1.144     brouard  2970:        if  (cptcovn>0) { /* Filter is here: Must be looked at for model=V1+V2+V3+V4 */
                   2971:          for (z1=1; z1<=cptcoveff; z1++)       
1.198     brouard  2972:             if (covar[Tvaraff[z1]][i]!= nbcode[Tvaraff[z1]][codtabm(j1,z1)]){
1.145     brouard  2973:                 /* Tests if the value of each of the covariates of i is equal to filter j1 */
1.144     brouard  2974:               bool=0;
1.198     brouard  2975:               /* 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", 
                   2976:                 bool,i,z1, z1, Tvaraff[z1],i,covar[Tvaraff[z1]][i],j1,z1,codtabm(j1,z1),
                   2977:                 j1,z1,nbcode[Tvaraff[z1]][codtabm(j1,z1)],j1);*/
                   2978:               /* For j1=7 in V1+V2+V3+V4 = 0 1 1 0 and codtabm(7,3)=1 and nbcde[3][?]=1*/
1.144     brouard  2979:             } 
1.126     brouard  2980:        }
1.144     brouard  2981:  
1.126     brouard  2982:        if (bool==1){
                   2983:          for(m=firstpass; m<=lastpass; m++){
                   2984:            k2=anint[m][i]+(mint[m][i]/12.);
                   2985:            /*if ((k2>=dateprev1) && (k2<=dateprev2)) {*/
                   2986:              if(agev[m][i]==0) agev[m][i]=iagemax+1;
                   2987:              if(agev[m][i]==1) agev[m][i]=iagemax+2;
                   2988:              if (s[m][i]>0 && s[m][i]<=nlstate) prop[s[m][i]][(int)agev[m][i]] += weight[i];
                   2989:              if (m<lastpass) {
                   2990:                freq[s[m][i]][s[m+1][i]][(int)agev[m][i]] += weight[i];
                   2991:                freq[s[m][i]][s[m+1][i]][iagemax+3] += weight[i];
                   2992:              }
                   2993:              
                   2994:              if ((agev[m][i]>1) && (agev[m][i]< (iagemax+3))) {
                   2995:                dateintsum=dateintsum+k2;
                   2996:                k2cpt++;
                   2997:              }
                   2998:              /*}*/
                   2999:          }
                   3000:        }
1.145     brouard  3001:       } /* end i */
1.126     brouard  3002:        
                   3003:       /*      fprintf(ficresp, "#Count between %.lf/%.lf/%.lf and %.lf/%.lf/%.lf\n",jprev1, mprev1,anprev1,jprev2, mprev2,anprev2);*/
                   3004:       pstamp(ficresp);
                   3005:       if  (cptcovn>0) {
                   3006:        fprintf(ficresp, "\n#********** Variable "); 
1.198     brouard  3007:        for (z1=1; z1<=cptcoveff; z1++) fprintf(ficresp, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
1.126     brouard  3008:        fprintf(ficresp, "**********\n#");
1.143     brouard  3009:        fprintf(ficlog, "\n#********** Variable "); 
1.198     brouard  3010:        for (z1=1; z1<=cptcoveff; z1++) fprintf(ficlog, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
1.143     brouard  3011:        fprintf(ficlog, "**********\n#");
1.126     brouard  3012:       }
                   3013:       for(i=1; i<=nlstate;i++) 
                   3014:        fprintf(ficresp, " Age Prev(%d) N(%d) N",i,i);
                   3015:       fprintf(ficresp, "\n");
                   3016:       
                   3017:       for(i=iagemin; i <= iagemax+3; i++){
                   3018:        if(i==iagemax+3){
                   3019:          fprintf(ficlog,"Total");
                   3020:        }else{
                   3021:          if(first==1){
                   3022:            first=0;
                   3023:            printf("See log file for details...\n");
                   3024:          }
                   3025:          fprintf(ficlog,"Age %d", i);
                   3026:        }
                   3027:        for(jk=1; jk <=nlstate ; jk++){
                   3028:          for(m=-1, pp[jk]=0; m <=nlstate+ndeath ; m++)
                   3029:            pp[jk] += freq[jk][m][i]; 
                   3030:        }
                   3031:        for(jk=1; jk <=nlstate ; jk++){
                   3032:          for(m=-1, pos=0; m <=0 ; m++)
                   3033:            pos += freq[jk][m][i];
                   3034:          if(pp[jk]>=1.e-10){
                   3035:            if(first==1){
1.132     brouard  3036:              printf(" %d.=%.0f loss[%d]=%.1f%%",jk,pp[jk],jk,100*pos/pp[jk]);
1.126     brouard  3037:            }
                   3038:            fprintf(ficlog," %d.=%.0f loss[%d]=%.1f%%",jk,pp[jk],jk,100*pos/pp[jk]);
                   3039:          }else{
                   3040:            if(first==1)
                   3041:              printf(" %d.=%.0f loss[%d]=NaNQ%%",jk,pp[jk],jk);
                   3042:            fprintf(ficlog," %d.=%.0f loss[%d]=NaNQ%%",jk,pp[jk],jk);
                   3043:          }
                   3044:        }
                   3045: 
                   3046:        for(jk=1; jk <=nlstate ; jk++){
                   3047:          for(m=0, pp[jk]=0; m <=nlstate+ndeath; m++)
                   3048:            pp[jk] += freq[jk][m][i];
                   3049:        }       
                   3050:        for(jk=1,pos=0,posprop=0; jk <=nlstate ; jk++){
                   3051:          pos += pp[jk];
                   3052:          posprop += prop[jk][i];
                   3053:        }
                   3054:        for(jk=1; jk <=nlstate ; jk++){
                   3055:          if(pos>=1.e-5){
                   3056:            if(first==1)
                   3057:              printf(" %d.=%.0f prev[%d]=%.1f%%",jk,pp[jk],jk,100*pp[jk]/pos);
                   3058:            fprintf(ficlog," %d.=%.0f prev[%d]=%.1f%%",jk,pp[jk],jk,100*pp[jk]/pos);
                   3059:          }else{
                   3060:            if(first==1)
                   3061:              printf(" %d.=%.0f prev[%d]=NaNQ%%",jk,pp[jk],jk);
                   3062:            fprintf(ficlog," %d.=%.0f prev[%d]=NaNQ%%",jk,pp[jk],jk);
                   3063:          }
                   3064:          if( i <= iagemax){
                   3065:            if(pos>=1.e-5){
                   3066:              fprintf(ficresp," %d %.5f %.0f %.0f",i,prop[jk][i]/posprop, prop[jk][i],posprop);
                   3067:              /*probs[i][jk][j1]= pp[jk]/pos;*/
                   3068:              /*printf("\ni=%d jk=%d j1=%d %.5f %.0f %.0f %f",i,jk,j1,pp[jk]/pos, pp[jk],pos,probs[i][jk][j1]);*/
                   3069:            }
                   3070:            else
                   3071:              fprintf(ficresp," %d NaNq %.0f %.0f",i,prop[jk][i],posprop);
                   3072:          }
                   3073:        }
                   3074:        
                   3075:        for(jk=-1; jk <=nlstate+ndeath; jk++)
                   3076:          for(m=-1; m <=nlstate+ndeath; m++)
                   3077:            if(freq[jk][m][i] !=0 ) {
                   3078:            if(first==1)
                   3079:              printf(" %d%d=%.0f",jk,m,freq[jk][m][i]);
                   3080:              fprintf(ficlog," %d%d=%.0f",jk,m,freq[jk][m][i]);
                   3081:            }
                   3082:        if(i <= iagemax)
                   3083:          fprintf(ficresp,"\n");
                   3084:        if(first==1)
                   3085:          printf("Others in log...\n");
                   3086:        fprintf(ficlog,"\n");
                   3087:       }
1.145     brouard  3088:       /*}*/
1.126     brouard  3089:   }
                   3090:   dateintmean=dateintsum/k2cpt; 
                   3091:  
                   3092:   fclose(ficresp);
                   3093:   free_ma3x(freq,-5,nlstate+ndeath,-5,nlstate+ndeath, iagemin, iagemax+3);
                   3094:   free_vector(pp,1,nlstate);
                   3095:   free_matrix(prop,1,nlstate,iagemin, iagemax+3);
                   3096:   /* End of Freq */
                   3097: }
                   3098: 
                   3099: /************ Prevalence ********************/
                   3100: 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)
                   3101: {  
                   3102:   /* Compute observed prevalence between dateprev1 and dateprev2 by counting the number of people
                   3103:      in each health status at the date of interview (if between dateprev1 and dateprev2).
                   3104:      We still use firstpass and lastpass as another selection.
                   3105:   */
                   3106:  
1.164     brouard  3107:   int i, m, jk, j1, bool, z1,j;
                   3108: 
                   3109:   double **prop;
                   3110:   double posprop; 
1.126     brouard  3111:   double  y2; /* in fractional years */
                   3112:   int iagemin, iagemax;
1.145     brouard  3113:   int first; /** to stop verbosity which is redirected to log file */
1.126     brouard  3114: 
                   3115:   iagemin= (int) agemin;
                   3116:   iagemax= (int) agemax;
                   3117:   /*pp=vector(1,nlstate);*/
                   3118:   prop=matrix(1,nlstate,iagemin,iagemax+3); 
                   3119:   /*  freq=ma3x(-1,nlstate+ndeath,-1,nlstate+ndeath,iagemin,iagemax+3);*/
                   3120:   j1=0;
                   3121:   
1.145     brouard  3122:   /*j=cptcoveff;*/
1.126     brouard  3123:   if (cptcovn<1) {j=1;ncodemax[1]=1;}
                   3124:   
1.145     brouard  3125:   first=1;
                   3126:   for(j1=1; j1<= (int) pow(2,cptcoveff);j1++){
                   3127:     /*for(i1=1; i1<=ncodemax[k1];i1++){
                   3128:       j1++;*/
1.126     brouard  3129:       
                   3130:       for (i=1; i<=nlstate; i++)  
                   3131:        for(m=iagemin; m <= iagemax+3; m++)
                   3132:          prop[i][m]=0.0;
                   3133:      
                   3134:       for (i=1; i<=imx; i++) { /* Each individual */
                   3135:        bool=1;
                   3136:        if  (cptcovn>0) {
                   3137:          for (z1=1; z1<=cptcoveff; z1++) 
1.198     brouard  3138:            if (covar[Tvaraff[z1]][i]!= nbcode[Tvaraff[z1]][codtabm(j1,z1)]) 
1.126     brouard  3139:              bool=0;
                   3140:        } 
                   3141:        if (bool==1) { 
                   3142:          for(m=firstpass; m<=lastpass; m++){/* Other selection (we can limit to certain interviews*/
                   3143:            y2=anint[m][i]+(mint[m][i]/12.); /* Fractional date in year */
                   3144:            if ((y2>=dateprev1) && (y2<=dateprev2)) { /* Here is the main selection (fractional years) */
                   3145:              if(agev[m][i]==0) agev[m][i]=iagemax+1;
                   3146:              if(agev[m][i]==1) agev[m][i]=iagemax+2;
                   3147:              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); 
                   3148:              if (s[m][i]>0 && s[m][i]<=nlstate) { 
                   3149:                /*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]]);*/
                   3150:                prop[s[m][i]][(int)agev[m][i]] += weight[i];
                   3151:                prop[s[m][i]][iagemax+3] += weight[i]; 
                   3152:              } 
                   3153:            }
                   3154:          } /* end selection of waves */
                   3155:        }
                   3156:       }
                   3157:       for(i=iagemin; i <= iagemax+3; i++){  
                   3158:        for(jk=1,posprop=0; jk <=nlstate ; jk++) { 
                   3159:          posprop += prop[jk][i]; 
                   3160:        } 
1.145     brouard  3161:        
1.126     brouard  3162:        for(jk=1; jk <=nlstate ; jk++){     
                   3163:          if( i <=  iagemax){ 
                   3164:            if(posprop>=1.e-5){ 
                   3165:              probs[i][jk][j1]= prop[jk][i]/posprop;
1.145     brouard  3166:            } else{
                   3167:              if(first==1){
                   3168:                first=0;
                   3169:                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]);
                   3170:              }
                   3171:            }
1.126     brouard  3172:          } 
                   3173:        }/* end jk */ 
                   3174:       }/* end i */ 
1.145     brouard  3175:     /*} *//* end i1 */
                   3176:   } /* end j1 */
1.126     brouard  3177:   
                   3178:   /*  free_ma3x(freq,-1,nlstate+ndeath,-1,nlstate+ndeath, iagemin, iagemax+3);*/
                   3179:   /*free_vector(pp,1,nlstate);*/
                   3180:   free_matrix(prop,1,nlstate, iagemin,iagemax+3);
                   3181: }  /* End of prevalence */
                   3182: 
                   3183: /************* Waves Concatenation ***************/
                   3184: 
                   3185: 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)
                   3186: {
                   3187:   /* Concatenates waves: wav[i] is the number of effective (useful waves) of individual i.
                   3188:      Death is a valid wave (if date is known).
                   3189:      mw[mi][i] is the mi (mi=1 to wav[i])  effective wave of individual i
                   3190:      dh[m][i] or dh[mw[mi][i]][i] is the delay between two effective waves m=mw[mi][i]
                   3191:      and mw[mi+1][i]. dh depends on stepm.
                   3192:      */
                   3193: 
                   3194:   int i, mi, m;
                   3195:   /* int j, k=0,jk, ju, jl,jmin=1e+5, jmax=-1;
                   3196:      double sum=0., jmean=0.;*/
                   3197:   int first;
                   3198:   int j, k=0,jk, ju, jl;
                   3199:   double sum=0.;
                   3200:   first=0;
1.164     brouard  3201:   jmin=100000;
1.126     brouard  3202:   jmax=-1;
                   3203:   jmean=0.;
                   3204:   for(i=1; i<=imx; i++){
                   3205:     mi=0;
                   3206:     m=firstpass;
                   3207:     while(s[m][i] <= nlstate){
                   3208:       if(s[m][i]>=1 || s[m][i]==-2 || s[m][i]==-4 || s[m][i]==-5)
                   3209:        mw[++mi][i]=m;
                   3210:       if(m >=lastpass)
                   3211:        break;
                   3212:       else
                   3213:        m++;
                   3214:     }/* end while */
                   3215:     if (s[m][i] > nlstate){
                   3216:       mi++;    /* Death is another wave */
                   3217:       /* if(mi==0)  never been interviewed correctly before death */
                   3218:         /* Only death is a correct wave */
                   3219:       mw[mi][i]=m;
                   3220:     }
                   3221: 
                   3222:     wav[i]=mi;
                   3223:     if(mi==0){
                   3224:       nbwarn++;
                   3225:       if(first==0){
                   3226:        printf("Warning! No valid information for individual %ld line=%d (skipped) and may be others, see log file\n",num[i],i);
                   3227:        first=1;
                   3228:       }
                   3229:       if(first==1){
                   3230:        fprintf(ficlog,"Warning! No valid information for individual %ld line=%d (skipped)\n",num[i],i);
                   3231:       }
                   3232:     } /* end mi==0 */
                   3233:   } /* End individuals */
                   3234: 
                   3235:   for(i=1; i<=imx; i++){
                   3236:     for(mi=1; mi<wav[i];mi++){
                   3237:       if (stepm <=0)
                   3238:        dh[mi][i]=1;
                   3239:       else{
                   3240:        if (s[mw[mi+1][i]][i] > nlstate) { /* A death */
                   3241:          if (agedc[i] < 2*AGESUP) {
                   3242:            j= rint(agedc[i]*12-agev[mw[mi][i]][i]*12); 
                   3243:            if(j==0) j=1;  /* Survives at least one month after exam */
                   3244:            else if(j<0){
                   3245:              nberr++;
                   3246:              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]);
                   3247:              j=1; /* Temporary Dangerous patch */
                   3248:              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);
                   3249:              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]);
                   3250:              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);
                   3251:            }
                   3252:            k=k+1;
                   3253:            if (j >= jmax){
                   3254:              jmax=j;
                   3255:              ijmax=i;
                   3256:            }
                   3257:            if (j <= jmin){
                   3258:              jmin=j;
                   3259:              ijmin=i;
                   3260:            }
                   3261:            sum=sum+j;
                   3262:            /*if (j<0) printf("j=%d num=%d \n",j,i);*/
                   3263:            /*    printf("%d %d %d %d\n", s[mw[mi][i]][i] ,s[mw[mi+1][i]][i],j,i);*/
                   3264:          }
                   3265:        }
                   3266:        else{
                   3267:          j= rint( (agev[mw[mi+1][i]][i]*12 - agev[mw[mi][i]][i]*12));
                   3268: /*       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]); */
                   3269: 
                   3270:          k=k+1;
                   3271:          if (j >= jmax) {
                   3272:            jmax=j;
                   3273:            ijmax=i;
                   3274:          }
                   3275:          else if (j <= jmin){
                   3276:            jmin=j;
                   3277:            ijmin=i;
                   3278:          }
                   3279:          /*        if (j<10) printf("j=%d jmin=%d num=%d ",j,jmin,i); */
                   3280:          /*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]);*/
                   3281:          if(j<0){
                   3282:            nberr++;
                   3283:            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]);
                   3284:            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]);
                   3285:          }
                   3286:          sum=sum+j;
                   3287:        }
                   3288:        jk= j/stepm;
                   3289:        jl= j -jk*stepm;
                   3290:        ju= j -(jk+1)*stepm;
                   3291:        if(mle <=1){ /* only if we use a the linear-interpoloation pseudo-likelihood */
                   3292:          if(jl==0){
                   3293:            dh[mi][i]=jk;
                   3294:            bh[mi][i]=0;
                   3295:          }else{ /* We want a negative bias in order to only have interpolation ie
1.136     brouard  3296:                  * to avoid the price of an extra matrix product in likelihood */
1.126     brouard  3297:            dh[mi][i]=jk+1;
                   3298:            bh[mi][i]=ju;
                   3299:          }
                   3300:        }else{
                   3301:          if(jl <= -ju){
                   3302:            dh[mi][i]=jk;
                   3303:            bh[mi][i]=jl;       /* bias is positive if real duration
                   3304:                                 * is higher than the multiple of stepm and negative otherwise.
                   3305:                                 */
                   3306:          }
                   3307:          else{
                   3308:            dh[mi][i]=jk+1;
                   3309:            bh[mi][i]=ju;
                   3310:          }
                   3311:          if(dh[mi][i]==0){
                   3312:            dh[mi][i]=1; /* At least one step */
                   3313:            bh[mi][i]=ju; /* At least one step */
                   3314:            /*  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);*/
                   3315:          }
                   3316:        } /* end if mle */
                   3317:       }
                   3318:     } /* end wave */
                   3319:   }
                   3320:   jmean=sum/k;
                   3321:   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  3322:   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  3323:  }
                   3324: 
                   3325: /*********** Tricode ****************************/
1.145     brouard  3326: void tricode(int *Tvar, int **nbcode, int imx, int *Ndum)
1.126     brouard  3327: {
1.144     brouard  3328:   /**< Uses cptcovn+2*cptcovprod as the number of covariates */
                   3329:   /*     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  3330:    * Boring subroutine which should only output nbcode[Tvar[j]][k]
1.145     brouard  3331:    * Tvar[5] in V2+V1+V3*age+V2*V4 is 2 (V2)
1.169     brouard  3332:    * nbcode[Tvar[j]][1]= 
1.144     brouard  3333:   */
1.130     brouard  3334: 
1.145     brouard  3335:   int ij=1, k=0, j=0, i=0, maxncov=NCOVMAX;
1.136     brouard  3336:   int modmaxcovj=0; /* Modality max of covariates j */
1.145     brouard  3337:   int cptcode=0; /* Modality max of covariates j */
                   3338:   int modmincovj=0; /* Modality min of covariates j */
                   3339: 
                   3340: 
1.126     brouard  3341:   cptcoveff=0; 
                   3342:  
1.144     brouard  3343:   for (k=1; k <= maxncov; k++) ncodemax[k]=0; /* Horrible constant again replaced by NCOVMAX */
1.126     brouard  3344: 
1.145     brouard  3345:   /* Loop on covariates without age and products */
1.186     brouard  3346:   for (j=1; j<=(cptcovs); j++) { /* From model V1 + V2*age+ V3 + V3*V4 keeps V1 + V3 = 2 only */
1.192     brouard  3347:     for (k=-1; k < maxncov; k++) Ndum[k]=0;
1.186     brouard  3348:     for (i=1; i<=imx; i++) { /* Loop on individuals: reads the data file to get the maximum value of the 
1.136     brouard  3349:                               modality of this covariate Vj*/ 
1.145     brouard  3350:       ij=(int)(covar[Tvar[j]][i]); /* ij=0 or 1 or -1. Value of the covariate Tvar[j] for individual i
                   3351:                                    * If product of Vn*Vm, still boolean *:
                   3352:                                    * If it was coded 1, 2, 3, 4 should be splitted into 3 boolean variables
                   3353:                                    * 1 => 0 0 0, 2 => 0 0 1, 3 => 0 1 1, 4=1 0 0   */
                   3354:       /* Finds for covariate j, n=Tvar[j] of Vn . ij is the
1.136     brouard  3355:                                      modality of the nth covariate of individual i. */
1.145     brouard  3356:       if (ij > modmaxcovj)
                   3357:         modmaxcovj=ij; 
                   3358:       else if (ij < modmincovj) 
                   3359:        modmincovj=ij; 
                   3360:       if ((ij < -1) && (ij > NCOVMAX)){
                   3361:        printf( "Error: minimal is less than -1 or maximal is bigger than %d. Exiting. \n", NCOVMAX );
                   3362:        exit(1);
                   3363:       }else
1.136     brouard  3364:       Ndum[ij]++; /*counts and stores the occurence of this modality 0, 1, -1*/
1.145     brouard  3365:       /*  If coded 1, 2, 3 , counts the number of 1 Ndum[1], number of 2, Ndum[2], etc */
1.126     brouard  3366:       /*printf("i=%d ij=%d Ndum[ij]=%d imx=%d",i,ij,Ndum[ij],imx);*/
1.136     brouard  3367:       /* getting the maximum value of the modality of the covariate
                   3368:         (should be 0 or 1 now) Tvar[j]. If V=sex and male is coded 0 and
                   3369:         female is 1, then modmaxcovj=1.*/
1.192     brouard  3370:     } /* end for loop on individuals i */
1.145     brouard  3371:     printf(" Minimal and maximal values of %d th covariate V%d: min=%d max=%d \n", j, Tvar[j], modmincovj, modmaxcovj);
1.192     brouard  3372:     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  3373:     cptcode=modmaxcovj;
1.137     brouard  3374:     /* Ndum[0] = frequency of 0 for model-covariate j, Ndum[1] frequency of 1 etc. */
1.145     brouard  3375:    /*for (i=0; i<=cptcode; i++) {*/
1.192     brouard  3376:     for (k=modmincovj;  k<=modmaxcovj; k++) { /* k=-1 ? 0 and 1*//* For each value k of the modality of model-cov j */
                   3377:       printf("Frequencies of covariates %d ie V%d with value %d: %d\n", j, Tvar[j], k, Ndum[k]);
                   3378:       fprintf(ficlog, "Frequencies of covariates %d ie V%d with value %d: %d\n", j, Tvar[j], k, Ndum[k]);
                   3379:       if( Ndum[k] != 0 ){ /* Counts if nobody answered modality k ie empty modality, we skip it and reorder */
                   3380:        if( k != -1){
                   3381:          ncodemax[j]++;  /* ncodemax[j]= Number of modalities of the j th
                   3382:                             covariate for which somebody answered excluding 
                   3383:                             undefined. Usually 2: 0 and 1. */
                   3384:        }
                   3385:        ncodemaxwundef[j]++; /* ncodemax[j]= Number of modalities of the j th
                   3386:                             covariate for which somebody answered including 
                   3387:                             undefined. Usually 3: -1, 0 and 1. */
1.145     brouard  3388:       }
                   3389:       /* In fact  ncodemax[j]=2 (dichotom. variables only) but it could be more for
                   3390:         historical reasons: 3 if coded 1, 2, 3 and 4 and Ndum[2]=0 */
1.131     brouard  3391:     } /* Ndum[-1] number of undefined modalities */
1.126     brouard  3392: 
1.136     brouard  3393:     /* j is a covariate, n=Tvar[j] of Vn; Fills nbcode */
1.186     brouard  3394:     /* For covariate j, modalities could be 1, 2, 3, 4, 5, 6, 7. 
                   3395:        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  3396:        modmincovj=3; modmaxcovj = 7;
1.186     brouard  3397:        There are only 3 modalities non empty 3, 6, 7 (or 2 if 27 is too few) : ncodemax[j]=3;
                   3398:        which will be coded 0, 1, 2 which in binary on 2=3-1 digits are 0=00 1=01, 2=10;
                   3399:        defining two dummy variables: variables V1_1 and V1_2.
1.145     brouard  3400:        nbcode[Tvar[j]][ij]=k;
                   3401:        nbcode[Tvar[j]][1]=0;
                   3402:        nbcode[Tvar[j]][2]=1;
                   3403:        nbcode[Tvar[j]][3]=2;
1.197     brouard  3404:        To be continued (not working yet).
1.145     brouard  3405:     */
1.197     brouard  3406:     ij=0; /* ij is similar to i but can jump over null modalities */
                   3407:     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*/
                   3408:        if (Ndum[i] == 0) { /* If nobody responded to this modality k */
1.192     brouard  3409:          break;
                   3410:        }
                   3411:        ij++;
1.197     brouard  3412:        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  3413:        cptcode = ij; /* New max modality for covar j */
                   3414:     } /* end of loop on modality i=-1 to 1 or more */
                   3415:       
                   3416:     /*   for (k=0; k<= cptcode; k++) { /\* k=-1 ? k=0 to 1 *\//\* Could be 1 to 4 *\//\* cptcode=modmaxcovj *\/ */
                   3417:     /*         /\*recode from 0 *\/ */
                   3418:     /*                                      k is a modality. If we have model=V1+V1*sex  */
                   3419:     /*                                      then: nbcode[1][1]=0 ; nbcode[1][2]=1; nbcode[2][1]=0 ; nbcode[2][2]=1; */
                   3420:     /*                                   But if some modality were not used, it is recoded from 0 to a newer modmaxcovj=cptcode *\/ */
                   3421:     /*         } */
                   3422:     /*         /\* cptcode = ij; *\/ /\* New max modality for covar j *\/ */
                   3423:     /*         if (ij > ncodemax[j]) { */
                   3424:     /*           printf( " Error ij=%d > ncodemax[%d]=%d\n", ij, j, ncodemax[j]);  */
                   3425:     /*           fprintf(ficlog, " Error ij=%d > ncodemax[%d]=%d\n", ij, j, ncodemax[j]); */
                   3426:     /*           break; */
                   3427:     /*         } */
                   3428:     /*   }  /\* end of loop on modality k *\/ */
1.137     brouard  3429:   } /* end of loop on model-covariate j. nbcode[Tvarj][1]=0 and nbcode[Tvarj][2]=1 sets the value of covariate j*/  
                   3430:   
1.145     brouard  3431:  for (k=-1; k< maxncov; k++) Ndum[k]=0; 
1.137     brouard  3432:   
1.187     brouard  3433:   for (i=1; i<=ncovmodel-2-nagesqr; i++) { /* -2, cste and age and eventually age*age */ 
1.145     brouard  3434:    /* Listing of all covariables in statement model to see if some covariates appear twice. For example, V1 appears twice in V1+V1*V2.*/ 
                   3435:    ij=Tvar[i]; /* Tvar might be -1 if status was unknown */ 
1.187     brouard  3436:    Ndum[ij]++; /* Might be supersed V1 + V1*age */
1.145     brouard  3437:  } 
1.126     brouard  3438: 
1.192     brouard  3439:  ij=0;
1.145     brouard  3440:  for (i=0; i<=  maxncov-1; i++) { /* modmaxcovj is unknown here. Only Ndum[2(V2),3(age*V3), 5(V3*V2) 6(V1*V4) */
                   3441:    /*printf("Ndum[%d]=%d\n",i, Ndum[i]);*/
1.126     brouard  3442:    if((Ndum[i]!=0) && (i<=ncovcol)){
1.192     brouard  3443:      ij++;
1.145     brouard  3444:      /*printf("diff Ndum[%d]=%d\n",i, Ndum[i]);*/
                   3445:      Tvaraff[ij]=i; /*For printing (unclear) */
1.192     brouard  3446:    }else{
                   3447:        /* Tvaraff[ij]=0; */
                   3448:    }
1.126     brouard  3449:  }
1.192     brouard  3450:  /* ij--; */
1.144     brouard  3451:  cptcoveff=ij; /*Number of total covariates*/
1.145     brouard  3452: 
1.126     brouard  3453: }
                   3454: 
1.145     brouard  3455: 
1.126     brouard  3456: /*********** Health Expectancies ****************/
                   3457: 
1.127     brouard  3458: 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  3459: 
                   3460: {
                   3461:   /* Health expectancies, no variances */
1.164     brouard  3462:   int i, j, nhstepm, hstepm, h, nstepm;
1.126     brouard  3463:   int nhstepma, nstepma; /* Decreasing with age */
                   3464:   double age, agelim, hf;
                   3465:   double ***p3mat;
                   3466:   double eip;
                   3467: 
                   3468:   pstamp(ficreseij);
                   3469:   fprintf(ficreseij,"# (a) Life expectancies by health status at initial age and (b) health expectancies by health status at initial age\n");
                   3470:   fprintf(ficreseij,"# Age");
                   3471:   for(i=1; i<=nlstate;i++){
                   3472:     for(j=1; j<=nlstate;j++){
                   3473:       fprintf(ficreseij," e%1d%1d ",i,j);
                   3474:     }
                   3475:     fprintf(ficreseij," e%1d. ",i);
                   3476:   }
                   3477:   fprintf(ficreseij,"\n");
                   3478: 
                   3479:   
                   3480:   if(estepm < stepm){
                   3481:     printf ("Problem %d lower than %d\n",estepm, stepm);
                   3482:   }
                   3483:   else  hstepm=estepm;   
                   3484:   /* We compute the life expectancy from trapezoids spaced every estepm months
                   3485:    * This is mainly to measure the difference between two models: for example
                   3486:    * if stepm=24 months pijx are given only every 2 years and by summing them
                   3487:    * we are calculating an estimate of the Life Expectancy assuming a linear 
                   3488:    * progression in between and thus overestimating or underestimating according
                   3489:    * to the curvature of the survival function. If, for the same date, we 
                   3490:    * estimate the model with stepm=1 month, we can keep estepm to 24 months
                   3491:    * to compare the new estimate of Life expectancy with the same linear 
                   3492:    * hypothesis. A more precise result, taking into account a more precise
                   3493:    * curvature will be obtained if estepm is as small as stepm. */
                   3494: 
                   3495:   /* For example we decided to compute the life expectancy with the smallest unit */
                   3496:   /* hstepm beeing the number of stepms, if hstepm=1 the length of hstepm is stepm. 
                   3497:      nhstepm is the number of hstepm from age to agelim 
                   3498:      nstepm is the number of stepm from age to agelin. 
                   3499:      Look at hpijx to understand the reason of that which relies in memory size
                   3500:      and note for a fixed period like estepm months */
                   3501:   /* We decided (b) to get a life expectancy respecting the most precise curvature of the
                   3502:      survival function given by stepm (the optimization length). Unfortunately it
                   3503:      means that if the survival funtion is printed only each two years of age and if
                   3504:      you sum them up and add 1 year (area under the trapezoids) you won't get the same 
                   3505:      results. So we changed our mind and took the option of the best precision.
                   3506:   */
                   3507:   hstepm=hstepm/stepm; /* Typically in stepm units, if stepm=6 & estepm=24 , = 24/6 months = 4 */ 
                   3508: 
                   3509:   agelim=AGESUP;
                   3510:   /* If stepm=6 months */
                   3511:     /* Computed by stepm unit matrices, product of hstepm matrices, stored
                   3512:        in an array of nhstepm length: nhstepm=10, hstepm=4, stepm=6 months */
                   3513:     
                   3514: /* nhstepm age range expressed in number of stepm */
                   3515:   nstepm=(int) rint((agelim-bage)*YEARM/stepm); /* Biggest nstepm */
                   3516:   /* Typically if 20 years nstepm = 20*12/6=40 stepm */ 
                   3517:   /* if (stepm >= YEARM) hstepm=1;*/
                   3518:   nhstepm = nstepm/hstepm;/* Expressed in hstepm, typically nhstepm=40/4=10 */
                   3519:   p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   3520: 
                   3521:   for (age=bage; age<=fage; age ++){ 
                   3522:     nstepma=(int) rint((agelim-bage)*YEARM/stepm); /* Biggest nstepm */
                   3523:     /* Typically if 20 years nstepm = 20*12/6=40 stepm */ 
                   3524:     /* if (stepm >= YEARM) hstepm=1;*/
                   3525:     nhstepma = nstepma/hstepm;/* Expressed in hstepm, typically nhstepma=40/4=10 */
                   3526: 
                   3527:     /* If stepm=6 months */
                   3528:     /* Computed by stepm unit matrices, product of hstepma matrices, stored
                   3529:        in an array of nhstepma length: nhstepma=10, hstepm=4, stepm=6 months */
                   3530:     
                   3531:     hpxij(p3mat,nhstepma,age,hstepm,x,nlstate,stepm,oldm, savm, cij);  
                   3532:     
                   3533:     hf=hstepm*stepm/YEARM;  /* Duration of hstepm expressed in year unit. */
                   3534:     
                   3535:     printf("%d|",(int)age);fflush(stdout);
                   3536:     fprintf(ficlog,"%d|",(int)age);fflush(ficlog);
                   3537:     
                   3538:     /* Computing expectancies */
                   3539:     for(i=1; i<=nlstate;i++)
                   3540:       for(j=1; j<=nlstate;j++)
                   3541:        for (h=0, eij[i][j][(int)age]=0; h<=nhstepm-1; h++){
                   3542:          eij[i][j][(int)age] += (p3mat[i][j][h]+p3mat[i][j][h+1])/2.0*hf;
                   3543:          
                   3544:          /* 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]);*/
                   3545: 
                   3546:        }
                   3547: 
                   3548:     fprintf(ficreseij,"%3.0f",age );
                   3549:     for(i=1; i<=nlstate;i++){
                   3550:       eip=0;
                   3551:       for(j=1; j<=nlstate;j++){
                   3552:        eip +=eij[i][j][(int)age];
                   3553:        fprintf(ficreseij,"%9.4f", eij[i][j][(int)age] );
                   3554:       }
                   3555:       fprintf(ficreseij,"%9.4f", eip );
                   3556:     }
                   3557:     fprintf(ficreseij,"\n");
                   3558:     
                   3559:   }
                   3560:   free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   3561:   printf("\n");
                   3562:   fprintf(ficlog,"\n");
                   3563:   
                   3564: }
                   3565: 
1.127     brouard  3566: 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  3567: 
                   3568: {
                   3569:   /* Covariances of health expectancies eij and of total life expectancies according
                   3570:    to initial status i, ei. .
                   3571:   */
                   3572:   int i, j, nhstepm, hstepm, h, nstepm, k, cptj, cptj2, i2, j2, ij, ji;
                   3573:   int nhstepma, nstepma; /* Decreasing with age */
                   3574:   double age, agelim, hf;
                   3575:   double ***p3matp, ***p3matm, ***varhe;
                   3576:   double **dnewm,**doldm;
                   3577:   double *xp, *xm;
                   3578:   double **gp, **gm;
                   3579:   double ***gradg, ***trgradg;
                   3580:   int theta;
                   3581: 
                   3582:   double eip, vip;
                   3583: 
                   3584:   varhe=ma3x(1,nlstate*nlstate,1,nlstate*nlstate,(int) bage, (int) fage);
                   3585:   xp=vector(1,npar);
                   3586:   xm=vector(1,npar);
                   3587:   dnewm=matrix(1,nlstate*nlstate,1,npar);
                   3588:   doldm=matrix(1,nlstate*nlstate,1,nlstate*nlstate);
                   3589:   
                   3590:   pstamp(ficresstdeij);
                   3591:   fprintf(ficresstdeij,"# Health expectancies with standard errors\n");
                   3592:   fprintf(ficresstdeij,"# Age");
                   3593:   for(i=1; i<=nlstate;i++){
                   3594:     for(j=1; j<=nlstate;j++)
                   3595:       fprintf(ficresstdeij," e%1d%1d (SE)",i,j);
                   3596:     fprintf(ficresstdeij," e%1d. ",i);
                   3597:   }
                   3598:   fprintf(ficresstdeij,"\n");
                   3599: 
                   3600:   pstamp(ficrescveij);
                   3601:   fprintf(ficrescveij,"# Subdiagonal matrix of covariances of health expectancies by age: cov(eij,ekl)\n");
                   3602:   fprintf(ficrescveij,"# Age");
                   3603:   for(i=1; i<=nlstate;i++)
                   3604:     for(j=1; j<=nlstate;j++){
                   3605:       cptj= (j-1)*nlstate+i;
                   3606:       for(i2=1; i2<=nlstate;i2++)
                   3607:        for(j2=1; j2<=nlstate;j2++){
                   3608:          cptj2= (j2-1)*nlstate+i2;
                   3609:          if(cptj2 <= cptj)
                   3610:            fprintf(ficrescveij,"  %1d%1d,%1d%1d",i,j,i2,j2);
                   3611:        }
                   3612:     }
                   3613:   fprintf(ficrescveij,"\n");
                   3614:   
                   3615:   if(estepm < stepm){
                   3616:     printf ("Problem %d lower than %d\n",estepm, stepm);
                   3617:   }
                   3618:   else  hstepm=estepm;   
                   3619:   /* We compute the life expectancy from trapezoids spaced every estepm months
                   3620:    * This is mainly to measure the difference between two models: for example
                   3621:    * if stepm=24 months pijx are given only every 2 years and by summing them
                   3622:    * we are calculating an estimate of the Life Expectancy assuming a linear 
                   3623:    * progression in between and thus overestimating or underestimating according
                   3624:    * to the curvature of the survival function. If, for the same date, we 
                   3625:    * estimate the model with stepm=1 month, we can keep estepm to 24 months
                   3626:    * to compare the new estimate of Life expectancy with the same linear 
                   3627:    * hypothesis. A more precise result, taking into account a more precise
                   3628:    * curvature will be obtained if estepm is as small as stepm. */
                   3629: 
                   3630:   /* For example we decided to compute the life expectancy with the smallest unit */
                   3631:   /* hstepm beeing the number of stepms, if hstepm=1 the length of hstepm is stepm. 
                   3632:      nhstepm is the number of hstepm from age to agelim 
                   3633:      nstepm is the number of stepm from age to agelin. 
                   3634:      Look at hpijx to understand the reason of that which relies in memory size
                   3635:      and note for a fixed period like estepm months */
                   3636:   /* We decided (b) to get a life expectancy respecting the most precise curvature of the
                   3637:      survival function given by stepm (the optimization length). Unfortunately it
                   3638:      means that if the survival funtion is printed only each two years of age and if
                   3639:      you sum them up and add 1 year (area under the trapezoids) you won't get the same 
                   3640:      results. So we changed our mind and took the option of the best precision.
                   3641:   */
                   3642:   hstepm=hstepm/stepm; /* Typically in stepm units, if stepm=6 & estepm=24 , = 24/6 months = 4 */ 
                   3643: 
                   3644:   /* If stepm=6 months */
                   3645:   /* nhstepm age range expressed in number of stepm */
                   3646:   agelim=AGESUP;
                   3647:   nstepm=(int) rint((agelim-bage)*YEARM/stepm); 
                   3648:   /* Typically if 20 years nstepm = 20*12/6=40 stepm */ 
                   3649:   /* if (stepm >= YEARM) hstepm=1;*/
                   3650:   nhstepm = nstepm/hstepm;/* Expressed in hstepm, typically nhstepm=40/4=10 */
                   3651:   
                   3652:   p3matp=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   3653:   p3matm=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   3654:   gradg=ma3x(0,nhstepm,1,npar,1,nlstate*nlstate);
                   3655:   trgradg =ma3x(0,nhstepm,1,nlstate*nlstate,1,npar);
                   3656:   gp=matrix(0,nhstepm,1,nlstate*nlstate);
                   3657:   gm=matrix(0,nhstepm,1,nlstate*nlstate);
                   3658: 
                   3659:   for (age=bage; age<=fage; age ++){ 
                   3660:     nstepma=(int) rint((agelim-bage)*YEARM/stepm); /* Biggest nstepm */
                   3661:     /* Typically if 20 years nstepm = 20*12/6=40 stepm */ 
                   3662:     /* if (stepm >= YEARM) hstepm=1;*/
                   3663:     nhstepma = nstepma/hstepm;/* Expressed in hstepm, typically nhstepma=40/4=10 */
                   3664: 
                   3665:     /* If stepm=6 months */
                   3666:     /* Computed by stepm unit matrices, product of hstepma matrices, stored
                   3667:        in an array of nhstepma length: nhstepma=10, hstepm=4, stepm=6 months */
                   3668:     
                   3669:     hf=hstepm*stepm/YEARM;  /* Duration of hstepm expressed in year unit. */
                   3670: 
                   3671:     /* Computing  Variances of health expectancies */
                   3672:     /* Gradient is computed with plus gp and minus gm. Code is duplicated in order to
                   3673:        decrease memory allocation */
                   3674:     for(theta=1; theta <=npar; theta++){
                   3675:       for(i=1; i<=npar; i++){ 
                   3676:        xp[i] = x[i] + (i==theta ?delti[theta]:0);
                   3677:        xm[i] = x[i] - (i==theta ?delti[theta]:0);
                   3678:       }
                   3679:       hpxij(p3matp,nhstepm,age,hstepm,xp,nlstate,stepm,oldm,savm, cij);  
                   3680:       hpxij(p3matm,nhstepm,age,hstepm,xm,nlstate,stepm,oldm,savm, cij);  
                   3681:   
                   3682:       for(j=1; j<= nlstate; j++){
                   3683:        for(i=1; i<=nlstate; i++){
                   3684:          for(h=0; h<=nhstepm-1; h++){
                   3685:            gp[h][(j-1)*nlstate + i] = (p3matp[i][j][h]+p3matp[i][j][h+1])/2.;
                   3686:            gm[h][(j-1)*nlstate + i] = (p3matm[i][j][h]+p3matm[i][j][h+1])/2.;
                   3687:          }
                   3688:        }
                   3689:       }
                   3690:      
                   3691:       for(ij=1; ij<= nlstate*nlstate; ij++)
                   3692:        for(h=0; h<=nhstepm-1; h++){
                   3693:          gradg[h][theta][ij]= (gp[h][ij]-gm[h][ij])/2./delti[theta];
                   3694:        }
                   3695:     }/* End theta */
                   3696:     
                   3697:     
                   3698:     for(h=0; h<=nhstepm-1; h++)
                   3699:       for(j=1; j<=nlstate*nlstate;j++)
                   3700:        for(theta=1; theta <=npar; theta++)
                   3701:          trgradg[h][j][theta]=gradg[h][theta][j];
                   3702:     
                   3703: 
                   3704:      for(ij=1;ij<=nlstate*nlstate;ij++)
                   3705:       for(ji=1;ji<=nlstate*nlstate;ji++)
                   3706:        varhe[ij][ji][(int)age] =0.;
                   3707: 
                   3708:      printf("%d|",(int)age);fflush(stdout);
                   3709:      fprintf(ficlog,"%d|",(int)age);fflush(ficlog);
                   3710:      for(h=0;h<=nhstepm-1;h++){
                   3711:       for(k=0;k<=nhstepm-1;k++){
                   3712:        matprod2(dnewm,trgradg[h],1,nlstate*nlstate,1,npar,1,npar,matcov);
                   3713:        matprod2(doldm,dnewm,1,nlstate*nlstate,1,npar,1,nlstate*nlstate,gradg[k]);
                   3714:        for(ij=1;ij<=nlstate*nlstate;ij++)
                   3715:          for(ji=1;ji<=nlstate*nlstate;ji++)
                   3716:            varhe[ij][ji][(int)age] += doldm[ij][ji]*hf*hf;
                   3717:       }
                   3718:     }
                   3719: 
                   3720:     /* Computing expectancies */
                   3721:     hpxij(p3matm,nhstepm,age,hstepm,x,nlstate,stepm,oldm, savm, cij);  
                   3722:     for(i=1; i<=nlstate;i++)
                   3723:       for(j=1; j<=nlstate;j++)
                   3724:        for (h=0, eij[i][j][(int)age]=0; h<=nhstepm-1; h++){
                   3725:          eij[i][j][(int)age] += (p3matm[i][j][h]+p3matm[i][j][h+1])/2.0*hf;
                   3726:          
                   3727:          /* 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]);*/
                   3728: 
                   3729:        }
                   3730: 
                   3731:     fprintf(ficresstdeij,"%3.0f",age );
                   3732:     for(i=1; i<=nlstate;i++){
                   3733:       eip=0.;
                   3734:       vip=0.;
                   3735:       for(j=1; j<=nlstate;j++){
                   3736:        eip += eij[i][j][(int)age];
                   3737:        for(k=1; k<=nlstate;k++) /* Sum on j and k of cov(eij,eik) */
                   3738:          vip += varhe[(j-1)*nlstate+i][(k-1)*nlstate+i][(int)age];
                   3739:        fprintf(ficresstdeij," %9.4f (%.4f)", eij[i][j][(int)age], sqrt(varhe[(j-1)*nlstate+i][(j-1)*nlstate+i][(int)age]) );
                   3740:       }
                   3741:       fprintf(ficresstdeij," %9.4f (%.4f)", eip, sqrt(vip));
                   3742:     }
                   3743:     fprintf(ficresstdeij,"\n");
                   3744: 
                   3745:     fprintf(ficrescveij,"%3.0f",age );
                   3746:     for(i=1; i<=nlstate;i++)
                   3747:       for(j=1; j<=nlstate;j++){
                   3748:        cptj= (j-1)*nlstate+i;
                   3749:        for(i2=1; i2<=nlstate;i2++)
                   3750:          for(j2=1; j2<=nlstate;j2++){
                   3751:            cptj2= (j2-1)*nlstate+i2;
                   3752:            if(cptj2 <= cptj)
                   3753:              fprintf(ficrescveij," %.4f", varhe[cptj][cptj2][(int)age]);
                   3754:          }
                   3755:       }
                   3756:     fprintf(ficrescveij,"\n");
                   3757:    
                   3758:   }
                   3759:   free_matrix(gm,0,nhstepm,1,nlstate*nlstate);
                   3760:   free_matrix(gp,0,nhstepm,1,nlstate*nlstate);
                   3761:   free_ma3x(gradg,0,nhstepm,1,npar,1,nlstate*nlstate);
                   3762:   free_ma3x(trgradg,0,nhstepm,1,nlstate*nlstate,1,npar);
                   3763:   free_ma3x(p3matm,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   3764:   free_ma3x(p3matp,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   3765:   printf("\n");
                   3766:   fprintf(ficlog,"\n");
                   3767: 
                   3768:   free_vector(xm,1,npar);
                   3769:   free_vector(xp,1,npar);
                   3770:   free_matrix(dnewm,1,nlstate*nlstate,1,npar);
                   3771:   free_matrix(doldm,1,nlstate*nlstate,1,nlstate*nlstate);
                   3772:   free_ma3x(varhe,1,nlstate*nlstate,1,nlstate*nlstate,(int) bage, (int)fage);
                   3773: }
                   3774: 
                   3775: /************ Variance ******************/
                   3776: 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[])
                   3777: {
                   3778:   /* Variance of health expectancies */
                   3779:   /*  double **prevalim(double **prlim, int nlstate, double *xp, double age, double **oldm, double ** savm,double ftolpl);*/
                   3780:   /* double **newm;*/
1.169     brouard  3781:   /* int movingaverage(double ***probs, double bage,double fage, double ***mobaverage, int mobilav)*/
                   3782:   
                   3783:   int movingaverage();
1.126     brouard  3784:   double **dnewm,**doldm;
                   3785:   double **dnewmp,**doldmp;
                   3786:   int i, j, nhstepm, hstepm, h, nstepm ;
1.164     brouard  3787:   int k;
1.126     brouard  3788:   double *xp;
                   3789:   double **gp, **gm;  /* for var eij */
                   3790:   double ***gradg, ***trgradg; /*for var eij */
                   3791:   double **gradgp, **trgradgp; /* for var p point j */
                   3792:   double *gpp, *gmp; /* for var p point j */
                   3793:   double **varppt; /* for var p point j nlstate to nlstate+ndeath */
                   3794:   double ***p3mat;
                   3795:   double age,agelim, hf;
                   3796:   double ***mobaverage;
                   3797:   int theta;
                   3798:   char digit[4];
                   3799:   char digitp[25];
                   3800: 
                   3801:   char fileresprobmorprev[FILENAMELENGTH];
                   3802: 
                   3803:   if(popbased==1){
                   3804:     if(mobilav!=0)
                   3805:       strcpy(digitp,"-populbased-mobilav-");
                   3806:     else strcpy(digitp,"-populbased-nomobil-");
                   3807:   }
                   3808:   else 
                   3809:     strcpy(digitp,"-stablbased-");
                   3810: 
                   3811:   if (mobilav!=0) {
                   3812:     mobaverage= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
                   3813:     if (movingaverage(probs, bage, fage, mobaverage,mobilav)!=0){
                   3814:       fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav);
                   3815:       printf(" Error in movingaverage mobilav=%d\n",mobilav);
                   3816:     }
                   3817:   }
                   3818: 
                   3819:   strcpy(fileresprobmorprev,"prmorprev"); 
                   3820:   sprintf(digit,"%-d",ij);
                   3821:   /*printf("DIGIT=%s, ij=%d ijr=%-d|\n",digit, ij,ij);*/
                   3822:   strcat(fileresprobmorprev,digit); /* Tvar to be done */
                   3823:   strcat(fileresprobmorprev,digitp); /* Popbased or not, mobilav or not */
                   3824:   strcat(fileresprobmorprev,fileres);
                   3825:   if((ficresprobmorprev=fopen(fileresprobmorprev,"w"))==NULL) {
                   3826:     printf("Problem with resultfile: %s\n", fileresprobmorprev);
                   3827:     fprintf(ficlog,"Problem with resultfile: %s\n", fileresprobmorprev);
                   3828:   }
                   3829:   printf("Computing total mortality p.j=w1*p1j+w2*p2j+..: result on file '%s' \n",fileresprobmorprev);
                   3830:  
                   3831:   fprintf(ficlog,"Computing total mortality p.j=w1*p1j+w2*p2j+..: result on file '%s' \n",fileresprobmorprev);
                   3832:   pstamp(ficresprobmorprev);
                   3833:   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);
                   3834:   fprintf(ficresprobmorprev,"# Age cov=%-d",ij);
                   3835:   for(j=nlstate+1; j<=(nlstate+ndeath);j++){
                   3836:     fprintf(ficresprobmorprev," p.%-d SE",j);
                   3837:     for(i=1; i<=nlstate;i++)
                   3838:       fprintf(ficresprobmorprev," w%1d p%-d%-d",i,i,j);
                   3839:   }  
                   3840:   fprintf(ficresprobmorprev,"\n");
                   3841:   fprintf(ficgp,"\n# Routine varevsij");
                   3842:   /* fprintf(fichtm, "#Local time at start: %s", strstart);*/
                   3843:   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");
                   3844:   fprintf(fichtm,"\n<br>%s  <br>\n",digitp);
                   3845: /*   } */
                   3846:   varppt = matrix(nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);
                   3847:   pstamp(ficresvij);
                   3848:   fprintf(ficresvij,"# Variance and covariance of health expectancies e.j \n#  (weighted average of eij where weights are ");
                   3849:   if(popbased==1)
1.128     brouard  3850:     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  3851:   else
                   3852:     fprintf(ficresvij,"the age specific period (stable) prevalences in each health state \n");
                   3853:   fprintf(ficresvij,"# Age");
                   3854:   for(i=1; i<=nlstate;i++)
                   3855:     for(j=1; j<=nlstate;j++)
                   3856:       fprintf(ficresvij," Cov(e.%1d, e.%1d)",i,j);
                   3857:   fprintf(ficresvij,"\n");
                   3858: 
                   3859:   xp=vector(1,npar);
                   3860:   dnewm=matrix(1,nlstate,1,npar);
                   3861:   doldm=matrix(1,nlstate,1,nlstate);
                   3862:   dnewmp= matrix(nlstate+1,nlstate+ndeath,1,npar);
                   3863:   doldmp= matrix(nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);
                   3864: 
                   3865:   gradgp=matrix(1,npar,nlstate+1,nlstate+ndeath);
                   3866:   gpp=vector(nlstate+1,nlstate+ndeath);
                   3867:   gmp=vector(nlstate+1,nlstate+ndeath);
                   3868:   trgradgp =matrix(nlstate+1,nlstate+ndeath,1,npar); /* mu or p point j*/
                   3869:   
                   3870:   if(estepm < stepm){
                   3871:     printf ("Problem %d lower than %d\n",estepm, stepm);
                   3872:   }
                   3873:   else  hstepm=estepm;   
                   3874:   /* For example we decided to compute the life expectancy with the smallest unit */
                   3875:   /* hstepm beeing the number of stepms, if hstepm=1 the length of hstepm is stepm. 
                   3876:      nhstepm is the number of hstepm from age to agelim 
                   3877:      nstepm is the number of stepm from age to agelin. 
1.128     brouard  3878:      Look at function hpijx to understand why (it is linked to memory size questions) */
1.126     brouard  3879:   /* We decided (b) to get a life expectancy respecting the most precise curvature of the
                   3880:      survival function given by stepm (the optimization length). Unfortunately it
                   3881:      means that if the survival funtion is printed every two years of age and if
                   3882:      you sum them up and add 1 year (area under the trapezoids) you won't get the same 
                   3883:      results. So we changed our mind and took the option of the best precision.
                   3884:   */
                   3885:   hstepm=hstepm/stepm; /* Typically in stepm units, if stepm=6 & estepm=24 , = 24/6 months = 4 */ 
                   3886:   agelim = AGESUP;
                   3887:   for (age=bage; age<=fage; age ++){ /* If stepm=6 months */
                   3888:     nstepm=(int) rint((agelim-age)*YEARM/stepm); /* Typically 20 years = 20*12/6=40 */ 
                   3889:     nhstepm = nstepm/hstepm;/* Expressed in hstepm, typically nhstepm=40/4=10 */
                   3890:     p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   3891:     gradg=ma3x(0,nhstepm,1,npar,1,nlstate);
                   3892:     gp=matrix(0,nhstepm,1,nlstate);
                   3893:     gm=matrix(0,nhstepm,1,nlstate);
                   3894: 
                   3895: 
                   3896:     for(theta=1; theta <=npar; theta++){
                   3897:       for(i=1; i<=npar; i++){ /* Computes gradient x + delta*/
                   3898:        xp[i] = x[i] + (i==theta ?delti[theta]:0);
                   3899:       }
                   3900:       hpxij(p3mat,nhstepm,age,hstepm,xp,nlstate,stepm,oldm,savm, ij);  
                   3901:       prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ij);
                   3902: 
                   3903:       if (popbased==1) {
                   3904:        if(mobilav ==0){
                   3905:          for(i=1; i<=nlstate;i++)
                   3906:            prlim[i][i]=probs[(int)age][i][ij];
                   3907:        }else{ /* mobilav */ 
                   3908:          for(i=1; i<=nlstate;i++)
                   3909:            prlim[i][i]=mobaverage[(int)age][i][ij];
                   3910:        }
                   3911:       }
                   3912:   
                   3913:       for(j=1; j<= nlstate; j++){
                   3914:        for(h=0; h<=nhstepm; h++){
                   3915:          for(i=1, gp[h][j]=0.;i<=nlstate;i++)
                   3916:            gp[h][j] += prlim[i][i]*p3mat[i][j][h];
                   3917:        }
                   3918:       }
                   3919:       /* This for computing probability of death (h=1 means
                   3920:          computed over hstepm matrices product = hstepm*stepm months) 
                   3921:          as a weighted average of prlim.
                   3922:       */
                   3923:       for(j=nlstate+1;j<=nlstate+ndeath;j++){
                   3924:        for(i=1,gpp[j]=0.; i<= nlstate; i++)
                   3925:          gpp[j] += prlim[i][i]*p3mat[i][j][1];
                   3926:       }    
                   3927:       /* end probability of death */
                   3928: 
                   3929:       for(i=1; i<=npar; i++) /* Computes gradient x - delta */
                   3930:        xp[i] = x[i] - (i==theta ?delti[theta]:0);
                   3931:       hpxij(p3mat,nhstepm,age,hstepm,xp,nlstate,stepm,oldm,savm, ij);  
                   3932:       prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ij);
                   3933:  
                   3934:       if (popbased==1) {
                   3935:        if(mobilav ==0){
                   3936:          for(i=1; i<=nlstate;i++)
                   3937:            prlim[i][i]=probs[(int)age][i][ij];
                   3938:        }else{ /* mobilav */ 
                   3939:          for(i=1; i<=nlstate;i++)
                   3940:            prlim[i][i]=mobaverage[(int)age][i][ij];
                   3941:        }
                   3942:       }
                   3943: 
1.128     brouard  3944:       for(j=1; j<= nlstate; j++){  /* Sum of wi * eij = e.j */
1.126     brouard  3945:        for(h=0; h<=nhstepm; h++){
                   3946:          for(i=1, gm[h][j]=0.;i<=nlstate;i++)
                   3947:            gm[h][j] += prlim[i][i]*p3mat[i][j][h];
                   3948:        }
                   3949:       }
                   3950:       /* This for computing probability of death (h=1 means
                   3951:          computed over hstepm matrices product = hstepm*stepm months) 
                   3952:          as a weighted average of prlim.
                   3953:       */
                   3954:       for(j=nlstate+1;j<=nlstate+ndeath;j++){
                   3955:        for(i=1,gmp[j]=0.; i<= nlstate; i++)
                   3956:          gmp[j] += prlim[i][i]*p3mat[i][j][1];
                   3957:       }    
                   3958:       /* end probability of death */
                   3959: 
                   3960:       for(j=1; j<= nlstate; j++) /* vareij */
                   3961:        for(h=0; h<=nhstepm; h++){
                   3962:          gradg[h][theta][j]= (gp[h][j]-gm[h][j])/2./delti[theta];
                   3963:        }
                   3964: 
                   3965:       for(j=nlstate+1; j<= nlstate+ndeath; j++){ /* var mu */
                   3966:        gradgp[theta][j]= (gpp[j]-gmp[j])/2./delti[theta];
                   3967:       }
                   3968: 
                   3969:     } /* End theta */
                   3970: 
                   3971:     trgradg =ma3x(0,nhstepm,1,nlstate,1,npar); /* veij */
                   3972: 
                   3973:     for(h=0; h<=nhstepm; h++) /* veij */
                   3974:       for(j=1; j<=nlstate;j++)
                   3975:        for(theta=1; theta <=npar; theta++)
                   3976:          trgradg[h][j][theta]=gradg[h][theta][j];
                   3977: 
                   3978:     for(j=nlstate+1; j<=nlstate+ndeath;j++) /* mu */
                   3979:       for(theta=1; theta <=npar; theta++)
                   3980:        trgradgp[j][theta]=gradgp[theta][j];
                   3981:   
                   3982: 
                   3983:     hf=hstepm*stepm/YEARM;  /* Duration of hstepm expressed in year unit. */
                   3984:     for(i=1;i<=nlstate;i++)
                   3985:       for(j=1;j<=nlstate;j++)
                   3986:        vareij[i][j][(int)age] =0.;
                   3987: 
                   3988:     for(h=0;h<=nhstepm;h++){
                   3989:       for(k=0;k<=nhstepm;k++){
                   3990:        matprod2(dnewm,trgradg[h],1,nlstate,1,npar,1,npar,matcov);
                   3991:        matprod2(doldm,dnewm,1,nlstate,1,npar,1,nlstate,gradg[k]);
                   3992:        for(i=1;i<=nlstate;i++)
                   3993:          for(j=1;j<=nlstate;j++)
                   3994:            vareij[i][j][(int)age] += doldm[i][j]*hf*hf;
                   3995:       }
                   3996:     }
                   3997:   
                   3998:     /* pptj */
                   3999:     matprod2(dnewmp,trgradgp,nlstate+1,nlstate+ndeath,1,npar,1,npar,matcov);
                   4000:     matprod2(doldmp,dnewmp,nlstate+1,nlstate+ndeath,1,npar,nlstate+1,nlstate+ndeath,gradgp);
                   4001:     for(j=nlstate+1;j<=nlstate+ndeath;j++)
                   4002:       for(i=nlstate+1;i<=nlstate+ndeath;i++)
                   4003:        varppt[j][i]=doldmp[j][i];
                   4004:     /* end ppptj */
                   4005:     /*  x centered again */
                   4006:     hpxij(p3mat,nhstepm,age,hstepm,x,nlstate,stepm,oldm,savm, ij);  
                   4007:     prevalim(prlim,nlstate,x,age,oldm,savm,ftolpl,ij);
                   4008:  
                   4009:     if (popbased==1) {
                   4010:       if(mobilav ==0){
                   4011:        for(i=1; i<=nlstate;i++)
                   4012:          prlim[i][i]=probs[(int)age][i][ij];
                   4013:       }else{ /* mobilav */ 
                   4014:        for(i=1; i<=nlstate;i++)
                   4015:          prlim[i][i]=mobaverage[(int)age][i][ij];
                   4016:       }
                   4017:     }
                   4018:              
                   4019:     /* This for computing probability of death (h=1 means
                   4020:        computed over hstepm (estepm) matrices product = hstepm*stepm months) 
                   4021:        as a weighted average of prlim.
                   4022:     */
                   4023:     for(j=nlstate+1;j<=nlstate+ndeath;j++){
                   4024:       for(i=1,gmp[j]=0.;i<= nlstate; i++) 
                   4025:        gmp[j] += prlim[i][i]*p3mat[i][j][1]; 
                   4026:     }    
                   4027:     /* end probability of death */
                   4028: 
                   4029:     fprintf(ficresprobmorprev,"%3d %d ",(int) age, ij);
                   4030:     for(j=nlstate+1; j<=(nlstate+ndeath);j++){
                   4031:       fprintf(ficresprobmorprev," %11.3e %11.3e",gmp[j], sqrt(varppt[j][j]));
                   4032:       for(i=1; i<=nlstate;i++){
                   4033:        fprintf(ficresprobmorprev," %11.3e %11.3e ",prlim[i][i],p3mat[i][j][1]);
                   4034:       }
                   4035:     } 
                   4036:     fprintf(ficresprobmorprev,"\n");
                   4037: 
                   4038:     fprintf(ficresvij,"%.0f ",age );
                   4039:     for(i=1; i<=nlstate;i++)
                   4040:       for(j=1; j<=nlstate;j++){
                   4041:        fprintf(ficresvij," %.4f", vareij[i][j][(int)age]);
                   4042:       }
                   4043:     fprintf(ficresvij,"\n");
                   4044:     free_matrix(gp,0,nhstepm,1,nlstate);
                   4045:     free_matrix(gm,0,nhstepm,1,nlstate);
                   4046:     free_ma3x(gradg,0,nhstepm,1,npar,1,nlstate);
                   4047:     free_ma3x(trgradg,0,nhstepm,1,nlstate,1,npar);
                   4048:     free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   4049:   } /* End age */
                   4050:   free_vector(gpp,nlstate+1,nlstate+ndeath);
                   4051:   free_vector(gmp,nlstate+1,nlstate+ndeath);
                   4052:   free_matrix(gradgp,1,npar,nlstate+1,nlstate+ndeath);
                   4053:   free_matrix(trgradgp,nlstate+1,nlstate+ndeath,1,npar); /* mu or p point j*/
1.199   ! brouard  4054:   /* fprintf(ficgp,"\nunset parametric;unset label; set ter png small size 320, 240"); */
        !          4055:   fprintf(ficgp,"\nunset parametric;unset label; set ter svg size 640, 480");
1.126     brouard  4056:   /* for(j=nlstate+1; j<= nlstate+ndeath; j++){ *//* Only the first actually */
1.131     brouard  4057:   fprintf(ficgp,"\n set log y; unset log x;set xlabel \"Age\"; set ylabel \"Force of mortality (year-1)\";");
1.126     brouard  4058: /*   fprintf(ficgp,"\n plot \"%s\"  u 1:($3*%6.3f) not w l 1 ",fileresprobmorprev,YEARM/estepm); */
                   4059: /*   fprintf(ficgp,"\n replot \"%s\"  u 1:(($3+1.96*$4)*%6.3f) t \"95\%% interval\" w l 2 ",fileresprobmorprev,YEARM/estepm); */
                   4060: /*   fprintf(ficgp,"\n replot \"%s\"  u 1:(($3-1.96*$4)*%6.3f) not w l 2 ",fileresprobmorprev,YEARM/estepm); */
1.145     brouard  4061:   fprintf(ficgp,"\n plot \"%s\"  u 1:($3) not w l lt 1 ",subdirf(fileresprobmorprev));
1.170     brouard  4062:   fprintf(ficgp,"\n replot \"%s\"  u 1:(($3+1.96*$4)) t \"95%% interval\" w l lt 2 ",subdirf(fileresprobmorprev));
1.145     brouard  4063:   fprintf(ficgp,"\n replot \"%s\"  u 1:(($3-1.96*$4)) not w l lt 2 ",subdirf(fileresprobmorprev));
1.126     brouard  4064:   fprintf(fichtm,"\n<br> File (multiple files are possible if covariates are present): <A href=\"%s\">%s</a>\n",subdirf(fileresprobmorprev),subdirf(fileresprobmorprev));
1.199   ! brouard  4065:   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);
        !          4066:   /*  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  4067: */
1.199   ! brouard  4068: /*   fprintf(ficgp,"\nset out \"varmuptjgr%s%s%s.svg\";replot;",digitp,optionfilefiname,digit); */
        !          4069:   fprintf(ficgp,"\nset out \"%s%s.svg\";replot;\n",subdirf3(optionfilefiname,"varmuptjgr",digitp),digit);
1.126     brouard  4070: 
                   4071:   free_vector(xp,1,npar);
                   4072:   free_matrix(doldm,1,nlstate,1,nlstate);
                   4073:   free_matrix(dnewm,1,nlstate,1,npar);
                   4074:   free_matrix(doldmp,nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);
                   4075:   free_matrix(dnewmp,nlstate+1,nlstate+ndeath,1,npar);
                   4076:   free_matrix(varppt,nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);
                   4077:   if (mobilav!=0) free_ma3x(mobaverage,1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
                   4078:   fclose(ficresprobmorprev);
                   4079:   fflush(ficgp);
                   4080:   fflush(fichtm); 
                   4081: }  /* end varevsij */
                   4082: 
                   4083: /************ Variance of prevlim ******************/
                   4084: 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[])
                   4085: {
                   4086:   /* Variance of prevalence limit */
                   4087:   /*  double **prevalim(double **prlim, int nlstate, double *xp, double age, double **oldm, double **savm,double ftolpl);*/
1.164     brouard  4088: 
1.126     brouard  4089:   double **dnewm,**doldm;
                   4090:   int i, j, nhstepm, hstepm;
                   4091:   double *xp;
                   4092:   double *gp, *gm;
                   4093:   double **gradg, **trgradg;
                   4094:   double age,agelim;
                   4095:   int theta;
                   4096:   
                   4097:   pstamp(ficresvpl);
                   4098:   fprintf(ficresvpl,"# Standard deviation of period (stable) prevalences \n");
                   4099:   fprintf(ficresvpl,"# Age");
                   4100:   for(i=1; i<=nlstate;i++)
                   4101:       fprintf(ficresvpl," %1d-%1d",i,i);
                   4102:   fprintf(ficresvpl,"\n");
                   4103: 
                   4104:   xp=vector(1,npar);
                   4105:   dnewm=matrix(1,nlstate,1,npar);
                   4106:   doldm=matrix(1,nlstate,1,nlstate);
                   4107:   
                   4108:   hstepm=1*YEARM; /* Every year of age */
                   4109:   hstepm=hstepm/stepm; /* Typically in stepm units, if j= 2 years, = 2/6 months = 4 */ 
                   4110:   agelim = AGESUP;
                   4111:   for (age=bage; age<=fage; age ++){ /* If stepm=6 months */
                   4112:     nhstepm=(int) rint((agelim-age)*YEARM/stepm); /* Typically 20 years = 20*12/6=40 */ 
                   4113:     if (stepm >= YEARM) hstepm=1;
                   4114:     nhstepm = nhstepm/hstepm; /* Typically 40/4=10 */
                   4115:     gradg=matrix(1,npar,1,nlstate);
                   4116:     gp=vector(1,nlstate);
                   4117:     gm=vector(1,nlstate);
                   4118: 
                   4119:     for(theta=1; theta <=npar; theta++){
                   4120:       for(i=1; i<=npar; i++){ /* Computes gradient */
                   4121:        xp[i] = x[i] + (i==theta ?delti[theta]:0);
                   4122:       }
                   4123:       prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ij);
                   4124:       for(i=1;i<=nlstate;i++)
                   4125:        gp[i] = prlim[i][i];
                   4126:     
                   4127:       for(i=1; i<=npar; i++) /* Computes gradient */
                   4128:        xp[i] = x[i] - (i==theta ?delti[theta]:0);
                   4129:       prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ij);
                   4130:       for(i=1;i<=nlstate;i++)
                   4131:        gm[i] = prlim[i][i];
                   4132: 
                   4133:       for(i=1;i<=nlstate;i++)
                   4134:        gradg[theta][i]= (gp[i]-gm[i])/2./delti[theta];
                   4135:     } /* End theta */
                   4136: 
                   4137:     trgradg =matrix(1,nlstate,1,npar);
                   4138: 
                   4139:     for(j=1; j<=nlstate;j++)
                   4140:       for(theta=1; theta <=npar; theta++)
                   4141:        trgradg[j][theta]=gradg[theta][j];
                   4142: 
                   4143:     for(i=1;i<=nlstate;i++)
                   4144:       varpl[i][(int)age] =0.;
                   4145:     matprod2(dnewm,trgradg,1,nlstate,1,npar,1,npar,matcov);
                   4146:     matprod2(doldm,dnewm,1,nlstate,1,npar,1,nlstate,gradg);
                   4147:     for(i=1;i<=nlstate;i++)
                   4148:       varpl[i][(int)age] = doldm[i][i]; /* Covariances are useless */
                   4149: 
                   4150:     fprintf(ficresvpl,"%.0f ",age );
                   4151:     for(i=1; i<=nlstate;i++)
                   4152:       fprintf(ficresvpl," %.5f (%.5f)",prlim[i][i],sqrt(varpl[i][(int)age]));
                   4153:     fprintf(ficresvpl,"\n");
                   4154:     free_vector(gp,1,nlstate);
                   4155:     free_vector(gm,1,nlstate);
                   4156:     free_matrix(gradg,1,npar,1,nlstate);
                   4157:     free_matrix(trgradg,1,nlstate,1,npar);
                   4158:   } /* End age */
                   4159: 
                   4160:   free_vector(xp,1,npar);
                   4161:   free_matrix(doldm,1,nlstate,1,npar);
                   4162:   free_matrix(dnewm,1,nlstate,1,nlstate);
                   4163: 
                   4164: }
                   4165: 
                   4166: /************ Variance of one-step probabilities  ******************/
                   4167: 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[])
                   4168: {
1.164     brouard  4169:   int i, j=0,  k1, l1, tj;
1.126     brouard  4170:   int k2, l2, j1,  z1;
1.164     brouard  4171:   int k=0, l;
1.145     brouard  4172:   int first=1, first1, first2;
1.126     brouard  4173:   double cv12, mu1, mu2, lc1, lc2, v12, v21, v11, v22,v1,v2, c12, tnalp;
                   4174:   double **dnewm,**doldm;
                   4175:   double *xp;
                   4176:   double *gp, *gm;
                   4177:   double **gradg, **trgradg;
                   4178:   double **mu;
1.164     brouard  4179:   double age, cov[NCOVMAX+1];
1.126     brouard  4180:   double std=2.0; /* Number of standard deviation wide of confidence ellipsoids */
                   4181:   int theta;
                   4182:   char fileresprob[FILENAMELENGTH];
                   4183:   char fileresprobcov[FILENAMELENGTH];
                   4184:   char fileresprobcor[FILENAMELENGTH];
                   4185:   double ***varpij;
                   4186: 
                   4187:   strcpy(fileresprob,"prob"); 
                   4188:   strcat(fileresprob,fileres);
                   4189:   if((ficresprob=fopen(fileresprob,"w"))==NULL) {
                   4190:     printf("Problem with resultfile: %s\n", fileresprob);
                   4191:     fprintf(ficlog,"Problem with resultfile: %s\n", fileresprob);
                   4192:   }
                   4193:   strcpy(fileresprobcov,"probcov"); 
                   4194:   strcat(fileresprobcov,fileres);
                   4195:   if((ficresprobcov=fopen(fileresprobcov,"w"))==NULL) {
                   4196:     printf("Problem with resultfile: %s\n", fileresprobcov);
                   4197:     fprintf(ficlog,"Problem with resultfile: %s\n", fileresprobcov);
                   4198:   }
                   4199:   strcpy(fileresprobcor,"probcor"); 
                   4200:   strcat(fileresprobcor,fileres);
                   4201:   if((ficresprobcor=fopen(fileresprobcor,"w"))==NULL) {
                   4202:     printf("Problem with resultfile: %s\n", fileresprobcor);
                   4203:     fprintf(ficlog,"Problem with resultfile: %s\n", fileresprobcor);
                   4204:   }
                   4205:   printf("Computing standard deviation of one-step probabilities: result on file '%s' \n",fileresprob);
                   4206:   fprintf(ficlog,"Computing standard deviation of one-step probabilities: result on file '%s' \n",fileresprob);
                   4207:   printf("Computing matrix of variance covariance of one-step probabilities: result on file '%s' \n",fileresprobcov);
                   4208:   fprintf(ficlog,"Computing matrix of variance covariance of one-step probabilities: result on file '%s' \n",fileresprobcov);
                   4209:   printf("and correlation matrix of one-step probabilities: result on file '%s' \n",fileresprobcor);
                   4210:   fprintf(ficlog,"and correlation matrix of one-step probabilities: result on file '%s' \n",fileresprobcor);
                   4211:   pstamp(ficresprob);
                   4212:   fprintf(ficresprob,"#One-step probabilities and stand. devi in ()\n");
                   4213:   fprintf(ficresprob,"# Age");
                   4214:   pstamp(ficresprobcov);
                   4215:   fprintf(ficresprobcov,"#One-step probabilities and covariance matrix\n");
                   4216:   fprintf(ficresprobcov,"# Age");
                   4217:   pstamp(ficresprobcor);
                   4218:   fprintf(ficresprobcor,"#One-step probabilities and correlation matrix\n");
                   4219:   fprintf(ficresprobcor,"# Age");
                   4220: 
                   4221: 
                   4222:   for(i=1; i<=nlstate;i++)
                   4223:     for(j=1; j<=(nlstate+ndeath);j++){
                   4224:       fprintf(ficresprob," p%1d-%1d (SE)",i,j);
                   4225:       fprintf(ficresprobcov," p%1d-%1d ",i,j);
                   4226:       fprintf(ficresprobcor," p%1d-%1d ",i,j);
                   4227:     }  
                   4228:  /* fprintf(ficresprob,"\n");
                   4229:   fprintf(ficresprobcov,"\n");
                   4230:   fprintf(ficresprobcor,"\n");
                   4231:  */
1.131     brouard  4232:   xp=vector(1,npar);
1.126     brouard  4233:   dnewm=matrix(1,(nlstate)*(nlstate+ndeath),1,npar);
                   4234:   doldm=matrix(1,(nlstate)*(nlstate+ndeath),1,(nlstate)*(nlstate+ndeath));
                   4235:   mu=matrix(1,(nlstate)*(nlstate+ndeath), (int) bage, (int)fage);
                   4236:   varpij=ma3x(1,nlstate*(nlstate+ndeath),1,nlstate*(nlstate+ndeath),(int) bage, (int) fage);
                   4237:   first=1;
                   4238:   fprintf(ficgp,"\n# Routine varprob");
                   4239:   fprintf(fichtm,"\n<li><h4> Computing and drawing one step probabilities with their confidence intervals</h4></li>\n");
                   4240:   fprintf(fichtm,"\n");
                   4241: 
1.197     brouard  4242:   fprintf(fichtm,"\n<li><h4> <a href=\"%s\">Matrix of variance-covariance of one-step probabilities (drawings)</a></h4></br>this page is important in order to visualize confidence intervals and especially correlation between disability and recovery</li>\n",optionfilehtmcov);
                   4243:   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);
                   4244:   fprintf(fichtmcov,"\nEllipsoids of confidence centered on point (p<inf>ij</inf>, p<inf>kl</inf>) are estimated \
1.126     brouard  4245: and drawn. It helps understanding how is the covariance between two incidences.\
                   4246:  They are expressed in year<sup>-1</sup> in order to be less dependent of stepm.<br>\n");
                   4247:   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. \
                   4248: It can be understood this way: if pij and pkl where uncorrelated the (2x2) matrix of covariance \
                   4249: would have been (1/(var pij), 0 , 0, 1/(var pkl)), and the confidence interval would be 2 \
                   4250: standard deviations wide on each axis. <br>\
                   4251:  Now, if both incidences are correlated (usual case) we diagonalised the inverse of the covariance matrix\
                   4252:  and made the appropriate rotation to look at the uncorrelated principal directions.<br>\
                   4253: To be simple, these graphs help to understand the significativity of each parameter in relation to a second other one.<br> \n");
                   4254: 
                   4255:   cov[1]=1;
1.145     brouard  4256:   /* tj=cptcoveff; */
                   4257:   tj = (int) pow(2,cptcoveff);
1.126     brouard  4258:   if (cptcovn<1) {tj=1;ncodemax[1]=1;}
                   4259:   j1=0;
1.145     brouard  4260:   for(j1=1; j1<=tj;j1++){
                   4261:     /*for(i1=1; i1<=ncodemax[t];i1++){ */
                   4262:     /*j1++;*/
1.126     brouard  4263:       if  (cptcovn>0) {
                   4264:        fprintf(ficresprob, "\n#********** Variable "); 
1.198     brouard  4265:        for (z1=1; z1<=cptcoveff; z1++) fprintf(ficresprob, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
1.126     brouard  4266:        fprintf(ficresprob, "**********\n#\n");
                   4267:        fprintf(ficresprobcov, "\n#********** Variable "); 
1.198     brouard  4268:        for (z1=1; z1<=cptcoveff; z1++) fprintf(ficresprobcov, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
1.126     brouard  4269:        fprintf(ficresprobcov, "**********\n#\n");
                   4270:        
                   4271:        fprintf(ficgp, "\n#********** Variable "); 
1.198     brouard  4272:        for (z1=1; z1<=cptcoveff; z1++) fprintf(ficgp, " V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
1.126     brouard  4273:        fprintf(ficgp, "**********\n#\n");
                   4274:        
                   4275:        
                   4276:        fprintf(fichtmcov, "\n<hr  size=\"2\" color=\"#EC5E5E\">********** Variable "); 
1.198     brouard  4277:        for (z1=1; z1<=cptcoveff; z1++) fprintf(fichtm, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
1.126     brouard  4278:        fprintf(fichtmcov, "**********\n<hr size=\"2\" color=\"#EC5E5E\">");
                   4279:        
                   4280:        fprintf(ficresprobcor, "\n#********** Variable ");    
1.198     brouard  4281:        for (z1=1; z1<=cptcoveff; z1++) fprintf(ficresprobcor, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
1.126     brouard  4282:        fprintf(ficresprobcor, "**********\n#");    
                   4283:       }
                   4284:       
1.145     brouard  4285:       gradg=matrix(1,npar,1,(nlstate)*(nlstate+ndeath));
                   4286:       trgradg=matrix(1,(nlstate)*(nlstate+ndeath),1,npar);
                   4287:       gp=vector(1,(nlstate)*(nlstate+ndeath));
                   4288:       gm=vector(1,(nlstate)*(nlstate+ndeath));
1.126     brouard  4289:       for (age=bage; age<=fage; age ++){ 
                   4290:        cov[2]=age;
1.187     brouard  4291:        if(nagesqr==1)
                   4292:          cov[3]= age*age;
1.126     brouard  4293:        for (k=1; k<=cptcovn;k++) {
1.198     brouard  4294:          cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(j1,Tvar[k])];/* j1 1 2 3 4
1.145     brouard  4295:                                                         * 1  1 1 1 1
                   4296:                                                         * 2  2 1 1 1
                   4297:                                                         * 3  1 2 1 1
                   4298:                                                         */
                   4299:          /* nbcode[1][1]=0 nbcode[1][2]=1;*/
1.126     brouard  4300:        }
1.186     brouard  4301:        /* for (k=1; k<=cptcovage;k++) cov[2+Tage[k]]=cov[2+Tage[k]]*cov[2]; */
1.198     brouard  4302:        for (k=1; k<=cptcovage;k++) cov[2+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(ij,Tvar[Tage[k]])]*cov[2];
1.126     brouard  4303:        for (k=1; k<=cptcovprod;k++)
1.198     brouard  4304:          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  4305:        
                   4306:     
                   4307:        for(theta=1; theta <=npar; theta++){
                   4308:          for(i=1; i<=npar; i++)
                   4309:            xp[i] = x[i] + (i==theta ?delti[theta]:(double)0);
                   4310:          
                   4311:          pmij(pmmij,cov,ncovmodel,xp,nlstate);
                   4312:          
                   4313:          k=0;
                   4314:          for(i=1; i<= (nlstate); i++){
                   4315:            for(j=1; j<=(nlstate+ndeath);j++){
                   4316:              k=k+1;
                   4317:              gp[k]=pmmij[i][j];
                   4318:            }
                   4319:          }
                   4320:          
                   4321:          for(i=1; i<=npar; i++)
                   4322:            xp[i] = x[i] - (i==theta ?delti[theta]:(double)0);
                   4323:     
                   4324:          pmij(pmmij,cov,ncovmodel,xp,nlstate);
                   4325:          k=0;
                   4326:          for(i=1; i<=(nlstate); i++){
                   4327:            for(j=1; j<=(nlstate+ndeath);j++){
                   4328:              k=k+1;
                   4329:              gm[k]=pmmij[i][j];
                   4330:            }
                   4331:          }
                   4332:      
                   4333:          for(i=1; i<= (nlstate)*(nlstate+ndeath); i++) 
                   4334:            gradg[theta][i]=(gp[i]-gm[i])/(double)2./delti[theta];  
                   4335:        }
                   4336: 
                   4337:        for(j=1; j<=(nlstate)*(nlstate+ndeath);j++)
                   4338:          for(theta=1; theta <=npar; theta++)
                   4339:            trgradg[j][theta]=gradg[theta][j];
                   4340:        
                   4341:        matprod2(dnewm,trgradg,1,(nlstate)*(nlstate+ndeath),1,npar,1,npar,matcov); 
                   4342:        matprod2(doldm,dnewm,1,(nlstate)*(nlstate+ndeath),1,npar,1,(nlstate)*(nlstate+ndeath),gradg);
                   4343: 
                   4344:        pmij(pmmij,cov,ncovmodel,x,nlstate);
                   4345:        
                   4346:        k=0;
                   4347:        for(i=1; i<=(nlstate); i++){
                   4348:          for(j=1; j<=(nlstate+ndeath);j++){
                   4349:            k=k+1;
                   4350:            mu[k][(int) age]=pmmij[i][j];
                   4351:          }
                   4352:        }
                   4353:        for(i=1;i<=(nlstate)*(nlstate+ndeath);i++)
                   4354:          for(j=1;j<=(nlstate)*(nlstate+ndeath);j++)
                   4355:            varpij[i][j][(int)age] = doldm[i][j];
                   4356: 
                   4357:        /*printf("\n%d ",(int)age);
                   4358:          for (i=1; i<=(nlstate)*(nlstate+ndeath);i++){
                   4359:          printf("%e [%e ;%e] ",gm[i],gm[i]-2*sqrt(doldm[i][i]),gm[i]+2*sqrt(doldm[i][i]));
                   4360:          fprintf(ficlog,"%e [%e ;%e] ",gm[i],gm[i]-2*sqrt(doldm[i][i]),gm[i]+2*sqrt(doldm[i][i]));
                   4361:          }*/
                   4362: 
                   4363:        fprintf(ficresprob,"\n%d ",(int)age);
                   4364:        fprintf(ficresprobcov,"\n%d ",(int)age);
                   4365:        fprintf(ficresprobcor,"\n%d ",(int)age);
                   4366: 
                   4367:        for (i=1; i<=(nlstate)*(nlstate+ndeath);i++)
                   4368:          fprintf(ficresprob,"%11.3e (%11.3e) ",mu[i][(int) age],sqrt(varpij[i][i][(int)age]));
                   4369:        for (i=1; i<=(nlstate)*(nlstate+ndeath);i++){
                   4370:          fprintf(ficresprobcov,"%11.3e ",mu[i][(int) age]);
                   4371:          fprintf(ficresprobcor,"%11.3e ",mu[i][(int) age]);
                   4372:        }
                   4373:        i=0;
                   4374:        for (k=1; k<=(nlstate);k++){
                   4375:          for (l=1; l<=(nlstate+ndeath);l++){ 
1.145     brouard  4376:            i++;
1.126     brouard  4377:            fprintf(ficresprobcov,"\n%d %d-%d",(int)age,k,l);
                   4378:            fprintf(ficresprobcor,"\n%d %d-%d",(int)age,k,l);
                   4379:            for (j=1; j<=i;j++){
1.145     brouard  4380:              /* printf(" k=%d l=%d i=%d j=%d\n",k,l,i,j);fflush(stdout); */
1.126     brouard  4381:              fprintf(ficresprobcov," %11.3e",varpij[i][j][(int)age]);
                   4382:              fprintf(ficresprobcor," %11.3e",varpij[i][j][(int) age]/sqrt(varpij[i][i][(int) age])/sqrt(varpij[j][j][(int)age]));
                   4383:            }
                   4384:          }
                   4385:        }/* end of loop for state */
                   4386:       } /* end of loop for age */
1.145     brouard  4387:       free_vector(gp,1,(nlstate+ndeath)*(nlstate+ndeath));
                   4388:       free_vector(gm,1,(nlstate+ndeath)*(nlstate+ndeath));
                   4389:       free_matrix(trgradg,1,(nlstate+ndeath)*(nlstate+ndeath),1,npar);
                   4390:       free_matrix(gradg,1,(nlstate+ndeath)*(nlstate+ndeath),1,npar);
                   4391:       
1.126     brouard  4392:       /* Confidence intervalle of pij  */
                   4393:       /*
1.131     brouard  4394:        fprintf(ficgp,"\nunset parametric;unset label");
1.126     brouard  4395:        fprintf(ficgp,"\nset log y;unset log x; set xlabel \"Age\";set ylabel \"probability (year-1)\"");
                   4396:        fprintf(ficgp,"\nset ter png small\nset size 0.65,0.65");
                   4397:        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);
                   4398:        fprintf(fichtm,"\n<br><img src=\"pijgr%s.png\"> ",optionfilefiname);
                   4399:        fprintf(ficgp,"\nset out \"pijgr%s.png\"",optionfilefiname);
                   4400:        fprintf(ficgp,"\nplot \"%s\" every :::%d::%d u 1:2 \"\%%lf",k1,k2,xfilevarprob);
                   4401:       */
                   4402: 
                   4403:       /* Drawing ellipsoids of confidence of two variables p(k1-l1,k2-l2)*/
1.145     brouard  4404:       first1=1;first2=2;
1.126     brouard  4405:       for (k2=1; k2<=(nlstate);k2++){
                   4406:        for (l2=1; l2<=(nlstate+ndeath);l2++){ 
                   4407:          if(l2==k2) continue;
                   4408:          j=(k2-1)*(nlstate+ndeath)+l2;
                   4409:          for (k1=1; k1<=(nlstate);k1++){
                   4410:            for (l1=1; l1<=(nlstate+ndeath);l1++){ 
                   4411:              if(l1==k1) continue;
                   4412:              i=(k1-1)*(nlstate+ndeath)+l1;
                   4413:              if(i<=j) continue;
                   4414:              for (age=bage; age<=fage; age ++){ 
                   4415:                if ((int)age %5==0){
                   4416:                  v1=varpij[i][i][(int)age]/stepm*YEARM/stepm*YEARM;
                   4417:                  v2=varpij[j][j][(int)age]/stepm*YEARM/stepm*YEARM;
                   4418:                  cv12=varpij[i][j][(int)age]/stepm*YEARM/stepm*YEARM;
                   4419:                  mu1=mu[i][(int) age]/stepm*YEARM ;
                   4420:                  mu2=mu[j][(int) age]/stepm*YEARM;
                   4421:                  c12=cv12/sqrt(v1*v2);
                   4422:                  /* Computing eigen value of matrix of covariance */
                   4423:                  lc1=((v1+v2)+sqrt((v1+v2)*(v1+v2) - 4*(v1*v2-cv12*cv12)))/2.;
                   4424:                  lc2=((v1+v2)-sqrt((v1+v2)*(v1+v2) - 4*(v1*v2-cv12*cv12)))/2.;
1.135     brouard  4425:                  if ((lc2 <0) || (lc1 <0) ){
1.145     brouard  4426:                    if(first2==1){
                   4427:                      first1=0;
                   4428:                    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);
                   4429:                    }
                   4430:                    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);
                   4431:                    /* lc1=fabs(lc1); */ /* If we want to have them positive */
                   4432:                    /* lc2=fabs(lc2); */
1.135     brouard  4433:                  }
                   4434: 
1.126     brouard  4435:                  /* Eigen vectors */
                   4436:                  v11=(1./sqrt(1+(v1-lc1)*(v1-lc1)/cv12/cv12));
                   4437:                  /*v21=sqrt(1.-v11*v11); *//* error */
                   4438:                  v21=(lc1-v1)/cv12*v11;
                   4439:                  v12=-v21;
                   4440:                  v22=v11;
                   4441:                  tnalp=v21/v11;
                   4442:                  if(first1==1){
                   4443:                    first1=0;
                   4444:                    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);
                   4445:                  }
                   4446:                  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);
                   4447:                  /*printf(fignu*/
                   4448:                  /* mu1+ v11*lc1*cost + v12*lc2*sin(t) */
                   4449:                  /* mu2+ v21*lc1*cost + v22*lc2*sin(t) */
                   4450:                  if(first==1){
                   4451:                    first=0;
                   4452:                    fprintf(ficgp,"\nset parametric;unset label");
                   4453:                    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  4454:                    fprintf(ficgp,"\nset ter svg size 640, 480");
1.126     brouard  4455:                    fprintf(fichtmcov,"\n<br>Ellipsoids of confidence cov(p%1d%1d,p%1d%1d) expressed in year<sup>-1</sup>\
1.199   ! brouard  4456:  :<a href=\"%s%d%1d%1d-%1d%1d.svg\">\
        !          4457: %s%d%1d%1d-%1d%1d.svg</A>, ",k1,l1,k2,l2,\
1.126     brouard  4458:                            subdirf2(optionfilefiname,"varpijgr"), j1,k1,l1,k2,l2,\
                   4459:                            subdirf2(optionfilefiname,"varpijgr"), j1,k1,l1,k2,l2);
1.199   ! brouard  4460:                    fprintf(fichtmcov,"\n<br><img src=\"%s%d%1d%1d-%1d%1d.svg\"> ",subdirf2(optionfilefiname,"varpijgr"), j1,k1,l1,k2,l2);
1.126     brouard  4461:                    fprintf(fichtmcov,"\n<br> Correlation at age %d (%.3f),",(int) age, c12);
1.199   ! brouard  4462:                    fprintf(ficgp,"\nset out \"%s%d%1d%1d-%1d%1d.svg\"",subdirf2(optionfilefiname,"varpijgr"), j1,k1,l1,k2,l2);
1.126     brouard  4463:                    fprintf(ficgp,"\nset label \"%d\" at %11.3e,%11.3e center",(int) age, mu1,mu2);
                   4464:                    fprintf(ficgp,"\n# Age %d, p%1d%1d - p%1d%1d",(int) age, k1,l1,k2,l2);
                   4465:                    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",\
                   4466:                            mu1,std,v11,sqrt(lc1),v12,sqrt(lc2),\
                   4467:                            mu2,std,v21,sqrt(lc1),v22,sqrt(lc2));
                   4468:                  }else{
                   4469:                    first=0;
                   4470:                    fprintf(fichtmcov," %d (%.3f),",(int) age, c12);
                   4471:                    fprintf(ficgp,"\n# Age %d, p%1d%1d - p%1d%1d",(int) age, k1,l1,k2,l2);
                   4472:                    fprintf(ficgp,"\nset label \"%d\" at %11.3e,%11.3e center",(int) age, mu1,mu2);
                   4473:                    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",\
                   4474:                            mu1,std,v11,sqrt(lc1),v12,sqrt(lc2),\
                   4475:                            mu2,std,v21,sqrt(lc1),v22,sqrt(lc2));
                   4476:                  }/* if first */
                   4477:                } /* age mod 5 */
                   4478:              } /* end loop age */
1.199   ! brouard  4479:              fprintf(ficgp,"\nset out \"%s%d%1d%1d-%1d%1d.svg\";replot;",subdirf2(optionfilefiname,"varpijgr"), j1,k1,l1,k2,l2);
1.126     brouard  4480:              first=1;
                   4481:            } /*l12 */
                   4482:          } /* k12 */
                   4483:        } /*l1 */
                   4484:       }/* k1 */
1.169     brouard  4485:       /* } */ /* loop covariates */
1.126     brouard  4486:   }
                   4487:   free_ma3x(varpij,1,nlstate,1,nlstate+ndeath,(int) bage, (int)fage);
                   4488:   free_matrix(mu,1,(nlstate+ndeath)*(nlstate+ndeath),(int) bage, (int)fage);
                   4489:   free_matrix(doldm,1,(nlstate)*(nlstate+ndeath),1,(nlstate)*(nlstate+ndeath));
                   4490:   free_matrix(dnewm,1,(nlstate)*(nlstate+ndeath),1,npar);
                   4491:   free_vector(xp,1,npar);
                   4492:   fclose(ficresprob);
                   4493:   fclose(ficresprobcov);
                   4494:   fclose(ficresprobcor);
                   4495:   fflush(ficgp);
                   4496:   fflush(fichtmcov);
                   4497: }
                   4498: 
                   4499: 
                   4500: /******************* Printing html file ***********/
                   4501: void printinghtml(char fileres[], char title[], char datafile[], int firstpass, \
                   4502:                  int lastpass, int stepm, int weightopt, char model[],\
                   4503:                  int imx,int jmin, int jmax, double jmeanint,char rfileres[],\
                   4504:                  int popforecast, int estepm ,\
                   4505:                  double jprev1, double mprev1,double anprev1, \
                   4506:                  double jprev2, double mprev2,double anprev2){
                   4507:   int jj1, k1, i1, cpt;
                   4508: 
                   4509:    fprintf(fichtm,"<ul><li><a href='#firstorder'>Result files (first order: no variance)</a>\n \
                   4510:    <li><a href='#secondorder'>Result files (second order (variance)</a>\n \
                   4511: </ul>");
                   4512:    fprintf(fichtm,"<ul><li><h4><a name='firstorder'>Result files (first order: no variance)</a></h4>\n \
                   4513:  - Observed prevalence in each state (during the period defined between %.lf/%.lf/%.lf and %.lf/%.lf/%.lf): <a href=\"%s\">%s</a> <br>\n ",
                   4514:           jprev1, mprev1,anprev1,jprev2, mprev2,anprev2,subdirf2(fileres,"p"),subdirf2(fileres,"p"));
                   4515:    fprintf(fichtm,"\
                   4516:  - Estimated transition probabilities over %d (stepm) months: <a href=\"%s\">%s</a><br>\n ",
                   4517:           stepm,subdirf2(fileres,"pij"),subdirf2(fileres,"pij"));
                   4518:    fprintf(fichtm,"\
                   4519:  - Period (stable) prevalence in each health state: <a href=\"%s\">%s</a> <br>\n",
                   4520:           subdirf2(fileres,"pl"),subdirf2(fileres,"pl"));
                   4521:    fprintf(fichtm,"\
1.128     brouard  4522:  - (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  4523:    <a href=\"%s\">%s</a> <br>\n",
                   4524:           estepm,subdirf2(fileres,"e"),subdirf2(fileres,"e"));
                   4525:    fprintf(fichtm,"\
                   4526:  - Population projections by age and states: \
                   4527:    <a href=\"%s\">%s</a> <br>\n</li>", subdirf2(fileres,"f"),subdirf2(fileres,"f"));
                   4528: 
                   4529: fprintf(fichtm," \n<ul><li><b>Graphs</b></li><p>");
                   4530: 
1.145     brouard  4531:  m=pow(2,cptcoveff);
1.126     brouard  4532:  if (cptcovn < 1) {m=1;ncodemax[1]=1;}
                   4533: 
                   4534:  jj1=0;
                   4535:  for(k1=1; k1<=m;k1++){
1.192     brouard  4536:    /* for(i1=1; i1<=ncodemax[k1];i1++){ */
1.126     brouard  4537:      jj1++;
                   4538:      if (cptcovn > 0) {
                   4539:        fprintf(fichtm,"<hr  size=\"2\" color=\"#EC5E5E\">************ Results for covariates");
1.192     brouard  4540:        for (cpt=1; cpt<=cptcoveff;cpt++){ 
1.198     brouard  4541:         fprintf(fichtm," V%d=%d ",Tvaraff[cpt],nbcode[Tvaraff[cpt]][codtabm(jj1,cpt)]);
                   4542:         printf(" V%d=%d ",Tvaraff[cpt],nbcode[Tvaraff[cpt]][codtabm(jj1,cpt)]);fflush(stdout);
1.192     brouard  4543:        }
1.126     brouard  4544:        fprintf(fichtm," ************\n<hr size=\"2\" color=\"#EC5E5E\">");
                   4545:      }
                   4546:      /* Pij */
1.199   ! brouard  4547:      fprintf(fichtm,"<br>- Pij or Conditional probabilities to be observed in state j being in state i, %d (stepm) months before: <a href=\"%s%d_1.svg\">%s%d_1.svg</a><br> \
        !          4548: <img src=\"%s%d_1.svg\">",stepm,subdirf2(optionfilefiname,"pe"),jj1,subdirf2(optionfilefiname,"pe"),jj1,subdirf2(optionfilefiname,"pe"),jj1);     
1.126     brouard  4549:      /* Quasi-incidences */
                   4550:      fprintf(fichtm,"<br>- Pij or Conditional probabilities to be observed in state j being in state i %d (stepm) months\
1.199   ! brouard  4551:  before but expressed in per year i.e. quasi incidences if stepm is small and probabilities too: <a href=\"%s%d_2.svg\">%s%d_2.svg</a><br> \
        !          4552: <img src=\"%s%d_2.svg\">",stepm,subdirf2(optionfilefiname,"pe"),jj1,subdirf2(optionfilefiname,"pe"),jj1,subdirf2(optionfilefiname,"pe"),jj1); 
1.126     brouard  4553:        /* Period (stable) prevalence in each health state */
1.154     brouard  4554:        for(cpt=1; cpt<=nlstate;cpt++){
1.199   ! brouard  4555:         fprintf(fichtm,"<br>- Convergence to period (stable) prevalence in state %d. Or probability to be in state %d being in state (1 to %d) at different ages. <a href=\"%s%d_%d.svg\">%s%d_%d.svg</a><br> \
        !          4556: <img src=\"%s%d_%d.svg\">", cpt, cpt, nlstate, subdirf2(optionfilefiname,"p"),cpt,jj1,subdirf2(optionfilefiname,"p"),cpt,jj1,subdirf2(optionfilefiname,"p"),cpt,jj1);
1.126     brouard  4557:        }
                   4558:      for(cpt=1; cpt<=nlstate;cpt++) {
1.199   ! brouard  4559:         fprintf(fichtm,"\n<br>- Life expectancy by health state (%d) at initial age and its decomposition into health expectancies in each alive state (1 to %d) : <a href=\"%s%d%d.svg\">%s%d%d.svg</a> <br> \
        !          4560: <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  4561:      }
1.192     brouard  4562:    /* } /\* end i1 *\/ */
1.126     brouard  4563:  }/* End k1 */
                   4564:  fprintf(fichtm,"</ul>");
                   4565: 
                   4566:  fprintf(fichtm,"\
                   4567: \n<br><li><h4> <a name='secondorder'>Result files (second order: variances)</a></h4>\n\
1.193     brouard  4568:  - Parameter file with estimated parameters and covariance matrix: <a href=\"%s\">%s</a> <br> \
1.197     brouard  4569:  - 95%% confidence intervals and Wald tests of the estimated parameters are in the log file.<br> \
                   4570: But because parameters are usually highly correlated (a higher incidence of disability \
                   4571: and a higher incidence of recovery can give very close observed transition) it might \
                   4572: be very useful to look not only at linear confidence intervals estimated from the \
                   4573: variances but at the covariance matrix. And instead of looking at the estimated coefficients \
                   4574: (parameters) of the logistic regression, it might be more meaningful to visualize the \
                   4575: covariance matrix of the one-step probabilities. \
                   4576: See page 'Matrix of variance-covariance of one-step probabilities' below. \n", rfileres,rfileres);
1.126     brouard  4577: 
1.193     brouard  4578:  fprintf(fichtm," - Standard deviation of one-step probabilities: <a href=\"%s\">%s</a> <br>\n",
1.126     brouard  4579:         subdirf2(fileres,"prob"),subdirf2(fileres,"prob"));
                   4580:  fprintf(fichtm,"\
                   4581:  - Variance-covariance of one-step probabilities: <a href=\"%s\">%s</a> <br>\n",
                   4582:         subdirf2(fileres,"probcov"),subdirf2(fileres,"probcov"));
                   4583: 
                   4584:  fprintf(fichtm,"\
                   4585:  - Correlation matrix of one-step probabilities: <a href=\"%s\">%s</a> <br>\n",
                   4586:         subdirf2(fileres,"probcor"),subdirf2(fileres,"probcor"));
                   4587:  fprintf(fichtm,"\
                   4588:  - 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): \
                   4589:    <a href=\"%s\">%s</a> <br>\n</li>",
                   4590:           estepm,subdirf2(fileres,"cve"),subdirf2(fileres,"cve"));
                   4591:  fprintf(fichtm,"\
                   4592:  - (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): \
                   4593:    <a href=\"%s\">%s</a> <br>\n</li>",
                   4594:           estepm,subdirf2(fileres,"stde"),subdirf2(fileres,"stde"));
                   4595:  fprintf(fichtm,"\
1.128     brouard  4596:  - Variances and covariances of health expectancies by age. Status (i) based health expectancies (in state j), e<sup>ij</sup> are weighted by the period prevalences in each state i (if popbased=1, an additional computation is done using the cross-sectional prevalences, i.e population based) (estepm=%d months): <a href=\"%s\">%s</a><br>\n",
1.126     brouard  4597:         estepm, subdirf2(fileres,"v"),subdirf2(fileres,"v"));
                   4598:  fprintf(fichtm,"\
1.128     brouard  4599:  - 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",
                   4600:         estepm, subdirf2(fileres,"t"),subdirf2(fileres,"t"));
1.126     brouard  4601:  fprintf(fichtm,"\
                   4602:  - Standard deviation of period (stable) prevalences: <a href=\"%s\">%s</a> <br>\n",\
                   4603:         subdirf2(fileres,"vpl"),subdirf2(fileres,"vpl"));
                   4604: 
                   4605: /*  if(popforecast==1) fprintf(fichtm,"\n */
                   4606: /*  - Prevalences forecasting: <a href=\"f%s\">f%s</a> <br>\n */
                   4607: /*  - Population forecasting (if popforecast=1): <a href=\"pop%s\">pop%s</a> <br>\n */
                   4608: /*     <br>",fileres,fileres,fileres,fileres); */
                   4609: /*  else  */
                   4610: /*    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); */
                   4611:  fflush(fichtm);
                   4612:  fprintf(fichtm," <ul><li><b>Graphs</b></li><p>");
                   4613: 
1.145     brouard  4614:  m=pow(2,cptcoveff);
1.126     brouard  4615:  if (cptcovn < 1) {m=1;ncodemax[1]=1;}
                   4616: 
                   4617:  jj1=0;
                   4618:  for(k1=1; k1<=m;k1++){
1.192     brouard  4619:    /* for(i1=1; i1<=ncodemax[k1];i1++){ */
1.126     brouard  4620:      jj1++;
                   4621:      if (cptcovn > 0) {
                   4622:        fprintf(fichtm,"<hr  size=\"2\" color=\"#EC5E5E\">************ Results for covariates");
                   4623:        for (cpt=1; cpt<=cptcoveff;cpt++) 
1.198     brouard  4624:         fprintf(fichtm," V%d=%d ",Tvaraff[cpt],nbcode[Tvaraff[cpt]][codtabm(jj1,cpt)]);
1.126     brouard  4625:        fprintf(fichtm," ************\n<hr size=\"2\" color=\"#EC5E5E\">");
                   4626:      }
                   4627:      for(cpt=1; cpt<=nlstate;cpt++) {
                   4628:        fprintf(fichtm,"<br>- Observed (cross-sectional) and period (incidence based) \
1.199   ! brouard  4629: prevalence (with 95%% confidence interval) in state (%d): %s%d_%d.svg <br>\
        !          4630: <img src=\"%s%d_%d.svg\">",cpt,subdirf2(optionfilefiname,"v"),cpt,jj1,subdirf2(optionfilefiname,"v"),cpt,jj1);  
1.126     brouard  4631:      }
                   4632:      fprintf(fichtm,"\n<br>- Total life expectancy by age and \
1.128     brouard  4633: health expectancies in states (1) and (2). If popbased=1 the smooth (due to the model) \
                   4634: true period expectancies (those weighted with period prevalences are also\
                   4635:  drawn in addition to the population based expectancies computed using\
1.199   ! brouard  4636:  observed and cahotic prevalences: %s%d.svg<br>\
        !          4637: <img src=\"%s%d.svg\">",subdirf2(optionfilefiname,"e"),jj1,subdirf2(optionfilefiname,"e"),jj1);
1.192     brouard  4638:    /* } /\* end i1 *\/ */
1.126     brouard  4639:  }/* End k1 */
                   4640:  fprintf(fichtm,"</ul>");
                   4641:  fflush(fichtm);
                   4642: }
                   4643: 
                   4644: /******************* Gnuplot file **************/
                   4645: void printinggnuplot(char fileres[], char optionfilefiname[], double ageminpar, double agemaxpar, double fage , char pathc[], double p[]){
                   4646: 
                   4647:   char dirfileres[132],optfileres[132];
1.164     brouard  4648:   int cpt=0,k1=0,i=0,k=0,j=0,jk=0,k2=0,k3=0,ij=0,l=0;
1.130     brouard  4649:   int ng=0;
1.126     brouard  4650: /*   if((ficgp=fopen(optionfilegnuplot,"a"))==NULL) { */
                   4651: /*     printf("Problem with file %s",optionfilegnuplot); */
                   4652: /*     fprintf(ficlog,"Problem with file %s",optionfilegnuplot); */
                   4653: /*   } */
                   4654: 
                   4655:   /*#ifdef windows */
                   4656:   fprintf(ficgp,"cd \"%s\" \n",pathc);
                   4657:     /*#endif */
                   4658:   m=pow(2,cptcoveff);
                   4659: 
                   4660:   strcpy(dirfileres,optionfilefiname);
                   4661:   strcpy(optfileres,"vpl");
                   4662:  /* 1eme*/
1.153     brouard  4663:   fprintf(ficgp,"\n# 1st: Period (stable) prevalence with CI: 'vpl' files\n");
1.126     brouard  4664:   for (cpt=1; cpt<= nlstate ; cpt ++) {
1.145     brouard  4665:     for (k1=1; k1<= m ; k1 ++) { /* plot [100000000000000000000:-100000000000000000000] "mysbiaspar/vplrmysbiaspar.txt to check */
1.199   ! brouard  4666:      fprintf(ficgp,"\nset out \"%s%d_%d.svg\" \n",subdirf2(optionfilefiname,"v"),cpt,k1);
        !          4667:      fprintf(ficgp,"\n#set out \"v%s%d_%d.svg\" \n",optionfilefiname,cpt,k1);
1.126     brouard  4668:      fprintf(ficgp,"set xlabel \"Age\" \n\
                   4669: set ylabel \"Probability\" \n\
1.199   ! brouard  4670: set ter svg size 640, 480\n\
1.170     brouard  4671: plot [%.f:%.f] \"%s\" every :::%d::%d u 1:2 \"%%lf",ageminpar,fage,subdirf2(fileres,"vpl"),k1-1,k1-1);
1.126     brouard  4672: 
                   4673:      for (i=1; i<= nlstate ; i ++) {
1.170     brouard  4674:        if (i==cpt) fprintf(ficgp," %%lf (%%lf)");
                   4675:        else        fprintf(ficgp," %%*lf (%%*lf)");
1.126     brouard  4676:      }
1.170     brouard  4677:      fprintf(ficgp,"\" t\"Period (stable) prevalence\" w l lt 0,\"%s\" every :::%d::%d u 1:($2+1.96*$3) \"%%lf",subdirf2(fileres,"vpl"),k1-1,k1-1);
1.126     brouard  4678:      for (i=1; i<= nlstate ; i ++) {
1.170     brouard  4679:        if (i==cpt) fprintf(ficgp," %%lf (%%lf)");
                   4680:        else fprintf(ficgp," %%*lf (%%*lf)");
1.126     brouard  4681:      } 
1.170     brouard  4682:      fprintf(ficgp,"\" t\"95%% CI\" w l lt 1,\"%s\" every :::%d::%d u 1:($2-1.96*$3) \"%%lf",subdirf2(fileres,"vpl"),k1-1,k1-1); 
1.126     brouard  4683:      for (i=1; i<= nlstate ; i ++) {
1.170     brouard  4684:        if (i==cpt) fprintf(ficgp," %%lf (%%lf)");
                   4685:        else fprintf(ficgp," %%*lf (%%*lf)");
1.126     brouard  4686:      }  
1.145     brouard  4687:      fprintf(ficgp,"\" t\"\" w l lt 1,\"%s\" every :::%d::%d u 1:($%d) t\"Observed prevalence \" w l lt 2",subdirf2(fileres,"p"),k1-1,k1-1,2+4*(cpt-1));
1.126     brouard  4688:    }
                   4689:   }
                   4690:   /*2 eme*/
1.153     brouard  4691:   fprintf(ficgp,"\n# 2nd: Total life expectancy with CI: 't' files\n");
1.126     brouard  4692:   for (k1=1; k1<= m ; k1 ++) { 
1.199   ! brouard  4693:     fprintf(ficgp,"\nset out \"%s%d.svg\" \n",subdirf2(optionfilefiname,"e"),k1);
        !          4694:     fprintf(ficgp,"set ylabel \"Years\" \nset ter svg size 640, 480\nplot [%.f:%.f] ",ageminpar,fage);
1.126     brouard  4695:     
                   4696:     for (i=1; i<= nlstate+1 ; i ++) {
                   4697:       k=2*i;
1.170     brouard  4698:       fprintf(ficgp,"\"%s\" every :::%d::%d u 1:2 \"%%lf",subdirf2(fileres,"t"),k1-1,k1-1);
1.126     brouard  4699:       for (j=1; j<= nlstate+1 ; j ++) {
1.170     brouard  4700:        if (j==i) fprintf(ficgp," %%lf (%%lf)");
                   4701:        else fprintf(ficgp," %%*lf (%%*lf)");
1.126     brouard  4702:       }   
                   4703:       if (i== 1) fprintf(ficgp,"\" t\"TLE\" w l ,");
                   4704:       else fprintf(ficgp,"\" t\"LE in state (%d)\" w l ,",i-1);
1.170     brouard  4705:       fprintf(ficgp,"\"%s\" every :::%d::%d u 1:($2-$3*2) \"%%lf",subdirf2(fileres,"t"),k1-1,k1-1);
1.126     brouard  4706:       for (j=1; j<= nlstate+1 ; j ++) {
1.170     brouard  4707:        if (j==i) fprintf(ficgp," %%lf (%%lf)");
                   4708:        else fprintf(ficgp," %%*lf (%%*lf)");
1.126     brouard  4709:       }   
1.145     brouard  4710:       fprintf(ficgp,"\" t\"\" w l lt 0,");
1.170     brouard  4711:       fprintf(ficgp,"\"%s\" every :::%d::%d u 1:($2+$3*2) \"%%lf",subdirf2(fileres,"t"),k1-1,k1-1);
1.126     brouard  4712:       for (j=1; j<= nlstate+1 ; j ++) {
1.170     brouard  4713:        if (j==i) fprintf(ficgp," %%lf (%%lf)");
                   4714:        else fprintf(ficgp," %%*lf (%%*lf)");
1.126     brouard  4715:       }   
1.145     brouard  4716:       if (i== (nlstate+1)) fprintf(ficgp,"\" t\"\" w l lt 0");
                   4717:       else fprintf(ficgp,"\" t\"\" w l lt 0,");
1.126     brouard  4718:     }
                   4719:   }
                   4720:   
                   4721:   /*3eme*/
                   4722:   
                   4723:   for (k1=1; k1<= m ; k1 ++) { 
                   4724:     for (cpt=1; cpt<= nlstate ; cpt ++) {
                   4725:       /*       k=2+nlstate*(2*cpt-2); */
                   4726:       k=2+(nlstate+1)*(cpt-1);
1.199   ! brouard  4727:       fprintf(ficgp,"\nset out \"%s%d%d.svg\" \n",subdirf2(optionfilefiname,"exp"),cpt,k1);
        !          4728:       fprintf(ficgp,"set ter svg size 640, 480\n\
1.126     brouard  4729: plot [%.f:%.f] \"%s\" every :::%d::%d u 1:%d t \"e%d1\" w l",ageminpar,fage,subdirf2(fileres,"e"),k1-1,k1-1,k,cpt);
                   4730:       /*fprintf(ficgp,",\"e%s\" every :::%d::%d u 1:($%d-2*$%d) \"\%%lf ",fileres,k1-1,k1-1,k,k+1);
                   4731:        for (i=1; i<= nlstate*2 ; i ++) fprintf(ficgp,"\%%lf (\%%lf) ");
                   4732:        fprintf(ficgp,"\" t \"e%d1\" w l",cpt);
                   4733:        fprintf(ficgp,",\"e%s\" every :::%d::%d u 1:($%d+2*$%d) \"\%%lf ",fileres,k1-1,k1-1,k,k+1);
                   4734:        for (i=1; i<= nlstate*2 ; i ++) fprintf(ficgp,"\%%lf (\%%lf) ");
                   4735:        fprintf(ficgp,"\" t \"e%d1\" w l",cpt);
                   4736:        
                   4737:       */
                   4738:       for (i=1; i< nlstate ; i ++) {
                   4739:        fprintf(ficgp," ,\"%s\" every :::%d::%d u 1:%d t \"e%d%d\" w l",subdirf2(fileres,"e"),k1-1,k1-1,k+i,cpt,i+1);
                   4740:        /*      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);*/
                   4741:        
                   4742:       } 
                   4743:       fprintf(ficgp," ,\"%s\" every :::%d::%d u 1:%d t \"e%d.\" w l",subdirf2(fileres,"e"),k1-1,k1-1,k+nlstate,cpt);
                   4744:     }
                   4745:   }
                   4746:   
                   4747:   /* CV preval stable (period) */
1.153     brouard  4748:   for (k1=1; k1<= m ; k1 ++) { /* For each multivariate if any */
                   4749:     for (cpt=1; cpt<=nlstate ; cpt ++) { /* For each life state */
1.126     brouard  4750:       k=3;
1.153     brouard  4751:       fprintf(ficgp,"\n#\n#\n#CV preval stable (period): 'pij' files, cov=%d state=%d",k1, cpt);
1.199   ! brouard  4752:       fprintf(ficgp,"\nset out \"%s%d_%d.svg\" \n",subdirf2(optionfilefiname,"p"),cpt,k1);
1.126     brouard  4753:       fprintf(ficgp,"set xlabel \"Age\" \nset ylabel \"Probability\" \n\
1.199   ! brouard  4754: set ter svg size 640, 480\n\
1.126     brouard  4755: unset log y\n\
1.153     brouard  4756: plot [%.f:%.f]  ", ageminpar, agemaxpar);
                   4757:       for (i=1; i<= nlstate ; i ++){
                   4758:        if(i==1)
                   4759:          fprintf(ficgp,"\"%s\"",subdirf2(fileres,"pij"));
                   4760:        else
                   4761:          fprintf(ficgp,", '' ");
1.154     brouard  4762:        l=(nlstate+ndeath)*(i-1)+1;
                   4763:        fprintf(ficgp," u ($1==%d ? ($3):1/0):($%d/($%d",k1,k+l+(cpt-1),k+l);
1.153     brouard  4764:        for (j=1; j<= (nlstate-1) ; j ++)
                   4765:          fprintf(ficgp,"+$%d",k+l+j);
                   4766:        fprintf(ficgp,")) t \"prev(%d,%d)\" w l",i,cpt);
                   4767:       } /* nlstate */
                   4768:       fprintf(ficgp,"\n");
                   4769:     } /* end cpt state*/ 
                   4770:   } /* end covariate */  
1.126     brouard  4771:   
                   4772:   /* proba elementaires */
1.187     brouard  4773:   fprintf(ficgp,"\n##############\n#MLE estimated parameters\n#############\n");
1.126     brouard  4774:   for(i=1,jk=1; i <=nlstate; i++){
1.187     brouard  4775:     fprintf(ficgp,"# initial state %d\n",i);
1.126     brouard  4776:     for(k=1; k <=(nlstate+ndeath); k++){
                   4777:       if (k != i) {
1.187     brouard  4778:        fprintf(ficgp,"#   current state %d\n",k);
1.126     brouard  4779:        for(j=1; j <=ncovmodel; j++){
1.187     brouard  4780:          fprintf(ficgp,"p%d=%f; ",jk,p[jk]);
1.126     brouard  4781:          jk++; 
                   4782:        }
1.187     brouard  4783:        fprintf(ficgp,"\n");
1.126     brouard  4784:       }
                   4785:     }
                   4786:    }
1.187     brouard  4787:   fprintf(ficgp,"##############\n#\n");
                   4788: 
1.145     brouard  4789:   /*goto avoid;*/
1.187     brouard  4790:   fprintf(ficgp,"\n##############\n#Graphics of of probabilities or incidences\n#############\n");
                   4791:   fprintf(ficgp,"# logi(p12/p11)=a12+b12*age+c12age*age+d12*V1+e12*V1*age\n");
                   4792:   fprintf(ficgp,"# logi(p12/p11)=p1 +p2*age +p3*age*age+ p4*V1+ p5*V1*age\n");
                   4793:   fprintf(ficgp,"# logi(p13/p11)=a13+b13*age+c13age*age+d13*V1+e13*V1*age\n");
                   4794:   fprintf(ficgp,"# logi(p13/p11)=p6 +p7*age +p8*age*age+ p9*V1+ p10*V1*age\n");
                   4795:   fprintf(ficgp,"# p12+p13+p14+p11=1=p11(1+exp(a12+b12*age+c12age*age+d12*V1+e12*V1*age)\n");
                   4796:   fprintf(ficgp,"#                      +exp(a13+b13*age+c13age*age+d13*V1+e13*V1*age)+...)\n");
                   4797:   fprintf(ficgp,"# p11=1/(1+exp(a12+b12*age+c12age*age+d12*V1+e12*V1*age)\n");
                   4798:   fprintf(ficgp,"#                      +exp(a13+b13*age+c13age*age+d13*V1+e13*V1*age)+...)\n");
                   4799:   fprintf(ficgp,"# p12=exp(a12+b12*age+c12age*age+d12*V1+e12*V1*age)/\n");
                   4800:   fprintf(ficgp,"#     (1+exp(a12+b12*age+c12age*age+d12*V1+e12*V1*age)\n");
                   4801:   fprintf(ficgp,"#       +exp(a13+b13*age+c13age*age+d13*V1+e13*V1*age))\n");
                   4802:   fprintf(ficgp,"#       +exp(a14+b14*age+c14age*age+d14*V1+e14*V1*age)+...)\n");
                   4803:   fprintf(ficgp,"#\n");
1.126     brouard  4804:    for(ng=1; ng<=2;ng++){ /* Number of graphics: first is probabilities second is incidence per year*/
1.187     brouard  4805:      fprintf(ficgp,"# ng=%d\n",ng);
                   4806:      fprintf(ficgp,"#   jk=1 to 2^%d=%d\n",cptcoveff,m);
1.126     brouard  4807:      for(jk=1; jk <=m; jk++) {
1.187     brouard  4808:        fprintf(ficgp,"#    jk=%d\n",jk);
1.199   ! brouard  4809:        fprintf(ficgp,"\nset out \"%s%d_%d.svg\" \n",subdirf2(optionfilefiname,"pe"),jk,ng); 
1.126     brouard  4810:        if (ng==2)
                   4811:         fprintf(ficgp,"\nset ylabel \"Quasi-incidence per year\"\n");
                   4812:        else
                   4813:         fprintf(ficgp,"\nset title \"Probability\"\n");
1.199   ! brouard  4814:        fprintf(ficgp,"\nset ter svg size 640, 480\nset log y\nplot  [%.f:%.f] ",ageminpar,agemaxpar);
1.126     brouard  4815:        i=1;
                   4816:        for(k2=1; k2<=nlstate; k2++) {
                   4817:         k3=i;
                   4818:         for(k=1; k<=(nlstate+ndeath); k++) {
                   4819:           if (k != k2){
                   4820:             if(ng==2)
1.187     brouard  4821:               if(nagesqr==0)
                   4822:                 fprintf(ficgp," %f*exp(p%d+p%d*x",YEARM/stepm,i,i+1);
                   4823:               else /* nagesqr =1 */
                   4824:                 fprintf(ficgp," %f*exp(p%d+p%d*x+p%d*x*x",YEARM/stepm,i,i+1,i+1+nagesqr);
1.126     brouard  4825:             else
1.187     brouard  4826:               if(nagesqr==0)
                   4827:                 fprintf(ficgp," exp(p%d+p%d*x",i,i+1);
                   4828:               else /* nagesqr =1 */
                   4829:                 fprintf(ficgp," exp(p%d+p%d*x+p%d*x*x",i,i+1,i+1+nagesqr);
1.141     brouard  4830:             ij=1;/* To be checked else nbcode[0][0] wrong */
1.187     brouard  4831:             for(j=3; j <=ncovmodel-nagesqr; j++) {
1.197     brouard  4832:               /* printf("Tage[%d]=%d, j=%d\n", ij, Tage[ij], j); */
                   4833:               if(ij <=cptcovage) { /* Bug valgrind */
                   4834:                 if((j-2)==Tage[ij]) { /* Bug valgrind */
1.198     brouard  4835:                   fprintf(ficgp,"+p%d*%d*x",i+j+nagesqr-1,nbcode[Tvar[j-2]][codtabm(jk,Tvar[j-2])]);
1.197     brouard  4836:                   ij++;
                   4837:                 }
1.186     brouard  4838:               }
                   4839:               else
1.198     brouard  4840:                 fprintf(ficgp,"+p%d*%d",i+j+nagesqr-1,nbcode[Tvar[j-2]][codtabm(jk,j-2)]);
1.126     brouard  4841:             }
                   4842:             fprintf(ficgp,")/(1");
                   4843:             
1.187     brouard  4844:             for(k1=1; k1 <=nlstate; k1++){ 
                   4845:               if(nagesqr==0)
                   4846:                 fprintf(ficgp,"+exp(p%d+p%d*x",k3+(k1-1)*ncovmodel,k3+(k1-1)*ncovmodel+1);
                   4847:               else /* nagesqr =1 */
                   4848:                 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);
                   4849:   
1.126     brouard  4850:               ij=1;
1.187     brouard  4851:               for(j=3; j <=ncovmodel-nagesqr; j++){
1.197     brouard  4852:                 if(ij <=cptcovage) { /* Bug valgrind */
                   4853:                   if((j-2)==Tage[ij]) { /* Bug valgrind */
1.198     brouard  4854:                     fprintf(ficgp,"+p%d*%d*x",k3+(k1-1)*ncovmodel+1+j-2+nagesqr,nbcode[Tvar[j-2]][codtabm(jk,Tvar[j-2])]);
1.197     brouard  4855:                     ij++;
                   4856:                   }
1.186     brouard  4857:                 }
                   4858:                 else
1.198     brouard  4859:                   fprintf(ficgp,"+p%d*%d",k3+(k1-1)*ncovmodel+1+j-2+nagesqr,nbcode[Tvar[j-2]][codtabm(jk,j-2)]);
1.126     brouard  4860:               }
                   4861:               fprintf(ficgp,")");
                   4862:             }
                   4863:             fprintf(ficgp,") t \"p%d%d\" ", k2,k);
                   4864:             if ((k+k2)!= (nlstate*2+ndeath)) fprintf(ficgp,",");
                   4865:             i=i+ncovmodel;
                   4866:           }
                   4867:         } /* end k */
                   4868:        } /* end k2 */
                   4869:      } /* end jk */
                   4870:    } /* end ng */
1.164     brouard  4871:  /* avoid: */
1.126     brouard  4872:    fflush(ficgp); 
                   4873: }  /* end gnuplot */
                   4874: 
                   4875: 
                   4876: /*************** Moving average **************/
                   4877: int movingaverage(double ***probs, double bage,double fage, double ***mobaverage, int mobilav){
                   4878: 
                   4879:   int i, cpt, cptcod;
                   4880:   int modcovmax =1;
                   4881:   int mobilavrange, mob;
                   4882:   double age;
                   4883: 
                   4884:   modcovmax=2*cptcoveff;/* Max number of modalities. We suppose 
                   4885:                           a covariate has 2 modalities */
                   4886:   if (cptcovn<1) modcovmax=1; /* At least 1 pass */
                   4887: 
                   4888:   if(mobilav==1||mobilav ==3 ||mobilav==5 ||mobilav== 7){
                   4889:     if(mobilav==1) mobilavrange=5; /* default */
                   4890:     else mobilavrange=mobilav;
                   4891:     for (age=bage; age<=fage; age++)
                   4892:       for (i=1; i<=nlstate;i++)
                   4893:        for (cptcod=1;cptcod<=modcovmax;cptcod++)
                   4894:          mobaverage[(int)age][i][cptcod]=probs[(int)age][i][cptcod];
                   4895:     /* We keep the original values on the extreme ages bage, fage and for 
                   4896:        fage+1 and bage-1 we use a 3 terms moving average; for fage+2 bage+2
                   4897:        we use a 5 terms etc. until the borders are no more concerned. 
                   4898:     */ 
                   4899:     for (mob=3;mob <=mobilavrange;mob=mob+2){
                   4900:       for (age=bage+(mob-1)/2; age<=fage-(mob-1)/2; age++){
                   4901:        for (i=1; i<=nlstate;i++){
                   4902:          for (cptcod=1;cptcod<=modcovmax;cptcod++){
                   4903:            mobaverage[(int)age][i][cptcod] =probs[(int)age][i][cptcod];
                   4904:              for (cpt=1;cpt<=(mob-1)/2;cpt++){
                   4905:                mobaverage[(int)age][i][cptcod] +=probs[(int)age-cpt][i][cptcod];
                   4906:                mobaverage[(int)age][i][cptcod] +=probs[(int)age+cpt][i][cptcod];
                   4907:              }
                   4908:            mobaverage[(int)age][i][cptcod]=mobaverage[(int)age][i][cptcod]/mob;
                   4909:          }
                   4910:        }
                   4911:       }/* end age */
                   4912:     }/* end mob */
                   4913:   }else return -1;
                   4914:   return 0;
                   4915: }/* End movingaverage */
                   4916: 
                   4917: 
                   4918: /************** Forecasting ******************/
1.169     brouard  4919: 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  4920:   /* proj1, year, month, day of starting projection 
                   4921:      agemin, agemax range of age
                   4922:      dateprev1 dateprev2 range of dates during which prevalence is computed
                   4923:      anproj2 year of en of projection (same day and month as proj1).
                   4924:   */
1.164     brouard  4925:   int yearp, stepsize, hstepm, nhstepm, j, k, cptcod, i, h, i1;
1.126     brouard  4926:   double agec; /* generic age */
                   4927:   double agelim, ppij, yp,yp1,yp2,jprojmean,mprojmean,anprojmean;
                   4928:   double *popeffectif,*popcount;
                   4929:   double ***p3mat;
                   4930:   double ***mobaverage;
                   4931:   char fileresf[FILENAMELENGTH];
                   4932: 
                   4933:   agelim=AGESUP;
                   4934:   prevalence(probs, ageminpar, agemax, s, agev, nlstate, imx, Tvar, nbcode, ncodemax, mint, anint, dateprev1, dateprev2, firstpass, lastpass);
                   4935:  
                   4936:   strcpy(fileresf,"f"); 
                   4937:   strcat(fileresf,fileres);
                   4938:   if((ficresf=fopen(fileresf,"w"))==NULL) {
                   4939:     printf("Problem with forecast resultfile: %s\n", fileresf);
                   4940:     fprintf(ficlog,"Problem with forecast resultfile: %s\n", fileresf);
                   4941:   }
                   4942:   printf("Computing forecasting: result on file '%s' \n", fileresf);
                   4943:   fprintf(ficlog,"Computing forecasting: result on file '%s' \n", fileresf);
                   4944: 
                   4945:   if (cptcoveff==0) ncodemax[cptcoveff]=1;
                   4946: 
                   4947:   if (mobilav!=0) {
                   4948:     mobaverage= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
                   4949:     if (movingaverage(probs, ageminpar, fage, mobaverage,mobilav)!=0){
                   4950:       fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav);
                   4951:       printf(" Error in movingaverage mobilav=%d\n",mobilav);
                   4952:     }
                   4953:   }
                   4954: 
                   4955:   stepsize=(int) (stepm+YEARM-1)/YEARM;
                   4956:   if (stepm<=12) stepsize=1;
                   4957:   if(estepm < stepm){
                   4958:     printf ("Problem %d lower than %d\n",estepm, stepm);
                   4959:   }
                   4960:   else  hstepm=estepm;   
                   4961: 
                   4962:   hstepm=hstepm/stepm; 
                   4963:   yp1=modf(dateintmean,&yp);/* extracts integral of datemean in yp  and
                   4964:                                fractional in yp1 */
                   4965:   anprojmean=yp;
                   4966:   yp2=modf((yp1*12),&yp);
                   4967:   mprojmean=yp;
                   4968:   yp1=modf((yp2*30.5),&yp);
                   4969:   jprojmean=yp;
                   4970:   if(jprojmean==0) jprojmean=1;
                   4971:   if(mprojmean==0) jprojmean=1;
                   4972: 
                   4973:   i1=cptcoveff;
                   4974:   if (cptcovn < 1){i1=1;}
                   4975:   
                   4976:   fprintf(ficresf,"# Mean day of interviews %.lf/%.lf/%.lf (%.2f) between %.2f and %.2f \n",jprojmean,mprojmean,anprojmean,dateintmean,dateprev1,dateprev2); 
                   4977:   
                   4978:   fprintf(ficresf,"#****** Routine prevforecast **\n");
                   4979: 
                   4980: /*           if (h==(int)(YEARM*yearp)){ */
                   4981:   for(cptcov=1, k=0;cptcov<=i1;cptcov++){
                   4982:     for(cptcod=1;cptcod<=ncodemax[cptcoveff];cptcod++){
                   4983:       k=k+1;
                   4984:       fprintf(ficresf,"\n#******");
                   4985:       for(j=1;j<=cptcoveff;j++) {
1.198     brouard  4986:        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  4987:       }
                   4988:       fprintf(ficresf,"******\n");
                   4989:       fprintf(ficresf,"# Covariate valuofcovar yearproj age");
                   4990:       for(j=1; j<=nlstate+ndeath;j++){ 
                   4991:        for(i=1; i<=nlstate;i++)              
                   4992:           fprintf(ficresf," p%d%d",i,j);
                   4993:        fprintf(ficresf," p.%d",j);
                   4994:       }
                   4995:       for (yearp=0; yearp<=(anproj2-anproj1);yearp +=stepsize) { 
                   4996:        fprintf(ficresf,"\n");
                   4997:        fprintf(ficresf,"\n# Forecasting at date %.lf/%.lf/%.lf ",jproj1,mproj1,anproj1+yearp);   
                   4998: 
                   4999:        for (agec=fage; agec>=(ageminpar-1); agec--){ 
                   5000:          nhstepm=(int) rint((agelim-agec)*YEARM/stepm); 
                   5001:          nhstepm = nhstepm/hstepm; 
                   5002:          p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   5003:          oldm=oldms;savm=savms;
                   5004:          hpxij(p3mat,nhstepm,agec,hstepm,p,nlstate,stepm,oldm,savm, k);  
                   5005:        
                   5006:          for (h=0; h<=nhstepm; h++){
                   5007:            if (h*hstepm/YEARM*stepm ==yearp) {
                   5008:               fprintf(ficresf,"\n");
                   5009:               for(j=1;j<=cptcoveff;j++) 
1.198     brouard  5010:                 fprintf(ficresf,"%d %d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
1.126     brouard  5011:              fprintf(ficresf,"%.f %.f ",anproj1+yearp,agec+h*hstepm/YEARM*stepm);
                   5012:            } 
                   5013:            for(j=1; j<=nlstate+ndeath;j++) {
                   5014:              ppij=0.;
                   5015:              for(i=1; i<=nlstate;i++) {
                   5016:                if (mobilav==1) 
                   5017:                  ppij=ppij+p3mat[i][j][h]*mobaverage[(int)agec][i][cptcod];
                   5018:                else {
                   5019:                  ppij=ppij+p3mat[i][j][h]*probs[(int)(agec)][i][cptcod];
                   5020:                }
                   5021:                if (h*hstepm/YEARM*stepm== yearp) {
                   5022:                  fprintf(ficresf," %.3f", p3mat[i][j][h]);
                   5023:                }
                   5024:              } /* end i */
                   5025:              if (h*hstepm/YEARM*stepm==yearp) {
                   5026:                fprintf(ficresf," %.3f", ppij);
                   5027:              }
                   5028:            }/* end j */
                   5029:          } /* end h */
                   5030:          free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   5031:        } /* end agec */
                   5032:       } /* end yearp */
                   5033:     } /* end cptcod */
                   5034:   } /* end  cptcov */
                   5035:        
                   5036:   if (mobilav!=0) free_ma3x(mobaverage,1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
                   5037: 
                   5038:   fclose(ficresf);
                   5039: }
                   5040: 
                   5041: /************** Forecasting *****not tested NB*************/
1.169     brouard  5042: 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  5043:   
                   5044:   int cpt, stepsize, hstepm, nhstepm, j,k,c, cptcod, i,h;
                   5045:   int *popage;
                   5046:   double calagedatem, agelim, kk1, kk2;
                   5047:   double *popeffectif,*popcount;
                   5048:   double ***p3mat,***tabpop,***tabpopprev;
                   5049:   double ***mobaverage;
                   5050:   char filerespop[FILENAMELENGTH];
                   5051: 
                   5052:   tabpop= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
                   5053:   tabpopprev= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
                   5054:   agelim=AGESUP;
                   5055:   calagedatem=(anpyram+mpyram/12.+jpyram/365.-dateintmean)*YEARM;
                   5056:   
                   5057:   prevalence(probs, ageminpar, agemax, s, agev, nlstate, imx, Tvar, nbcode, ncodemax, mint, anint, dateprev1, dateprev2, firstpass, lastpass);
                   5058:   
                   5059:   
                   5060:   strcpy(filerespop,"pop"); 
                   5061:   strcat(filerespop,fileres);
                   5062:   if((ficrespop=fopen(filerespop,"w"))==NULL) {
                   5063:     printf("Problem with forecast resultfile: %s\n", filerespop);
                   5064:     fprintf(ficlog,"Problem with forecast resultfile: %s\n", filerespop);
                   5065:   }
                   5066:   printf("Computing forecasting: result on file '%s' \n", filerespop);
                   5067:   fprintf(ficlog,"Computing forecasting: result on file '%s' \n", filerespop);
                   5068: 
                   5069:   if (cptcoveff==0) ncodemax[cptcoveff]=1;
                   5070: 
                   5071:   if (mobilav!=0) {
                   5072:     mobaverage= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
                   5073:     if (movingaverage(probs, ageminpar, fage, mobaverage,mobilav)!=0){
                   5074:       fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav);
                   5075:       printf(" Error in movingaverage mobilav=%d\n",mobilav);
                   5076:     }
                   5077:   }
                   5078: 
                   5079:   stepsize=(int) (stepm+YEARM-1)/YEARM;
                   5080:   if (stepm<=12) stepsize=1;
                   5081:   
                   5082:   agelim=AGESUP;
                   5083:   
                   5084:   hstepm=1;
                   5085:   hstepm=hstepm/stepm; 
                   5086:   
                   5087:   if (popforecast==1) {
                   5088:     if((ficpop=fopen(popfile,"r"))==NULL) {
                   5089:       printf("Problem with population file : %s\n",popfile);exit(0);
                   5090:       fprintf(ficlog,"Problem with population file : %s\n",popfile);exit(0);
                   5091:     } 
                   5092:     popage=ivector(0,AGESUP);
                   5093:     popeffectif=vector(0,AGESUP);
                   5094:     popcount=vector(0,AGESUP);
                   5095:     
                   5096:     i=1;   
                   5097:     while ((c=fscanf(ficpop,"%d %lf\n",&popage[i],&popcount[i])) != EOF) i=i+1;
                   5098:    
                   5099:     imx=i;
                   5100:     for (i=1; i<imx;i++) popeffectif[popage[i]]=popcount[i];
                   5101:   }
                   5102: 
                   5103:   for(cptcov=1,k=0;cptcov<=i2;cptcov++){
                   5104:    for(cptcod=1;cptcod<=ncodemax[cptcoveff];cptcod++){
                   5105:       k=k+1;
                   5106:       fprintf(ficrespop,"\n#******");
                   5107:       for(j=1;j<=cptcoveff;j++) {
1.198     brouard  5108:        fprintf(ficrespop," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
1.126     brouard  5109:       }
                   5110:       fprintf(ficrespop,"******\n");
                   5111:       fprintf(ficrespop,"# Age");
                   5112:       for(j=1; j<=nlstate+ndeath;j++) fprintf(ficrespop," P.%d",j);
                   5113:       if (popforecast==1)  fprintf(ficrespop," [Population]");
                   5114:       
                   5115:       for (cpt=0; cpt<=0;cpt++) { 
                   5116:        fprintf(ficrespop,"\n\n# Forecasting at date %.lf/%.lf/%.lf ",jpyram,mpyram,anpyram+cpt);   
                   5117:        
                   5118:        for (agedeb=(fage-((int)calagedatem %12/12.)); agedeb>=(ageminpar-((int)calagedatem %12)/12.); agedeb--){ 
                   5119:          nhstepm=(int) rint((agelim-agedeb)*YEARM/stepm); 
                   5120:          nhstepm = nhstepm/hstepm; 
                   5121:          
                   5122:          p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   5123:          oldm=oldms;savm=savms;
                   5124:          hpxij(p3mat,nhstepm,agedeb,hstepm,p,nlstate,stepm,oldm,savm, k);  
                   5125:        
                   5126:          for (h=0; h<=nhstepm; h++){
                   5127:            if (h==(int) (calagedatem+YEARM*cpt)) {
                   5128:              fprintf(ficrespop,"\n %3.f ",agedeb+h*hstepm/YEARM*stepm);
                   5129:            } 
                   5130:            for(j=1; j<=nlstate+ndeath;j++) {
                   5131:              kk1=0.;kk2=0;
                   5132:              for(i=1; i<=nlstate;i++) {              
                   5133:                if (mobilav==1) 
                   5134:                  kk1=kk1+p3mat[i][j][h]*mobaverage[(int)agedeb+1][i][cptcod];
                   5135:                else {
                   5136:                  kk1=kk1+p3mat[i][j][h]*probs[(int)(agedeb+1)][i][cptcod];
                   5137:                }
                   5138:              }
                   5139:              if (h==(int)(calagedatem+12*cpt)){
                   5140:                tabpop[(int)(agedeb)][j][cptcod]=kk1;
                   5141:                  /*fprintf(ficrespop," %.3f", kk1);
                   5142:                    if (popforecast==1) fprintf(ficrespop," [%.f]", kk1*popeffectif[(int)agedeb+1]);*/
                   5143:              }
                   5144:            }
                   5145:            for(i=1; i<=nlstate;i++){
                   5146:              kk1=0.;
                   5147:                for(j=1; j<=nlstate;j++){
                   5148:                  kk1= kk1+tabpop[(int)(agedeb)][j][cptcod]; 
                   5149:                }
                   5150:                  tabpopprev[(int)(agedeb)][i][cptcod]=tabpop[(int)(agedeb)][i][cptcod]/kk1*popeffectif[(int)(agedeb+(calagedatem+12*cpt)*hstepm/YEARM*stepm-1)];
                   5151:            }
                   5152: 
                   5153:            if (h==(int)(calagedatem+12*cpt)) for(j=1; j<=nlstate;j++) 
                   5154:              fprintf(ficrespop," %15.2f",tabpopprev[(int)(agedeb+1)][j][cptcod]);
                   5155:          }
                   5156:          free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   5157:        }
                   5158:       }
                   5159:  
                   5160:   /******/
                   5161: 
                   5162:       for (cpt=1; cpt<=(anpyram1-anpyram);cpt++) { 
                   5163:        fprintf(ficrespop,"\n\n# Forecasting at date %.lf/%.lf/%.lf ",jpyram,mpyram,anpyram+cpt);   
                   5164:        for (agedeb=(fage-((int)calagedatem %12/12.)); agedeb>=(ageminpar-((int)calagedatem %12)/12.); agedeb--){ 
                   5165:          nhstepm=(int) rint((agelim-agedeb)*YEARM/stepm); 
                   5166:          nhstepm = nhstepm/hstepm; 
                   5167:          
                   5168:          p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   5169:          oldm=oldms;savm=savms;
                   5170:          hpxij(p3mat,nhstepm,agedeb,hstepm,p,nlstate,stepm,oldm,savm, k);  
                   5171:          for (h=0; h<=nhstepm; h++){
                   5172:            if (h==(int) (calagedatem+YEARM*cpt)) {
                   5173:              fprintf(ficresf,"\n %3.f ",agedeb+h*hstepm/YEARM*stepm);
                   5174:            } 
                   5175:            for(j=1; j<=nlstate+ndeath;j++) {
                   5176:              kk1=0.;kk2=0;
                   5177:              for(i=1; i<=nlstate;i++) {              
                   5178:                kk1=kk1+p3mat[i][j][h]*tabpopprev[(int)agedeb+1][i][cptcod];    
                   5179:              }
                   5180:              if (h==(int)(calagedatem+12*cpt)) fprintf(ficresf," %15.2f", kk1);        
                   5181:            }
                   5182:          }
                   5183:          free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   5184:        }
                   5185:       }
                   5186:    } 
                   5187:   }
                   5188:  
                   5189:   if (mobilav!=0) free_ma3x(mobaverage,1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
                   5190: 
                   5191:   if (popforecast==1) {
                   5192:     free_ivector(popage,0,AGESUP);
                   5193:     free_vector(popeffectif,0,AGESUP);
                   5194:     free_vector(popcount,0,AGESUP);
                   5195:   }
                   5196:   free_ma3x(tabpop,1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
                   5197:   free_ma3x(tabpopprev,1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
                   5198:   fclose(ficrespop);
                   5199: } /* End of popforecast */
                   5200: 
                   5201: int fileappend(FILE *fichier, char *optionfich)
                   5202: {
                   5203:   if((fichier=fopen(optionfich,"a"))==NULL) {
                   5204:     printf("Problem with file: %s\n", optionfich);
                   5205:     fprintf(ficlog,"Problem with file: %s\n", optionfich);
                   5206:     return (0);
                   5207:   }
                   5208:   fflush(fichier);
                   5209:   return (1);
                   5210: }
                   5211: 
                   5212: 
                   5213: /**************** function prwizard **********************/
                   5214: void prwizard(int ncovmodel, int nlstate, int ndeath,  char model[], FILE *ficparo)
                   5215: {
                   5216: 
                   5217:   /* Wizard to print covariance matrix template */
                   5218: 
1.164     brouard  5219:   char ca[32], cb[32];
                   5220:   int i,j, k, li, lj, lk, ll, jj, npar, itimes;
1.126     brouard  5221:   int numlinepar;
                   5222: 
                   5223:   printf("# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
                   5224:   fprintf(ficparo,"# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
                   5225:   for(i=1; i <=nlstate; i++){
                   5226:     jj=0;
                   5227:     for(j=1; j <=nlstate+ndeath; j++){
                   5228:       if(j==i) continue;
                   5229:       jj++;
                   5230:       /*ca[0]= k+'a'-1;ca[1]='\0';*/
                   5231:       printf("%1d%1d",i,j);
                   5232:       fprintf(ficparo,"%1d%1d",i,j);
                   5233:       for(k=1; k<=ncovmodel;k++){
                   5234:        /*        printf(" %lf",param[i][j][k]); */
                   5235:        /*        fprintf(ficparo," %lf",param[i][j][k]); */
                   5236:        printf(" 0.");
                   5237:        fprintf(ficparo," 0.");
                   5238:       }
                   5239:       printf("\n");
                   5240:       fprintf(ficparo,"\n");
                   5241:     }
                   5242:   }
                   5243:   printf("# Scales (for hessian or gradient estimation)\n");
                   5244:   fprintf(ficparo,"# Scales (for hessian or gradient estimation)\n");
                   5245:   npar= (nlstate+ndeath-1)*nlstate*ncovmodel; /* Number of parameters*/ 
                   5246:   for(i=1; i <=nlstate; i++){
                   5247:     jj=0;
                   5248:     for(j=1; j <=nlstate+ndeath; j++){
                   5249:       if(j==i) continue;
                   5250:       jj++;
                   5251:       fprintf(ficparo,"%1d%1d",i,j);
                   5252:       printf("%1d%1d",i,j);
                   5253:       fflush(stdout);
                   5254:       for(k=1; k<=ncovmodel;k++){
                   5255:        /*      printf(" %le",delti3[i][j][k]); */
                   5256:        /*      fprintf(ficparo," %le",delti3[i][j][k]); */
                   5257:        printf(" 0.");
                   5258:        fprintf(ficparo," 0.");
                   5259:       }
                   5260:       numlinepar++;
                   5261:       printf("\n");
                   5262:       fprintf(ficparo,"\n");
                   5263:     }
                   5264:   }
                   5265:   printf("# Covariance matrix\n");
                   5266: /* # 121 Var(a12)\n\ */
                   5267: /* # 122 Cov(b12,a12) Var(b12)\n\ */
                   5268: /* # 131 Cov(a13,a12) Cov(a13,b12, Var(a13)\n\ */
                   5269: /* # 132 Cov(b13,a12) Cov(b13,b12, Cov(b13,a13) Var(b13)\n\ */
                   5270: /* # 212 Cov(a21,a12) Cov(a21,b12, Cov(a21,a13) Cov(a21,b13) Var(a21)\n\ */
                   5271: /* # 212 Cov(b21,a12) Cov(b21,b12, Cov(b21,a13) Cov(b21,b13) Cov(b21,a21) Var(b21)\n\ */
                   5272: /* # 232 Cov(a23,a12) Cov(a23,b12, Cov(a23,a13) Cov(a23,b13) Cov(a23,a21) Cov(a23,b21) Var(a23)\n\ */
                   5273: /* # 232 Cov(b23,a12) Cov(b23,b12) ... Var (b23)\n" */
                   5274:   fflush(stdout);
                   5275:   fprintf(ficparo,"# Covariance matrix\n");
                   5276:   /* # 121 Var(a12)\n\ */
                   5277:   /* # 122 Cov(b12,a12) Var(b12)\n\ */
                   5278:   /* #   ...\n\ */
                   5279:   /* # 232 Cov(b23,a12)  Cov(b23,b12) ... Var (b23)\n" */
                   5280:   
                   5281:   for(itimes=1;itimes<=2;itimes++){
                   5282:     jj=0;
                   5283:     for(i=1; i <=nlstate; i++){
                   5284:       for(j=1; j <=nlstate+ndeath; j++){
                   5285:        if(j==i) continue;
                   5286:        for(k=1; k<=ncovmodel;k++){
                   5287:          jj++;
                   5288:          ca[0]= k+'a'-1;ca[1]='\0';
                   5289:          if(itimes==1){
                   5290:            printf("#%1d%1d%d",i,j,k);
                   5291:            fprintf(ficparo,"#%1d%1d%d",i,j,k);
                   5292:          }else{
                   5293:            printf("%1d%1d%d",i,j,k);
                   5294:            fprintf(ficparo,"%1d%1d%d",i,j,k);
                   5295:            /*  printf(" %.5le",matcov[i][j]); */
                   5296:          }
                   5297:          ll=0;
                   5298:          for(li=1;li <=nlstate; li++){
                   5299:            for(lj=1;lj <=nlstate+ndeath; lj++){
                   5300:              if(lj==li) continue;
                   5301:              for(lk=1;lk<=ncovmodel;lk++){
                   5302:                ll++;
                   5303:                if(ll<=jj){
                   5304:                  cb[0]= lk +'a'-1;cb[1]='\0';
                   5305:                  if(ll<jj){
                   5306:                    if(itimes==1){
                   5307:                      printf(" Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
                   5308:                      fprintf(ficparo," Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
                   5309:                    }else{
                   5310:                      printf(" 0.");
                   5311:                      fprintf(ficparo," 0.");
                   5312:                    }
                   5313:                  }else{
                   5314:                    if(itimes==1){
                   5315:                      printf(" Var(%s%1d%1d)",ca,i,j);
                   5316:                      fprintf(ficparo," Var(%s%1d%1d)",ca,i,j);
                   5317:                    }else{
                   5318:                      printf(" 0.");
                   5319:                      fprintf(ficparo," 0.");
                   5320:                    }
                   5321:                  }
                   5322:                }
                   5323:              } /* end lk */
                   5324:            } /* end lj */
                   5325:          } /* end li */
                   5326:          printf("\n");
                   5327:          fprintf(ficparo,"\n");
                   5328:          numlinepar++;
                   5329:        } /* end k*/
                   5330:       } /*end j */
                   5331:     } /* end i */
                   5332:   } /* end itimes */
                   5333: 
                   5334: } /* end of prwizard */
                   5335: /******************* Gompertz Likelihood ******************************/
                   5336: double gompertz(double x[])
                   5337: { 
                   5338:   double A,B,L=0.0,sump=0.,num=0.;
                   5339:   int i,n=0; /* n is the size of the sample */
                   5340: 
                   5341:   for (i=0;i<=imx-1 ; i++) {
                   5342:     sump=sump+weight[i];
                   5343:     /*    sump=sump+1;*/
                   5344:     num=num+1;
                   5345:   }
                   5346:  
                   5347:  
                   5348:   /* for (i=0; i<=imx; i++) 
                   5349:      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]);*/
                   5350: 
                   5351:   for (i=1;i<=imx ; i++)
                   5352:     {
                   5353:       if (cens[i] == 1 && wav[i]>1)
                   5354:        A=-x[1]/(x[2])*(exp(x[2]*(agecens[i]-agegomp))-exp(x[2]*(ageexmed[i]-agegomp)));
                   5355:       
                   5356:       if (cens[i] == 0 && wav[i]>1)
                   5357:        A=-x[1]/(x[2])*(exp(x[2]*(agedc[i]-agegomp))-exp(x[2]*(ageexmed[i]-agegomp)))
                   5358:             +log(x[1]/YEARM)+x[2]*(agedc[i]-agegomp)+log(YEARM);  
                   5359:       
                   5360:       /*if (wav[i] > 1 && agecens[i] > 15) {*/ /* ??? */
                   5361:       if (wav[i] > 1 ) { /* ??? */
                   5362:        L=L+A*weight[i];
                   5363:        /*      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]);*/
                   5364:       }
                   5365:     }
                   5366: 
                   5367:  /*printf("x1=%2.9f x2=%2.9f x3=%2.9f L=%f\n",x[1],x[2],x[3],L);*/
                   5368:  
                   5369:   return -2*L*num/sump;
                   5370: }
                   5371: 
1.136     brouard  5372: #ifdef GSL
                   5373: /******************* Gompertz_f Likelihood ******************************/
                   5374: double gompertz_f(const gsl_vector *v, void *params)
                   5375: { 
                   5376:   double A,B,LL=0.0,sump=0.,num=0.;
                   5377:   double *x= (double *) v->data;
                   5378:   int i,n=0; /* n is the size of the sample */
                   5379: 
                   5380:   for (i=0;i<=imx-1 ; i++) {
                   5381:     sump=sump+weight[i];
                   5382:     /*    sump=sump+1;*/
                   5383:     num=num+1;
                   5384:   }
                   5385:  
                   5386:  
                   5387:   /* for (i=0; i<=imx; i++) 
                   5388:      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]);*/
                   5389:   printf("x[0]=%lf x[1]=%lf\n",x[0],x[1]);
                   5390:   for (i=1;i<=imx ; i++)
                   5391:     {
                   5392:       if (cens[i] == 1 && wav[i]>1)
                   5393:        A=-x[0]/(x[1])*(exp(x[1]*(agecens[i]-agegomp))-exp(x[1]*(ageexmed[i]-agegomp)));
                   5394:       
                   5395:       if (cens[i] == 0 && wav[i]>1)
                   5396:        A=-x[0]/(x[1])*(exp(x[1]*(agedc[i]-agegomp))-exp(x[1]*(ageexmed[i]-agegomp)))
                   5397:             +log(x[0]/YEARM)+x[1]*(agedc[i]-agegomp)+log(YEARM);  
                   5398:       
                   5399:       /*if (wav[i] > 1 && agecens[i] > 15) {*/ /* ??? */
                   5400:       if (wav[i] > 1 ) { /* ??? */
                   5401:        LL=LL+A*weight[i];
                   5402:        /*      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]);*/
                   5403:       }
                   5404:     }
                   5405: 
                   5406:  /*printf("x1=%2.9f x2=%2.9f x3=%2.9f L=%f\n",x[1],x[2],x[3],L);*/
                   5407:   printf("x[0]=%lf x[1]=%lf -2*LL*num/sump=%lf\n",x[0],x[1],-2*LL*num/sump);
                   5408:  
                   5409:   return -2*LL*num/sump;
                   5410: }
                   5411: #endif
                   5412: 
1.126     brouard  5413: /******************* Printing html file ***********/
                   5414: void printinghtmlmort(char fileres[], char title[], char datafile[], int firstpass, \
                   5415:                  int lastpass, int stepm, int weightopt, char model[],\
                   5416:                  int imx,  double p[],double **matcov,double agemortsup){
                   5417:   int i,k;
                   5418: 
                   5419:   fprintf(fichtm,"<ul><li><h4>Result files </h4>\n Force of mortality. Parameters of the Gompertz fit (with confidence interval in brackets):<br>");
                   5420:   fprintf(fichtm,"  mu(age) =%lf*exp(%lf*(age-%d)) per year<br><br>",p[1],p[2],agegomp);
                   5421:   for (i=1;i<=2;i++) 
                   5422:     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  5423:   fprintf(fichtm,"<br><br><img src=\"graphmort.svg\">");
1.126     brouard  5424:   fprintf(fichtm,"</ul>");
                   5425: 
                   5426: fprintf(fichtm,"<ul><li><h4>Life table</h4>\n <br>");
                   5427: 
                   5428:  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>");
                   5429: 
                   5430:  for (k=agegomp;k<(agemortsup-2);k++) 
                   5431:    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]);
                   5432: 
                   5433:  
                   5434:   fflush(fichtm);
                   5435: }
                   5436: 
                   5437: /******************* Gnuplot file **************/
                   5438: void printinggnuplotmort(char fileres[], char optionfilefiname[], double ageminpar, double agemaxpar, double fage , char pathc[], double p[]){
                   5439: 
                   5440:   char dirfileres[132],optfileres[132];
1.164     brouard  5441: 
1.126     brouard  5442:   int ng;
                   5443: 
                   5444: 
                   5445:   /*#ifdef windows */
                   5446:   fprintf(ficgp,"cd \"%s\" \n",pathc);
                   5447:     /*#endif */
                   5448: 
                   5449: 
                   5450:   strcpy(dirfileres,optionfilefiname);
                   5451:   strcpy(optfileres,"vpl");
1.199   ! brouard  5452:   fprintf(ficgp,"set out \"graphmort.svg\"\n "); 
1.126     brouard  5453:   fprintf(ficgp,"set xlabel \"Age\"\n set ylabel \"Force of mortality (per year)\" \n "); 
1.199   ! brouard  5454:   fprintf(ficgp, "set ter svg size 640, 480\n set log y\n"); 
1.145     brouard  5455:   /* fprintf(ficgp, "set size 0.65,0.65\n"); */
1.126     brouard  5456:   fprintf(ficgp,"plot [%d:100] %lf*exp(%lf*(x-%d))",agegomp,p[1],p[2],agegomp);
                   5457: 
                   5458: } 
                   5459: 
1.136     brouard  5460: int readdata(char datafile[], int firstobs, int lastobs, int *imax)
                   5461: {
1.126     brouard  5462: 
1.136     brouard  5463:   /*-------- data file ----------*/
                   5464:   FILE *fic;
                   5465:   char dummy[]="                         ";
1.164     brouard  5466:   int i=0, j=0, n=0;
1.136     brouard  5467:   int linei, month, year,iout;
                   5468:   char line[MAXLINE], linetmp[MAXLINE];
1.164     brouard  5469:   char stra[MAXLINE], strb[MAXLINE];
1.136     brouard  5470:   char *stratrunc;
                   5471:   int lstra;
1.126     brouard  5472: 
                   5473: 
1.136     brouard  5474:   if((fic=fopen(datafile,"r"))==NULL)    {
1.195     brouard  5475:     printf("Problem while opening datafile: %s\n", datafile);fflush(stdout);
                   5476:     fprintf(ficlog,"Problem while opening datafile: %s\n", datafile);fflush(ficlog);return 1;
1.136     brouard  5477:   }
1.126     brouard  5478: 
1.136     brouard  5479:   i=1;
                   5480:   linei=0;
                   5481:   while ((fgets(line, MAXLINE, fic) != NULL) &&((i >= firstobs) && (i <=lastobs))) {
                   5482:     linei=linei+1;
                   5483:     for(j=strlen(line); j>=0;j--){  /* Untabifies line */
                   5484:       if(line[j] == '\t')
                   5485:        line[j] = ' ';
                   5486:     }
                   5487:     for(j=strlen(line)-1; (line[j]==' ')||(line[j]==10)||(line[j]==13);j--){
                   5488:       ;
                   5489:     };
                   5490:     line[j+1]=0;  /* Trims blanks at end of line */
                   5491:     if(line[0]=='#'){
                   5492:       fprintf(ficlog,"Comment line\n%s\n",line);
                   5493:       printf("Comment line\n%s\n",line);
                   5494:       continue;
                   5495:     }
                   5496:     trimbb(linetmp,line); /* Trims multiple blanks in line */
1.164     brouard  5497:     strcpy(line, linetmp);
1.136     brouard  5498:   
1.126     brouard  5499: 
1.136     brouard  5500:     for (j=maxwav;j>=1;j--){
1.137     brouard  5501:       cutv(stra, strb, line, ' '); 
1.136     brouard  5502:       if(strb[0]=='.') { /* Missing status */
                   5503:        lval=-1;
                   5504:       }else{
                   5505:        errno=0;
                   5506:        lval=strtol(strb,&endptr,10); 
                   5507:       /*       if (errno == ERANGE && (lval == LONG_MAX || lval == LONG_MIN))*/
                   5508:        if( strb[0]=='\0' || (*endptr != '\0')){
1.141     brouard  5509:          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);
                   5510:          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  5511:          return 1;
                   5512:        }
                   5513:       }
                   5514:       s[j][i]=lval;
                   5515:       
                   5516:       strcpy(line,stra);
                   5517:       cutv(stra, strb,line,' ');
1.169     brouard  5518:       if( (iout=sscanf(strb,"%d/%d",&month, &year)) != 0){
1.136     brouard  5519:       }
1.169     brouard  5520:       else  if( (iout=sscanf(strb,"%s.",dummy)) != 0){
1.136     brouard  5521:        month=99;
                   5522:        year=9999;
                   5523:       }else{
1.141     brouard  5524:        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);
                   5525:        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  5526:        return 1;
                   5527:       }
                   5528:       anint[j][i]= (double) year; 
                   5529:       mint[j][i]= (double)month; 
                   5530:       strcpy(line,stra);
                   5531:     } /* ENd Waves */
                   5532:     
                   5533:     cutv(stra, strb,line,' '); 
1.169     brouard  5534:     if( (iout=sscanf(strb,"%d/%d",&month, &year)) != 0){
1.136     brouard  5535:     }
1.169     brouard  5536:     else  if( (iout=sscanf(strb,"%s.",dummy)) != 0){
1.136     brouard  5537:       month=99;
                   5538:       year=9999;
                   5539:     }else{
1.141     brouard  5540:       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);
                   5541:        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  5542:        return 1;
                   5543:     }
                   5544:     andc[i]=(double) year; 
                   5545:     moisdc[i]=(double) month; 
                   5546:     strcpy(line,stra);
                   5547:     
                   5548:     cutv(stra, strb,line,' '); 
1.169     brouard  5549:     if( (iout=sscanf(strb,"%d/%d",&month, &year)) != 0){
1.136     brouard  5550:     }
1.169     brouard  5551:     else  if( (iout=sscanf(strb,"%s.", dummy)) != 0){
1.136     brouard  5552:       month=99;
                   5553:       year=9999;
                   5554:     }else{
1.141     brouard  5555:       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);
                   5556:       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  5557:        return 1;
                   5558:     }
                   5559:     if (year==9999) {
1.141     brouard  5560:       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);
                   5561:       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  5562:        return 1;
1.126     brouard  5563: 
1.136     brouard  5564:     }
                   5565:     annais[i]=(double)(year);
                   5566:     moisnais[i]=(double)(month); 
                   5567:     strcpy(line,stra);
                   5568:     
                   5569:     cutv(stra, strb,line,' '); 
                   5570:     errno=0;
                   5571:     dval=strtod(strb,&endptr); 
                   5572:     if( strb[0]=='\0' || (*endptr != '\0')){
1.141     brouard  5573:       printf("Error reading data around '%f' at line number %d, \"%s\" for individual %d\nShould be a weight.  Exiting.\n",dval, i,line,linei);
                   5574:       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  5575:       fflush(ficlog);
                   5576:       return 1;
                   5577:     }
                   5578:     weight[i]=dval; 
                   5579:     strcpy(line,stra);
                   5580:     
                   5581:     for (j=ncovcol;j>=1;j--){
                   5582:       cutv(stra, strb,line,' '); 
                   5583:       if(strb[0]=='.') { /* Missing status */
                   5584:        lval=-1;
                   5585:       }else{
                   5586:        errno=0;
                   5587:        lval=strtol(strb,&endptr,10); 
                   5588:        if( strb[0]=='\0' || (*endptr != '\0')){
1.141     brouard  5589:          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);
                   5590:          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  5591:          return 1;
                   5592:        }
                   5593:       }
                   5594:       if(lval <-1 || lval >1){
1.141     brouard  5595:        printf("Error reading data around '%ld' at line number %d for individual %d, '%s'\n \
1.136     brouard  5596:  Should be a value of %d(nth) covariate (0 should be the value for the reference and 1\n \
                   5597:  for the alternative. IMaCh does not build design variables automatically, do it yourself.\n \
                   5598:  For example, for multinomial values like 1, 2 and 3,\n \
                   5599:  build V1=0 V2=0 for the reference value (1),\n \
                   5600:         V1=1 V2=0 for (2) \n \
                   5601:  and V1=0 V2=1 for (3). V1=1 V2=1 should not exist and the corresponding\n \
                   5602:  output of IMaCh is often meaningless.\n \
                   5603:  Exiting.\n",lval,linei, i,line,j);
1.141     brouard  5604:        fprintf(ficlog,"Error reading data around '%ld' at line number %d for individual %d, '%s'\n \
1.136     brouard  5605:  Should be a value of %d(nth) covariate (0 should be the value for the reference and 1\n \
                   5606:  for the alternative. IMaCh does not build design variables automatically, do it yourself.\n \
                   5607:  For example, for multinomial values like 1, 2 and 3,\n \
                   5608:  build V1=0 V2=0 for the reference value (1),\n \
                   5609:         V1=1 V2=0 for (2) \n \
                   5610:  and V1=0 V2=1 for (3). V1=1 V2=1 should not exist and the corresponding\n \
                   5611:  output of IMaCh is often meaningless.\n \
                   5612:  Exiting.\n",lval,linei, i,line,j);fflush(ficlog);
                   5613:        return 1;
                   5614:       }
                   5615:       covar[j][i]=(double)(lval);
                   5616:       strcpy(line,stra);
                   5617:     }  
                   5618:     lstra=strlen(stra);
                   5619:      
                   5620:     if(lstra > 9){ /* More than 2**32 or max of what printf can write with %ld */
                   5621:       stratrunc = &(stra[lstra-9]);
                   5622:       num[i]=atol(stratrunc);
                   5623:     }
                   5624:     else
                   5625:       num[i]=atol(stra);
                   5626:     /*if((s[2][i]==2) && (s[3][i]==-1)&&(s[4][i]==9)){
                   5627:       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;}*/
                   5628:     
                   5629:     i=i+1;
                   5630:   } /* End loop reading  data */
1.126     brouard  5631: 
1.136     brouard  5632:   *imax=i-1; /* Number of individuals */
                   5633:   fclose(fic);
                   5634:  
                   5635:   return (0);
1.164     brouard  5636:   /* endread: */
1.136     brouard  5637:     printf("Exiting readdata: ");
                   5638:     fclose(fic);
                   5639:     return (1);
1.126     brouard  5640: 
                   5641: 
                   5642: 
1.136     brouard  5643: }
1.145     brouard  5644: void removespace(char *str) {
                   5645:   char *p1 = str, *p2 = str;
                   5646:   do
                   5647:     while (*p2 == ' ')
                   5648:       p2++;
1.169     brouard  5649:   while (*p1++ == *p2++);
1.145     brouard  5650: }
                   5651: 
                   5652: int decodemodel ( char model[], int lastobs) /**< This routine decode the model and returns:
1.187     brouard  5653:    * Model  V1+V2+V3+V8+V7*V8+V5*V6+V8*age+V3*age+age*age
                   5654:    * - nagesqr = 1 if age*age in the model, otherwise 0.
                   5655:    * - cptcovt total number of covariates of the model nbocc(+)+1 = 8 excepting constant and age and age*age
                   5656:    * - cptcovn or number of covariates k of the models excluding age*products =6 and age*age
1.145     brouard  5657:    * - cptcovage number of covariates with age*products =2
                   5658:    * - cptcovs number of simple covariates
                   5659:    * - 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
                   5660:    *     which is a new column after the 9 (ncovcol) variables. 
                   5661:    * - if k is a product Vn*Vm covar[k][i] is filled with correct values for each individual
                   5662:    * - Tprod[l] gives the kth covariates of the product Vn*Vm l=1 to cptcovprod-cptcovage
                   5663:    *    Tprod[1]@2 {5, 6}: position of first product V7*V8 is 5, and second V5*V6 is 6.
                   5664:    * - Tvard[k]  p Tvard[1][1]@4 {7, 8, 5, 6} for V7*V8 and V5*V6 .
                   5665:  */
1.136     brouard  5666: {
1.145     brouard  5667:   int i, j, k, ks;
1.164     brouard  5668:   int  j1, k1, k2;
1.136     brouard  5669:   char modelsav[80];
1.145     brouard  5670:   char stra[80], strb[80], strc[80], strd[80],stre[80];
1.187     brouard  5671:   char *strpt;
1.136     brouard  5672: 
1.145     brouard  5673:   /*removespace(model);*/
1.136     brouard  5674:   if (strlen(model) >1){ /* If there is at least 1 covariate */
1.145     brouard  5675:     j=0, j1=0, k1=0, k2=-1, ks=0, cptcovn=0;
1.137     brouard  5676:     if (strstr(model,"AGE") !=0){
1.192     brouard  5677:       printf("Error. AGE must be in lower case 'age' model=1+age+%s. ",model);
                   5678:       fprintf(ficlog,"Error. AGE must be in lower case model=1+age+%s. ",model);fflush(ficlog);
1.136     brouard  5679:       return 1;
                   5680:     }
1.141     brouard  5681:     if (strstr(model,"v") !=0){
                   5682:       printf("Error. 'v' must be in upper case 'V' model=%s ",model);
                   5683:       fprintf(ficlog,"Error. 'v' must be in upper case model=%s ",model);fflush(ficlog);
                   5684:       return 1;
                   5685:     }
1.187     brouard  5686:     strcpy(modelsav,model); 
                   5687:     if ((strpt=strstr(model,"age*age")) !=0){
                   5688:       printf(" strpt=%s, model=%s\n",strpt, model);
                   5689:       if(strpt != model){
                   5690:       printf("Error in model: 'model=%s'; 'age*age' should in first place before other covariates\n \
1.192     brouard  5691:  'model=1+age+age*age+V1.' or 'model=1+age+age*age+V1+V1*age.', please swap as well as \n \
1.187     brouard  5692:  corresponding column of parameters.\n",model);
                   5693:       fprintf(ficlog,"Error in model: 'model=%s'; 'age*age' should in first place before other covariates\n \
1.192     brouard  5694:  'model=1+age+age*age+V1.' or 'model=1+age+age*age+V1+V1*age.', please swap as well as \n \
1.187     brouard  5695:  corresponding column of parameters.\n",model); fflush(ficlog);
                   5696:       return 1;
                   5697:     }
                   5698: 
                   5699:       nagesqr=1;
                   5700:       if (strstr(model,"+age*age") !=0)
                   5701:        substrchaine(modelsav, model, "+age*age");
                   5702:       else if (strstr(model,"age*age+") !=0)
                   5703:        substrchaine(modelsav, model, "age*age+");
                   5704:       else 
                   5705:        substrchaine(modelsav, model, "age*age");
                   5706:     }else
                   5707:       nagesqr=0;
                   5708:     if (strlen(modelsav) >1){
                   5709:       j=nbocc(modelsav,'+'); /**< j=Number of '+' */
                   5710:       j1=nbocc(modelsav,'*'); /**< j1=Number of '*' */
                   5711:       cptcovs=j+1-j1; /**<  Number of simple covariates V1+V1*age+V3 +V3*V4+age*age=> V1 + V3 =2  */
                   5712:       cptcovt= j+1; /* Number of total covariates in the model, not including
                   5713:                   * cst, age and age*age 
                   5714:                   * V1+V1*age+ V3 + V3*V4+age*age=> 4*/
                   5715:                   /* including age products which are counted in cptcovage.
                   5716:                  * but the covariates which are products must be treated 
                   5717:                  * separately: ncovn=4- 2=2 (V1+V3). */
                   5718:       cptcovprod=j1; /**< Number of products  V1*V2 +v3*age = 2 */
                   5719:       cptcovprodnoage=0; /**< Number of covariate products without age: V3*V4 =1  */
                   5720: 
                   5721:     
                   5722:       /*   Design
                   5723:        *  V1   V2   V3   V4  V5  V6  V7  V8  V9 Weight
                   5724:        *  <          ncovcol=8                >
                   5725:        * Model V2 + V1 + V3*age + V3 + V5*V6 + V7*V8 + V8*age + V8
                   5726:        *   k=  1    2      3       4     5       6      7        8
                   5727:        *  cptcovn number of covariates (not including constant and age ) = # of + plus 1 = 7+1=8
                   5728:        *  covar[k,i], value of kth covariate if not including age for individual i:
                   5729:        *       covar[1][i]= (V2), covar[4][i]=(V3), covar[8][i]=(V8)
                   5730:        *  Tvar[k] # of the kth covariate:  Tvar[1]=2  Tvar[4]=3 Tvar[8]=8
                   5731:        *       if multiplied by age: V3*age Tvar[3=V3*age]=3 (V3) Tvar[7]=8 and 
                   5732:        *  Tage[++cptcovage]=k
                   5733:        *       if products, new covar are created after ncovcol with k1
                   5734:        *  Tvar[k]=ncovcol+k1; # of the kth covariate product:  Tvar[5]=ncovcol+1=10  Tvar[6]=ncovcol+1=11
                   5735:        *  Tprod[k1]=k; Tprod[1]=5 Tprod[2]= 6; gives the position of the k1th product
                   5736:        *  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
                   5737:        *  Tvar[cptcovn+k2]=Tvard[k1][1];Tvar[cptcovn+k2+1]=Tvard[k1][2];
                   5738:        *  Tvar[8+1]=5;Tvar[8+2]=6;Tvar[8+3]=7;Tvar[8+4]=8 inverted
                   5739:        *  V1   V2   V3   V4  V5  V6  V7  V8  V9  V10  V11
                   5740:        *  <          ncovcol=8                >
                   5741:        *       Model V2 + V1 + V3*age + V3 + V5*V6 + V7*V8 + V8*age + V8    d1   d1   d2  d2
                   5742:        *          k=  1    2      3       4     5       6      7        8    9   10   11  12
                   5743:        *     Tvar[k]= 2    1      3       3    10      11      8        8    5    6    7   8
                   5744:        * p Tvar[1]@12={2,   1,     3,      3,   11,     10,     8,       8,   7,   8,   5,  6}
                   5745:        * p Tprod[1]@2={                         6, 5}
                   5746:        *p Tvard[1][1]@4= {7, 8, 5, 6}
                   5747:        * covar[k][i]= V2   V1      ?      V3    V5*V6?   V7*V8?  ?       V8   
                   5748:        *  cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*cov[2];
                   5749:        *How to reorganize?
                   5750:        * Model V1 + V2 + V3 + V8 + V5*V6 + V7*V8 + V3*age + V8*age
                   5751:        * Tvars {2,   1,     3,      3,   11,     10,     8,       8,   7,   8,   5,  6}
                   5752:        *       {2,   1,     4,      8,    5,      6,     3,       7}
                   5753:        * Struct []
                   5754:        */
1.145     brouard  5755: 
1.187     brouard  5756:       /* This loop fills the array Tvar from the string 'model'.*/
                   5757:       /* j is the number of + signs in the model V1+V2+V3 j=2 i=3 to 1 */
                   5758:       /*   modelsav=V2+V1+V4+age*V3 strb=age*V3 stra=V2+V1+V4  */
                   5759:       /*       k=4 (age*V3) Tvar[k=4]= 3 (from V3) Tage[cptcovage=1]=4 */
                   5760:       /*       k=3 V4 Tvar[k=3]= 4 (from V4) */
                   5761:       /*       k=2 V1 Tvar[k=2]= 1 (from V1) */
                   5762:       /*       k=1 Tvar[1]=2 (from V2) */
                   5763:       /*       k=5 Tvar[5] */
                   5764:       /* for (k=1; k<=cptcovn;k++) { */
1.198     brouard  5765:       /*       cov[2+k]=nbcode[Tvar[k]][codtabm(ij,Tvar[k])]; */
1.187     brouard  5766:       /*       } */
1.198     brouard  5767:       /* for (k=1; k<=cptcovage;k++) cov[2+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(ij,Tvar[Tage[k])]]*cov[2]; */
1.187     brouard  5768:       /*
                   5769:        * Treating invertedly V2+V1+V3*age+V2*V4 is as if written V2*V4 +V3*age + V1 + V2 */
                   5770:       for(k=cptcovt; k>=1;k--) /**< Number of covariates */
1.145     brouard  5771:         Tvar[k]=0;
1.187     brouard  5772:       cptcovage=0;
                   5773:       for(k=1; k<=cptcovt;k++){ /* Loop on total covariates of the model */
                   5774:        cutl(stra,strb,modelsav,'+'); /* keeps in strb after the first '+' 
                   5775:                                         modelsav==V2+V1+V4+V3*age strb=V3*age stra=V2+V1+V4 */ 
                   5776:        if (nbocc(modelsav,'+')==0) strcpy(strb,modelsav); /* and analyzes it */
                   5777:        /*      printf("i=%d a=%s b=%s sav=%s\n",i, stra,strb,modelsav);*/
                   5778:        /*scanf("%d",i);*/
                   5779:        if (strchr(strb,'*')) {  /**< Model includes a product V2+V1+V4+V3*age strb=V3*age */
                   5780:          cutl(strc,strd,strb,'*'); /**< strd*strc  Vm*Vn: strb=V3*age(input) strc=age strd=V3 ; V3*V2 strc=V2, strd=V3 */
                   5781:          if (strcmp(strc,"age")==0) { /**< Model includes age: Vn*age */
                   5782:            /* covar is not filled and then is empty */
                   5783:            cptcovprod--;
                   5784:            cutl(stre,strb,strd,'V'); /* strd=V3(input): stre="3" */
                   5785:            Tvar[k]=atoi(stre);  /* V2+V1+V4+V3*age Tvar[4]=3 ; V1+V2*age Tvar[2]=2; V1+V1*age Tvar[2]=1 */
                   5786:            cptcovage++; /* Sums the number of covariates which include age as a product */
                   5787:            Tage[cptcovage]=k;  /* Tvar[4]=3, Tage[1] = 4 or V1+V1*age Tvar[2]=1, Tage[1]=2 */
                   5788:            /*printf("stre=%s ", stre);*/
                   5789:          } else if (strcmp(strd,"age")==0) { /* or age*Vn */
                   5790:            cptcovprod--;
                   5791:            cutl(stre,strb,strc,'V');
                   5792:            Tvar[k]=atoi(stre);
                   5793:            cptcovage++;
                   5794:            Tage[cptcovage]=k;
                   5795:          } else {  /* Age is not in the model product V2+V1+V1*V4+V3*age+V3*V2  strb=V3*V2*/
                   5796:            /* loops on k1=1 (V3*V2) and k1=2 V4*V3 */
                   5797:            cptcovn++;
                   5798:            cptcovprodnoage++;k1++;
                   5799:            cutl(stre,strb,strc,'V'); /* strc= Vn, stre is n; strb=V3*V2 stre=3 strc=*/
                   5800:            Tvar[k]=ncovcol+k1; /* For model-covariate k tells which data-covariate to use but
                   5801:                                   because this model-covariate is a construction we invent a new column
                   5802:                                   ncovcol + k1
                   5803:                                   If already ncovcol=4 and model=V2+V1+V1*V4+age*V3+V3*V2
                   5804:                                   Tvar[3=V1*V4]=4+1 Tvar[5=V3*V2]=4 + 2= 6, etc */
                   5805:            cutl(strc,strb,strd,'V'); /* strd was Vm, strc is m */
                   5806:            Tprod[k1]=k;  /* Tprod[1]=3(=V1*V4) for V2+V1+V1*V4+age*V3+V3*V2  */
                   5807:            Tvard[k1][1] =atoi(strc); /* m 1 for V1*/
                   5808:            Tvard[k1][2] =atoi(stre); /* n 4 for V4*/
                   5809:            k2=k2+2;
                   5810:            Tvar[cptcovt+k2]=Tvard[k1][1]; /* Tvar[(cptcovt=4+k2=1)=5]= 1 (V1) */
                   5811:            Tvar[cptcovt+k2+1]=Tvard[k1][2];  /* Tvar[(cptcovt=4+(k2=1)+1)=6]= 4 (V4) */
                   5812:            for (i=1; i<=lastobs;i++){
                   5813:              /* Computes the new covariate which is a product of
                   5814:                 covar[n][i]* covar[m][i] and stores it at ncovol+k1 May not be defined */
                   5815:              covar[ncovcol+k1][i]=covar[atoi(stre)][i]*covar[atoi(strc)][i];
                   5816:            }
                   5817:          } /* End age is not in the model */
                   5818:        } /* End if model includes a product */
                   5819:        else { /* no more sum */
                   5820:          /*printf("d=%s c=%s b=%s\n", strd,strc,strb);*/
                   5821:          /*  scanf("%d",i);*/
                   5822:          cutl(strd,strc,strb,'V');
                   5823:          ks++; /**< Number of simple covariates */
1.145     brouard  5824:          cptcovn++;
1.187     brouard  5825:          Tvar[k]=atoi(strd);
                   5826:        }
                   5827:        strcpy(modelsav,stra);  /* modelsav=V2+V1+V4 stra=V2+V1+V4 */ 
                   5828:        /*printf("a=%s b=%s sav=%s\n", stra,strb,modelsav);
                   5829:          scanf("%d",i);*/
                   5830:       } /* end of loop + on total covariates */
                   5831:     } /* end if strlen(modelsave == 0) age*age might exist */
                   5832:   } /* end if strlen(model == 0) */
1.136     brouard  5833:   
                   5834:   /*The number n of Vn is stored in Tvar. cptcovage =number of age covariate. Tage gives the position of age. cptcovprod= number of products.
                   5835:     If model=V1+V1*age then Tvar[1]=1 Tvar[2]=1 cptcovage=1 Tage[1]=2 cptcovprod=0*/
                   5836: 
                   5837:   /* printf("tvar1=%d tvar2=%d tvar3=%d cptcovage=%d Tage=%d",Tvar[1],Tvar[2],Tvar[3],cptcovage,Tage[1]);
                   5838:   printf("cptcovprod=%d ", cptcovprod);
                   5839:   fprintf(ficlog,"cptcovprod=%d ", cptcovprod);
                   5840: 
                   5841:   scanf("%d ",i);*/
                   5842: 
                   5843: 
1.137     brouard  5844:   return (0); /* with covar[new additional covariate if product] and Tage if age */ 
1.164     brouard  5845:   /*endread:*/
1.136     brouard  5846:     printf("Exiting decodemodel: ");
                   5847:     return (1);
                   5848: }
                   5849: 
1.169     brouard  5850: int calandcheckages(int imx, int maxwav, double *agemin, double *agemax, int *nberr, int *nbwarn )
1.136     brouard  5851: {
                   5852:   int i, m;
                   5853: 
                   5854:   for (i=1; i<=imx; i++) {
                   5855:     for(m=2; (m<= maxwav); m++) {
                   5856:       if (((int)mint[m][i]== 99) && (s[m][i] <= nlstate)){
                   5857:        anint[m][i]=9999;
                   5858:        s[m][i]=-1;
                   5859:       }
                   5860:       if((int)moisdc[i]==99 && (int)andc[i]==9999 && s[m][i]>nlstate){
1.169     brouard  5861:        *nberr = *nberr + 1;
                   5862:        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);
                   5863:        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  5864:        s[m][i]=-1;
                   5865:       }
                   5866:       if((int)moisdc[i]==99 && (int)andc[i]!=9999 && s[m][i]>nlstate){
1.169     brouard  5867:        (*nberr)++;
1.136     brouard  5868:        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]); 
                   5869:        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]); 
                   5870:        s[m][i]=-1; /* We prefer to skip it (and to skip it in version 0.8a1 too */
                   5871:       }
                   5872:     }
                   5873:   }
                   5874: 
                   5875:   for (i=1; i<=imx; i++)  {
                   5876:     agedc[i]=(moisdc[i]/12.+andc[i])-(moisnais[i]/12.+annais[i]);
                   5877:     for(m=firstpass; (m<= lastpass); m++){
                   5878:       if(s[m][i] >0 || s[m][i]==-2 || s[m][i]==-4 || s[m][i]==-5){
                   5879:        if (s[m][i] >= nlstate+1) {
1.169     brouard  5880:          if(agedc[i]>0){
                   5881:            if((int)moisdc[i]!=99 && (int)andc[i]!=9999){
1.136     brouard  5882:              agev[m][i]=agedc[i];
                   5883:          /*if(moisdc[i]==99 && andc[i]==9999) s[m][i]=-1;*/
1.169     brouard  5884:            }else {
1.136     brouard  5885:              if ((int)andc[i]!=9999){
                   5886:                nbwarn++;
                   5887:                printf("Warning negative age at death: %ld line:%d\n",num[i],i);
                   5888:                fprintf(ficlog,"Warning negative age at death: %ld line:%d\n",num[i],i);
                   5889:                agev[m][i]=-1;
                   5890:              }
                   5891:            }
1.169     brouard  5892:          } /* agedc > 0 */
1.136     brouard  5893:        }
                   5894:        else if(s[m][i] !=9){ /* Standard case, age in fractional
                   5895:                                 years but with the precision of a month */
                   5896:          agev[m][i]=(mint[m][i]/12.+1./24.+anint[m][i])-(moisnais[i]/12.+1./24.+annais[i]);
                   5897:          if((int)mint[m][i]==99 || (int)anint[m][i]==9999)
                   5898:            agev[m][i]=1;
                   5899:          else if(agev[m][i] < *agemin){ 
                   5900:            *agemin=agev[m][i];
                   5901:            printf(" Min anint[%d][%d]=%.2f annais[%d]=%.2f, agemin=%.2f\n",m,i,anint[m][i], i,annais[i], *agemin);
                   5902:          }
                   5903:          else if(agev[m][i] >*agemax){
                   5904:            *agemax=agev[m][i];
1.156     brouard  5905:            /* printf(" Max anint[%d][%d]=%.0f annais[%d]=%.0f, agemax=%.2f\n",m,i,anint[m][i], i,annais[i], *agemax);*/
1.136     brouard  5906:          }
                   5907:          /*agev[m][i]=anint[m][i]-annais[i];*/
                   5908:          /*     agev[m][i] = age[i]+2*m;*/
                   5909:        }
                   5910:        else { /* =9 */
                   5911:          agev[m][i]=1;
                   5912:          s[m][i]=-1;
                   5913:        }
                   5914:       }
                   5915:       else /*= 0 Unknown */
                   5916:        agev[m][i]=1;
                   5917:     }
                   5918:     
                   5919:   }
                   5920:   for (i=1; i<=imx; i++)  {
                   5921:     for(m=firstpass; (m<=lastpass); m++){
                   5922:       if (s[m][i] > (nlstate+ndeath)) {
1.169     brouard  5923:        (*nberr)++;
1.136     brouard  5924:        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);     
                   5925:        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);     
                   5926:        return 1;
                   5927:       }
                   5928:     }
                   5929:   }
                   5930: 
                   5931:   /*for (i=1; i<=imx; i++){
                   5932:   for (m=firstpass; (m<lastpass); m++){
                   5933:      printf("%ld %d %.lf %d %d\n", num[i],(covar[1][i]),agev[m][i],s[m][i],s[m+1][i]);
                   5934: }
                   5935: 
                   5936: }*/
                   5937: 
                   5938: 
1.139     brouard  5939:   printf("Total number of individuals= %d, Agemin = %.2f, Agemax= %.2f\n\n", imx, *agemin, *agemax);
                   5940:   fprintf(ficlog,"Total number of individuals= %d, Agemin = %.2f, Agemax= %.2f\n\n", imx, *agemin, *agemax); 
1.136     brouard  5941: 
                   5942:   return (0);
1.164     brouard  5943:  /* endread:*/
1.136     brouard  5944:     printf("Exiting calandcheckages: ");
                   5945:     return (1);
                   5946: }
                   5947: 
1.172     brouard  5948: #if defined(_MSC_VER)
                   5949: /*printf("Visual C++ compiler: %s \n;", _MSC_FULL_VER);*/
                   5950: /*fprintf(ficlog, "Visual C++ compiler: %s \n;", _MSC_FULL_VER);*/
                   5951: //#include "stdafx.h"
                   5952: //#include <stdio.h>
                   5953: //#include <tchar.h>
                   5954: //#include <windows.h>
                   5955: //#include <iostream>
                   5956: typedef BOOL(WINAPI *LPFN_ISWOW64PROCESS) (HANDLE, PBOOL);
                   5957: 
                   5958: LPFN_ISWOW64PROCESS fnIsWow64Process;
                   5959: 
                   5960: BOOL IsWow64()
                   5961: {
                   5962:        BOOL bIsWow64 = FALSE;
                   5963: 
                   5964:        //typedef BOOL (APIENTRY *LPFN_ISWOW64PROCESS)
                   5965:        //  (HANDLE, PBOOL);
                   5966: 
                   5967:        //LPFN_ISWOW64PROCESS fnIsWow64Process;
                   5968: 
                   5969:        HMODULE module = GetModuleHandle(_T("kernel32"));
                   5970:        const char funcName[] = "IsWow64Process";
                   5971:        fnIsWow64Process = (LPFN_ISWOW64PROCESS)
                   5972:                GetProcAddress(module, funcName);
                   5973: 
                   5974:        if (NULL != fnIsWow64Process)
                   5975:        {
                   5976:                if (!fnIsWow64Process(GetCurrentProcess(),
                   5977:                        &bIsWow64))
                   5978:                        //throw std::exception("Unknown error");
                   5979:                        printf("Unknown error\n");
                   5980:        }
                   5981:        return bIsWow64 != FALSE;
                   5982: }
                   5983: #endif
1.177     brouard  5984: 
1.191     brouard  5985: void syscompilerinfo(int logged)
1.167     brouard  5986:  {
                   5987:    /* #include "syscompilerinfo.h"*/
1.185     brouard  5988:    /* command line Intel compiler 32bit windows, XP compatible:*/
                   5989:    /* /GS /W3 /Gy
                   5990:       /Zc:wchar_t /Zi /O2 /Fd"Release\vc120.pdb" /D "WIN32" /D "NDEBUG" /D
                   5991:       "_CONSOLE" /D "_LIB" /D "_USING_V110_SDK71_" /D "_UNICODE" /D
                   5992:       "UNICODE" /Qipo /Zc:forScope /Gd /Oi /MT /Fa"Release\" /EHsc /nologo
1.186     brouard  5993:       /Fo"Release\" /Qprof-dir "Release\" /Fp"Release\IMaCh.pch"
                   5994:    */ 
                   5995:    /* 64 bits */
1.185     brouard  5996:    /*
                   5997:      /GS /W3 /Gy
                   5998:      /Zc:wchar_t /Zi /O2 /Fd"x64\Release\vc120.pdb" /D "WIN32" /D "NDEBUG"
                   5999:      /D "_CONSOLE" /D "_LIB" /D "_UNICODE" /D "UNICODE" /Qipo /Zc:forScope
                   6000:      /Oi /MD /Fa"x64\Release\" /EHsc /nologo /Fo"x64\Release\" /Qprof-dir
                   6001:      "x64\Release\" /Fp"x64\Release\IMaCh.pch" */
                   6002:    /* Optimization are useless and O3 is slower than O2 */
                   6003:    /*
                   6004:      /GS /W3 /Gy /Zc:wchar_t /Zi /O3 /Fd"x64\Release\vc120.pdb" /D "WIN32" 
                   6005:      /D "NDEBUG" /D "_CONSOLE" /D "_LIB" /D "_UNICODE" /D "UNICODE" /Qipo 
                   6006:      /Zc:forScope /Oi /MD /Fa"x64\Release\" /EHsc /nologo /Qparallel 
                   6007:      /Fo"x64\Release\" /Qprof-dir "x64\Release\" /Fp"x64\Release\IMaCh.pch" 
                   6008:    */
1.186     brouard  6009:    /* Link is */ /* /OUT:"visual studio
1.185     brouard  6010:       2013\Projects\IMaCh\Release\IMaCh.exe" /MANIFEST /NXCOMPAT
                   6011:       /PDB:"visual studio
                   6012:       2013\Projects\IMaCh\Release\IMaCh.pdb" /DYNAMICBASE
                   6013:       "kernel32.lib" "user32.lib" "gdi32.lib" "winspool.lib"
                   6014:       "comdlg32.lib" "advapi32.lib" "shell32.lib" "ole32.lib"
                   6015:       "oleaut32.lib" "uuid.lib" "odbc32.lib" "odbccp32.lib"
                   6016:       /MACHINE:X86 /OPT:REF /SAFESEH /INCREMENTAL:NO
                   6017:       /SUBSYSTEM:CONSOLE",5.01" /MANIFESTUAC:"level='asInvoker'
                   6018:       uiAccess='false'"
                   6019:       /ManifestFile:"Release\IMaCh.exe.intermediate.manifest" /OPT:ICF
                   6020:       /NOLOGO /TLBID:1
                   6021:    */
1.177     brouard  6022: #if defined __INTEL_COMPILER
1.178     brouard  6023: #if defined(__GNUC__)
                   6024:        struct utsname sysInfo;  /* For Intel on Linux and OS/X */
                   6025: #endif
1.177     brouard  6026: #elif defined(__GNUC__) 
1.179     brouard  6027: #ifndef  __APPLE__
1.174     brouard  6028: #include <gnu/libc-version.h>  /* Only on gnu */
1.179     brouard  6029: #endif
1.177     brouard  6030:    struct utsname sysInfo;
1.178     brouard  6031:    int cross = CROSS;
                   6032:    if (cross){
                   6033:           printf("Cross-");
1.191     brouard  6034:           if(logged) fprintf(ficlog, "Cross-");
1.178     brouard  6035:    }
1.174     brouard  6036: #endif
                   6037: 
1.171     brouard  6038: #include <stdint.h>
1.178     brouard  6039: 
1.191     brouard  6040:    printf("Compiled with:");if(logged)fprintf(ficlog,"Compiled with:");
1.169     brouard  6041: #if defined(__clang__)
1.191     brouard  6042:    printf(" Clang/LLVM");if(logged)fprintf(ficlog," Clang/LLVM");      /* Clang/LLVM. ---------------------------------------------- */
1.169     brouard  6043: #endif
                   6044: #if defined(__ICC) || defined(__INTEL_COMPILER)
1.191     brouard  6045:    printf(" Intel ICC/ICPC");if(logged)fprintf(ficlog," Intel ICC/ICPC");/* Intel ICC/ICPC. ------------------------------------------ */
1.169     brouard  6046: #endif
                   6047: #if defined(__GNUC__) || defined(__GNUG__)
1.191     brouard  6048:    printf(" GNU GCC/G++");if(logged)fprintf(ficlog," GNU GCC/G++");/* GNU GCC/G++. --------------------------------------------- */
1.169     brouard  6049: #endif
                   6050: #if defined(__HP_cc) || defined(__HP_aCC)
1.191     brouard  6051:    printf(" Hewlett-Packard C/aC++");if(logged)fprintf(fcilog," Hewlett-Packard C/aC++"); /* Hewlett-Packard C/aC++. ---------------------------------- */
1.169     brouard  6052: #endif
                   6053: #if defined(__IBMC__) || defined(__IBMCPP__)
1.191     brouard  6054:    printf(" IBM XL C/C++"); if(logged) fprintf(ficlog," IBM XL C/C++");/* IBM XL C/C++. -------------------------------------------- */
1.169     brouard  6055: #endif
                   6056: #if defined(_MSC_VER)
1.191     brouard  6057:    printf(" Microsoft Visual Studio");if(logged)fprintf(ficlog," Microsoft Visual Studio");/* Microsoft Visual Studio. --------------------------------- */
1.169     brouard  6058: #endif
                   6059: #if defined(__PGI)
1.191     brouard  6060:    printf(" Portland Group PGCC/PGCPP");if(logged) fprintf(ficlog," Portland Group PGCC/PGCPP");/* Portland Group PGCC/PGCPP. ------------------------------- */
1.169     brouard  6061: #endif
                   6062: #if defined(__SUNPRO_C) || defined(__SUNPRO_CC)
1.191     brouard  6063:    printf(" Oracle Solaris Studio");if(logged)fprintf(ficlog," Oracle Solaris Studio\n");/* Oracle Solaris Studio. ----------------------------------- */
1.167     brouard  6064: #endif
1.191     brouard  6065:    printf(" for "); if (logged) fprintf(ficlog, " for ");
1.169     brouard  6066:    
1.167     brouard  6067: // http://stackoverflow.com/questions/4605842/how-to-identify-platform-compiler-from-preprocessor-macros
                   6068: #ifdef _WIN32 // note the underscore: without it, it's not msdn official!
                   6069:     // Windows (x64 and x86)
1.191     brouard  6070:    printf("Windows (x64 and x86) ");if(logged) fprintf(ficlog,"Windows (x64 and x86) ");
1.167     brouard  6071: #elif __unix__ // all unices, not all compilers
                   6072:     // Unix
1.191     brouard  6073:    printf("Unix ");if(logged) fprintf(ficlog,"Unix ");
1.167     brouard  6074: #elif __linux__
                   6075:     // linux
1.191     brouard  6076:    printf("linux ");if(logged) fprintf(ficlog,"linux ");
1.167     brouard  6077: #elif __APPLE__
1.174     brouard  6078:     // Mac OS, not sure if this is covered by __posix__ and/or __unix__ though..
1.191     brouard  6079:    printf("Mac OS ");if(logged) fprintf(ficlog,"Mac OS ");
1.167     brouard  6080: #endif
                   6081: 
                   6082: /*  __MINGW32__          */
                   6083: /*  __CYGWIN__  */
                   6084: /* __MINGW64__  */
                   6085: // http://msdn.microsoft.com/en-us/library/b0084kay.aspx
                   6086: /* _MSC_VER  //the Visual C++ compiler is 17.00.51106.1, the _MSC_VER macro evaluates to 1700. Type cl /?  */
                   6087: /* _MSC_FULL_VER //the Visual C++ compiler is 15.00.20706.01, the _MSC_FULL_VER macro evaluates to 150020706 */
                   6088: /* _WIN64  // Defined for applications for Win64. */
                   6089: /* _M_X64 // Defined for compilations that target x64 processors. */
                   6090: /* _DEBUG // Defined when you compile with /LDd, /MDd, and /MTd. */
1.171     brouard  6091: 
1.167     brouard  6092: #if UINTPTR_MAX == 0xffffffff
1.191     brouard  6093:    printf(" 32-bit"); if(logged) fprintf(ficlog," 32-bit");/* 32-bit */
1.167     brouard  6094: #elif UINTPTR_MAX == 0xffffffffffffffff
1.191     brouard  6095:    printf(" 64-bit"); if(logged) fprintf(ficlog," 64-bit");/* 64-bit */
1.167     brouard  6096: #else
1.191     brouard  6097:    printf(" wtf-bit"); if(logged) fprintf(ficlog," wtf-bit");/* wtf */
1.167     brouard  6098: #endif
                   6099: 
1.169     brouard  6100: #if defined(__GNUC__)
                   6101: # if defined(__GNUC_PATCHLEVEL__)
                   6102: #  define __GNUC_VERSION__ (__GNUC__ * 10000 \
                   6103:                             + __GNUC_MINOR__ * 100 \
                   6104:                             + __GNUC_PATCHLEVEL__)
                   6105: # else
                   6106: #  define __GNUC_VERSION__ (__GNUC__ * 10000 \
                   6107:                             + __GNUC_MINOR__ * 100)
                   6108: # endif
1.174     brouard  6109:    printf(" using GNU C version %d.\n", __GNUC_VERSION__);
1.191     brouard  6110:    if(logged) fprintf(ficlog, " using GNU C version %d.\n", __GNUC_VERSION__);
1.176     brouard  6111: 
                   6112:    if (uname(&sysInfo) != -1) {
                   6113:      printf("Running on: %s %s %s %s %s\n",sysInfo.sysname, sysInfo.nodename, sysInfo.release, sysInfo.version, sysInfo.machine);
1.191     brouard  6114:         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  6115:    }
                   6116:    else
                   6117:       perror("uname() error");
1.179     brouard  6118:    //#ifndef __INTEL_COMPILER 
                   6119: #if !defined (__INTEL_COMPILER) && !defined(__APPLE__)
1.174     brouard  6120:    printf("GNU libc version: %s\n", gnu_get_libc_version()); 
1.191     brouard  6121:    if(logged) fprintf(ficlog,"GNU libc version: %s\n", gnu_get_libc_version());
1.177     brouard  6122: #endif
1.169     brouard  6123: #endif
1.172     brouard  6124: 
                   6125:    //   void main()
                   6126:    //   {
1.169     brouard  6127: #if defined(_MSC_VER)
1.174     brouard  6128:    if (IsWow64()){
1.191     brouard  6129:           printf("\nThe program (probably compiled for 32bit) is running under WOW64 (64bit) emulation.\n");
                   6130:           if (logged) fprintf(ficlog, "\nThe program (probably compiled for 32bit) is running under WOW64 (64bit) emulation.\n");
1.174     brouard  6131:    }
                   6132:    else{
1.191     brouard  6133:           printf("\nThe program is not running under WOW64 (i.e probably on a 64bit Windows).\n");
                   6134:           if (logged) fprintf(ficlog, "\nThe programm is not running under WOW64 (i.e probably on a 64bit Windows).\n");
1.174     brouard  6135:    }
1.172     brouard  6136:    //     printf("\nPress Enter to continue...");
                   6137:    //     getchar();
                   6138:    //   }
                   6139: 
1.169     brouard  6140: #endif
                   6141:    
1.167     brouard  6142: 
                   6143:  }
1.136     brouard  6144: 
1.180     brouard  6145: int prevalence_limit(double *p, double **prlim, double ageminpar, double agemaxpar){
                   6146:   /*--------------- Prevalence limit  (period or stable prevalence) --------------*/
                   6147:   int i, j, k, i1 ;
                   6148:   double ftolpl = 1.e-10;
                   6149:   double age, agebase, agelim;
                   6150: 
                   6151:     strcpy(filerespl,"pl");
                   6152:     strcat(filerespl,fileres);
                   6153:     if((ficrespl=fopen(filerespl,"w"))==NULL) {
                   6154:       printf("Problem with period (stable) prevalence resultfile: %s\n", filerespl);return 1;
                   6155:       fprintf(ficlog,"Problem with period (stable) prevalence resultfile: %s\n", filerespl);return 1;
                   6156:     }
                   6157:     printf("Computing period (stable) prevalence: result on file '%s' \n", filerespl);
                   6158:     fprintf(ficlog,"Computing period (stable) prevalence: result on file '%s' \n", filerespl);
                   6159:     pstamp(ficrespl);
                   6160:     fprintf(ficrespl,"# Period (stable) prevalence \n");
                   6161:     fprintf(ficrespl,"#Age ");
                   6162:     for(i=1; i<=nlstate;i++) fprintf(ficrespl,"%d-%d ",i,i);
                   6163:     fprintf(ficrespl,"\n");
                   6164:   
                   6165:     /* prlim=matrix(1,nlstate,1,nlstate);*/ /* back in main */
                   6166: 
                   6167:     agebase=ageminpar;
                   6168:     agelim=agemaxpar;
                   6169: 
                   6170:     i1=pow(2,cptcoveff);
                   6171:     if (cptcovn < 1){i1=1;}
                   6172: 
                   6173:     for(cptcov=1,k=0;cptcov<=i1;cptcov++){
                   6174:     /* for(cptcov=1,k=0;cptcov<=1;cptcov++){ */
                   6175:       //for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){
                   6176:        k=k+1;
                   6177:        /* to clean */
1.198     brouard  6178:        //printf("cptcov=%d cptcod=%d codtab=%d\n",cptcov, cptcod,codtabm(cptcod,cptcov));
1.180     brouard  6179:        fprintf(ficrespl,"\n#******");
                   6180:        printf("\n#******");
                   6181:        fprintf(ficlog,"\n#******");
                   6182:        for(j=1;j<=cptcoveff;j++) {
1.198     brouard  6183:          fprintf(ficrespl," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
                   6184:          printf(" V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
                   6185:          fprintf(ficlog," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
1.180     brouard  6186:        }
                   6187:        fprintf(ficrespl,"******\n");
                   6188:        printf("******\n");
                   6189:        fprintf(ficlog,"******\n");
                   6190: 
                   6191:        fprintf(ficrespl,"#Age ");
                   6192:        for(j=1;j<=cptcoveff;j++) {
1.198     brouard  6193:          fprintf(ficrespl,"V%d %d",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
1.180     brouard  6194:        }
                   6195:        for(i=1; i<=nlstate;i++) fprintf(ficrespl,"%d-%d ",i,i);
                   6196:        fprintf(ficrespl,"\n");
                   6197:        
                   6198:        for (age=agebase; age<=agelim; age++){
                   6199:        /* for (age=agebase; age<=agebase; age++){ */
                   6200:          prevalim(prlim, nlstate, p, age, oldm, savm,ftolpl,k);
                   6201:          fprintf(ficrespl,"%.0f ",age );
                   6202:          for(j=1;j<=cptcoveff;j++)
1.198     brouard  6203:            fprintf(ficrespl,"%d %d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
1.180     brouard  6204:          for(i=1; i<=nlstate;i++)
                   6205:            fprintf(ficrespl," %.5f", prlim[i][i]);
                   6206:          fprintf(ficrespl,"\n");
                   6207:        } /* Age */
                   6208:        /* was end of cptcod */
                   6209:     } /* cptcov */
1.184     brouard  6210:        return 0;
1.180     brouard  6211: }
                   6212: 
                   6213: int hPijx(double *p, int bage, int fage){
                   6214:     /*------------- h Pij x at various ages ------------*/
                   6215: 
                   6216:   int stepsize;
                   6217:   int agelim;
                   6218:   int hstepm;
                   6219:   int nhstepm;
                   6220:   int h, i, i1, j, k;
                   6221: 
                   6222:   double agedeb;
                   6223:   double ***p3mat;
                   6224: 
                   6225:     strcpy(filerespij,"pij");  strcat(filerespij,fileres);
                   6226:     if((ficrespij=fopen(filerespij,"w"))==NULL) {
                   6227:       printf("Problem with Pij resultfile: %s\n", filerespij); return 1;
                   6228:       fprintf(ficlog,"Problem with Pij resultfile: %s\n", filerespij); return 1;
                   6229:     }
                   6230:     printf("Computing pij: result on file '%s' \n", filerespij);
                   6231:     fprintf(ficlog,"Computing pij: result on file '%s' \n", filerespij);
                   6232:   
                   6233:     stepsize=(int) (stepm+YEARM-1)/YEARM;
                   6234:     /*if (stepm<=24) stepsize=2;*/
                   6235: 
                   6236:     agelim=AGESUP;
                   6237:     hstepm=stepsize*YEARM; /* Every year of age */
                   6238:     hstepm=hstepm/stepm; /* Typically 2 years, = 2/6 months = 4 */ 
                   6239: 
                   6240:     /* hstepm=1;   aff par mois*/
                   6241:     pstamp(ficrespij);
                   6242:     fprintf(ficrespij,"#****** h Pij x Probability to be in state j at age x+h being in i at x ");
                   6243:     i1= pow(2,cptcoveff);
1.183     brouard  6244:    /* for(cptcov=1,k=0;cptcov<=i1;cptcov++){ */
                   6245:    /*    /\*for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){*\/ */
                   6246:    /*          k=k+1;  */
                   6247:     for (k=1; k <= (int) pow(2,cptcoveff); k++){
                   6248:       fprintf(ficrespij,"\n#****** ");
                   6249:       for(j=1;j<=cptcoveff;j++) 
1.198     brouard  6250:        fprintf(ficrespij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
1.183     brouard  6251:       fprintf(ficrespij,"******\n");
                   6252:       
                   6253:       for (agedeb=fage; agedeb>=bage; agedeb--){ /* If stepm=6 months */
                   6254:        nhstepm=(int) rint((agelim-agedeb)*YEARM/stepm); /* Typically 20 years = 20*12/6=40 */ 
                   6255:        nhstepm = nhstepm/hstepm; /* Typically 40/4=10 */
                   6256:        
                   6257:        /*        nhstepm=nhstepm*YEARM; aff par mois*/
1.180     brouard  6258:        
1.183     brouard  6259:        p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   6260:        oldm=oldms;savm=savms;
                   6261:        hpxij(p3mat,nhstepm,agedeb,hstepm,p,nlstate,stepm,oldm,savm, k);  
                   6262:        fprintf(ficrespij,"# Cov Agex agex+h hpijx with i,j=");
                   6263:        for(i=1; i<=nlstate;i++)
                   6264:          for(j=1; j<=nlstate+ndeath;j++)
                   6265:            fprintf(ficrespij," %1d-%1d",i,j);
                   6266:        fprintf(ficrespij,"\n");
                   6267:        for (h=0; h<=nhstepm; h++){
                   6268:          /*agedebphstep = agedeb + h*hstepm/YEARM*stepm;*/
                   6269:          fprintf(ficrespij,"%d %3.f %3.f",k, agedeb, agedeb + h*hstepm/YEARM*stepm );
1.180     brouard  6270:          for(i=1; i<=nlstate;i++)
                   6271:            for(j=1; j<=nlstate+ndeath;j++)
1.183     brouard  6272:              fprintf(ficrespij," %.5f", p3mat[i][j][h]);
1.180     brouard  6273:          fprintf(ficrespij,"\n");
                   6274:        }
1.183     brouard  6275:        free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   6276:        fprintf(ficrespij,"\n");
                   6277:       }
1.180     brouard  6278:       /*}*/
                   6279:     }
1.184     brouard  6280:        return 0;
1.180     brouard  6281: }
                   6282: 
                   6283: 
1.136     brouard  6284: /***********************************************/
                   6285: /**************** Main Program *****************/
                   6286: /***********************************************/
                   6287: 
                   6288: int main(int argc, char *argv[])
                   6289: {
                   6290: #ifdef GSL
                   6291:   const gsl_multimin_fminimizer_type *T;
                   6292:   size_t iteri = 0, it;
                   6293:   int rval = GSL_CONTINUE;
                   6294:   int status = GSL_SUCCESS;
                   6295:   double ssval;
                   6296: #endif
                   6297:   int movingaverage(double ***probs, double bage,double fage, double ***mobaverage, int mobilav);
1.164     brouard  6298:   int i,j, k, n=MAXN,iter=0,m,size=100, cptcod;
                   6299: 
                   6300:   int jj, ll, li, lj, lk;
1.136     brouard  6301:   int numlinepar=0; /* Current linenumber of parameter file */
1.197     brouard  6302:   int num_filled;
1.136     brouard  6303:   int itimes;
                   6304:   int NDIM=2;
                   6305:   int vpopbased=0;
                   6306: 
1.164     brouard  6307:   char ca[32], cb[32];
1.136     brouard  6308:   /*  FILE *fichtm; *//* Html File */
                   6309:   /* FILE *ficgp;*/ /*Gnuplot File */
                   6310:   struct stat info;
1.191     brouard  6311:   double agedeb=0.;
1.194     brouard  6312: 
                   6313:   double ageminpar=AGEOVERFLOW,agemin=AGEOVERFLOW, agemaxpar=-AGEOVERFLOW, agemax=-AGEOVERFLOW;
1.136     brouard  6314: 
1.165     brouard  6315:   double fret;
1.191     brouard  6316:   double dum=0.; /* Dummy variable */
1.136     brouard  6317:   double ***p3mat;
                   6318:   double ***mobaverage;
1.164     brouard  6319: 
                   6320:   char line[MAXLINE];
1.197     brouard  6321:   char path[MAXLINE],pathc[MAXLINE],pathcd[MAXLINE],pathtot[MAXLINE];
                   6322: 
                   6323:   char model[MAXLINE], modeltemp[MAXLINE];
1.136     brouard  6324:   char pathr[MAXLINE], pathimach[MAXLINE]; 
1.164     brouard  6325:   char *tok, *val; /* pathtot */
1.136     brouard  6326:   int firstobs=1, lastobs=10;
1.195     brouard  6327:   int c,  h , cpt, c2;
1.191     brouard  6328:   int jl=0;
                   6329:   int i1, j1, jk, stepsize=0;
1.194     brouard  6330:   int count=0;
                   6331: 
1.164     brouard  6332:   int *tab; 
1.136     brouard  6333:   int mobilavproj=0 , prevfcast=0 ; /* moving average of prev, If prevfcast=1 prevalence projection */
                   6334:   int mobilav=0,popforecast=0;
1.191     brouard  6335:   int hstepm=0, nhstepm=0;
1.136     brouard  6336:   int agemortsup;
                   6337:   float  sumlpop=0.;
                   6338:   double jprev1=1, mprev1=1,anprev1=2000,jprev2=1, mprev2=1,anprev2=2000;
                   6339:   double jpyram=1, mpyram=1,anpyram=2000,jpyram1=1, mpyram1=1,anpyram1=2000;
                   6340: 
1.191     brouard  6341:   double bage=0, fage=110., age, agelim=0., agebase=0.;
1.136     brouard  6342:   double ftolpl=FTOL;
                   6343:   double **prlim;
                   6344:   double ***param; /* Matrix of parameters */
                   6345:   double  *p;
                   6346:   double **matcov; /* Matrix of covariance */
                   6347:   double ***delti3; /* Scale */
                   6348:   double *delti; /* Scale */
                   6349:   double ***eij, ***vareij;
                   6350:   double **varpl; /* Variances of prevalence limits by age */
                   6351:   double *epj, vepp;
1.164     brouard  6352: 
1.136     brouard  6353:   double dateprev1, dateprev2,jproj1=1,mproj1=1,anproj1=2000,jproj2=1,mproj2=1,anproj2=2000;
                   6354:   double **ximort;
1.145     brouard  6355:   char *alph[]={"a","a","b","c","d","e"}, str[4]="1234";
1.136     brouard  6356:   int *dcwave;
                   6357: 
1.164     brouard  6358:   char z[1]="c";
1.136     brouard  6359: 
                   6360:   /*char  *strt;*/
                   6361:   char strtend[80];
1.126     brouard  6362: 
1.164     brouard  6363: 
1.126     brouard  6364: /*   setlocale (LC_ALL, ""); */
                   6365: /*   bindtextdomain (PACKAGE, LOCALEDIR); */
                   6366: /*   textdomain (PACKAGE); */
                   6367: /*   setlocale (LC_CTYPE, ""); */
                   6368: /*   setlocale (LC_MESSAGES, ""); */
                   6369: 
                   6370:   /*   gettimeofday(&start_time, (struct timezone*)0); */ /* at first time */
1.157     brouard  6371:   rstart_time = time(NULL);  
                   6372:   /*  (void) gettimeofday(&start_time,&tzp);*/
                   6373:   start_time = *localtime(&rstart_time);
1.126     brouard  6374:   curr_time=start_time;
1.157     brouard  6375:   /*tml = *localtime(&start_time.tm_sec);*/
                   6376:   /* strcpy(strstart,asctime(&tml)); */
                   6377:   strcpy(strstart,asctime(&start_time));
1.126     brouard  6378: 
                   6379: /*  printf("Localtime (at start)=%s",strstart); */
1.157     brouard  6380: /*  tp.tm_sec = tp.tm_sec +86400; */
                   6381: /*  tm = *localtime(&start_time.tm_sec); */
1.126     brouard  6382: /*   tmg.tm_year=tmg.tm_year +dsign*dyear; */
                   6383: /*   tmg.tm_mon=tmg.tm_mon +dsign*dmonth; */
                   6384: /*   tmg.tm_hour=tmg.tm_hour + 1; */
1.157     brouard  6385: /*   tp.tm_sec = mktime(&tmg); */
1.126     brouard  6386: /*   strt=asctime(&tmg); */
                   6387: /*   printf("Time(after) =%s",strstart);  */
                   6388: /*  (void) time (&time_value);
                   6389: *  printf("time=%d,t-=%d\n",time_value,time_value-86400);
                   6390: *  tm = *localtime(&time_value);
                   6391: *  strstart=asctime(&tm);
                   6392: *  printf("tim_value=%d,asctime=%s\n",time_value,strstart); 
                   6393: */
                   6394: 
                   6395:   nberr=0; /* Number of errors and warnings */
                   6396:   nbwarn=0;
1.184     brouard  6397: #ifdef WIN32
                   6398:   _getcwd(pathcd, size);
                   6399: #else
1.126     brouard  6400:   getcwd(pathcd, size);
1.184     brouard  6401: #endif
1.191     brouard  6402:   syscompilerinfo(0);
1.196     brouard  6403:   printf("\nIMaCh version %s, %s\n%s",version, copyright, fullversion);
1.126     brouard  6404:   if(argc <=1){
                   6405:     printf("\nEnter the parameter file name: ");
                   6406:     fgets(pathr,FILENAMELENGTH,stdin);
                   6407:     i=strlen(pathr);
                   6408:     if(pathr[i-1]=='\n')
                   6409:       pathr[i-1]='\0';
1.156     brouard  6410:     i=strlen(pathr);
                   6411:     if(pathr[i-1]==' ') /* This may happen when dragging on oS/X! */
                   6412:       pathr[i-1]='\0';
1.126     brouard  6413:    for (tok = pathr; tok != NULL; ){
                   6414:       printf("Pathr |%s|\n",pathr);
                   6415:       while ((val = strsep(&tok, "\"" )) != NULL && *val == '\0');
                   6416:       printf("val= |%s| pathr=%s\n",val,pathr);
                   6417:       strcpy (pathtot, val);
                   6418:       if(pathr[0] == '\0') break; /* Dirty */
                   6419:     }
                   6420:   }
                   6421:   else{
                   6422:     strcpy(pathtot,argv[1]);
                   6423:   }
                   6424:   /*if(getcwd(pathcd, MAXLINE)!= NULL)printf ("Error pathcd\n");*/
                   6425:   /*cygwin_split_path(pathtot,path,optionfile);
                   6426:     printf("pathtot=%s, path=%s, optionfile=%s\n",pathtot,path,optionfile);*/
                   6427:   /* cutv(path,optionfile,pathtot,'\\');*/
                   6428: 
                   6429:   /* Split argv[0], imach program to get pathimach */
                   6430:   printf("\nargv[0]=%s argv[1]=%s, \n",argv[0],argv[1]);
                   6431:   split(argv[0],pathimach,optionfile,optionfilext,optionfilefiname);
                   6432:   printf("\nargv[0]=%s pathimach=%s, \noptionfile=%s \noptionfilext=%s \noptionfilefiname=%s\n",argv[0],pathimach,optionfile,optionfilext,optionfilefiname);
                   6433:  /*   strcpy(pathimach,argv[0]); */
                   6434:   /* Split argv[1]=pathtot, parameter file name to get path, optionfile, extension and name */
                   6435:   split(pathtot,path,optionfile,optionfilext,optionfilefiname);
                   6436:   printf("\npathtot=%s,\npath=%s,\noptionfile=%s \noptionfilext=%s \noptionfilefiname=%s\n",pathtot,path,optionfile,optionfilext,optionfilefiname);
1.184     brouard  6437: #ifdef WIN32
                   6438:   _chdir(path); /* Can be a relative path */
                   6439:   if(_getcwd(pathcd,MAXLINE) > 0) /* So pathcd is the full path */
                   6440: #else
1.126     brouard  6441:   chdir(path); /* Can be a relative path */
1.184     brouard  6442:   if (getcwd(pathcd, MAXLINE) > 0) /* So pathcd is the full path */
                   6443: #endif
                   6444:   printf("Current directory %s!\n",pathcd);
1.126     brouard  6445:   strcpy(command,"mkdir ");
                   6446:   strcat(command,optionfilefiname);
                   6447:   if((outcmd=system(command)) != 0){
1.169     brouard  6448:     printf("Directory already exists (or can't create it) %s%s, err=%d\n",path,optionfilefiname,outcmd);
1.126     brouard  6449:     /* fprintf(ficlog,"Problem creating directory %s%s\n",path,optionfilefiname); */
                   6450:     /* fclose(ficlog); */
                   6451: /*     exit(1); */
                   6452:   }
                   6453: /*   if((imk=mkdir(optionfilefiname))<0){ */
                   6454: /*     perror("mkdir"); */
                   6455: /*   } */
                   6456: 
                   6457:   /*-------- arguments in the command line --------*/
                   6458: 
1.186     brouard  6459:   /* Main Log file */
1.126     brouard  6460:   strcat(filelog, optionfilefiname);
                   6461:   strcat(filelog,".log");    /* */
                   6462:   if((ficlog=fopen(filelog,"w"))==NULL)    {
                   6463:     printf("Problem with logfile %s\n",filelog);
                   6464:     goto end;
                   6465:   }
                   6466:   fprintf(ficlog,"Log filename:%s\n",filelog);
1.197     brouard  6467:   fprintf(ficlog,"Version %s %s",version,fullversion);
1.126     brouard  6468:   fprintf(ficlog,"\nEnter the parameter file name: \n");
                   6469:   fprintf(ficlog,"pathimach=%s\npathtot=%s\n\
                   6470:  path=%s \n\
                   6471:  optionfile=%s\n\
                   6472:  optionfilext=%s\n\
1.156     brouard  6473:  optionfilefiname='%s'\n",pathimach,pathtot,path,optionfile,optionfilext,optionfilefiname);
1.126     brouard  6474: 
1.197     brouard  6475:   syscompilerinfo(1);
1.167     brouard  6476: 
1.126     brouard  6477:   printf("Local time (at start):%s",strstart);
                   6478:   fprintf(ficlog,"Local time (at start): %s",strstart);
                   6479:   fflush(ficlog);
                   6480: /*   (void) gettimeofday(&curr_time,&tzp); */
1.157     brouard  6481: /*   printf("Elapsed time %d\n", asc_diff_time(curr_time.tm_sec-start_time.tm_sec,tmpout)); */
1.126     brouard  6482: 
                   6483:   /* */
                   6484:   strcpy(fileres,"r");
                   6485:   strcat(fileres, optionfilefiname);
                   6486:   strcat(fileres,".txt");    /* Other files have txt extension */
                   6487: 
1.186     brouard  6488:   /* Main ---------arguments file --------*/
1.126     brouard  6489: 
                   6490:   if((ficpar=fopen(optionfile,"r"))==NULL)    {
1.155     brouard  6491:     printf("Problem with optionfile '%s' with errno='%s'\n",optionfile,strerror(errno));
                   6492:     fprintf(ficlog,"Problem with optionfile '%s' with errno='%s'\n",optionfile,strerror(errno));
1.126     brouard  6493:     fflush(ficlog);
1.149     brouard  6494:     /* goto end; */
                   6495:     exit(70); 
1.126     brouard  6496:   }
                   6497: 
                   6498: 
                   6499: 
                   6500:   strcpy(filereso,"o");
                   6501:   strcat(filereso,fileres);
                   6502:   if((ficparo=fopen(filereso,"w"))==NULL) { /* opened on subdirectory */
                   6503:     printf("Problem with Output resultfile: %s\n", filereso);
                   6504:     fprintf(ficlog,"Problem with Output resultfile: %s\n", filereso);
                   6505:     fflush(ficlog);
                   6506:     goto end;
                   6507:   }
                   6508: 
                   6509:   /* Reads comments: lines beginning with '#' */
                   6510:   numlinepar=0;
1.197     brouard  6511: 
                   6512:     /* First parameter line */
                   6513:   while(fgets(line, MAXLINE, ficpar)) {
                   6514:     /* If line starts with a # it is a comment */
                   6515:     if (line[0] == '#') {
                   6516:       numlinepar++;
                   6517:       fputs(line,stdout);
                   6518:       fputs(line,ficparo);
                   6519:       fputs(line,ficlog);
                   6520:       continue;
                   6521:     }else
                   6522:       break;
                   6523:   }
                   6524:   if((num_filled=sscanf(line,"title=%s datafile=%s lastobs=%d firstpass=%d lastpass=%d\n", \
                   6525:                        title, datafile, &lastobs, &firstpass,&lastpass)) !=EOF){
                   6526:     if (num_filled != 5) {
                   6527:       printf("Should be 5 parameters\n");
                   6528:     }
1.126     brouard  6529:     numlinepar++;
1.197     brouard  6530:     printf("title=%s datafile=%s lastobs=%d firstpass=%d lastpass=%d\n", title, datafile, lastobs, firstpass,lastpass);
                   6531:   }
                   6532:   /* Second parameter line */
                   6533:   while(fgets(line, MAXLINE, ficpar)) {
                   6534:     /* If line starts with a # it is a comment */
                   6535:     if (line[0] == '#') {
                   6536:       numlinepar++;
                   6537:       fputs(line,stdout);
                   6538:       fputs(line,ficparo);
                   6539:       fputs(line,ficlog);
                   6540:       continue;
                   6541:     }else
                   6542:       break;
                   6543:   }
                   6544:   if((num_filled=sscanf(line,"ftol=%lf stepm=%d ncovcol=%d nlstate=%d ndeath=%d maxwav=%d mle=%d weight=%d\n", \
                   6545:                        &ftol, &stepm, &ncovcol, &nlstate, &ndeath, &maxwav, &mle, &weightopt)) !=EOF){
                   6546:     if (num_filled != 8) {
                   6547:       printf("Not 8\n");
                   6548:     }
                   6549:     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  6550:   }
                   6551: 
1.197     brouard  6552:   /* Third parameter line */
                   6553:   while(fgets(line, MAXLINE, ficpar)) {
                   6554:     /* If line starts with a # it is a comment */
                   6555:     if (line[0] == '#') {
                   6556:       numlinepar++;
                   6557:       fputs(line,stdout);
                   6558:       fputs(line,ficparo);
                   6559:       fputs(line,ficlog);
                   6560:       continue;
                   6561:     }else
                   6562:       break;
                   6563:   }
                   6564:   if((num_filled=sscanf(line,"model=1+age%[^.\n]\n", model)) !=EOF){
                   6565:     if (num_filled != 1) {
                   6566:       printf("ERROR %d: Model should be at minimum 'model=1+age.' %s\n",num_filled, line);
                   6567:       fprintf(ficlog,"ERROR %d: Model should be at minimum 'model=1+age.' %s\n",num_filled, line);
                   6568:       model[0]='\0';
                   6569:       goto end;
                   6570:     }
                   6571:     else{
                   6572:       if (model[0]=='+'){
                   6573:        for(i=1; i<=strlen(model);i++)
                   6574:          modeltemp[i-1]=model[i];
                   6575:       }
                   6576:       strcpy(model,modeltemp); 
                   6577:     }
1.199   ! brouard  6578:     /* printf(" model=1+age%s modeltemp= %s, model=%s\n",model, modeltemp, model);fflush(stdout); */
1.197     brouard  6579:   }
                   6580:   /* 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); */
                   6581:   /* numlinepar=numlinepar+3; /\* In general *\/ */
                   6582:   /* 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  6583:   if(model[strlen(model)-1]=='.') /* Suppressing leading dot in the model */
                   6584:     model[strlen(model)-1]='\0';
1.197     brouard  6585:   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);
                   6586:   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  6587:   fflush(ficlog);
1.190     brouard  6588:   /* if(model[0]=='#'|| model[0]== '\0'){ */
                   6589:   if(model[0]=='#'){
1.187     brouard  6590:     printf("Error in 'model' line: model should start with 'model=1+age+' and end with '.' \n \
                   6591:  'model=1+age+.' or 'model=1+age+V1.' or 'model=1+age+age*age+V1+V1*age.' or \n \
                   6592:  'model=1+age+V1+V2.' or 'model=1+age+V1+V2+V1*V2.' etc. \n");         \
                   6593:     if(mle != -1){
                   6594:       printf("Fix the model line and run imach with mle=-1 to get a correct template of the parameter file.\n");
                   6595:       exit(1);
                   6596:     }
                   6597:   }
1.126     brouard  6598:   while((c=getc(ficpar))=='#' && c!= EOF){
                   6599:     ungetc(c,ficpar);
                   6600:     fgets(line, MAXLINE, ficpar);
                   6601:     numlinepar++;
1.195     brouard  6602:     if(line[1]=='q'){ /* This #q will quit imach (the answer is q) */
                   6603:       z[0]=line[1];
                   6604:     }
                   6605:     /* printf("****line [1] = %c \n",line[1]); */
1.141     brouard  6606:     fputs(line, stdout);
                   6607:     //puts(line);
1.126     brouard  6608:     fputs(line,ficparo);
                   6609:     fputs(line,ficlog);
                   6610:   }
                   6611:   ungetc(c,ficpar);
                   6612: 
                   6613:    
1.145     brouard  6614:   covar=matrix(0,NCOVMAX,1,n);  /**< used in readdata */
1.136     brouard  6615:   cptcovn=0; /*Number of covariates, i.e. number of '+' in model statement plus one, indepently of n in Vn*/
                   6616:   /* v1+v2+v3+v2*v4+v5*age makes cptcovn = 5
                   6617:      v1+v2*age+v2*v3 makes cptcovn = 3
                   6618:   */
                   6619:   if (strlen(model)>1) 
1.187     brouard  6620:     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  6621:   else
1.187     brouard  6622:     ncovmodel=2; /* Constant and age */
1.133     brouard  6623:   nforce= (nlstate+ndeath-1)*nlstate; /* Number of forces ij from state i to j */
                   6624:   npar= nforce*ncovmodel; /* Number of parameters like aij*/
1.131     brouard  6625:   if(npar >MAXPARM || nlstate >NLSTATEMAX || ndeath >NDEATHMAX || ncovmodel>NCOVMAX){
                   6626:     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);
                   6627:     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);
                   6628:     fflush(stdout);
                   6629:     fclose (ficlog);
                   6630:     goto end;
                   6631:   }
1.126     brouard  6632:   delti3= ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel);
                   6633:   delti=delti3[1][1];
                   6634:   /*delti=vector(1,npar); *//* Scale of each paramater (output from hesscov)*/
                   6635:   if(mle==-1){ /* Print a wizard for help writing covariance matrix */
                   6636:     prwizard(ncovmodel, nlstate, ndeath, model, ficparo);
1.191     brouard  6637:     printf(" You chose mle=-1, look at file %s for a template of covariance matrix \n",filereso);
                   6638:     fprintf(ficlog," You chose mle=-1, look at file %s for a template of covariance matrix \n",filereso);
1.126     brouard  6639:     free_ma3x(delti3,1,nlstate,1, nlstate+ndeath-1,1,ncovmodel); 
                   6640:     fclose (ficparo);
                   6641:     fclose (ficlog);
                   6642:     goto end;
                   6643:     exit(0);
                   6644:   }
1.186     brouard  6645:   else if(mle==-3) { /* Main Wizard */
1.126     brouard  6646:     prwizard(ncovmodel, nlstate, ndeath, model, ficparo);
1.192     brouard  6647:     printf(" You chose mle=-3, look at file %s for a template of covariance matrix \n",filereso);
                   6648:     fprintf(ficlog," You chose mle=-3, look at file %s for a template of covariance matrix \n",filereso);
1.126     brouard  6649:     param= ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel);
                   6650:     matcov=matrix(1,npar,1,npar);
                   6651:   }
                   6652:   else{
1.145     brouard  6653:     /* Read guessed parameters */
1.126     brouard  6654:     /* Reads comments: lines beginning with '#' */
                   6655:     while((c=getc(ficpar))=='#' && c!= EOF){
                   6656:       ungetc(c,ficpar);
                   6657:       fgets(line, MAXLINE, ficpar);
                   6658:       numlinepar++;
1.141     brouard  6659:       fputs(line,stdout);
1.126     brouard  6660:       fputs(line,ficparo);
                   6661:       fputs(line,ficlog);
                   6662:     }
                   6663:     ungetc(c,ficpar);
                   6664:     
                   6665:     param= ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel);
                   6666:     for(i=1; i <=nlstate; i++){
                   6667:       j=0;
                   6668:       for(jj=1; jj <=nlstate+ndeath; jj++){
                   6669:        if(jj==i) continue;
                   6670:        j++;
                   6671:        fscanf(ficpar,"%1d%1d",&i1,&j1);
1.193     brouard  6672:        if ((i1 != i) || (j1 != jj)){
1.126     brouard  6673:          printf("Error in line parameters number %d, %1d%1d instead of %1d%1d \n \
                   6674: It might be a problem of design; if ncovcol and the model are correct\n \
                   6675: run imach with mle=-1 to get a correct template of the parameter file.\n",numlinepar, i,j, i1, j1);
                   6676:          exit(1);
                   6677:        }
                   6678:        fprintf(ficparo,"%1d%1d",i1,j1);
                   6679:        if(mle==1)
1.193     brouard  6680:          printf("%1d%1d",i,jj);
                   6681:        fprintf(ficlog,"%1d%1d",i,jj);
1.126     brouard  6682:        for(k=1; k<=ncovmodel;k++){
                   6683:          fscanf(ficpar," %lf",&param[i][j][k]);
                   6684:          if(mle==1){
                   6685:            printf(" %lf",param[i][j][k]);
                   6686:            fprintf(ficlog," %lf",param[i][j][k]);
                   6687:          }
                   6688:          else
                   6689:            fprintf(ficlog," %lf",param[i][j][k]);
                   6690:          fprintf(ficparo," %lf",param[i][j][k]);
                   6691:        }
                   6692:        fscanf(ficpar,"\n");
                   6693:        numlinepar++;
                   6694:        if(mle==1)
                   6695:          printf("\n");
                   6696:        fprintf(ficlog,"\n");
                   6697:        fprintf(ficparo,"\n");
                   6698:       }
                   6699:     }  
                   6700:     fflush(ficlog);
                   6701: 
1.145     brouard  6702:     /* Reads scales values */
1.126     brouard  6703:     p=param[1][1];
                   6704:     
                   6705:     /* Reads comments: lines beginning with '#' */
                   6706:     while((c=getc(ficpar))=='#' && c!= EOF){
                   6707:       ungetc(c,ficpar);
                   6708:       fgets(line, MAXLINE, ficpar);
                   6709:       numlinepar++;
1.141     brouard  6710:       fputs(line,stdout);
1.126     brouard  6711:       fputs(line,ficparo);
                   6712:       fputs(line,ficlog);
                   6713:     }
                   6714:     ungetc(c,ficpar);
                   6715: 
                   6716:     for(i=1; i <=nlstate; i++){
                   6717:       for(j=1; j <=nlstate+ndeath-1; j++){
                   6718:        fscanf(ficpar,"%1d%1d",&i1,&j1);
1.164     brouard  6719:        if ( (i1-i) * (j1-j) != 0){
1.126     brouard  6720:          printf("Error in line parameters number %d, %1d%1d instead of %1d%1d \n",numlinepar, i,j, i1, j1);
                   6721:          exit(1);
                   6722:        }
                   6723:        printf("%1d%1d",i,j);
                   6724:        fprintf(ficparo,"%1d%1d",i1,j1);
                   6725:        fprintf(ficlog,"%1d%1d",i1,j1);
                   6726:        for(k=1; k<=ncovmodel;k++){
                   6727:          fscanf(ficpar,"%le",&delti3[i][j][k]);
                   6728:          printf(" %le",delti3[i][j][k]);
                   6729:          fprintf(ficparo," %le",delti3[i][j][k]);
                   6730:          fprintf(ficlog," %le",delti3[i][j][k]);
                   6731:        }
                   6732:        fscanf(ficpar,"\n");
                   6733:        numlinepar++;
                   6734:        printf("\n");
                   6735:        fprintf(ficparo,"\n");
                   6736:        fprintf(ficlog,"\n");
                   6737:       }
                   6738:     }
                   6739:     fflush(ficlog);
                   6740: 
1.145     brouard  6741:     /* Reads covariance matrix */
1.126     brouard  6742:     delti=delti3[1][1];
                   6743: 
                   6744: 
                   6745:     /* free_ma3x(delti3,1,nlstate,1,nlstate+ndeath-1,1,ncovmodel); */ /* Hasn't to to freed here otherwise delti is no more allocated */
                   6746:   
                   6747:     /* Reads comments: lines beginning with '#' */
                   6748:     while((c=getc(ficpar))=='#' && c!= EOF){
                   6749:       ungetc(c,ficpar);
                   6750:       fgets(line, MAXLINE, ficpar);
                   6751:       numlinepar++;
1.141     brouard  6752:       fputs(line,stdout);
1.126     brouard  6753:       fputs(line,ficparo);
                   6754:       fputs(line,ficlog);
                   6755:     }
                   6756:     ungetc(c,ficpar);
                   6757:   
                   6758:     matcov=matrix(1,npar,1,npar);
1.131     brouard  6759:     for(i=1; i <=npar; i++)
                   6760:       for(j=1; j <=npar; j++) matcov[i][j]=0.;
                   6761:       
1.194     brouard  6762:     /* Scans npar lines */
1.126     brouard  6763:     for(i=1; i <=npar; i++){
1.194     brouard  6764:       count=fscanf(ficpar,"%1d%1d%1d",&i1,&j1,&jk);
                   6765:       if(count != 3){
                   6766:        printf("Error! Error in parameter file %s at line %d after line starting with %1d%1d%1d\n\
                   6767: This is probably because your covariance matrix doesn't \n  contain exactly %d lines corresponding to your model line '1+age+%s'.\n\
                   6768: Please run with mle=-1 to get a correct covariance matrix.\n",optionfile,numlinepar, i1,j1,jk, npar, model);
                   6769:        fprintf(ficlog,"Error! Error in parameter file %s at line %d after line starting with %1d%1d%1d\n\
                   6770: This is probably because your covariance matrix doesn't \n  contain exactly %d lines corresponding to your model line '1+age+%s'.\n\
                   6771: Please run with mle=-1 to get a correct covariance matrix.\n",optionfile,numlinepar, i1,j1,jk, npar, model);
                   6772:        exit(1);
                   6773:       }else
1.126     brouard  6774:       if(mle==1)
1.194     brouard  6775:        printf("%1d%1d%1d",i1,j1,jk);
                   6776:       fprintf(ficlog,"%1d%1d%1d",i1,j1,jk);
                   6777:       fprintf(ficparo,"%1d%1d%1d",i1,j1,jk);
1.126     brouard  6778:       for(j=1; j <=i; j++){
                   6779:        fscanf(ficpar," %le",&matcov[i][j]);
                   6780:        if(mle==1){
                   6781:          printf(" %.5le",matcov[i][j]);
                   6782:        }
                   6783:        fprintf(ficlog," %.5le",matcov[i][j]);
                   6784:        fprintf(ficparo," %.5le",matcov[i][j]);
                   6785:       }
                   6786:       fscanf(ficpar,"\n");
                   6787:       numlinepar++;
                   6788:       if(mle==1)
                   6789:        printf("\n");
                   6790:       fprintf(ficlog,"\n");
                   6791:       fprintf(ficparo,"\n");
                   6792:     }
1.194     brouard  6793:     /* End of read covariance matrix npar lines */
1.126     brouard  6794:     for(i=1; i <=npar; i++)
                   6795:       for(j=i+1;j<=npar;j++)
                   6796:        matcov[i][j]=matcov[j][i];
                   6797:     
                   6798:     if(mle==1)
                   6799:       printf("\n");
                   6800:     fprintf(ficlog,"\n");
                   6801:     
                   6802:     fflush(ficlog);
                   6803:     
                   6804:     /*-------- Rewriting parameter file ----------*/
                   6805:     strcpy(rfileres,"r");    /* "Rparameterfile */
                   6806:     strcat(rfileres,optionfilefiname);    /* Parameter file first name*/
                   6807:     strcat(rfileres,".");    /* */
                   6808:     strcat(rfileres,optionfilext);    /* Other files have txt extension */
                   6809:     if((ficres =fopen(rfileres,"w"))==NULL) {
                   6810:       printf("Problem writing new parameter file: %s\n", fileres);goto end;
                   6811:       fprintf(ficlog,"Problem writing new parameter file: %s\n", fileres);goto end;
                   6812:     }
                   6813:     fprintf(ficres,"#%s\n",version);
                   6814:   }    /* End of mle != -3 */
                   6815: 
1.186     brouard  6816:   /*  Main data
                   6817:    */
1.126     brouard  6818:   n= lastobs;
                   6819:   num=lvector(1,n);
                   6820:   moisnais=vector(1,n);
                   6821:   annais=vector(1,n);
                   6822:   moisdc=vector(1,n);
                   6823:   andc=vector(1,n);
                   6824:   agedc=vector(1,n);
                   6825:   cod=ivector(1,n);
                   6826:   weight=vector(1,n);
                   6827:   for(i=1;i<=n;i++) weight[i]=1.0; /* Equal weights, 1 by default */
                   6828:   mint=matrix(1,maxwav,1,n);
                   6829:   anint=matrix(1,maxwav,1,n);
1.131     brouard  6830:   s=imatrix(1,maxwav+1,1,n); /* s[i][j] health state for wave i and individual j */ 
1.126     brouard  6831:   tab=ivector(1,NCOVMAX);
1.144     brouard  6832:   ncodemax=ivector(1,NCOVMAX); /* Number of code per covariate; if O and 1 only, 2**ncov; V1+V2+V3+V4=>16 */
1.192     brouard  6833:   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  6834: 
1.136     brouard  6835:   /* Reads data from file datafile */
                   6836:   if (readdata(datafile, firstobs, lastobs, &imx)==1)
                   6837:     goto end;
                   6838: 
                   6839:   /* Calculation of the number of parameters from char model */
1.137     brouard  6840:     /*    modelsav=V2+V1+V4+age*V3 strb=age*V3 stra=V2+V1+V4 
                   6841:        k=4 (age*V3) Tvar[k=4]= 3 (from V3) Tag[cptcovage=1]=4
                   6842:        k=3 V4 Tvar[k=3]= 4 (from V4)
                   6843:        k=2 V1 Tvar[k=2]= 1 (from V1)
                   6844:        k=1 Tvar[1]=2 (from V2)
                   6845:     */
                   6846:   Tvar=ivector(1,NCOVMAX); /* Was 15 changed to NCOVMAX. */
                   6847:   /*  V2+V1+V4+age*V3 is a model with 4 covariates (3 plus signs). 
                   6848:       For each model-covariate stores the data-covariate id. Tvar[1]=2, Tvar[2]=1, Tvar[3]=4, 
                   6849:       Tvar[4=age*V3] is 3 and 'age' is recorded in Tage.
                   6850:   */
                   6851:   /* For model-covariate k tells which data-covariate to use but
                   6852:     because this model-covariate is a construction we invent a new column
                   6853:     ncovcol + k1
                   6854:     If already ncovcol=4 and model=V2+V1+V1*V4+age*V3
                   6855:     Tvar[3=V1*V4]=4+1 etc */
1.145     brouard  6856:   Tprod=ivector(1,NCOVMAX); /* Gives the position of a product */
1.137     brouard  6857:   /* Tprod[k1=1]=3(=V1*V4) for V2+V1+V1*V4+age*V3
                   6858:      if  V2+V1+V1*V4+age*V3+V3*V2   TProd[k1=2]=5 (V3*V2)
                   6859:   */
1.145     brouard  6860:   Tvaraff=ivector(1,NCOVMAX); /* Unclear */
                   6861:   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  6862:                            * For V3*V2 (in V2+V1+V1*V4+age*V3+V3*V2), V3*V2 position is 2nd. 
                   6863:                            * Tvard[k1=2][1]=3 (V3) Tvard[k1=2][2]=2(V2) */
1.145     brouard  6864:   Tage=ivector(1,NCOVMAX); /* Gives the covariate id of covariates associated with age: V2 + V1 + age*V4 + V3*age
1.137     brouard  6865:                         4 covariates (3 plus signs)
                   6866:                         Tage[1=V3*age]= 4; Tage[2=age*V4] = 3
                   6867:                      */  
1.136     brouard  6868: 
1.186     brouard  6869: /* Main decodemodel */
                   6870: 
1.187     brouard  6871: 
1.136     brouard  6872:   if(decodemodel(model, lastobs) == 1)
                   6873:     goto end;
                   6874: 
1.137     brouard  6875:   if((double)(lastobs-imx)/(double)imx > 1.10){
                   6876:     nbwarn++;
                   6877:     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); 
                   6878:     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); 
                   6879:   }
1.136     brouard  6880:     /*  if(mle==1){*/
1.137     brouard  6881:   if (weightopt != 1) { /* Maximisation without weights. We can have weights different from 1 but want no weight*/
                   6882:     for(i=1;i<=imx;i++) weight[i]=1.0; /* changed to imx */
1.136     brouard  6883:   }
                   6884: 
                   6885:     /*-calculation of age at interview from date of interview and age at death -*/
                   6886:   agev=matrix(1,maxwav,1,imx);
                   6887: 
                   6888:   if(calandcheckages(imx, maxwav, &agemin, &agemax, &nberr, &nbwarn) == 1)
                   6889:     goto end;
                   6890: 
1.126     brouard  6891: 
1.136     brouard  6892:   agegomp=(int)agemin;
                   6893:   free_vector(moisnais,1,n);
                   6894:   free_vector(annais,1,n);
1.126     brouard  6895:   /* free_matrix(mint,1,maxwav,1,n);
                   6896:      free_matrix(anint,1,maxwav,1,n);*/
                   6897:   free_vector(moisdc,1,n);
                   6898:   free_vector(andc,1,n);
1.145     brouard  6899:   /* */
                   6900:   
1.126     brouard  6901:   wav=ivector(1,imx);
                   6902:   dh=imatrix(1,lastpass-firstpass+1,1,imx);
                   6903:   bh=imatrix(1,lastpass-firstpass+1,1,imx);
                   6904:   mw=imatrix(1,lastpass-firstpass+1,1,imx);
                   6905:    
                   6906:   /* Concatenates waves */
                   6907:   concatwav(wav, dh, bh, mw, s, agedc, agev,  firstpass, lastpass, imx, nlstate, stepm);
1.145     brouard  6908:   /* */
                   6909:  
1.126     brouard  6910:   /* Routine tricode is to calculate cptcoveff (real number of unique covariates) and to associate covariable number and modality */
                   6911: 
                   6912:   nbcode=imatrix(0,NCOVMAX,0,NCOVMAX); 
                   6913:   ncodemax[1]=1;
1.145     brouard  6914:   Ndum =ivector(-1,NCOVMAX);  
1.187     brouard  6915:   if (ncovmodel-nagesqr > 2 ) /* That is if covariate other than cst, age and age*age */
1.145     brouard  6916:     tricode(Tvar,nbcode,imx, Ndum); /**< Fills nbcode[Tvar[j]][l]; */
1.186     brouard  6917:   /* Nbcode gives the value of the lth modality of jth covariate, in
                   6918:      V2+V1*age, there are 3 covariates Tvar[2]=1 (V1).*/
                   6919:   /* 1 to ncodemax[j] is the maximum value of this jth covariate */
1.145     brouard  6920: 
                   6921:   codtab=imatrix(1,100,1,10); /* codtab[h,k]=( (h-1) - mod(k-1,2**(k-1) )/2**(k-1) */
1.198     brouard  6922:   /*printf(" codtab[1,1],codtab[100,10]=%d,%d\n", codtab[1][1],codtabm(100,10));*/
1.186     brouard  6923:   /* codtab gives the value 1 or 2 of the hth combination of k covariates (1 or 2).*/
1.145     brouard  6924:   h=0;
                   6925: 
                   6926: 
                   6927:   /*if (cptcovn > 0) */
1.126     brouard  6928:       
1.145     brouard  6929:  
1.126     brouard  6930:   m=pow(2,cptcoveff);
                   6931:  
1.144     brouard  6932:          /**< codtab(h,k)  k   = codtab[h,k]=( (h-1) - mod(k-1,2**(k-1) )/2**(k-1) + 1
1.186     brouard  6933:           * For k=4 covariates, h goes from 1 to 2**k
                   6934:           * codtabm(h,k)=  1 & (h-1) >> (k-1) ;
                   6935:           *     h\k   1     2     3     4
1.143     brouard  6936:           *______________________________  
                   6937:           *     1 i=1 1 i=1 1 i=1 1 i=1 1
                   6938:           *     2     2     1     1     1
                   6939:           *     3 i=2 1     2     1     1
                   6940:           *     4     2     2     1     1
                   6941:           *     5 i=3 1 i=2 1     2     1
                   6942:           *     6     2     1     2     1
                   6943:           *     7 i=4 1     2     2     1
                   6944:           *     8     2     2     2     1
1.197     brouard  6945:           *     9 i=5 1 i=3 1 i=2 1     2
                   6946:           *    10     2     1     1     2
                   6947:           *    11 i=6 1     2     1     2
                   6948:           *    12     2     2     1     2
                   6949:           *    13 i=7 1 i=4 1     2     2    
                   6950:           *    14     2     1     2     2
                   6951:           *    15 i=8 1     2     2     2
                   6952:           *    16     2     2     2     2
1.143     brouard  6953:           */
1.197     brouard  6954:   for(h=1; h <=100 ;h++){ 
                   6955:     /* printf("h=%2d ", h); */
                   6956:      for(k=1; k <=10; k++){
                   6957:        /* printf("k=%d %d ",k,codtabm(h,k)); */
                   6958:        codtab[h][k]=codtabm(h,k);
                   6959:      }
                   6960:      /* printf("\n"); */
                   6961:   }
                   6962:   /* for(k=1;k<=cptcoveff; k++){ /\* scans any effective covariate *\/ */
                   6963:   /*   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 *\/  */
                   6964:   /*     for(j=1; j <= ncodemax[k]; j++){ /\* For each modality of this covariate ncodemax=2*\/ */
                   6965:   /*   for(cpt=1; cpt <=pow(2,k-1); cpt++){  /\* cpt=1 to 8/2**(3+1-1 or 3+1-3) =1 or 4 *\/  */
                   6966:   /*     h++; */
                   6967:   /*     if (h>m)  */
                   6968:   /*       h=1; */
                   6969:   /*     codtab[h][k]=j; */
                   6970:   /*     /\* codtab[12][3]=1; *\/ */
                   6971:   /*     /\*codtab[h][Tvar[k]]=j;*\/ */
                   6972:   /*     /\* 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]]); *\/ */
                   6973:   /*   }  */
                   6974:   /*     } */
                   6975:   /*   } */
                   6976:   /* }  */
1.126     brouard  6977:   /* printf("codtab[1][2]=%d codtab[2][2]=%d",codtab[1][2],codtab[2][2]); 
                   6978:      codtab[1][2]=1;codtab[2][2]=2; */
1.197     brouard  6979:   /* for(i=1; i <=m ;i++){  */
                   6980:   /*    for(k=1; k <=cptcovn; k++){ */
                   6981:   /*      printf("i=%d k=%d %d %d ",i,k,codtab[i][k], cptcoveff); */
                   6982:   /*    } */
                   6983:   /*    printf("\n"); */
                   6984:   /* } */
                   6985:   /*   scanf("%d",i);*/
1.145     brouard  6986: 
                   6987:  free_ivector(Ndum,-1,NCOVMAX);
                   6988: 
                   6989: 
1.126     brouard  6990:     
1.186     brouard  6991:   /* Initialisation of ----------- gnuplot -------------*/
1.126     brouard  6992:   strcpy(optionfilegnuplot,optionfilefiname);
                   6993:   if(mle==-3)
                   6994:     strcat(optionfilegnuplot,"-mort");
                   6995:   strcat(optionfilegnuplot,".gp");
                   6996: 
                   6997:   if((ficgp=fopen(optionfilegnuplot,"w"))==NULL) {
                   6998:     printf("Problem with file %s",optionfilegnuplot);
                   6999:   }
                   7000:   else{
                   7001:     fprintf(ficgp,"\n# %s\n", version); 
                   7002:     fprintf(ficgp,"# %s\n", optionfilegnuplot); 
1.141     brouard  7003:     //fprintf(ficgp,"set missing 'NaNq'\n");
                   7004:     fprintf(ficgp,"set datafile missing 'NaNq'\n");
1.126     brouard  7005:   }
                   7006:   /*  fclose(ficgp);*/
1.186     brouard  7007: 
                   7008: 
                   7009:   /* Initialisation of --------- index.htm --------*/
1.126     brouard  7010: 
                   7011:   strcpy(optionfilehtm,optionfilefiname); /* Main html file */
                   7012:   if(mle==-3)
                   7013:     strcat(optionfilehtm,"-mort");
                   7014:   strcat(optionfilehtm,".htm");
                   7015:   if((fichtm=fopen(optionfilehtm,"w"))==NULL)    {
1.131     brouard  7016:     printf("Problem with %s \n",optionfilehtm);
                   7017:     exit(0);
1.126     brouard  7018:   }
                   7019: 
                   7020:   strcpy(optionfilehtmcov,optionfilefiname); /* Only for matrix of covariance */
                   7021:   strcat(optionfilehtmcov,"-cov.htm");
                   7022:   if((fichtmcov=fopen(optionfilehtmcov,"w"))==NULL)    {
                   7023:     printf("Problem with %s \n",optionfilehtmcov), exit(0);
                   7024:   }
                   7025:   else{
                   7026:   fprintf(fichtmcov,"<html><head>\n<title>IMaCh Cov %s</title></head>\n <body><font size=\"2\">%s <br> %s</font> \
                   7027: <hr size=\"2\" color=\"#EC5E5E\"> \n\
                   7028: Title=%s <br>Datafile=%s Firstpass=%d Lastpass=%d Stepm=%d Weight=%d Model=%s<br>\n",\
                   7029:          optionfilehtmcov,version,fullversion,title,datafile,firstpass,lastpass,stepm, weightopt, model);
                   7030:   }
                   7031: 
                   7032:   fprintf(fichtm,"<html><head>\n<title>IMaCh %s</title></head>\n <body><font size=\"2\">%s <br> %s</font> \
                   7033: <hr size=\"2\" color=\"#EC5E5E\"> \n\
                   7034: Title=%s <br>Datafile=%s Firstpass=%d Lastpass=%d Stepm=%d Weight=%d Model=%s<br>\n\
                   7035: \n\
                   7036: <hr  size=\"2\" color=\"#EC5E5E\">\
                   7037:  <ul><li><h4>Parameter files</h4>\n\
                   7038:  - Parameter file: <a href=\"%s.%s\">%s.%s</a><br>\n\
                   7039:  - Copy of the parameter file: <a href=\"o%s\">o%s</a><br>\n\
                   7040:  - Log file of the run: <a href=\"%s\">%s</a><br>\n\
                   7041:  - Gnuplot file name: <a href=\"%s\">%s</a><br>\n\
                   7042:  - Date and time at start: %s</ul>\n",\
                   7043:          optionfilehtm,version,fullversion,title,datafile,firstpass,lastpass,stepm, weightopt, model,\
                   7044:          optionfilefiname,optionfilext,optionfilefiname,optionfilext,\
                   7045:          fileres,fileres,\
                   7046:          filelog,filelog,optionfilegnuplot,optionfilegnuplot,strstart);
                   7047:   fflush(fichtm);
                   7048: 
                   7049:   strcpy(pathr,path);
                   7050:   strcat(pathr,optionfilefiname);
1.184     brouard  7051: #ifdef WIN32
                   7052:   _chdir(optionfilefiname); /* Move to directory named optionfile */
                   7053: #else
1.126     brouard  7054:   chdir(optionfilefiname); /* Move to directory named optionfile */
1.184     brouard  7055: #endif
                   7056:          
1.126     brouard  7057:   
                   7058:   /* Calculates basic frequencies. Computes observed prevalence at single age
                   7059:      and prints on file fileres'p'. */
                   7060:   freqsummary(fileres, agemin, agemax, s, agev, nlstate, imx,Tvaraff,nbcode, ncodemax,mint,anint,strstart);
                   7061: 
                   7062:   fprintf(fichtm,"\n");
                   7063:   fprintf(fichtm,"<br>Total number of observations=%d <br>\n\
                   7064: Youngest age at first (selected) pass %.2f, oldest age %.2f<br>\n\
                   7065: Interval (in months) between two waves: Min=%d Max=%d Mean=%.2lf<br>\n",\
                   7066:          imx,agemin,agemax,jmin,jmax,jmean);
                   7067:   pmmij= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
                   7068:     oldms= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
                   7069:     newms= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
                   7070:     savms= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
                   7071:     oldm=oldms; newm=newms; savm=savms; /* Keeps fixed addresses to free */
                   7072:     
                   7073:    
                   7074:   /* For Powell, parameters are in a vector p[] starting at p[1]
                   7075:      so we point p on param[1][1] so that p[1] maps on param[1][1][1] */
                   7076:   p=param[1][1]; /* *(*(*(param +1)+1)+0) */
                   7077: 
                   7078:   globpr=0; /* To get the number ipmx of contributions and the sum of weights*/
1.186     brouard  7079:   /* For mortality only */
1.126     brouard  7080:   if (mle==-3){
1.136     brouard  7081:     ximort=matrix(1,NDIM,1,NDIM); 
1.186     brouard  7082:     /*     ximort=gsl_matrix_alloc(1,NDIM,1,NDIM); */
1.126     brouard  7083:     cens=ivector(1,n);
                   7084:     ageexmed=vector(1,n);
                   7085:     agecens=vector(1,n);
                   7086:     dcwave=ivector(1,n);
                   7087:  
                   7088:     for (i=1; i<=imx; i++){
                   7089:       dcwave[i]=-1;
                   7090:       for (m=firstpass; m<=lastpass; m++)
                   7091:        if (s[m][i]>nlstate) {
                   7092:          dcwave[i]=m;
                   7093:          /*    printf("i=%d j=%d s=%d dcwave=%d\n",i,j, s[j][i],dcwave[i]);*/
                   7094:          break;
                   7095:        }
                   7096:     }
                   7097: 
                   7098:     for (i=1; i<=imx; i++) {
                   7099:       if (wav[i]>0){
                   7100:        ageexmed[i]=agev[mw[1][i]][i];
                   7101:        j=wav[i];
                   7102:        agecens[i]=1.; 
                   7103: 
                   7104:        if (ageexmed[i]> 1 && wav[i] > 0){
                   7105:          agecens[i]=agev[mw[j][i]][i];
                   7106:          cens[i]= 1;
                   7107:        }else if (ageexmed[i]< 1) 
                   7108:          cens[i]= -1;
                   7109:        if (agedc[i]< AGESUP && agedc[i]>1 && dcwave[i]>firstpass && dcwave[i]<=lastpass)
                   7110:          cens[i]=0 ;
                   7111:       }
                   7112:       else cens[i]=-1;
                   7113:     }
                   7114:     
                   7115:     for (i=1;i<=NDIM;i++) {
                   7116:       for (j=1;j<=NDIM;j++)
                   7117:        ximort[i][j]=(i == j ? 1.0 : 0.0);
                   7118:     }
                   7119:     
1.145     brouard  7120:     /*p[1]=0.0268; p[NDIM]=0.083;*/
1.126     brouard  7121:     /*printf("%lf %lf", p[1], p[2]);*/
                   7122:     
                   7123:     
1.136     brouard  7124: #ifdef GSL
                   7125:     printf("GSL optimization\n");  fprintf(ficlog,"Powell\n");
1.162     brouard  7126: #else
1.126     brouard  7127:     printf("Powell\n");  fprintf(ficlog,"Powell\n");
1.136     brouard  7128: #endif
1.126     brouard  7129:     strcpy(filerespow,"pow-mort"); 
                   7130:     strcat(filerespow,fileres);
                   7131:     if((ficrespow=fopen(filerespow,"w"))==NULL) {
                   7132:       printf("Problem with resultfile: %s\n", filerespow);
                   7133:       fprintf(ficlog,"Problem with resultfile: %s\n", filerespow);
                   7134:     }
1.136     brouard  7135: #ifdef GSL
                   7136:     fprintf(ficrespow,"# GSL optimization\n# iter -2*LL");
1.162     brouard  7137: #else
1.126     brouard  7138:     fprintf(ficrespow,"# Powell\n# iter -2*LL");
1.136     brouard  7139: #endif
1.126     brouard  7140:     /*  for (i=1;i<=nlstate;i++)
                   7141:        for(j=1;j<=nlstate+ndeath;j++)
                   7142:        if(j!=i)fprintf(ficrespow," p%1d%1d",i,j);
                   7143:     */
                   7144:     fprintf(ficrespow,"\n");
1.136     brouard  7145: #ifdef GSL
                   7146:     /* gsl starts here */ 
                   7147:     T = gsl_multimin_fminimizer_nmsimplex;
                   7148:     gsl_multimin_fminimizer *sfm = NULL;
                   7149:     gsl_vector *ss, *x;
                   7150:     gsl_multimin_function minex_func;
                   7151: 
                   7152:     /* Initial vertex size vector */
                   7153:     ss = gsl_vector_alloc (NDIM);
                   7154:     
                   7155:     if (ss == NULL){
                   7156:       GSL_ERROR_VAL ("failed to allocate space for ss", GSL_ENOMEM, 0);
                   7157:     }
                   7158:     /* Set all step sizes to 1 */
                   7159:     gsl_vector_set_all (ss, 0.001);
                   7160: 
                   7161:     /* Starting point */
1.126     brouard  7162:     
1.136     brouard  7163:     x = gsl_vector_alloc (NDIM);
                   7164:     
                   7165:     if (x == NULL){
                   7166:       gsl_vector_free(ss);
                   7167:       GSL_ERROR_VAL ("failed to allocate space for x", GSL_ENOMEM, 0);
                   7168:     }
                   7169:   
                   7170:     /* Initialize method and iterate */
                   7171:     /*     p[1]=0.0268; p[NDIM]=0.083; */
1.186     brouard  7172:     /*     gsl_vector_set(x, 0, 0.0268); */
                   7173:     /*     gsl_vector_set(x, 1, 0.083); */
1.136     brouard  7174:     gsl_vector_set(x, 0, p[1]);
                   7175:     gsl_vector_set(x, 1, p[2]);
                   7176: 
                   7177:     minex_func.f = &gompertz_f;
                   7178:     minex_func.n = NDIM;
                   7179:     minex_func.params = (void *)&p; /* ??? */
                   7180:     
                   7181:     sfm = gsl_multimin_fminimizer_alloc (T, NDIM);
                   7182:     gsl_multimin_fminimizer_set (sfm, &minex_func, x, ss);
                   7183:     
                   7184:     printf("Iterations beginning .....\n\n");
                   7185:     printf("Iter. #    Intercept       Slope     -Log Likelihood     Simplex size\n");
                   7186: 
                   7187:     iteri=0;
                   7188:     while (rval == GSL_CONTINUE){
                   7189:       iteri++;
                   7190:       status = gsl_multimin_fminimizer_iterate(sfm);
                   7191:       
                   7192:       if (status) printf("error: %s\n", gsl_strerror (status));
                   7193:       fflush(0);
                   7194:       
                   7195:       if (status) 
                   7196:         break;
                   7197:       
                   7198:       rval = gsl_multimin_test_size (gsl_multimin_fminimizer_size (sfm), 1e-6);
                   7199:       ssval = gsl_multimin_fminimizer_size (sfm);
                   7200:       
                   7201:       if (rval == GSL_SUCCESS)
                   7202:         printf ("converged to a local maximum at\n");
                   7203:       
                   7204:       printf("%5d ", iteri);
                   7205:       for (it = 0; it < NDIM; it++){
                   7206:        printf ("%10.5f ", gsl_vector_get (sfm->x, it));
                   7207:       }
                   7208:       printf("f() = %-10.5f ssize = %.7f\n", sfm->fval, ssval);
                   7209:     }
                   7210:     
                   7211:     printf("\n\n Please note: Program should be run many times with varying starting points to detemine global maximum\n\n");
                   7212:     
                   7213:     gsl_vector_free(x); /* initial values */
                   7214:     gsl_vector_free(ss); /* inital step size */
                   7215:     for (it=0; it<NDIM; it++){
                   7216:       p[it+1]=gsl_vector_get(sfm->x,it);
                   7217:       fprintf(ficrespow," %.12lf", p[it]);
                   7218:     }
                   7219:     gsl_multimin_fminimizer_free (sfm); /* p *(sfm.x.data) et p *(sfm.x.data+1)  */
                   7220: #endif
                   7221: #ifdef POWELL
                   7222:      powell(p,ximort,NDIM,ftol,&iter,&fret,gompertz);
                   7223: #endif  
1.126     brouard  7224:     fclose(ficrespow);
                   7225:     
                   7226:     hesscov(matcov, p, NDIM, delti, 1e-4, gompertz); 
                   7227: 
                   7228:     for(i=1; i <=NDIM; i++)
                   7229:       for(j=i+1;j<=NDIM;j++)
                   7230:        matcov[i][j]=matcov[j][i];
                   7231:     
                   7232:     printf("\nCovariance matrix\n ");
                   7233:     for(i=1; i <=NDIM; i++) {
                   7234:       for(j=1;j<=NDIM;j++){ 
                   7235:        printf("%f ",matcov[i][j]);
                   7236:       }
                   7237:       printf("\n ");
                   7238:     }
                   7239:     
                   7240:     printf("iter=%d MLE=%f Eq=%lf*exp(%lf*(age-%d))\n",iter,-gompertz(p),p[1],p[2],agegomp);
1.193     brouard  7241:     for (i=1;i<=NDIM;i++) {
1.126     brouard  7242:       printf("%f [%f ; %f]\n",p[i],p[i]-2*sqrt(matcov[i][i]),p[i]+2*sqrt(matcov[i][i]));
1.193     brouard  7243:       fprintf(ficlog,"%f [%f ; %f]\n",p[i],p[i]-2*sqrt(matcov[i][i]),p[i]+2*sqrt(matcov[i][i]));
                   7244:     }
1.126     brouard  7245:     lsurv=vector(1,AGESUP);
                   7246:     lpop=vector(1,AGESUP);
                   7247:     tpop=vector(1,AGESUP);
                   7248:     lsurv[agegomp]=100000;
                   7249:     
                   7250:     for (k=agegomp;k<=AGESUP;k++) {
                   7251:       agemortsup=k;
                   7252:       if (p[1]*exp(p[2]*(k-agegomp))>1) break;
                   7253:     }
                   7254:     
                   7255:     for (k=agegomp;k<agemortsup;k++)
                   7256:       lsurv[k+1]=lsurv[k]-lsurv[k]*(p[1]*exp(p[2]*(k-agegomp)));
                   7257:     
                   7258:     for (k=agegomp;k<agemortsup;k++){
                   7259:       lpop[k]=(lsurv[k]+lsurv[k+1])/2.;
                   7260:       sumlpop=sumlpop+lpop[k];
                   7261:     }
                   7262:     
                   7263:     tpop[agegomp]=sumlpop;
                   7264:     for (k=agegomp;k<(agemortsup-3);k++){
                   7265:       /*  tpop[k+1]=2;*/
                   7266:       tpop[k+1]=tpop[k]-lpop[k];
                   7267:     }
                   7268:     
                   7269:     
                   7270:     printf("\nAge   lx     qx    dx    Lx     Tx     e(x)\n");
                   7271:     for (k=agegomp;k<(agemortsup-2);k++) 
                   7272:       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]);
                   7273:     
                   7274:     
                   7275:     replace_back_to_slash(pathc,pathcd); /* Even gnuplot wants a / */
1.194     brouard  7276:     if(ageminpar == AGEOVERFLOW ||agemaxpar == AGEOVERFLOW){
                   7277:        printf("Warning! Error in gnuplot file with ageminpar %f or agemaxpar %f overflow\n\
                   7278: This is probably because your parameter file doesn't \n  contain the exact number of lines (or columns) corresponding to your model line.\n\
                   7279: Please run with mle=-1 to get a correct covariance matrix.\n",ageminpar,agemaxpar);
                   7280:        fprintf(ficlog,"Warning! Error in gnuplot file with ageminpar %f or agemaxpar %f overflow\n\
                   7281: This is probably because your parameter file doesn't \n  contain the exact number of lines (or columns) corresponding to your model line.\n\
                   7282: Please run with mle=-1 to get a correct covariance matrix.\n",ageminpar,agemaxpar);
                   7283:     }else
                   7284:       printinggnuplotmort(fileres, optionfilefiname,ageminpar,agemaxpar,fage, pathc,p);
1.126     brouard  7285:     printinghtmlmort(fileres,title,datafile, firstpass, lastpass, \
                   7286:                     stepm, weightopt,\
                   7287:                     model,imx,p,matcov,agemortsup);
                   7288:     
                   7289:     free_vector(lsurv,1,AGESUP);
                   7290:     free_vector(lpop,1,AGESUP);
                   7291:     free_vector(tpop,1,AGESUP);
1.136     brouard  7292: #ifdef GSL
                   7293:     free_ivector(cens,1,n);
                   7294:     free_vector(agecens,1,n);
                   7295:     free_ivector(dcwave,1,n);
                   7296:     free_matrix(ximort,1,NDIM,1,NDIM);
                   7297: #endif
1.186     brouard  7298:   } /* Endof if mle==-3 mortality only */
                   7299:   /* Standard maximisation */
1.126     brouard  7300:   else{ /* For mle >=1 */
1.132     brouard  7301:     globpr=0;/* debug */
1.186     brouard  7302:     /* Computes likelihood for initial parameters */
1.132     brouard  7303:     likelione(ficres, p, npar, nlstate, &globpr, &ipmx, &sw, &fretone, funcone); /* Prints the contributions to the likelihood */
1.126     brouard  7304:     printf("First Likeli=%12.6f ipmx=%ld sw=%12.6f",fretone,ipmx,sw);
                   7305:     for (k=1; k<=npar;k++)
                   7306:       printf(" %d %8.5f",k,p[k]);
                   7307:     printf("\n");
1.186     brouard  7308:     globpr=1; /* again, to print the contributions */
1.126     brouard  7309:     likelione(ficres, p, npar, nlstate, &globpr, &ipmx, &sw, &fretone, funcone); /* Prints the contributions to the likelihood */
                   7310:     printf("Second Likeli=%12.6f ipmx=%ld sw=%12.6f",fretone,ipmx,sw);
                   7311:     for (k=1; k<=npar;k++)
                   7312:       printf(" %d %8.5f",k,p[k]);
                   7313:     printf("\n");
1.186     brouard  7314:     if(mle>=1){ /* Could be 1 or 2, Real Maximisation */
1.126     brouard  7315:       mlikeli(ficres,p, npar, ncovmodel, nlstate, ftol, func);
                   7316:     }
                   7317:     
                   7318:     /*--------- results files --------------*/
1.192     brouard  7319:     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  7320:     
                   7321:     
                   7322:     fprintf(ficres,"# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
                   7323:     printf("# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
                   7324:     fprintf(ficlog,"# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
                   7325:     for(i=1,jk=1; i <=nlstate; i++){
                   7326:       for(k=1; k <=(nlstate+ndeath); k++){
                   7327:        if (k != i) {
                   7328:          printf("%d%d ",i,k);
                   7329:          fprintf(ficlog,"%d%d ",i,k);
                   7330:          fprintf(ficres,"%1d%1d ",i,k);
                   7331:          for(j=1; j <=ncovmodel; j++){
1.190     brouard  7332:            printf("%12.7f ",p[jk]);
                   7333:            fprintf(ficlog,"%12.7f ",p[jk]);
                   7334:            fprintf(ficres,"%12.7f ",p[jk]);
1.126     brouard  7335:            jk++; 
                   7336:          }
                   7337:          printf("\n");
                   7338:          fprintf(ficlog,"\n");
                   7339:          fprintf(ficres,"\n");
                   7340:        }
                   7341:       }
                   7342:     }
                   7343:     if(mle!=0){
                   7344:       /* Computing hessian and covariance matrix */
                   7345:       ftolhess=ftol; /* Usually correct */
                   7346:       hesscov(matcov, p, npar, delti, ftolhess, func);
                   7347:     }
1.197     brouard  7348:     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");
                   7349:     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  7350:     for(i=1,jk=1; i <=nlstate; i++){
                   7351:       for(k=1; k <=(nlstate+ndeath); k++){
                   7352:        if (k != i) {
                   7353:          printf("%d%d ",i,k);
                   7354:          fprintf(ficlog,"%d%d ",i,k);
                   7355:          for(j=1; j <=ncovmodel; j++){
1.197     brouard  7356:            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]));
                   7357:            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  7358:            jk++; 
                   7359:          }
                   7360:          printf("\n");
                   7361:          fprintf(ficlog,"\n");
                   7362:        }
                   7363:       }
                   7364:     }
                   7365: 
1.126     brouard  7366:     fprintf(ficres,"# Scales (for hessian or gradient estimation)\n");
                   7367:     printf("# Scales (for hessian or gradient estimation)\n");
                   7368:     fprintf(ficlog,"# Scales (for hessian or gradient estimation)\n");
                   7369:     for(i=1,jk=1; i <=nlstate; i++){
                   7370:       for(j=1; j <=nlstate+ndeath; j++){
                   7371:        if (j!=i) {
                   7372:          fprintf(ficres,"%1d%1d",i,j);
                   7373:          printf("%1d%1d",i,j);
                   7374:          fprintf(ficlog,"%1d%1d",i,j);
                   7375:          for(k=1; k<=ncovmodel;k++){
                   7376:            printf(" %.5e",delti[jk]);
                   7377:            fprintf(ficlog," %.5e",delti[jk]);
                   7378:            fprintf(ficres," %.5e",delti[jk]);
                   7379:            jk++;
                   7380:          }
                   7381:          printf("\n");
                   7382:          fprintf(ficlog,"\n");
                   7383:          fprintf(ficres,"\n");
                   7384:        }
                   7385:       }
                   7386:     }
                   7387:     
                   7388:     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");
                   7389:     if(mle>=1)
                   7390:       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");
                   7391:     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");
                   7392:     /* # 121 Var(a12)\n\ */
                   7393:     /* # 122 Cov(b12,a12) Var(b12)\n\ */
                   7394:     /* # 131 Cov(a13,a12) Cov(a13,b12, Var(a13)\n\ */
                   7395:     /* # 132 Cov(b13,a12) Cov(b13,b12, Cov(b13,a13) Var(b13)\n\ */
                   7396:     /* # 212 Cov(a21,a12) Cov(a21,b12, Cov(a21,a13) Cov(a21,b13) Var(a21)\n\ */
                   7397:     /* # 212 Cov(b21,a12) Cov(b21,b12, Cov(b21,a13) Cov(b21,b13) Cov(b21,a21) Var(b21)\n\ */
                   7398:     /* # 232 Cov(a23,a12) Cov(a23,b12, Cov(a23,a13) Cov(a23,b13) Cov(a23,a21) Cov(a23,b21) Var(a23)\n\ */
                   7399:     /* # 232 Cov(b23,a12) Cov(b23,b12) ... Var (b23)\n" */
                   7400:     
                   7401:     
                   7402:     /* Just to have a covariance matrix which will be more understandable
                   7403:        even is we still don't want to manage dictionary of variables
                   7404:     */
                   7405:     for(itimes=1;itimes<=2;itimes++){
                   7406:       jj=0;
                   7407:       for(i=1; i <=nlstate; i++){
                   7408:        for(j=1; j <=nlstate+ndeath; j++){
                   7409:          if(j==i) continue;
                   7410:          for(k=1; k<=ncovmodel;k++){
                   7411:            jj++;
                   7412:            ca[0]= k+'a'-1;ca[1]='\0';
                   7413:            if(itimes==1){
                   7414:              if(mle>=1)
                   7415:                printf("#%1d%1d%d",i,j,k);
                   7416:              fprintf(ficlog,"#%1d%1d%d",i,j,k);
                   7417:              fprintf(ficres,"#%1d%1d%d",i,j,k);
                   7418:            }else{
                   7419:              if(mle>=1)
                   7420:                printf("%1d%1d%d",i,j,k);
                   7421:              fprintf(ficlog,"%1d%1d%d",i,j,k);
                   7422:              fprintf(ficres,"%1d%1d%d",i,j,k);
                   7423:            }
                   7424:            ll=0;
                   7425:            for(li=1;li <=nlstate; li++){
                   7426:              for(lj=1;lj <=nlstate+ndeath; lj++){
                   7427:                if(lj==li) continue;
                   7428:                for(lk=1;lk<=ncovmodel;lk++){
                   7429:                  ll++;
                   7430:                  if(ll<=jj){
                   7431:                    cb[0]= lk +'a'-1;cb[1]='\0';
                   7432:                    if(ll<jj){
                   7433:                      if(itimes==1){
                   7434:                        if(mle>=1)
                   7435:                          printf(" Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
                   7436:                        fprintf(ficlog," Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
                   7437:                        fprintf(ficres," Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
                   7438:                      }else{
                   7439:                        if(mle>=1)
                   7440:                          printf(" %.5e",matcov[jj][ll]); 
                   7441:                        fprintf(ficlog," %.5e",matcov[jj][ll]); 
                   7442:                        fprintf(ficres," %.5e",matcov[jj][ll]); 
                   7443:                      }
                   7444:                    }else{
                   7445:                      if(itimes==1){
                   7446:                        if(mle>=1)
                   7447:                          printf(" Var(%s%1d%1d)",ca,i,j);
                   7448:                        fprintf(ficlog," Var(%s%1d%1d)",ca,i,j);
                   7449:                        fprintf(ficres," Var(%s%1d%1d)",ca,i,j);
                   7450:                      }else{
                   7451:                        if(mle>=1)
                   7452:                          printf(" %.5e",matcov[jj][ll]); 
                   7453:                        fprintf(ficlog," %.5e",matcov[jj][ll]); 
                   7454:                        fprintf(ficres," %.5e",matcov[jj][ll]); 
                   7455:                      }
                   7456:                    }
                   7457:                  }
                   7458:                } /* end lk */
                   7459:              } /* end lj */
                   7460:            } /* end li */
                   7461:            if(mle>=1)
                   7462:              printf("\n");
                   7463:            fprintf(ficlog,"\n");
                   7464:            fprintf(ficres,"\n");
                   7465:            numlinepar++;
                   7466:          } /* end k*/
                   7467:        } /*end j */
                   7468:       } /* end i */
                   7469:     } /* end itimes */
                   7470:     
                   7471:     fflush(ficlog);
                   7472:     fflush(ficres);
                   7473:     
                   7474:     while((c=getc(ficpar))=='#' && c!= EOF){
                   7475:       ungetc(c,ficpar);
                   7476:       fgets(line, MAXLINE, ficpar);
1.141     brouard  7477:       fputs(line,stdout);
1.126     brouard  7478:       fputs(line,ficparo);
                   7479:     }
                   7480:     ungetc(c,ficpar);
                   7481:     
                   7482:     estepm=0;
                   7483:     fscanf(ficpar,"agemin=%lf agemax=%lf bage=%lf fage=%lf estepm=%d\n",&ageminpar,&agemaxpar, &bage, &fage, &estepm);
                   7484:     if (estepm==0 || estepm < stepm) estepm=stepm;
                   7485:     if (fage <= 2) {
                   7486:       bage = ageminpar;
                   7487:       fage = agemaxpar;
                   7488:     }
                   7489:     
                   7490:     fprintf(ficres,"# agemin agemax for life expectancy, bage fage (if mle==0 ie no data nor Max likelihood).\n");
                   7491:     fprintf(ficres,"agemin=%.0f agemax=%.0f bage=%.0f fage=%.0f estepm=%d\n",ageminpar,agemaxpar,bage,fage, estepm);
                   7492:     fprintf(ficparo,"agemin=%.0f agemax=%.0f bage=%.0f fage=%.0f estepm=%d\n",ageminpar,agemaxpar,bage,fage, estepm);
1.186     brouard  7493: 
                   7494:     /* Other stuffs, more or less useful */    
1.126     brouard  7495:     while((c=getc(ficpar))=='#' && c!= EOF){
                   7496:       ungetc(c,ficpar);
                   7497:       fgets(line, MAXLINE, ficpar);
1.141     brouard  7498:       fputs(line,stdout);
1.126     brouard  7499:       fputs(line,ficparo);
                   7500:     }
                   7501:     ungetc(c,ficpar);
                   7502:     
                   7503:     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);
                   7504:     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);
                   7505:     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);
                   7506:     printf("begin-prev-date=%.lf/%.lf/%.lf end-prev-date=%.lf/%.lf/%.lf mov_average=%d\n",jprev1, mprev1,anprev1,jprev2, mprev2,anprev2,mobilav);
                   7507:     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);
                   7508:     
                   7509:     while((c=getc(ficpar))=='#' && c!= EOF){
                   7510:       ungetc(c,ficpar);
                   7511:       fgets(line, MAXLINE, ficpar);
1.141     brouard  7512:       fputs(line,stdout);
1.126     brouard  7513:       fputs(line,ficparo);
                   7514:     }
                   7515:     ungetc(c,ficpar);
                   7516:     
                   7517:     
                   7518:     dateprev1=anprev1+(mprev1-1)/12.+(jprev1-1)/365.;
                   7519:     dateprev2=anprev2+(mprev2-1)/12.+(jprev2-1)/365.;
                   7520:     
                   7521:     fscanf(ficpar,"pop_based=%d\n",&popbased);
1.193     brouard  7522:     fprintf(ficlog,"pop_based=%d\n",popbased);
1.126     brouard  7523:     fprintf(ficparo,"pop_based=%d\n",popbased);   
                   7524:     fprintf(ficres,"pop_based=%d\n",popbased);   
                   7525:     
                   7526:     while((c=getc(ficpar))=='#' && c!= EOF){
                   7527:       ungetc(c,ficpar);
                   7528:       fgets(line, MAXLINE, ficpar);
1.141     brouard  7529:       fputs(line,stdout);
1.126     brouard  7530:       fputs(line,ficparo);
                   7531:     }
                   7532:     ungetc(c,ficpar);
                   7533:     
                   7534:     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);
                   7535:     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);
                   7536:     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);
                   7537:     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);
                   7538:     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);
                   7539:     /* day and month of proj2 are not used but only year anproj2.*/
                   7540:     
                   7541:     
                   7542:     
1.145     brouard  7543:      /* freqsummary(fileres, agemin, agemax, s, agev, nlstate, imx,Tvaraff,nbcode, ncodemax,mint,anint); */
                   7544:     /* ,dateprev1,dateprev2,jprev1, mprev1,anprev1,jprev2, mprev2,anprev2); */
1.126     brouard  7545:     
                   7546:     replace_back_to_slash(pathc,pathcd); /* Even gnuplot wants a / */
1.194     brouard  7547:     if(ageminpar == AGEOVERFLOW ||agemaxpar == -AGEOVERFLOW){
                   7548:        printf("Warning! Error in gnuplot file with ageminpar %f or agemaxpar %f overflow\n\
                   7549: This is probably because your parameter file doesn't \n  contain the exact number of lines (or columns) corresponding to your model line.\n\
                   7550: Please run with mle=-1 to get a correct covariance matrix.\n",ageminpar,agemaxpar);
                   7551:        fprintf(ficlog,"Warning! Error in gnuplot file with ageminpar %f or agemaxpar %f overflow\n\
                   7552: This is probably because your parameter file doesn't \n  contain the exact number of lines (or columns) corresponding to your model line.\n\
                   7553: Please run with mle=-1 to get a correct covariance matrix.\n",ageminpar,agemaxpar);
                   7554:     }else
                   7555:       printinggnuplot(fileres, optionfilefiname,ageminpar,agemaxpar,fage, pathc,p);
1.126     brouard  7556:     
                   7557:     printinghtml(fileres,title,datafile, firstpass, lastpass, stepm, weightopt,\
                   7558:                 model,imx,jmin,jmax,jmean,rfileres,popforecast,estepm,\
                   7559:                 jprev1,mprev1,anprev1,jprev2,mprev2,anprev2);
                   7560:       
                   7561:    /*------------ free_vector  -------------*/
                   7562:    /*  chdir(path); */
                   7563:  
                   7564:     free_ivector(wav,1,imx);
                   7565:     free_imatrix(dh,1,lastpass-firstpass+1,1,imx);
                   7566:     free_imatrix(bh,1,lastpass-firstpass+1,1,imx);
                   7567:     free_imatrix(mw,1,lastpass-firstpass+1,1,imx);   
                   7568:     free_lvector(num,1,n);
                   7569:     free_vector(agedc,1,n);
                   7570:     /*free_matrix(covar,0,NCOVMAX,1,n);*/
                   7571:     /*free_matrix(covar,1,NCOVMAX,1,n);*/
                   7572:     fclose(ficparo);
                   7573:     fclose(ficres);
                   7574: 
                   7575: 
1.186     brouard  7576:     /* Other results (useful)*/
                   7577: 
                   7578: 
1.126     brouard  7579:     /*--------------- Prevalence limit  (period or stable prevalence) --------------*/
1.180     brouard  7580:     /*#include "prevlim.h"*/  /* Use ficrespl, ficlog */
                   7581:     prlim=matrix(1,nlstate,1,nlstate);
                   7582:     prevalence_limit(p, prlim,  ageminpar, agemaxpar);
1.126     brouard  7583:     fclose(ficrespl);
                   7584: 
1.145     brouard  7585: #ifdef FREEEXIT2
                   7586: #include "freeexit2.h"
                   7587: #endif
                   7588: 
1.126     brouard  7589:     /*------------- h Pij x at various ages ------------*/
1.180     brouard  7590:     /*#include "hpijx.h"*/
                   7591:     hPijx(p, bage, fage);
1.145     brouard  7592:     fclose(ficrespij);
1.126     brouard  7593: 
1.145     brouard  7594:   /*-------------- Variance of one-step probabilities---*/
                   7595:     k=1;
1.126     brouard  7596:     varprob(optionfilefiname, matcov, p, delti, nlstate, bage, fage,k,Tvar,nbcode, ncodemax,strstart);
                   7597: 
                   7598: 
                   7599:     probs= ma3x(1,AGESUP,1,NCOVMAX, 1,NCOVMAX);
                   7600:     for(i=1;i<=AGESUP;i++)
                   7601:       for(j=1;j<=NCOVMAX;j++)
                   7602:        for(k=1;k<=NCOVMAX;k++)
                   7603:          probs[i][j][k]=0.;
                   7604: 
                   7605:     /*---------- Forecasting ------------------*/
                   7606:     /*if((stepm == 1) && (strcmp(model,".")==0)){*/
                   7607:     if(prevfcast==1){
                   7608:       /*    if(stepm ==1){*/
                   7609:       prevforecast(fileres, anproj1, mproj1, jproj1, agemin, agemax, dateprev1, dateprev2, mobilavproj, bage, fage, firstpass, lastpass, anproj2, p, cptcoveff);
                   7610:       /* (popforecast==1) populforecast(fileres, anpyram,mpyram,jpyram, agemin,agemax, dateprev1, dateprev2,mobilav, agedeb, fage, popforecast, popfile, anpyram1,p, i1);*/
                   7611:       /*      }  */
                   7612:       /*      else{ */
                   7613:       /*        erreur=108; */
                   7614:       /*        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); */
                   7615:       /*        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); */
                   7616:       /*      } */
                   7617:     }
1.186     brouard  7618:  
                   7619:     /* ------ Other prevalence ratios------------ */
1.126     brouard  7620: 
1.127     brouard  7621:     /* Computes prevalence between agemin (i.e minimal age computed) and no more ageminpar */
                   7622: 
                   7623:     prevalence(probs, agemin, agemax, s, agev, nlstate, imx, Tvar, nbcode, ncodemax, mint, anint, dateprev1, dateprev2, firstpass, lastpass);
                   7624:     /*  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",\
                   7625:        ageminpar, agemax, s[lastpass][imx], agev[lastpass][imx], nlstate, imx, mint[lastpass][imx],anint[lastpass][imx], dateprev1, dateprev2, firstpass, lastpass);
                   7626:     */
1.126     brouard  7627: 
1.127     brouard  7628:     if (mobilav!=0) {
                   7629:       mobaverage= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
                   7630:       if (movingaverage(probs, bage, fage, mobaverage,mobilav)!=0){
                   7631:        fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav);
                   7632:        printf(" Error in movingaverage mobilav=%d\n",mobilav);
                   7633:       }
1.126     brouard  7634:     }
                   7635: 
                   7636: 
1.127     brouard  7637:     /*---------- Health expectancies, no variances ------------*/
                   7638: 
1.126     brouard  7639:     strcpy(filerese,"e");
                   7640:     strcat(filerese,fileres);
                   7641:     if((ficreseij=fopen(filerese,"w"))==NULL) {
                   7642:       printf("Problem with Health Exp. resultfile: %s\n", filerese); exit(0);
                   7643:       fprintf(ficlog,"Problem with Health Exp. resultfile: %s\n", filerese); exit(0);
                   7644:     }
                   7645:     printf("Computing Health Expectancies: result on file '%s' \n", filerese);
                   7646:     fprintf(ficlog,"Computing Health Expectancies: result on file '%s' \n", filerese);
1.145     brouard  7647:     /*for(cptcov=1,k=0;cptcov<=i1;cptcov++){
                   7648:       for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){*/
                   7649:           
                   7650:     for (k=1; k <= (int) pow(2,cptcoveff); k++){
1.127     brouard  7651:        fprintf(ficreseij,"\n#****** ");
                   7652:        for(j=1;j<=cptcoveff;j++) {
                   7653:          fprintf(ficreseij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
                   7654:        }
                   7655:        fprintf(ficreseij,"******\n");
                   7656: 
                   7657:        eij=ma3x(1,nlstate,1,nlstate,(int) bage, (int) fage);
                   7658:        oldm=oldms;savm=savms;
                   7659:        evsij(eij, p, nlstate, stepm, (int) bage, (int)fage, oldm, savm, k, estepm, strstart);  
                   7660:       
                   7661:        free_ma3x(eij,1,nlstate,1,nlstate,(int) bage, (int)fage);
1.145     brouard  7662:       /*}*/
1.127     brouard  7663:     }
                   7664:     fclose(ficreseij);
                   7665: 
                   7666: 
                   7667:     /*---------- Health expectancies and variances ------------*/
                   7668: 
                   7669: 
                   7670:     strcpy(filerest,"t");
                   7671:     strcat(filerest,fileres);
                   7672:     if((ficrest=fopen(filerest,"w"))==NULL) {
                   7673:       printf("Problem with total LE resultfile: %s\n", filerest);goto end;
                   7674:       fprintf(ficlog,"Problem with total LE resultfile: %s\n", filerest);goto end;
                   7675:     }
                   7676:     printf("Computing Total Life expectancies with their standard errors: file '%s' \n", filerest); 
                   7677:     fprintf(ficlog,"Computing Total Life expectancies with their standard errors: file '%s' \n", filerest); 
                   7678: 
1.126     brouard  7679: 
                   7680:     strcpy(fileresstde,"stde");
                   7681:     strcat(fileresstde,fileres);
                   7682:     if((ficresstdeij=fopen(fileresstde,"w"))==NULL) {
                   7683:       printf("Problem with Health Exp. and std errors resultfile: %s\n", fileresstde); exit(0);
                   7684:       fprintf(ficlog,"Problem with Health Exp. and std errors resultfile: %s\n", fileresstde); exit(0);
                   7685:     }
                   7686:     printf("Computing Health Expectancies and standard errors: result on file '%s' \n", fileresstde);
                   7687:     fprintf(ficlog,"Computing Health Expectancies and standard errors: result on file '%s' \n", fileresstde);
                   7688: 
                   7689:     strcpy(filerescve,"cve");
                   7690:     strcat(filerescve,fileres);
                   7691:     if((ficrescveij=fopen(filerescve,"w"))==NULL) {
                   7692:       printf("Problem with Covar. Health Exp. resultfile: %s\n", filerescve); exit(0);
                   7693:       fprintf(ficlog,"Problem with Covar. Health Exp. resultfile: %s\n", filerescve); exit(0);
                   7694:     }
                   7695:     printf("Computing Covar. of Health Expectancies: result on file '%s' \n", filerescve);
                   7696:     fprintf(ficlog,"Computing Covar. of Health Expectancies: result on file '%s' \n", filerescve);
                   7697: 
                   7698:     strcpy(fileresv,"v");
                   7699:     strcat(fileresv,fileres);
                   7700:     if((ficresvij=fopen(fileresv,"w"))==NULL) {
                   7701:       printf("Problem with variance resultfile: %s\n", fileresv);exit(0);
                   7702:       fprintf(ficlog,"Problem with variance resultfile: %s\n", fileresv);exit(0);
                   7703:     }
                   7704:     printf("Computing Variance-covariance of DFLEs: file '%s' \n", fileresv);
                   7705:     fprintf(ficlog,"Computing Variance-covariance of DFLEs: file '%s' \n", fileresv);
                   7706: 
1.145     brouard  7707:     /*for(cptcov=1,k=0;cptcov<=i1;cptcov++){
                   7708:       for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){*/
                   7709:           
                   7710:     for (k=1; k <= (int) pow(2,cptcoveff); k++){
                   7711:        fprintf(ficrest,"\n#****** ");
1.126     brouard  7712:        for(j=1;j<=cptcoveff;j++) 
                   7713:          fprintf(ficrest,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
                   7714:        fprintf(ficrest,"******\n");
                   7715: 
                   7716:        fprintf(ficresstdeij,"\n#****** ");
                   7717:        fprintf(ficrescveij,"\n#****** ");
                   7718:        for(j=1;j<=cptcoveff;j++) {
                   7719:          fprintf(ficresstdeij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
                   7720:          fprintf(ficrescveij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
                   7721:        }
                   7722:        fprintf(ficresstdeij,"******\n");
                   7723:        fprintf(ficrescveij,"******\n");
                   7724: 
                   7725:        fprintf(ficresvij,"\n#****** ");
                   7726:        for(j=1;j<=cptcoveff;j++) 
                   7727:          fprintf(ficresvij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
                   7728:        fprintf(ficresvij,"******\n");
                   7729: 
                   7730:        eij=ma3x(1,nlstate,1,nlstate,(int) bage, (int) fage);
                   7731:        oldm=oldms;savm=savms;
1.127     brouard  7732:        cvevsij(eij, p, nlstate, stepm, (int) bage, (int)fage, oldm, savm, k, estepm, delti, matcov, strstart);  
1.145     brouard  7733:        /*
                   7734:         */
                   7735:        /* goto endfree; */
1.126     brouard  7736:  
                   7737:        vareij=ma3x(1,nlstate,1,nlstate,(int) bage, (int) fage);
                   7738:        pstamp(ficrest);
1.145     brouard  7739: 
                   7740: 
1.128     brouard  7741:        for(vpopbased=0; vpopbased <= popbased; vpopbased++){ /* Done for vpopbased=0 and vpopbased=1 if popbased==1*/
1.199   ! brouard  7742:          oldm=oldms;savm=savms; /* ZZ Segmentation fault */
1.161     brouard  7743:          cptcod= 0; /* To be deleted */
                   7744:          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  7745:          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  7746:          if(vpopbased==1)
                   7747:            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);
                   7748:          else
                   7749:            fprintf(ficrest,"the age specific period (stable) prevalences in each health state \n");
                   7750:          fprintf(ficrest,"# Age e.. (std) ");
                   7751:          for (i=1;i<=nlstate;i++) fprintf(ficrest,"e.%d (std) ",i);
                   7752:          fprintf(ficrest,"\n");
1.199   ! brouard  7753:          /* printf("Which p?\n"); for(i=1;i<=npar;i++)printf("p[i=%d]=%lf,",i,p[i]);printf("\n"); */
1.128     brouard  7754:          epj=vector(1,nlstate+1);
                   7755:          for(age=bage; age <=fage ;age++){
1.199   ! brouard  7756:            prevalim(prlim, nlstate, p, age, oldm, savm,ftolpl,k); /*ZZ Is it the correct prevalim */
1.128     brouard  7757:            if (vpopbased==1) {
                   7758:              if(mobilav ==0){
                   7759:                for(i=1; i<=nlstate;i++)
                   7760:                  prlim[i][i]=probs[(int)age][i][k];
                   7761:              }else{ /* mobilav */ 
                   7762:                for(i=1; i<=nlstate;i++)
                   7763:                  prlim[i][i]=mobaverage[(int)age][i][k];
                   7764:              }
1.126     brouard  7765:            }
                   7766:        
1.128     brouard  7767:            fprintf(ficrest," %4.0f",age);
1.199   ! brouard  7768:            /* printf(" age %4.0f ",age); */
1.128     brouard  7769:            for(j=1, epj[nlstate+1]=0.;j <=nlstate;j++){
                   7770:              for(i=1, epj[j]=0.;i <=nlstate;i++) {
                   7771:                epj[j] += prlim[i][i]*eij[i][j][(int)age];
1.199   ! brouard  7772:                /*ZZZ  printf("%lf %lf ", prlim[i][i] ,eij[i][j][(int)age]);*/
        !          7773:                /* printf("%lf %lf ", prlim[i][i] ,eij[i][j][(int)age]); */
1.128     brouard  7774:              }
                   7775:              epj[nlstate+1] +=epj[j];
1.126     brouard  7776:            }
1.199   ! brouard  7777:            /* printf(" age %4.0f \n",age); */
1.126     brouard  7778: 
1.128     brouard  7779:            for(i=1, vepp=0.;i <=nlstate;i++)
                   7780:              for(j=1;j <=nlstate;j++)
                   7781:                vepp += vareij[i][j][(int)age];
                   7782:            fprintf(ficrest," %7.3f (%7.3f)", epj[nlstate+1],sqrt(vepp));
                   7783:            for(j=1;j <=nlstate;j++){
                   7784:              fprintf(ficrest," %7.3f (%7.3f)", epj[j],sqrt(vareij[j][j][(int)age]));
                   7785:            }
                   7786:            fprintf(ficrest,"\n");
1.126     brouard  7787:          }
                   7788:        }
                   7789:        free_ma3x(eij,1,nlstate,1,nlstate,(int) bage, (int)fage);
                   7790:        free_ma3x(vareij,1,nlstate,1,nlstate,(int) bage, (int)fage);
                   7791:        free_vector(epj,1,nlstate+1);
1.145     brouard  7792:       /*}*/
1.126     brouard  7793:     }
                   7794:     free_vector(weight,1,n);
1.145     brouard  7795:     free_imatrix(Tvard,1,NCOVMAX,1,2);
1.126     brouard  7796:     free_imatrix(s,1,maxwav+1,1,n);
                   7797:     free_matrix(anint,1,maxwav,1,n); 
                   7798:     free_matrix(mint,1,maxwav,1,n);
                   7799:     free_ivector(cod,1,n);
                   7800:     free_ivector(tab,1,NCOVMAX);
                   7801:     fclose(ficresstdeij);
                   7802:     fclose(ficrescveij);
                   7803:     fclose(ficresvij);
                   7804:     fclose(ficrest);
                   7805:     fclose(ficpar);
                   7806:   
                   7807:     /*------- Variance of period (stable) prevalence------*/   
                   7808: 
                   7809:     strcpy(fileresvpl,"vpl");
                   7810:     strcat(fileresvpl,fileres);
                   7811:     if((ficresvpl=fopen(fileresvpl,"w"))==NULL) {
                   7812:       printf("Problem with variance of period (stable) prevalence  resultfile: %s\n", fileresvpl);
                   7813:       exit(0);
                   7814:     }
                   7815:     printf("Computing Variance-covariance of period (stable) prevalence: file '%s' \n", fileresvpl);
                   7816: 
1.145     brouard  7817:     /*for(cptcov=1,k=0;cptcov<=i1;cptcov++){
                   7818:       for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){*/
                   7819:           
                   7820:     for (k=1; k <= (int) pow(2,cptcoveff); k++){
                   7821:        fprintf(ficresvpl,"\n#****** ");
1.126     brouard  7822:        for(j=1;j<=cptcoveff;j++) 
                   7823:          fprintf(ficresvpl,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
                   7824:        fprintf(ficresvpl,"******\n");
                   7825:       
                   7826:        varpl=matrix(1,nlstate,(int) bage, (int) fage);
                   7827:        oldm=oldms;savm=savms;
                   7828:        varprevlim(fileres, varpl, matcov, p, delti, nlstate, stepm, (int) bage, (int) fage, oldm, savm, prlim, ftolpl,k,strstart);
                   7829:        free_matrix(varpl,1,nlstate,(int) bage, (int)fage);
1.145     brouard  7830:       /*}*/
1.126     brouard  7831:     }
                   7832: 
                   7833:     fclose(ficresvpl);
                   7834: 
                   7835:     /*---------- End : free ----------------*/
                   7836:     if (mobilav!=0) free_ma3x(mobaverage,1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
                   7837:     free_ma3x(probs,1,AGESUP,1,NCOVMAX, 1,NCOVMAX);
                   7838:   }  /* mle==-3 arrives here for freeing */
1.164     brouard  7839:  /* endfree:*/
1.141     brouard  7840:     free_matrix(prlim,1,nlstate,1,nlstate); /*here or after loop ? */
1.126     brouard  7841:     free_matrix(pmmij,1,nlstate+ndeath,1,nlstate+ndeath);
                   7842:     free_matrix(oldms, 1,nlstate+ndeath,1,nlstate+ndeath);
                   7843:     free_matrix(newms, 1,nlstate+ndeath,1,nlstate+ndeath);
                   7844:     free_matrix(savms, 1,nlstate+ndeath,1,nlstate+ndeath);
                   7845:     free_matrix(covar,0,NCOVMAX,1,n);
                   7846:     free_matrix(matcov,1,npar,1,npar);
                   7847:     /*free_vector(delti,1,npar);*/
                   7848:     free_ma3x(delti3,1,nlstate,1, nlstate+ndeath-1,1,ncovmodel); 
                   7849:     free_matrix(agev,1,maxwav,1,imx);
                   7850:     free_ma3x(param,1,nlstate,1, nlstate+ndeath-1,1,ncovmodel);
                   7851: 
1.145     brouard  7852:     free_ivector(ncodemax,1,NCOVMAX);
1.192     brouard  7853:     free_ivector(ncodemaxwundef,1,NCOVMAX);
1.145     brouard  7854:     free_ivector(Tvar,1,NCOVMAX);
                   7855:     free_ivector(Tprod,1,NCOVMAX);
                   7856:     free_ivector(Tvaraff,1,NCOVMAX);
                   7857:     free_ivector(Tage,1,NCOVMAX);
1.126     brouard  7858: 
                   7859:     free_imatrix(nbcode,0,NCOVMAX,0,NCOVMAX);
                   7860:     free_imatrix(codtab,1,100,1,10);
                   7861:   fflush(fichtm);
                   7862:   fflush(ficgp);
                   7863:   
                   7864: 
                   7865:   if((nberr >0) || (nbwarn>0)){
                   7866:     printf("End of Imach with %d errors and/or %d warnings\n",nberr,nbwarn);
                   7867:     fprintf(ficlog,"End of Imach with %d errors and/or warnings %d\n",nberr,nbwarn);
                   7868:   }else{
                   7869:     printf("End of Imach\n");
                   7870:     fprintf(ficlog,"End of Imach\n");
                   7871:   }
                   7872:   printf("See log file on %s\n",filelog);
                   7873:   /*  gettimeofday(&end_time, (struct timezone*)0);*/  /* after time */
1.157     brouard  7874:   /*(void) gettimeofday(&end_time,&tzp);*/
                   7875:   rend_time = time(NULL);  
                   7876:   end_time = *localtime(&rend_time);
                   7877:   /* tml = *localtime(&end_time.tm_sec); */
                   7878:   strcpy(strtend,asctime(&end_time));
1.126     brouard  7879:   printf("Local time at start %s\nLocal time at end   %s",strstart, strtend); 
                   7880:   fprintf(ficlog,"Local time at start %s\nLocal time at end   %s\n",strstart, strtend); 
1.157     brouard  7881:   printf("Total time used %s\n", asc_diff_time(rend_time -rstart_time,tmpout));
1.126     brouard  7882: 
1.157     brouard  7883:   printf("Total time was %.0lf Sec.\n", difftime(rend_time,rstart_time));
                   7884:   fprintf(ficlog,"Total time used %s\n", asc_diff_time(rend_time -rstart_time,tmpout));
                   7885:   fprintf(ficlog,"Total time was %.0lf Sec.\n", difftime(rend_time,rstart_time));
1.126     brouard  7886:   /*  printf("Total time was %d uSec.\n", total_usecs);*/
                   7887: /*   if(fileappend(fichtm,optionfilehtm)){ */
                   7888:   fprintf(fichtm,"<br>Local time at start %s<br>Local time at end   %s<br>\n</body></html>",strstart, strtend);
                   7889:   fclose(fichtm);
                   7890:   fprintf(fichtmcov,"<br>Local time at start %s<br>Local time at end   %s<br>\n</body></html>",strstart, strtend);
                   7891:   fclose(fichtmcov);
                   7892:   fclose(ficgp);
                   7893:   fclose(ficlog);
                   7894:   /*------ End -----------*/
                   7895: 
                   7896: 
                   7897:    printf("Before Current directory %s!\n",pathcd);
1.184     brouard  7898: #ifdef WIN32
                   7899:    if (_chdir(pathcd) != 0)
                   7900:           printf("Can't move to directory %s!\n",path);
                   7901:    if(_getcwd(pathcd,MAXLINE) > 0)
                   7902: #else
1.126     brouard  7903:    if(chdir(pathcd) != 0)
1.184     brouard  7904:           printf("Can't move to directory %s!\n", path);
                   7905:    if (getcwd(pathcd, MAXLINE) > 0)
                   7906: #endif 
1.126     brouard  7907:     printf("Current directory %s!\n",pathcd);
                   7908:   /*strcat(plotcmd,CHARSEPARATOR);*/
                   7909:   sprintf(plotcmd,"gnuplot");
1.157     brouard  7910: #ifdef _WIN32
1.126     brouard  7911:   sprintf(plotcmd,"\"%sgnuplot.exe\"",pathimach);
                   7912: #endif
                   7913:   if(!stat(plotcmd,&info)){
1.158     brouard  7914:     printf("Error or gnuplot program not found: '%s'\n",plotcmd);fflush(stdout);
1.126     brouard  7915:     if(!stat(getenv("GNUPLOTBIN"),&info)){
1.158     brouard  7916:       printf("Error or gnuplot program not found: '%s' Environment GNUPLOTBIN not set.\n",plotcmd);fflush(stdout);
1.126     brouard  7917:     }else
                   7918:       strcpy(pplotcmd,plotcmd);
1.157     brouard  7919: #ifdef __unix
1.126     brouard  7920:     strcpy(plotcmd,GNUPLOTPROGRAM);
                   7921:     if(!stat(plotcmd,&info)){
1.158     brouard  7922:       printf("Error gnuplot program not found: '%s'\n",plotcmd);fflush(stdout);
1.126     brouard  7923:     }else
                   7924:       strcpy(pplotcmd,plotcmd);
                   7925: #endif
                   7926:   }else
                   7927:     strcpy(pplotcmd,plotcmd);
                   7928:   
                   7929:   sprintf(plotcmd,"%s %s",pplotcmd, optionfilegnuplot);
1.158     brouard  7930:   printf("Starting graphs with: '%s'\n",plotcmd);fflush(stdout);
1.126     brouard  7931: 
                   7932:   if((outcmd=system(plotcmd)) != 0){
1.158     brouard  7933:     printf("gnuplot command might not be in your path: '%s', err=%d\n", plotcmd, outcmd);
1.154     brouard  7934:     printf("\n Trying if gnuplot resides on the same directory that IMaCh\n");
1.152     brouard  7935:     sprintf(plotcmd,"%sgnuplot %s", pathimach, optionfilegnuplot);
1.150     brouard  7936:     if((outcmd=system(plotcmd)) != 0)
1.153     brouard  7937:       printf("\n Still a problem with gnuplot command %s, err=%d\n", plotcmd, outcmd);
1.126     brouard  7938:   }
1.158     brouard  7939:   printf(" Successful, please wait...");
1.126     brouard  7940:   while (z[0] != 'q') {
                   7941:     /* chdir(path); */
1.154     brouard  7942:     printf("\nType e to edit results with your browser, g to graph again and q for exit: ");
1.126     brouard  7943:     scanf("%s",z);
                   7944: /*     if (z[0] == 'c') system("./imach"); */
                   7945:     if (z[0] == 'e') {
1.158     brouard  7946: #ifdef __APPLE__
1.152     brouard  7947:       sprintf(pplotcmd, "open %s", optionfilehtm);
1.157     brouard  7948: #elif __linux
                   7949:       sprintf(pplotcmd, "xdg-open %s", optionfilehtm);
1.153     brouard  7950: #else
1.152     brouard  7951:       sprintf(pplotcmd, "%s", optionfilehtm);
1.153     brouard  7952: #endif
                   7953:       printf("Starting browser with: %s",pplotcmd);fflush(stdout);
                   7954:       system(pplotcmd);
1.126     brouard  7955:     }
                   7956:     else if (z[0] == 'g') system(plotcmd);
                   7957:     else if (z[0] == 'q') exit(0);
                   7958:   }
                   7959:   end:
                   7960:   while (z[0] != 'q') {
1.195     brouard  7961:     printf("\nType  q for exiting: "); fflush(stdout);
1.126     brouard  7962:     scanf("%s",z);
                   7963:   }
                   7964: }

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