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

1.209   ! brouard     1: /* $Id: imach.c,v 1.208 2015/11/17 14:31:57 brouard Exp $
1.126     brouard     2:   $State: Exp $
1.163     brouard     3:   $Log: imach.c,v $
1.209   ! brouard     4:   Revision 1.208  2015/11/17 14:31:57  brouard
        !             5:   Summary: temporary
        !             6: 
1.208     brouard     7:   Revision 1.207  2015/10/27 17:36:57  brouard
                      8:   *** empty log message ***
                      9: 
1.207     brouard    10:   Revision 1.206  2015/10/24 07:14:11  brouard
                     11:   *** empty log message ***
                     12: 
1.206     brouard    13:   Revision 1.205  2015/10/23 15:50:53  brouard
                     14:   Summary: 0.98r3 some clarification for graphs on likelihood contributions
                     15: 
1.205     brouard    16:   Revision 1.204  2015/10/01 16:20:26  brouard
                     17:   Summary: Some new graphs of contribution to likelihood
                     18: 
1.204     brouard    19:   Revision 1.203  2015/09/30 17:45:14  brouard
                     20:   Summary: looking at better estimation of the hessian
                     21: 
                     22:   Also a better criteria for convergence to the period prevalence And
                     23:   therefore adding the number of years needed to converge. (The
                     24:   prevalence in any alive state shold sum to one
                     25: 
1.203     brouard    26:   Revision 1.202  2015/09/22 19:45:16  brouard
                     27:   Summary: Adding some overall graph on contribution to likelihood. Might change
                     28: 
1.202     brouard    29:   Revision 1.201  2015/09/15 17:34:58  brouard
                     30:   Summary: 0.98r0
                     31: 
                     32:   - Some new graphs like suvival functions
                     33:   - Some bugs fixed like model=1+age+V2.
                     34: 
1.201     brouard    35:   Revision 1.200  2015/09/09 16:53:55  brouard
                     36:   Summary: Big bug thanks to Flavia
                     37: 
                     38:   Even model=1+age+V2. did not work anymore
                     39: 
1.200     brouard    40:   Revision 1.199  2015/09/07 14:09:23  brouard
                     41:   Summary: 0.98q6 changing default small png format for graph to vectorized svg.
                     42: 
1.199     brouard    43:   Revision 1.198  2015/09/03 07:14:39  brouard
                     44:   Summary: 0.98q5 Flavia
                     45: 
1.198     brouard    46:   Revision 1.197  2015/09/01 18:24:39  brouard
                     47:   *** empty log message ***
                     48: 
1.197     brouard    49:   Revision 1.196  2015/08/18 23:17:52  brouard
                     50:   Summary: 0.98q5
                     51: 
1.196     brouard    52:   Revision 1.195  2015/08/18 16:28:39  brouard
                     53:   Summary: Adding a hack for testing purpose
                     54: 
                     55:   After reading the title, ftol and model lines, if the comment line has
                     56:   a q, starting with #q, the answer at the end of the run is quit. It
                     57:   permits to run test files in batch with ctest. The former workaround was
                     58:   $ echo q | imach foo.imach
                     59: 
1.195     brouard    60:   Revision 1.194  2015/08/18 13:32:00  brouard
                     61:   Summary:  Adding error when the covariance matrix doesn't contain the exact number of lines required by the model line.
                     62: 
1.194     brouard    63:   Revision 1.193  2015/08/04 07:17:42  brouard
                     64:   Summary: 0.98q4
                     65: 
1.193     brouard    66:   Revision 1.192  2015/07/16 16:49:02  brouard
                     67:   Summary: Fixing some outputs
                     68: 
1.192     brouard    69:   Revision 1.191  2015/07/14 10:00:33  brouard
                     70:   Summary: Some fixes
                     71: 
1.191     brouard    72:   Revision 1.190  2015/05/05 08:51:13  brouard
                     73:   Summary: Adding digits in output parameters (7 digits instead of 6)
                     74: 
                     75:   Fix 1+age+.
                     76: 
1.190     brouard    77:   Revision 1.189  2015/04/30 14:45:16  brouard
                     78:   Summary: 0.98q2
                     79: 
1.189     brouard    80:   Revision 1.188  2015/04/30 08:27:53  brouard
                     81:   *** empty log message ***
                     82: 
1.188     brouard    83:   Revision 1.187  2015/04/29 09:11:15  brouard
                     84:   *** empty log message ***
                     85: 
1.187     brouard    86:   Revision 1.186  2015/04/23 12:01:52  brouard
                     87:   Summary: V1*age is working now, version 0.98q1
                     88: 
                     89:   Some codes had been disabled in order to simplify and Vn*age was
                     90:   working in the optimization phase, ie, giving correct MLE parameters,
                     91:   but, as usual, outputs were not correct and program core dumped.
                     92: 
1.186     brouard    93:   Revision 1.185  2015/03/11 13:26:42  brouard
                     94:   Summary: Inclusion of compile and links command line for Intel Compiler
                     95: 
1.185     brouard    96:   Revision 1.184  2015/03/11 11:52:39  brouard
                     97:   Summary: Back from Windows 8. Intel Compiler
                     98: 
1.184     brouard    99:   Revision 1.183  2015/03/10 20:34:32  brouard
                    100:   Summary: 0.98q0, trying with directest, mnbrak fixed
                    101: 
                    102:   We use directest instead of original Powell test; probably no
                    103:   incidence on the results, but better justifications;
                    104:   We fixed Numerical Recipes mnbrak routine which was wrong and gave
                    105:   wrong results.
                    106: 
1.183     brouard   107:   Revision 1.182  2015/02/12 08:19:57  brouard
                    108:   Summary: Trying to keep directest which seems simpler and more general
                    109:   Author: Nicolas Brouard
                    110: 
1.182     brouard   111:   Revision 1.181  2015/02/11 23:22:24  brouard
                    112:   Summary: Comments on Powell added
                    113: 
                    114:   Author:
                    115: 
1.181     brouard   116:   Revision 1.180  2015/02/11 17:33:45  brouard
                    117:   Summary: Finishing move from main to function (hpijx and prevalence_limit)
                    118: 
1.180     brouard   119:   Revision 1.179  2015/01/04 09:57:06  brouard
                    120:   Summary: back to OS/X
                    121: 
1.179     brouard   122:   Revision 1.178  2015/01/04 09:35:48  brouard
                    123:   *** empty log message ***
                    124: 
1.178     brouard   125:   Revision 1.177  2015/01/03 18:40:56  brouard
                    126:   Summary: Still testing ilc32 on OSX
                    127: 
1.177     brouard   128:   Revision 1.176  2015/01/03 16:45:04  brouard
                    129:   *** empty log message ***
                    130: 
1.176     brouard   131:   Revision 1.175  2015/01/03 16:33:42  brouard
                    132:   *** empty log message ***
                    133: 
1.175     brouard   134:   Revision 1.174  2015/01/03 16:15:49  brouard
                    135:   Summary: Still in cross-compilation
                    136: 
1.174     brouard   137:   Revision 1.173  2015/01/03 12:06:26  brouard
                    138:   Summary: trying to detect cross-compilation
                    139: 
1.173     brouard   140:   Revision 1.172  2014/12/27 12:07:47  brouard
                    141:   Summary: Back from Visual Studio and Intel, options for compiling for Windows XP
                    142: 
1.172     brouard   143:   Revision 1.171  2014/12/23 13:26:59  brouard
                    144:   Summary: Back from Visual C
                    145: 
                    146:   Still problem with utsname.h on Windows
                    147: 
1.171     brouard   148:   Revision 1.170  2014/12/23 11:17:12  brouard
                    149:   Summary: Cleaning some \%% back to %%
                    150: 
                    151:   The escape was mandatory for a specific compiler (which one?), but too many warnings.
                    152: 
1.170     brouard   153:   Revision 1.169  2014/12/22 23:08:31  brouard
                    154:   Summary: 0.98p
                    155: 
                    156:   Outputs some informations on compiler used, OS etc. Testing on different platforms.
                    157: 
1.169     brouard   158:   Revision 1.168  2014/12/22 15:17:42  brouard
1.170     brouard   159:   Summary: update
1.169     brouard   160: 
1.168     brouard   161:   Revision 1.167  2014/12/22 13:50:56  brouard
                    162:   Summary: Testing uname and compiler version and if compiled 32 or 64
                    163: 
                    164:   Testing on Linux 64
                    165: 
1.167     brouard   166:   Revision 1.166  2014/12/22 11:40:47  brouard
                    167:   *** empty log message ***
                    168: 
1.166     brouard   169:   Revision 1.165  2014/12/16 11:20:36  brouard
                    170:   Summary: After compiling on Visual C
                    171: 
                    172:   * imach.c (Module): Merging 1.61 to 1.162
                    173: 
1.165     brouard   174:   Revision 1.164  2014/12/16 10:52:11  brouard
                    175:   Summary: Merging with Visual C after suppressing some warnings for unused variables. Also fixing Saito's bug 0.98Xn
                    176: 
                    177:   * imach.c (Module): Merging 1.61 to 1.162
                    178: 
1.164     brouard   179:   Revision 1.163  2014/12/16 10:30:11  brouard
                    180:   * imach.c (Module): Merging 1.61 to 1.162
                    181: 
1.163     brouard   182:   Revision 1.162  2014/09/25 11:43:39  brouard
                    183:   Summary: temporary backup 0.99!
                    184: 
1.162     brouard   185:   Revision 1.1  2014/09/16 11:06:58  brouard
                    186:   Summary: With some code (wrong) for nlopt
                    187: 
                    188:   Author:
                    189: 
                    190:   Revision 1.161  2014/09/15 20:41:41  brouard
                    191:   Summary: Problem with macro SQR on Intel compiler
                    192: 
1.161     brouard   193:   Revision 1.160  2014/09/02 09:24:05  brouard
                    194:   *** empty log message ***
                    195: 
1.160     brouard   196:   Revision 1.159  2014/09/01 10:34:10  brouard
                    197:   Summary: WIN32
                    198:   Author: Brouard
                    199: 
1.159     brouard   200:   Revision 1.158  2014/08/27 17:11:51  brouard
                    201:   *** empty log message ***
                    202: 
1.158     brouard   203:   Revision 1.157  2014/08/27 16:26:55  brouard
                    204:   Summary: Preparing windows Visual studio version
                    205:   Author: Brouard
                    206: 
                    207:   In order to compile on Visual studio, time.h is now correct and time_t
                    208:   and tm struct should be used. difftime should be used but sometimes I
                    209:   just make the differences in raw time format (time(&now).
                    210:   Trying to suppress #ifdef LINUX
                    211:   Add xdg-open for __linux in order to open default browser.
                    212: 
1.157     brouard   213:   Revision 1.156  2014/08/25 20:10:10  brouard
                    214:   *** empty log message ***
                    215: 
1.156     brouard   216:   Revision 1.155  2014/08/25 18:32:34  brouard
                    217:   Summary: New compile, minor changes
                    218:   Author: Brouard
                    219: 
1.155     brouard   220:   Revision 1.154  2014/06/20 17:32:08  brouard
                    221:   Summary: Outputs now all graphs of convergence to period prevalence
                    222: 
1.154     brouard   223:   Revision 1.153  2014/06/20 16:45:46  brouard
                    224:   Summary: If 3 live state, convergence to period prevalence on same graph
                    225:   Author: Brouard
                    226: 
1.153     brouard   227:   Revision 1.152  2014/06/18 17:54:09  brouard
                    228:   Summary: open browser, use gnuplot on same dir than imach if not found in the path
                    229: 
1.152     brouard   230:   Revision 1.151  2014/06/18 16:43:30  brouard
                    231:   *** empty log message ***
                    232: 
1.151     brouard   233:   Revision 1.150  2014/06/18 16:42:35  brouard
                    234:   Summary: If gnuplot is not in the path try on same directory than imach binary (OSX)
                    235:   Author: brouard
                    236: 
1.150     brouard   237:   Revision 1.149  2014/06/18 15:51:14  brouard
                    238:   Summary: Some fixes in parameter files errors
                    239:   Author: Nicolas Brouard
                    240: 
1.149     brouard   241:   Revision 1.148  2014/06/17 17:38:48  brouard
                    242:   Summary: Nothing new
                    243:   Author: Brouard
                    244: 
                    245:   Just a new packaging for OS/X version 0.98nS
                    246: 
1.148     brouard   247:   Revision 1.147  2014/06/16 10:33:11  brouard
                    248:   *** empty log message ***
                    249: 
1.147     brouard   250:   Revision 1.146  2014/06/16 10:20:28  brouard
                    251:   Summary: Merge
                    252:   Author: Brouard
                    253: 
                    254:   Merge, before building revised version.
                    255: 
1.146     brouard   256:   Revision 1.145  2014/06/10 21:23:15  brouard
                    257:   Summary: Debugging with valgrind
                    258:   Author: Nicolas Brouard
                    259: 
                    260:   Lot of changes in order to output the results with some covariates
                    261:   After the Edimburgh REVES conference 2014, it seems mandatory to
                    262:   improve the code.
                    263:   No more memory valgrind error but a lot has to be done in order to
                    264:   continue the work of splitting the code into subroutines.
                    265:   Also, decodemodel has been improved. Tricode is still not
                    266:   optimal. nbcode should be improved. Documentation has been added in
                    267:   the source code.
                    268: 
1.144     brouard   269:   Revision 1.143  2014/01/26 09:45:38  brouard
                    270:   Summary: Version 0.98nR (to be improved, but gives same optimization results as 0.98k. Nice, promising
                    271: 
                    272:   * imach.c (Module): Trying to merge old staffs together while being at Tokyo. Not tested...
                    273:   (Module): Version 0.98nR Running ok, but output format still only works for three covariates.
                    274: 
1.143     brouard   275:   Revision 1.142  2014/01/26 03:57:36  brouard
                    276:   Summary: gnuplot changed plot w l 1 has to be changed to plot w l lt 2
                    277: 
                    278:   * imach.c (Module): Trying to merge old staffs together while being at Tokyo. Not tested...
                    279: 
1.142     brouard   280:   Revision 1.141  2014/01/26 02:42:01  brouard
                    281:   * imach.c (Module): Trying to merge old staffs together while being at Tokyo. Not tested...
                    282: 
1.141     brouard   283:   Revision 1.140  2011/09/02 10:37:54  brouard
                    284:   Summary: times.h is ok with mingw32 now.
                    285: 
1.140     brouard   286:   Revision 1.139  2010/06/14 07:50:17  brouard
                    287:   After the theft of my laptop, I probably lost some lines of codes which were not uploaded to the CVS tree.
                    288:   I remember having already fixed agemin agemax which are pointers now but not cvs saved.
                    289: 
1.139     brouard   290:   Revision 1.138  2010/04/30 18:19:40  brouard
                    291:   *** empty log message ***
                    292: 
1.138     brouard   293:   Revision 1.137  2010/04/29 18:11:38  brouard
                    294:   (Module): Checking covariates for more complex models
                    295:   than V1+V2. A lot of change to be done. Unstable.
                    296: 
1.137     brouard   297:   Revision 1.136  2010/04/26 20:30:53  brouard
                    298:   (Module): merging some libgsl code. Fixing computation
                    299:   of likelione (using inter/intrapolation if mle = 0) in order to
                    300:   get same likelihood as if mle=1.
                    301:   Some cleaning of code and comments added.
                    302: 
1.136     brouard   303:   Revision 1.135  2009/10/29 15:33:14  brouard
                    304:   (Module): Now imach stops if date of birth, at least year of birth, is not given. Some cleaning of the code.
                    305: 
1.135     brouard   306:   Revision 1.134  2009/10/29 13:18:53  brouard
                    307:   (Module): Now imach stops if date of birth, at least year of birth, is not given. Some cleaning of the code.
                    308: 
1.134     brouard   309:   Revision 1.133  2009/07/06 10:21:25  brouard
                    310:   just nforces
                    311: 
1.133     brouard   312:   Revision 1.132  2009/07/06 08:22:05  brouard
                    313:   Many tings
                    314: 
1.132     brouard   315:   Revision 1.131  2009/06/20 16:22:47  brouard
                    316:   Some dimensions resccaled
                    317: 
1.131     brouard   318:   Revision 1.130  2009/05/26 06:44:34  brouard
                    319:   (Module): Max Covariate is now set to 20 instead of 8. A
                    320:   lot of cleaning with variables initialized to 0. Trying to make
                    321:   V2+V3*age+V1+V4 strb=V3*age+V1+V4 working better.
                    322: 
1.130     brouard   323:   Revision 1.129  2007/08/31 13:49:27  lievre
                    324:   Modification of the way of exiting when the covariate is not binary in order to see on the window the error message before exiting
                    325: 
1.129     lievre    326:   Revision 1.128  2006/06/30 13:02:05  brouard
                    327:   (Module): Clarifications on computing e.j
                    328: 
1.128     brouard   329:   Revision 1.127  2006/04/28 18:11:50  brouard
                    330:   (Module): Yes the sum of survivors was wrong since
                    331:   imach-114 because nhstepm was no more computed in the age
                    332:   loop. Now we define nhstepma in the age loop.
                    333:   (Module): In order to speed up (in case of numerous covariates) we
                    334:   compute health expectancies (without variances) in a first step
                    335:   and then all the health expectancies with variances or standard
                    336:   deviation (needs data from the Hessian matrices) which slows the
                    337:   computation.
                    338:   In the future we should be able to stop the program is only health
                    339:   expectancies and graph are needed without standard deviations.
                    340: 
1.127     brouard   341:   Revision 1.126  2006/04/28 17:23:28  brouard
                    342:   (Module): Yes the sum of survivors was wrong since
                    343:   imach-114 because nhstepm was no more computed in the age
                    344:   loop. Now we define nhstepma in the age loop.
                    345:   Version 0.98h
                    346: 
1.126     brouard   347:   Revision 1.125  2006/04/04 15:20:31  lievre
                    348:   Errors in calculation of health expectancies. Age was not initialized.
                    349:   Forecasting file added.
                    350: 
                    351:   Revision 1.124  2006/03/22 17:13:53  lievre
                    352:   Parameters are printed with %lf instead of %f (more numbers after the comma).
                    353:   The log-likelihood is printed in the log file
                    354: 
                    355:   Revision 1.123  2006/03/20 10:52:43  brouard
                    356:   * imach.c (Module): <title> changed, corresponds to .htm file
                    357:   name. <head> headers where missing.
                    358: 
                    359:   * imach.c (Module): Weights can have a decimal point as for
                    360:   English (a comma might work with a correct LC_NUMERIC environment,
                    361:   otherwise the weight is truncated).
                    362:   Modification of warning when the covariates values are not 0 or
                    363:   1.
                    364:   Version 0.98g
                    365: 
                    366:   Revision 1.122  2006/03/20 09:45:41  brouard
                    367:   (Module): Weights can have a decimal point as for
                    368:   English (a comma might work with a correct LC_NUMERIC environment,
                    369:   otherwise the weight is truncated).
                    370:   Modification of warning when the covariates values are not 0 or
                    371:   1.
                    372:   Version 0.98g
                    373: 
                    374:   Revision 1.121  2006/03/16 17:45:01  lievre
                    375:   * imach.c (Module): Comments concerning covariates added
                    376: 
                    377:   * imach.c (Module): refinements in the computation of lli if
                    378:   status=-2 in order to have more reliable computation if stepm is
                    379:   not 1 month. Version 0.98f
                    380: 
                    381:   Revision 1.120  2006/03/16 15:10:38  lievre
                    382:   (Module): refinements in the computation of lli if
                    383:   status=-2 in order to have more reliable computation if stepm is
                    384:   not 1 month. Version 0.98f
                    385: 
                    386:   Revision 1.119  2006/03/15 17:42:26  brouard
                    387:   (Module): Bug if status = -2, the loglikelihood was
                    388:   computed as likelihood omitting the logarithm. Version O.98e
                    389: 
                    390:   Revision 1.118  2006/03/14 18:20:07  brouard
                    391:   (Module): varevsij Comments added explaining the second
                    392:   table of variances if popbased=1 .
                    393:   (Module): Covariances of eij, ekl added, graphs fixed, new html link.
                    394:   (Module): Function pstamp added
                    395:   (Module): Version 0.98d
                    396: 
                    397:   Revision 1.117  2006/03/14 17:16:22  brouard
                    398:   (Module): varevsij Comments added explaining the second
                    399:   table of variances if popbased=1 .
                    400:   (Module): Covariances of eij, ekl added, graphs fixed, new html link.
                    401:   (Module): Function pstamp added
                    402:   (Module): Version 0.98d
                    403: 
                    404:   Revision 1.116  2006/03/06 10:29:27  brouard
                    405:   (Module): Variance-covariance wrong links and
                    406:   varian-covariance of ej. is needed (Saito).
                    407: 
                    408:   Revision 1.115  2006/02/27 12:17:45  brouard
                    409:   (Module): One freematrix added in mlikeli! 0.98c
                    410: 
                    411:   Revision 1.114  2006/02/26 12:57:58  brouard
                    412:   (Module): Some improvements in processing parameter
                    413:   filename with strsep.
                    414: 
                    415:   Revision 1.113  2006/02/24 14:20:24  brouard
                    416:   (Module): Memory leaks checks with valgrind and:
                    417:   datafile was not closed, some imatrix were not freed and on matrix
                    418:   allocation too.
                    419: 
                    420:   Revision 1.112  2006/01/30 09:55:26  brouard
                    421:   (Module): Back to gnuplot.exe instead of wgnuplot.exe
                    422: 
                    423:   Revision 1.111  2006/01/25 20:38:18  brouard
                    424:   (Module): Lots of cleaning and bugs added (Gompertz)
                    425:   (Module): Comments can be added in data file. Missing date values
                    426:   can be a simple dot '.'.
                    427: 
                    428:   Revision 1.110  2006/01/25 00:51:50  brouard
                    429:   (Module): Lots of cleaning and bugs added (Gompertz)
                    430: 
                    431:   Revision 1.109  2006/01/24 19:37:15  brouard
                    432:   (Module): Comments (lines starting with a #) are allowed in data.
                    433: 
                    434:   Revision 1.108  2006/01/19 18:05:42  lievre
                    435:   Gnuplot problem appeared...
                    436:   To be fixed
                    437: 
                    438:   Revision 1.107  2006/01/19 16:20:37  brouard
                    439:   Test existence of gnuplot in imach path
                    440: 
                    441:   Revision 1.106  2006/01/19 13:24:36  brouard
                    442:   Some cleaning and links added in html output
                    443: 
                    444:   Revision 1.105  2006/01/05 20:23:19  lievre
                    445:   *** empty log message ***
                    446: 
                    447:   Revision 1.104  2005/09/30 16:11:43  lievre
                    448:   (Module): sump fixed, loop imx fixed, and simplifications.
                    449:   (Module): If the status is missing at the last wave but we know
                    450:   that the person is alive, then we can code his/her status as -2
                    451:   (instead of missing=-1 in earlier versions) and his/her
                    452:   contributions to the likelihood is 1 - Prob of dying from last
                    453:   health status (= 1-p13= p11+p12 in the easiest case of somebody in
                    454:   the healthy state at last known wave). Version is 0.98
                    455: 
                    456:   Revision 1.103  2005/09/30 15:54:49  lievre
                    457:   (Module): sump fixed, loop imx fixed, and simplifications.
                    458: 
                    459:   Revision 1.102  2004/09/15 17:31:30  brouard
                    460:   Add the possibility to read data file including tab characters.
                    461: 
                    462:   Revision 1.101  2004/09/15 10:38:38  brouard
                    463:   Fix on curr_time
                    464: 
                    465:   Revision 1.100  2004/07/12 18:29:06  brouard
                    466:   Add version for Mac OS X. Just define UNIX in Makefile
                    467: 
                    468:   Revision 1.99  2004/06/05 08:57:40  brouard
                    469:   *** empty log message ***
                    470: 
                    471:   Revision 1.98  2004/05/16 15:05:56  brouard
                    472:   New version 0.97 . First attempt to estimate force of mortality
                    473:   directly from the data i.e. without the need of knowing the health
                    474:   state at each age, but using a Gompertz model: log u =a + b*age .
                    475:   This is the basic analysis of mortality and should be done before any
                    476:   other analysis, in order to test if the mortality estimated from the
                    477:   cross-longitudinal survey is different from the mortality estimated
                    478:   from other sources like vital statistic data.
                    479: 
                    480:   The same imach parameter file can be used but the option for mle should be -3.
                    481: 
1.133     brouard   482:   Agnès, who wrote this part of the code, tried to keep most of the
1.126     brouard   483:   former routines in order to include the new code within the former code.
                    484: 
                    485:   The output is very simple: only an estimate of the intercept and of
                    486:   the slope with 95% confident intervals.
                    487: 
                    488:   Current limitations:
                    489:   A) Even if you enter covariates, i.e. with the
                    490:   model= V1+V2 equation for example, the programm does only estimate a unique global model without covariates.
                    491:   B) There is no computation of Life Expectancy nor Life Table.
                    492: 
                    493:   Revision 1.97  2004/02/20 13:25:42  lievre
                    494:   Version 0.96d. Population forecasting command line is (temporarily)
                    495:   suppressed.
                    496: 
                    497:   Revision 1.96  2003/07/15 15:38:55  brouard
                    498:   * imach.c (Repository): Errors in subdirf, 2, 3 while printing tmpout is
                    499:   rewritten within the same printf. Workaround: many printfs.
                    500: 
                    501:   Revision 1.95  2003/07/08 07:54:34  brouard
                    502:   * imach.c (Repository):
                    503:   (Repository): Using imachwizard code to output a more meaningful covariance
                    504:   matrix (cov(a12,c31) instead of numbers.
                    505: 
                    506:   Revision 1.94  2003/06/27 13:00:02  brouard
                    507:   Just cleaning
                    508: 
                    509:   Revision 1.93  2003/06/25 16:33:55  brouard
                    510:   (Module): On windows (cygwin) function asctime_r doesn't
                    511:   exist so I changed back to asctime which exists.
                    512:   (Module): Version 0.96b
                    513: 
                    514:   Revision 1.92  2003/06/25 16:30:45  brouard
                    515:   (Module): On windows (cygwin) function asctime_r doesn't
                    516:   exist so I changed back to asctime which exists.
                    517: 
                    518:   Revision 1.91  2003/06/25 15:30:29  brouard
                    519:   * imach.c (Repository): Duplicated warning errors corrected.
                    520:   (Repository): Elapsed time after each iteration is now output. It
                    521:   helps to forecast when convergence will be reached. Elapsed time
                    522:   is stamped in powell.  We created a new html file for the graphs
                    523:   concerning matrix of covariance. It has extension -cov.htm.
                    524: 
                    525:   Revision 1.90  2003/06/24 12:34:15  brouard
                    526:   (Module): Some bugs corrected for windows. Also, when
                    527:   mle=-1 a template is output in file "or"mypar.txt with the design
                    528:   of the covariance matrix to be input.
                    529: 
                    530:   Revision 1.89  2003/06/24 12:30:52  brouard
                    531:   (Module): Some bugs corrected for windows. Also, when
                    532:   mle=-1 a template is output in file "or"mypar.txt with the design
                    533:   of the covariance matrix to be input.
                    534: 
                    535:   Revision 1.88  2003/06/23 17:54:56  brouard
                    536:   * 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.
                    537: 
                    538:   Revision 1.87  2003/06/18 12:26:01  brouard
                    539:   Version 0.96
                    540: 
                    541:   Revision 1.86  2003/06/17 20:04:08  brouard
                    542:   (Module): Change position of html and gnuplot routines and added
                    543:   routine fileappend.
                    544: 
                    545:   Revision 1.85  2003/06/17 13:12:43  brouard
                    546:   * imach.c (Repository): Check when date of death was earlier that
                    547:   current date of interview. It may happen when the death was just
                    548:   prior to the death. In this case, dh was negative and likelihood
                    549:   was wrong (infinity). We still send an "Error" but patch by
                    550:   assuming that the date of death was just one stepm after the
                    551:   interview.
                    552:   (Repository): Because some people have very long ID (first column)
                    553:   we changed int to long in num[] and we added a new lvector for
                    554:   memory allocation. But we also truncated to 8 characters (left
                    555:   truncation)
                    556:   (Repository): No more line truncation errors.
                    557: 
                    558:   Revision 1.84  2003/06/13 21:44:43  brouard
                    559:   * imach.c (Repository): Replace "freqsummary" at a correct
                    560:   place. It differs from routine "prevalence" which may be called
                    561:   many times. Probs is memory consuming and must be used with
                    562:   parcimony.
                    563:   Version 0.95a3 (should output exactly the same maximization than 0.8a2)
                    564: 
                    565:   Revision 1.83  2003/06/10 13:39:11  lievre
                    566:   *** empty log message ***
                    567: 
                    568:   Revision 1.82  2003/06/05 15:57:20  brouard
                    569:   Add log in  imach.c and  fullversion number is now printed.
                    570: 
                    571: */
                    572: /*
                    573:    Interpolated Markov Chain
                    574: 
                    575:   Short summary of the programme:
                    576:   
                    577:   This program computes Healthy Life Expectancies from
                    578:   cross-longitudinal data. Cross-longitudinal data consist in: -1- a
                    579:   first survey ("cross") where individuals from different ages are
                    580:   interviewed on their health status or degree of disability (in the
                    581:   case of a health survey which is our main interest) -2- at least a
                    582:   second wave of interviews ("longitudinal") which measure each change
                    583:   (if any) in individual health status.  Health expectancies are
                    584:   computed from the time spent in each health state according to a
                    585:   model. More health states you consider, more time is necessary to reach the
                    586:   Maximum Likelihood of the parameters involved in the model.  The
                    587:   simplest model is the multinomial logistic model where pij is the
                    588:   probability to be observed in state j at the second wave
                    589:   conditional to be observed in state i at the first wave. Therefore
                    590:   the model is: log(pij/pii)= aij + bij*age+ cij*sex + etc , where
                    591:   'age' is age and 'sex' is a covariate. If you want to have a more
                    592:   complex model than "constant and age", you should modify the program
                    593:   where the markup *Covariates have to be included here again* invites
                    594:   you to do it.  More covariates you add, slower the
                    595:   convergence.
                    596: 
                    597:   The advantage of this computer programme, compared to a simple
                    598:   multinomial logistic model, is clear when the delay between waves is not
                    599:   identical for each individual. Also, if a individual missed an
                    600:   intermediate interview, the information is lost, but taken into
                    601:   account using an interpolation or extrapolation.  
                    602: 
                    603:   hPijx is the probability to be observed in state i at age x+h
                    604:   conditional to the observed state i at age x. The delay 'h' can be
                    605:   split into an exact number (nh*stepm) of unobserved intermediate
                    606:   states. This elementary transition (by month, quarter,
                    607:   semester or year) is modelled as a multinomial logistic.  The hPx
                    608:   matrix is simply the matrix product of nh*stepm elementary matrices
                    609:   and the contribution of each individual to the likelihood is simply
                    610:   hPijx.
                    611: 
                    612:   Also this programme outputs the covariance matrix of the parameters but also
                    613:   of the life expectancies. It also computes the period (stable) prevalence. 
                    614:   
1.133     brouard   615:   Authors: Nicolas Brouard (brouard@ined.fr) and Agnès Lièvre (lievre@ined.fr).
                    616:            Institut national d'études démographiques, Paris.
1.126     brouard   617:   This software have been partly granted by Euro-REVES, a concerted action
                    618:   from the European Union.
                    619:   It is copyrighted identically to a GNU software product, ie programme and
                    620:   software can be distributed freely for non commercial use. Latest version
                    621:   can be accessed at http://euroreves.ined.fr/imach .
                    622: 
                    623:   Help to debug: LD_PRELOAD=/usr/local/lib/libnjamd.so ./imach foo.imach
                    624:   or better on gdb : set env LD_PRELOAD=/usr/local/lib/libnjamd.so
                    625:   
                    626:   **********************************************************************/
                    627: /*
                    628:   main
                    629:   read parameterfile
                    630:   read datafile
                    631:   concatwav
                    632:   freqsummary
                    633:   if (mle >= 1)
                    634:     mlikeli
                    635:   print results files
                    636:   if mle==1 
                    637:      computes hessian
                    638:   read end of parameter file: agemin, agemax, bage, fage, estepm
                    639:       begin-prev-date,...
                    640:   open gnuplot file
                    641:   open html file
1.145     brouard   642:   period (stable) prevalence      | pl_nom    1-1 2-2 etc by covariate
                    643:    for age prevalim()             | #****** V1=0  V2=1  V3=1  V4=0 ******
                    644:                                   | 65 1 0 2 1 3 1 4 0  0.96326 0.03674
                    645:     freexexit2 possible for memory heap.
                    646: 
                    647:   h Pij x                         | pij_nom  ficrestpij
                    648:    # Cov Agex agex+h hpijx with i,j= 1-1 1-2     1-3     2-1     2-2     2-3
                    649:        1  85   85    1.00000             0.00000 0.00000 0.00000 1.00000 0.00000
                    650:        1  85   86    0.68299             0.22291 0.09410 0.71093 0.00000 0.28907
                    651: 
                    652:        1  65   99    0.00364             0.00322 0.99314 0.00350 0.00310 0.99340
                    653:        1  65  100    0.00214             0.00204 0.99581 0.00206 0.00196 0.99597
                    654:   variance of p one-step probabilities varprob  | prob_nom   ficresprob #One-step probabilities and stand. devi in ()
                    655:    Standard deviation of one-step probabilities | probcor_nom   ficresprobcor #One-step probabilities and correlation matrix
                    656:    Matrix of variance covariance of one-step probabilities |  probcov_nom ficresprobcov #One-step probabilities and covariance matrix
                    657: 
1.126     brouard   658:   forecasting if prevfcast==1 prevforecast call prevalence()
                    659:   health expectancies
                    660:   Variance-covariance of DFLE
                    661:   prevalence()
                    662:    movingaverage()
                    663:   varevsij() 
                    664:   if popbased==1 varevsij(,popbased)
                    665:   total life expectancies
                    666:   Variance of period (stable) prevalence
                    667:  end
                    668: */
                    669: 
1.187     brouard   670: /* #define DEBUG */
                    671: /* #define DEBUGBRENT */
1.203     brouard   672: /* #define DEBUGLINMIN */
                    673: /* #define DEBUGHESS */
                    674: #define DEBUGHESSIJ
                    675: /* #define LINMINORIGINAL  /\* Don't use loop on scale in linmin (accepting nan)*\/ */
1.165     brouard   676: #define POWELL /* Instead of NLOPT */
1.192     brouard   677: #define POWELLF1F3 /* Skip test */
1.186     brouard   678: /* #define POWELLORIGINAL /\* Don't use Directest to decide new direction but original Powell test *\/ */
                    679: /* #define MNBRAKORIGINAL /\* Don't use mnbrak fix *\/ */
1.126     brouard   680: 
                    681: #include <math.h>
                    682: #include <stdio.h>
                    683: #include <stdlib.h>
                    684: #include <string.h>
1.159     brouard   685: 
                    686: #ifdef _WIN32
                    687: #include <io.h>
1.172     brouard   688: #include <windows.h>
                    689: #include <tchar.h>
1.159     brouard   690: #else
1.126     brouard   691: #include <unistd.h>
1.159     brouard   692: #endif
1.126     brouard   693: 
                    694: #include <limits.h>
                    695: #include <sys/types.h>
1.171     brouard   696: 
                    697: #if defined(__GNUC__)
                    698: #include <sys/utsname.h> /* Doesn't work on Windows */
                    699: #endif
                    700: 
1.126     brouard   701: #include <sys/stat.h>
                    702: #include <errno.h>
1.159     brouard   703: /* extern int errno; */
1.126     brouard   704: 
1.157     brouard   705: /* #ifdef LINUX */
                    706: /* #include <time.h> */
                    707: /* #include "timeval.h" */
                    708: /* #else */
                    709: /* #include <sys/time.h> */
                    710: /* #endif */
                    711: 
1.126     brouard   712: #include <time.h>
                    713: 
1.136     brouard   714: #ifdef GSL
                    715: #include <gsl/gsl_errno.h>
                    716: #include <gsl/gsl_multimin.h>
                    717: #endif
                    718: 
1.167     brouard   719: 
1.162     brouard   720: #ifdef NLOPT
                    721: #include <nlopt.h>
                    722: typedef struct {
                    723:   double (* function)(double [] );
                    724: } myfunc_data ;
                    725: #endif
                    726: 
1.126     brouard   727: /* #include <libintl.h> */
                    728: /* #define _(String) gettext (String) */
                    729: 
1.141     brouard   730: #define MAXLINE 1024 /* Was 256. Overflow with 312 with 2 states and 4 covariates. Should be ok */
1.126     brouard   731: 
                    732: #define GNUPLOTPROGRAM "gnuplot"
                    733: /*#define GNUPLOTPROGRAM "..\\gp37mgw\\wgnuplot"*/
                    734: #define FILENAMELENGTH 132
                    735: 
                    736: #define        GLOCK_ERROR_NOPATH              -1      /* empty path */
                    737: #define        GLOCK_ERROR_GETCWD              -2      /* cannot get cwd */
                    738: 
1.144     brouard   739: #define MAXPARM 128 /**< Maximum number of parameters for the optimization */
                    740: #define NPARMAX 64 /**< (nlstate+ndeath-1)*nlstate*ncovmodel */
1.126     brouard   741: 
                    742: #define NINTERVMAX 8
1.144     brouard   743: #define NLSTATEMAX 8 /**< Maximum number of live states (for func) */
                    744: #define NDEATHMAX 8 /**< Maximum number of dead states (for func) */
                    745: #define NCOVMAX 20 /**< Maximum number of covariates, including generated covariates V1*V2 */
1.197     brouard   746: #define codtabm(h,k)  (1 & (h-1) >> (k-1))+1
1.126     brouard   747: #define MAXN 20000
1.144     brouard   748: #define YEARM 12. /**< Number of months per year */
1.126     brouard   749: #define AGESUP 130
                    750: #define AGEBASE 40
1.194     brouard   751: #define AGEOVERFLOW 1.e20
1.164     brouard   752: #define AGEGOMP 10 /**< Minimal age for Gompertz adjustment */
1.157     brouard   753: #ifdef _WIN32
                    754: #define DIRSEPARATOR '\\'
                    755: #define CHARSEPARATOR "\\"
                    756: #define ODIRSEPARATOR '/'
                    757: #else
1.126     brouard   758: #define DIRSEPARATOR '/'
                    759: #define CHARSEPARATOR "/"
                    760: #define ODIRSEPARATOR '\\'
                    761: #endif
                    762: 
1.209   ! brouard   763: /* $Id: imach.c,v 1.208 2015/11/17 14:31:57 brouard Exp $ */
1.126     brouard   764: /* $State: Exp $ */
1.196     brouard   765: #include "version.h"
                    766: char version[]=__IMACH_VERSION__;
1.204     brouard   767: char copyright[]="October 2015,INED-EUROREVES-Institut de longevite-Japan Society for the Promotion of Science (Grant-in-Aid for Scientific Research 25293121), Intel Software 2015";
1.209   ! brouard   768: char fullversion[]="$Revision: 1.208 $ $Date: 2015/11/17 14:31:57 $"; 
1.126     brouard   769: char strstart[80];
                    770: char optionfilext[10], optionfilefiname[FILENAMELENGTH];
1.130     brouard   771: int erreur=0, nberr=0, nbwarn=0; /* Error number, number of errors number of warnings  */
1.187     brouard   772: int nagesqr=0, nforce=0; /* nagesqr=1 if model is including age*age, number of forces */
1.145     brouard   773: /* Number of covariates model=V2+V1+ V3*age+V2*V4 */
                    774: int cptcovn=0; /**< cptcovn number of covariates added in the model (excepting constant and age and age*product) */
                    775: int cptcovt=0; /**< cptcovt number of covariates added in the model (excepting constant and age) */
                    776: int cptcovs=0; /**< cptcovs number of simple covariates V2+V1 =2 */
                    777: int cptcovage=0; /**< Number of covariates with age: V3*age only =1 */
                    778: int cptcovprodnoage=0; /**< Number of covariate products without age */   
                    779: int cptcoveff=0; /* Total number of covariates to vary for printing results */
                    780: int cptcov=0; /* Working variable */
1.126     brouard   781: int npar=NPARMAX;
                    782: int nlstate=2; /* Number of live states */
                    783: int ndeath=1; /* Number of dead states */
1.130     brouard   784: int ncovmodel=0, ncovcol=0;     /* Total number of covariables including constant a12*1 +b12*x ncovmodel=2 */
1.126     brouard   785: int popbased=0;
                    786: 
                    787: int *wav; /* Number of waves for this individuual 0 is possible */
1.130     brouard   788: int maxwav=0; /* Maxim number of waves */
                    789: int jmin=0, jmax=0; /* min, max spacing between 2 waves */
                    790: int ijmin=0, ijmax=0; /* Individuals having jmin and jmax */ 
                    791: int gipmx=0, gsw=0; /* Global variables on the number of contributions 
1.126     brouard   792:                   to the likelihood and the sum of weights (done by funcone)*/
1.130     brouard   793: int mle=1, weightopt=0;
1.126     brouard   794: int **mw; /* mw[mi][i] is number of the mi wave for this individual */
                    795: int **dh; /* dh[mi][i] is number of steps between mi,mi+1 for this individual */
                    796: int **bh; /* bh[mi][i] is the bias (+ or -) for this individual if the delay between
                    797:           * wave mi and wave mi+1 is not an exact multiple of stepm. */
1.162     brouard   798: int countcallfunc=0;  /* Count the number of calls to func */
1.130     brouard   799: double jmean=1; /* Mean space between 2 waves */
1.145     brouard   800: double **matprod2(); /* test */
1.126     brouard   801: double **oldm, **newm, **savm; /* Working pointers to matrices */
                    802: double **oldms, **newms, **savms; /* Fixed working pointers to matrices */
1.136     brouard   803: /*FILE *fic ; */ /* Used in readdata only */
                    804: FILE *ficpar, *ficparo,*ficres, *ficresp, *ficrespl, *ficrespij, *ficrest,*ficresf,*ficrespop;
1.126     brouard   805: FILE *ficlog, *ficrespow;
1.130     brouard   806: int globpr=0; /* Global variable for printing or not */
1.126     brouard   807: double fretone; /* Only one call to likelihood */
1.130     brouard   808: long ipmx=0; /* Number of contributions */
1.126     brouard   809: double sw; /* Sum of weights */
                    810: char filerespow[FILENAMELENGTH];
                    811: char fileresilk[FILENAMELENGTH]; /* File of individual contributions to the likelihood */
                    812: FILE *ficresilk;
                    813: FILE *ficgp,*ficresprob,*ficpop, *ficresprobcov, *ficresprobcor;
                    814: FILE *ficresprobmorprev;
                    815: FILE *fichtm, *fichtmcov; /* Html File */
                    816: FILE *ficreseij;
                    817: char filerese[FILENAMELENGTH];
                    818: FILE *ficresstdeij;
                    819: char fileresstde[FILENAMELENGTH];
                    820: FILE *ficrescveij;
                    821: char filerescve[FILENAMELENGTH];
                    822: FILE  *ficresvij;
                    823: char fileresv[FILENAMELENGTH];
                    824: FILE  *ficresvpl;
                    825: char fileresvpl[FILENAMELENGTH];
                    826: char title[MAXLINE];
                    827: char optionfile[FILENAMELENGTH], datafile[FILENAMELENGTH],  filerespl[FILENAMELENGTH];
                    828: char plotcmd[FILENAMELENGTH], pplotcmd[FILENAMELENGTH];
                    829: char tmpout[FILENAMELENGTH],  tmpout2[FILENAMELENGTH]; 
                    830: char command[FILENAMELENGTH];
                    831: int  outcmd=0;
                    832: 
                    833: char fileres[FILENAMELENGTH], filerespij[FILENAMELENGTH], filereso[FILENAMELENGTH], rfileres[FILENAMELENGTH];
1.202     brouard   834: char fileresu[FILENAMELENGTH]; /* fileres without r in front */
1.126     brouard   835: char filelog[FILENAMELENGTH]; /* Log file */
                    836: char filerest[FILENAMELENGTH];
                    837: char fileregp[FILENAMELENGTH];
                    838: char popfile[FILENAMELENGTH];
                    839: 
                    840: char optionfilegnuplot[FILENAMELENGTH], optionfilehtm[FILENAMELENGTH], optionfilehtmcov[FILENAMELENGTH] ;
                    841: 
1.157     brouard   842: /* struct timeval start_time, end_time, curr_time, last_time, forecast_time; */
                    843: /* struct timezone tzp; */
                    844: /* extern int gettimeofday(); */
                    845: struct tm tml, *gmtime(), *localtime();
                    846: 
                    847: extern time_t time();
                    848: 
                    849: struct tm start_time, end_time, curr_time, last_time, forecast_time;
                    850: time_t  rstart_time, rend_time, rcurr_time, rlast_time, rforecast_time; /* raw time */
                    851: struct tm tm;
                    852: 
1.126     brouard   853: char strcurr[80], strfor[80];
                    854: 
                    855: char *endptr;
                    856: long lval;
                    857: double dval;
                    858: 
                    859: #define NR_END 1
                    860: #define FREE_ARG char*
                    861: #define FTOL 1.0e-10
                    862: 
                    863: #define NRANSI 
                    864: #define ITMAX 200 
                    865: 
                    866: #define TOL 2.0e-4 
                    867: 
                    868: #define CGOLD 0.3819660 
                    869: #define ZEPS 1.0e-10 
                    870: #define SHFT(a,b,c,d) (a)=(b);(b)=(c);(c)=(d); 
                    871: 
                    872: #define GOLD 1.618034 
                    873: #define GLIMIT 100.0 
                    874: #define TINY 1.0e-20 
                    875: 
                    876: static double maxarg1,maxarg2;
                    877: #define FMAX(a,b) (maxarg1=(a),maxarg2=(b),(maxarg1)>(maxarg2)? (maxarg1):(maxarg2))
                    878: #define FMIN(a,b) (maxarg1=(a),maxarg2=(b),(maxarg1)<(maxarg2)? (maxarg1):(maxarg2))
                    879:   
                    880: #define SIGN(a,b) ((b)>0.0 ? fabs(a) : -fabs(a))
                    881: #define rint(a) floor(a+0.5)
1.166     brouard   882: /* http://www.thphys.uni-heidelberg.de/~robbers/cmbeasy/doc/html/myutils_8h-source.html */
1.183     brouard   883: #define mytinydouble 1.0e-16
1.166     brouard   884: /* #define DEQUAL(a,b) (fabs((a)-(b))<mytinydouble) */
                    885: /* http://www.thphys.uni-heidelberg.de/~robbers/cmbeasy/doc/html/mynrutils_8h-source.html */
                    886: /* static double dsqrarg; */
                    887: /* #define DSQR(a) (DEQUAL((dsqrarg=(a)),0.0) ? 0.0 : dsqrarg*dsqrarg) */
1.126     brouard   888: static double sqrarg;
                    889: #define SQR(a) ((sqrarg=(a)) == 0.0 ? 0.0 :sqrarg*sqrarg)
                    890: #define SWAP(a,b) {temp=(a);(a)=(b);(b)=temp;} 
                    891: int agegomp= AGEGOMP;
                    892: 
                    893: int imx; 
                    894: int stepm=1;
                    895: /* Stepm, step in month: minimum step interpolation*/
                    896: 
                    897: int estepm;
                    898: /* Estepm, step in month to interpolate survival function in order to approximate Life Expectancy*/
                    899: 
                    900: int m,nb;
                    901: long *num;
1.197     brouard   902: int firstpass=0, lastpass=4,*cod, *cens;
1.192     brouard   903: int *ncodemax;  /* ncodemax[j]= Number of modalities of the j th
                    904:                   covariate for which somebody answered excluding 
                    905:                   undefined. Usually 2: 0 and 1. */
                    906: int *ncodemaxwundef;  /* ncodemax[j]= Number of modalities of the j th
                    907:                             covariate for which somebody answered including 
                    908:                             undefined. Usually 3: -1, 0 and 1. */
1.126     brouard   909: double **agev,*moisnais, *annais, *moisdc, *andc,**mint, **anint;
                    910: double **pmmij, ***probs;
                    911: double *ageexmed,*agecens;
                    912: double dateintmean=0;
                    913: 
                    914: double *weight;
                    915: int **s; /* Status */
1.141     brouard   916: double *agedc;
1.145     brouard   917: double  **covar; /**< covar[j,i], value of jth covariate for individual i,
1.141     brouard   918:                  * covar=matrix(0,NCOVMAX,1,n); 
1.187     brouard   919:                  * cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*age; */
1.141     brouard   920: double  idx; 
                    921: int **nbcode, *Tvar; /**< model=V2 => Tvar[1]= 2 */
1.197     brouard   922: int *Tage;
1.145     brouard   923: int *Ndum; /** Freq of modality (tricode */
1.200     brouard   924: /* int **codtab;*/ /**< codtab=imatrix(1,100,1,10); */
1.141     brouard   925: int **Tvard, *Tprod, cptcovprod, *Tvaraff;
1.126     brouard   926: double *lsurv, *lpop, *tpop;
                    927: 
1.143     brouard   928: double ftol=FTOL; /**< Tolerance for computing Max Likelihood */
                    929: double ftolhess; /**< Tolerance for computing hessian */
1.126     brouard   930: 
                    931: /**************** split *************************/
                    932: static int split( char *path, char *dirc, char *name, char *ext, char *finame )
                    933: {
                    934:   /* From a file name with (full) path (either Unix or Windows) we extract the directory (dirc)
                    935:      the name of the file (name), its extension only (ext) and its first part of the name (finame)
                    936:   */ 
                    937:   char *ss;                            /* pointer */
1.186     brouard   938:   int  l1=0, l2=0;                             /* length counters */
1.126     brouard   939: 
                    940:   l1 = strlen(path );                  /* length of path */
                    941:   if ( l1 == 0 ) return( GLOCK_ERROR_NOPATH );
                    942:   ss= strrchr( path, DIRSEPARATOR );           /* find last / */
                    943:   if ( ss == NULL ) {                  /* no directory, so determine current directory */
                    944:     strcpy( name, path );              /* we got the fullname name because no directory */
                    945:     /*if(strrchr(path, ODIRSEPARATOR )==NULL)
                    946:       printf("Warning you should use %s as a separator\n",DIRSEPARATOR);*/
                    947:     /* get current working directory */
                    948:     /*    extern  char* getcwd ( char *buf , int len);*/
1.184     brouard   949: #ifdef WIN32
                    950:     if (_getcwd( dirc, FILENAME_MAX ) == NULL ) {
                    951: #else
                    952:        if (getcwd(dirc, FILENAME_MAX) == NULL) {
                    953: #endif
1.126     brouard   954:       return( GLOCK_ERROR_GETCWD );
                    955:     }
                    956:     /* got dirc from getcwd*/
                    957:     printf(" DIRC = %s \n",dirc);
1.205     brouard   958:   } else {                             /* strip directory from path */
1.126     brouard   959:     ss++;                              /* after this, the filename */
                    960:     l2 = strlen( ss );                 /* length of filename */
                    961:     if ( l2 == 0 ) return( GLOCK_ERROR_NOPATH );
                    962:     strcpy( name, ss );                /* save file name */
                    963:     strncpy( dirc, path, l1 - l2 );    /* now the directory */
1.186     brouard   964:     dirc[l1-l2] = '\0';                        /* add zero */
1.126     brouard   965:     printf(" DIRC2 = %s \n",dirc);
                    966:   }
                    967:   /* We add a separator at the end of dirc if not exists */
                    968:   l1 = strlen( dirc );                 /* length of directory */
                    969:   if( dirc[l1-1] != DIRSEPARATOR ){
                    970:     dirc[l1] =  DIRSEPARATOR;
                    971:     dirc[l1+1] = 0; 
                    972:     printf(" DIRC3 = %s \n",dirc);
                    973:   }
                    974:   ss = strrchr( name, '.' );           /* find last / */
                    975:   if (ss >0){
                    976:     ss++;
                    977:     strcpy(ext,ss);                    /* save extension */
                    978:     l1= strlen( name);
                    979:     l2= strlen(ss)+1;
                    980:     strncpy( finame, name, l1-l2);
                    981:     finame[l1-l2]= 0;
                    982:   }
                    983: 
                    984:   return( 0 );                         /* we're done */
                    985: }
                    986: 
                    987: 
                    988: /******************************************/
                    989: 
                    990: void replace_back_to_slash(char *s, char*t)
                    991: {
                    992:   int i;
                    993:   int lg=0;
                    994:   i=0;
                    995:   lg=strlen(t);
                    996:   for(i=0; i<= lg; i++) {
                    997:     (s[i] = t[i]);
                    998:     if (t[i]== '\\') s[i]='/';
                    999:   }
                   1000: }
                   1001: 
1.132     brouard  1002: char *trimbb(char *out, char *in)
1.137     brouard  1003: { /* Trim multiple blanks in line but keeps first blanks if line starts with blanks */
1.132     brouard  1004:   char *s;
                   1005:   s=out;
                   1006:   while (*in != '\0'){
1.137     brouard  1007:     while( *in == ' ' && *(in+1) == ' '){ /* && *(in+1) != '\0'){*/
1.132     brouard  1008:       in++;
                   1009:     }
                   1010:     *out++ = *in++;
                   1011:   }
                   1012:   *out='\0';
                   1013:   return s;
                   1014: }
                   1015: 
1.187     brouard  1016: /* char *substrchaine(char *out, char *in, char *chain) */
                   1017: /* { */
                   1018: /*   /\* Substract chain 'chain' from 'in', return and output 'out' *\/ */
                   1019: /*   char *s, *t; */
                   1020: /*   t=in;s=out; */
                   1021: /*   while ((*in != *chain) && (*in != '\0')){ */
                   1022: /*     *out++ = *in++; */
                   1023: /*   } */
                   1024: 
                   1025: /*   /\* *in matches *chain *\/ */
                   1026: /*   while ((*in++ == *chain++) && (*in != '\0')){ */
                   1027: /*     printf("*in = %c, *out= %c *chain= %c \n", *in, *out, *chain);  */
                   1028: /*   } */
                   1029: /*   in--; chain--; */
                   1030: /*   while ( (*in != '\0')){ */
                   1031: /*     printf("Bef *in = %c, *out= %c *chain= %c \n", *in, *out, *chain);  */
                   1032: /*     *out++ = *in++; */
                   1033: /*     printf("Aft *in = %c, *out= %c *chain= %c \n", *in, *out, *chain);  */
                   1034: /*   } */
                   1035: /*   *out='\0'; */
                   1036: /*   out=s; */
                   1037: /*   return out; */
                   1038: /* } */
                   1039: char *substrchaine(char *out, char *in, char *chain)
                   1040: {
                   1041:   /* Substract chain 'chain' from 'in', return and output 'out' */
                   1042:   /* in="V1+V1*age+age*age+V2", chain="age*age" */
                   1043: 
                   1044:   char *strloc;
                   1045: 
                   1046:   strcpy (out, in); 
                   1047:   strloc = strstr(out, chain); /* strloc points to out at age*age+V2 */
                   1048:   printf("Bef strloc=%s chain=%s out=%s \n", strloc, chain, out);
                   1049:   if(strloc != NULL){ 
                   1050:     /* will affect out */ /* strloc+strlenc(chain)=+V2 */ /* Will also work in Unicode */
                   1051:     memmove(strloc,strloc+strlen(chain), strlen(strloc+strlen(chain))+1);
                   1052:     /* strcpy (strloc, strloc +strlen(chain));*/
                   1053:   }
                   1054:   printf("Aft strloc=%s chain=%s in=%s out=%s \n", strloc, chain, in, out);
                   1055:   return out;
                   1056: }
                   1057: 
                   1058: 
1.145     brouard  1059: char *cutl(char *blocc, char *alocc, char *in, char occ)
                   1060: {
1.187     brouard  1061:   /* cuts string in into blocc and alocc where blocc ends before FIRST occurence of char 'occ' 
1.145     brouard  1062:      and alocc starts after first occurence of char 'occ' : ex cutv(blocc,alocc,"abcdef2ghi2j",'2')
1.187     brouard  1063:      gives blocc="abcdef" and alocc="ghi2j".
1.145     brouard  1064:      If occ is not found blocc is null and alocc is equal to in. Returns blocc
                   1065:   */
1.160     brouard  1066:   char *s, *t;
1.145     brouard  1067:   t=in;s=in;
                   1068:   while ((*in != occ) && (*in != '\0')){
                   1069:     *alocc++ = *in++;
                   1070:   }
                   1071:   if( *in == occ){
                   1072:     *(alocc)='\0';
                   1073:     s=++in;
                   1074:   }
                   1075:  
                   1076:   if (s == t) {/* occ not found */
                   1077:     *(alocc-(in-s))='\0';
                   1078:     in=s;
                   1079:   }
                   1080:   while ( *in != '\0'){
                   1081:     *blocc++ = *in++;
                   1082:   }
                   1083: 
                   1084:   *blocc='\0';
                   1085:   return t;
                   1086: }
1.137     brouard  1087: char *cutv(char *blocc, char *alocc, char *in, char occ)
                   1088: {
1.187     brouard  1089:   /* cuts string in into blocc and alocc where blocc ends before LAST occurence of char 'occ' 
1.137     brouard  1090:      and alocc starts after last occurence of char 'occ' : ex cutv(blocc,alocc,"abcdef2ghi2j",'2')
                   1091:      gives blocc="abcdef2ghi" and alocc="j".
                   1092:      If occ is not found blocc is null and alocc is equal to in. Returns alocc
                   1093:   */
                   1094:   char *s, *t;
                   1095:   t=in;s=in;
                   1096:   while (*in != '\0'){
                   1097:     while( *in == occ){
                   1098:       *blocc++ = *in++;
                   1099:       s=in;
                   1100:     }
                   1101:     *blocc++ = *in++;
                   1102:   }
                   1103:   if (s == t) /* occ not found */
                   1104:     *(blocc-(in-s))='\0';
                   1105:   else
                   1106:     *(blocc-(in-s)-1)='\0';
                   1107:   in=s;
                   1108:   while ( *in != '\0'){
                   1109:     *alocc++ = *in++;
                   1110:   }
                   1111: 
                   1112:   *alocc='\0';
                   1113:   return s;
                   1114: }
                   1115: 
1.126     brouard  1116: int nbocc(char *s, char occ)
                   1117: {
                   1118:   int i,j=0;
                   1119:   int lg=20;
                   1120:   i=0;
                   1121:   lg=strlen(s);
                   1122:   for(i=0; i<= lg; i++) {
                   1123:   if  (s[i] == occ ) j++;
                   1124:   }
                   1125:   return j;
                   1126: }
                   1127: 
1.137     brouard  1128: /* void cutv(char *u,char *v, char*t, char occ) */
                   1129: /* { */
                   1130: /*   /\* cuts string t into u and v where u ends before last occurence of char 'occ'  */
                   1131: /*      and v starts after last occurence of char 'occ' : ex cutv(u,v,"abcdef2ghi2j",'2') */
                   1132: /*      gives u="abcdef2ghi" and v="j" *\/ */
                   1133: /*   int i,lg,j,p=0; */
                   1134: /*   i=0; */
                   1135: /*   lg=strlen(t); */
                   1136: /*   for(j=0; j<=lg-1; j++) { */
                   1137: /*     if((t[j]!= occ) && (t[j+1]== occ)) p=j+1; */
                   1138: /*   } */
1.126     brouard  1139: 
1.137     brouard  1140: /*   for(j=0; j<p; j++) { */
                   1141: /*     (u[j] = t[j]); */
                   1142: /*   } */
                   1143: /*      u[p]='\0'; */
1.126     brouard  1144: 
1.137     brouard  1145: /*    for(j=0; j<= lg; j++) { */
                   1146: /*     if (j>=(p+1))(v[j-p-1] = t[j]); */
                   1147: /*   } */
                   1148: /* } */
1.126     brouard  1149: 
1.160     brouard  1150: #ifdef _WIN32
                   1151: char * strsep(char **pp, const char *delim)
                   1152: {
                   1153:   char *p, *q;
                   1154:          
                   1155:   if ((p = *pp) == NULL)
                   1156:     return 0;
                   1157:   if ((q = strpbrk (p, delim)) != NULL)
                   1158:   {
                   1159:     *pp = q + 1;
                   1160:     *q = '\0';
                   1161:   }
                   1162:   else
                   1163:     *pp = 0;
                   1164:   return p;
                   1165: }
                   1166: #endif
                   1167: 
1.126     brouard  1168: /********************** nrerror ********************/
                   1169: 
                   1170: void nrerror(char error_text[])
                   1171: {
                   1172:   fprintf(stderr,"ERREUR ...\n");
                   1173:   fprintf(stderr,"%s\n",error_text);
                   1174:   exit(EXIT_FAILURE);
                   1175: }
                   1176: /*********************** vector *******************/
                   1177: double *vector(int nl, int nh)
                   1178: {
                   1179:   double *v;
                   1180:   v=(double *) malloc((size_t)((nh-nl+1+NR_END)*sizeof(double)));
                   1181:   if (!v) nrerror("allocation failure in vector");
                   1182:   return v-nl+NR_END;
                   1183: }
                   1184: 
                   1185: /************************ free vector ******************/
                   1186: void free_vector(double*v, int nl, int nh)
                   1187: {
                   1188:   free((FREE_ARG)(v+nl-NR_END));
                   1189: }
                   1190: 
                   1191: /************************ivector *******************************/
                   1192: int *ivector(long nl,long nh)
                   1193: {
                   1194:   int *v;
                   1195:   v=(int *) malloc((size_t)((nh-nl+1+NR_END)*sizeof(int)));
                   1196:   if (!v) nrerror("allocation failure in ivector");
                   1197:   return v-nl+NR_END;
                   1198: }
                   1199: 
                   1200: /******************free ivector **************************/
                   1201: void free_ivector(int *v, long nl, long nh)
                   1202: {
                   1203:   free((FREE_ARG)(v+nl-NR_END));
                   1204: }
                   1205: 
                   1206: /************************lvector *******************************/
                   1207: long *lvector(long nl,long nh)
                   1208: {
                   1209:   long *v;
                   1210:   v=(long *) malloc((size_t)((nh-nl+1+NR_END)*sizeof(long)));
                   1211:   if (!v) nrerror("allocation failure in ivector");
                   1212:   return v-nl+NR_END;
                   1213: }
                   1214: 
                   1215: /******************free lvector **************************/
                   1216: void free_lvector(long *v, long nl, long nh)
                   1217: {
                   1218:   free((FREE_ARG)(v+nl-NR_END));
                   1219: }
                   1220: 
                   1221: /******************* imatrix *******************************/
                   1222: int **imatrix(long nrl, long nrh, long ncl, long nch) 
                   1223:      /* allocate a int matrix with subscript range m[nrl..nrh][ncl..nch] */ 
                   1224: { 
                   1225:   long i, nrow=nrh-nrl+1,ncol=nch-ncl+1; 
                   1226:   int **m; 
                   1227:   
                   1228:   /* allocate pointers to rows */ 
                   1229:   m=(int **) malloc((size_t)((nrow+NR_END)*sizeof(int*))); 
                   1230:   if (!m) nrerror("allocation failure 1 in matrix()"); 
                   1231:   m += NR_END; 
                   1232:   m -= nrl; 
                   1233:   
                   1234:   
                   1235:   /* allocate rows and set pointers to them */ 
                   1236:   m[nrl]=(int *) malloc((size_t)((nrow*ncol+NR_END)*sizeof(int))); 
                   1237:   if (!m[nrl]) nrerror("allocation failure 2 in matrix()"); 
                   1238:   m[nrl] += NR_END; 
                   1239:   m[nrl] -= ncl; 
                   1240:   
                   1241:   for(i=nrl+1;i<=nrh;i++) m[i]=m[i-1]+ncol; 
                   1242:   
                   1243:   /* return pointer to array of pointers to rows */ 
                   1244:   return m; 
                   1245: } 
                   1246: 
                   1247: /****************** free_imatrix *************************/
                   1248: void free_imatrix(m,nrl,nrh,ncl,nch)
                   1249:       int **m;
                   1250:       long nch,ncl,nrh,nrl; 
                   1251:      /* free an int matrix allocated by imatrix() */ 
                   1252: { 
                   1253:   free((FREE_ARG) (m[nrl]+ncl-NR_END)); 
                   1254:   free((FREE_ARG) (m+nrl-NR_END)); 
                   1255: } 
                   1256: 
                   1257: /******************* matrix *******************************/
                   1258: double **matrix(long nrl, long nrh, long ncl, long nch)
                   1259: {
                   1260:   long i, nrow=nrh-nrl+1, ncol=nch-ncl+1;
                   1261:   double **m;
                   1262: 
                   1263:   m=(double **) malloc((size_t)((nrow+NR_END)*sizeof(double*)));
                   1264:   if (!m) nrerror("allocation failure 1 in matrix()");
                   1265:   m += NR_END;
                   1266:   m -= nrl;
                   1267: 
                   1268:   m[nrl]=(double *) malloc((size_t)((nrow*ncol+NR_END)*sizeof(double)));
                   1269:   if (!m[nrl]) nrerror("allocation failure 2 in matrix()");
                   1270:   m[nrl] += NR_END;
                   1271:   m[nrl] -= ncl;
                   1272: 
                   1273:   for (i=nrl+1; i<=nrh; i++) m[i]=m[i-1]+ncol;
                   1274:   return m;
1.145     brouard  1275:   /* print *(*(m+1)+70) or print m[1][70]; print m+1 or print &(m[1]) or &(m[1][0])
                   1276: m[i] = address of ith row of the table. &(m[i]) is its value which is another adress
                   1277: that of m[i][0]. In order to get the value p m[i][0] but it is unitialized.
1.126     brouard  1278:    */
                   1279: }
                   1280: 
                   1281: /*************************free matrix ************************/
                   1282: void free_matrix(double **m, long nrl, long nrh, long ncl, long nch)
                   1283: {
                   1284:   free((FREE_ARG)(m[nrl]+ncl-NR_END));
                   1285:   free((FREE_ARG)(m+nrl-NR_END));
                   1286: }
                   1287: 
                   1288: /******************* ma3x *******************************/
                   1289: double ***ma3x(long nrl, long nrh, long ncl, long nch, long nll, long nlh)
                   1290: {
                   1291:   long i, j, nrow=nrh-nrl+1, ncol=nch-ncl+1, nlay=nlh-nll+1;
                   1292:   double ***m;
                   1293: 
                   1294:   m=(double ***) malloc((size_t)((nrow+NR_END)*sizeof(double*)));
                   1295:   if (!m) nrerror("allocation failure 1 in matrix()");
                   1296:   m += NR_END;
                   1297:   m -= nrl;
                   1298: 
                   1299:   m[nrl]=(double **) malloc((size_t)((nrow*ncol+NR_END)*sizeof(double)));
                   1300:   if (!m[nrl]) nrerror("allocation failure 2 in matrix()");
                   1301:   m[nrl] += NR_END;
                   1302:   m[nrl] -= ncl;
                   1303: 
                   1304:   for (i=nrl+1; i<=nrh; i++) m[i]=m[i-1]+ncol;
                   1305: 
                   1306:   m[nrl][ncl]=(double *) malloc((size_t)((nrow*ncol*nlay+NR_END)*sizeof(double)));
                   1307:   if (!m[nrl][ncl]) nrerror("allocation failure 3 in matrix()");
                   1308:   m[nrl][ncl] += NR_END;
                   1309:   m[nrl][ncl] -= nll;
                   1310:   for (j=ncl+1; j<=nch; j++) 
                   1311:     m[nrl][j]=m[nrl][j-1]+nlay;
                   1312:   
                   1313:   for (i=nrl+1; i<=nrh; i++) {
                   1314:     m[i][ncl]=m[i-1l][ncl]+ncol*nlay;
                   1315:     for (j=ncl+1; j<=nch; j++) 
                   1316:       m[i][j]=m[i][j-1]+nlay;
                   1317:   }
                   1318:   return m; 
                   1319:   /*  gdb: p *(m+1) <=> p m[1] and p (m+1) <=> p (m+1) <=> p &(m[1])
                   1320:            &(m[i][j][k]) <=> *((*(m+i) + j)+k)
                   1321:   */
                   1322: }
                   1323: 
                   1324: /*************************free ma3x ************************/
                   1325: void free_ma3x(double ***m, long nrl, long nrh, long ncl, long nch,long nll, long nlh)
                   1326: {
                   1327:   free((FREE_ARG)(m[nrl][ncl]+ nll-NR_END));
                   1328:   free((FREE_ARG)(m[nrl]+ncl-NR_END));
                   1329:   free((FREE_ARG)(m+nrl-NR_END));
                   1330: }
                   1331: 
                   1332: /*************** function subdirf ***********/
                   1333: char *subdirf(char fileres[])
                   1334: {
                   1335:   /* Caution optionfilefiname is hidden */
                   1336:   strcpy(tmpout,optionfilefiname);
                   1337:   strcat(tmpout,"/"); /* Add to the right */
                   1338:   strcat(tmpout,fileres);
                   1339:   return tmpout;
                   1340: }
                   1341: 
                   1342: /*************** function subdirf2 ***********/
                   1343: char *subdirf2(char fileres[], char *preop)
                   1344: {
                   1345:   
                   1346:   /* Caution optionfilefiname is hidden */
                   1347:   strcpy(tmpout,optionfilefiname);
                   1348:   strcat(tmpout,"/");
                   1349:   strcat(tmpout,preop);
                   1350:   strcat(tmpout,fileres);
                   1351:   return tmpout;
                   1352: }
                   1353: 
                   1354: /*************** function subdirf3 ***********/
                   1355: char *subdirf3(char fileres[], char *preop, char *preop2)
                   1356: {
                   1357:   
                   1358:   /* Caution optionfilefiname is hidden */
                   1359:   strcpy(tmpout,optionfilefiname);
                   1360:   strcat(tmpout,"/");
                   1361:   strcat(tmpout,preop);
                   1362:   strcat(tmpout,preop2);
                   1363:   strcat(tmpout,fileres);
                   1364:   return tmpout;
                   1365: }
                   1366: 
1.162     brouard  1367: char *asc_diff_time(long time_sec, char ascdiff[])
                   1368: {
                   1369:   long sec_left, days, hours, minutes;
                   1370:   days = (time_sec) / (60*60*24);
                   1371:   sec_left = (time_sec) % (60*60*24);
                   1372:   hours = (sec_left) / (60*60) ;
                   1373:   sec_left = (sec_left) %(60*60);
                   1374:   minutes = (sec_left) /60;
                   1375:   sec_left = (sec_left) % (60);
                   1376:   sprintf(ascdiff,"%ld day(s) %ld hour(s) %ld minute(s) %ld second(s)",days, hours, minutes, sec_left);  
                   1377:   return ascdiff;
                   1378: }
                   1379: 
1.126     brouard  1380: /***************** f1dim *************************/
                   1381: extern int ncom; 
                   1382: extern double *pcom,*xicom;
                   1383: extern double (*nrfunc)(double []); 
                   1384:  
                   1385: double f1dim(double x) 
                   1386: { 
                   1387:   int j; 
                   1388:   double f;
                   1389:   double *xt; 
                   1390:  
                   1391:   xt=vector(1,ncom); 
                   1392:   for (j=1;j<=ncom;j++) xt[j]=pcom[j]+x*xicom[j]; 
                   1393:   f=(*nrfunc)(xt); 
                   1394:   free_vector(xt,1,ncom); 
                   1395:   return f; 
                   1396: } 
                   1397: 
                   1398: /*****************brent *************************/
                   1399: double brent(double ax, double bx, double cx, double (*f)(double), double tol,         double *xmin) 
1.187     brouard  1400: {
                   1401:   /* Given a function f, and given a bracketing triplet of abscissas ax, bx, cx (such that bx is
                   1402:    * between ax and cx, and f(bx) is less than both f(ax) and f(cx) ), this routine isolates
                   1403:    * the minimum to a fractional precision of about tol using Brent’s method. The abscissa of
                   1404:    * the minimum is returned as xmin, and the minimum function value is returned as brent , the
                   1405:    * returned function value. 
                   1406:   */
1.126     brouard  1407:   int iter; 
                   1408:   double a,b,d,etemp;
1.159     brouard  1409:   double fu=0,fv,fw,fx;
1.164     brouard  1410:   double ftemp=0.;
1.126     brouard  1411:   double p,q,r,tol1,tol2,u,v,w,x,xm; 
                   1412:   double e=0.0; 
                   1413:  
                   1414:   a=(ax < cx ? ax : cx); 
                   1415:   b=(ax > cx ? ax : cx); 
                   1416:   x=w=v=bx; 
                   1417:   fw=fv=fx=(*f)(x); 
                   1418:   for (iter=1;iter<=ITMAX;iter++) { 
                   1419:     xm=0.5*(a+b); 
                   1420:     tol2=2.0*(tol1=tol*fabs(x)+ZEPS); 
                   1421:     /*         if (2.0*fabs(fp-(*fret)) <= ftol*(fabs(fp)+fabs(*fret)))*/
                   1422:     printf(".");fflush(stdout);
                   1423:     fprintf(ficlog,".");fflush(ficlog);
1.162     brouard  1424: #ifdef DEBUGBRENT
1.126     brouard  1425:     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);
                   1426:     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);
                   1427:     /*         if ((fabs(x-xm) <= (tol2-0.5*(b-a)))||(2.0*fabs(fu-ftemp) <= ftol*1.e-2*(fabs(fu)+fabs(ftemp)))) { */
                   1428: #endif
                   1429:     if (fabs(x-xm) <= (tol2-0.5*(b-a))){ 
                   1430:       *xmin=x; 
                   1431:       return fx; 
                   1432:     } 
                   1433:     ftemp=fu;
                   1434:     if (fabs(e) > tol1) { 
                   1435:       r=(x-w)*(fx-fv); 
                   1436:       q=(x-v)*(fx-fw); 
                   1437:       p=(x-v)*q-(x-w)*r; 
                   1438:       q=2.0*(q-r); 
                   1439:       if (q > 0.0) p = -p; 
                   1440:       q=fabs(q); 
                   1441:       etemp=e; 
                   1442:       e=d; 
                   1443:       if (fabs(p) >= fabs(0.5*q*etemp) || p <= q*(a-x) || p >= q*(b-x)) 
                   1444:        d=CGOLD*(e=(x >= xm ? a-x : b-x)); 
                   1445:       else { 
                   1446:        d=p/q; 
                   1447:        u=x+d; 
                   1448:        if (u-a < tol2 || b-u < tol2) 
                   1449:          d=SIGN(tol1,xm-x); 
                   1450:       } 
                   1451:     } else { 
                   1452:       d=CGOLD*(e=(x >= xm ? a-x : b-x)); 
                   1453:     } 
                   1454:     u=(fabs(d) >= tol1 ? x+d : x+SIGN(tol1,d)); 
                   1455:     fu=(*f)(u); 
                   1456:     if (fu <= fx) { 
                   1457:       if (u >= x) a=x; else b=x; 
                   1458:       SHFT(v,w,x,u) 
1.183     brouard  1459:       SHFT(fv,fw,fx,fu) 
                   1460:     } else { 
                   1461:       if (u < x) a=u; else b=u; 
                   1462:       if (fu <= fw || w == x) { 
                   1463:        v=w; 
                   1464:        w=u; 
                   1465:        fv=fw; 
                   1466:        fw=fu; 
                   1467:       } else if (fu <= fv || v == x || v == w) { 
                   1468:        v=u; 
                   1469:        fv=fu; 
                   1470:       } 
                   1471:     } 
1.126     brouard  1472:   } 
                   1473:   nrerror("Too many iterations in brent"); 
                   1474:   *xmin=x; 
                   1475:   return fx; 
                   1476: } 
                   1477: 
                   1478: /****************** mnbrak ***********************/
                   1479: 
                   1480: void mnbrak(double *ax, double *bx, double *cx, double *fa, double *fb, double *fc, 
                   1481:            double (*func)(double)) 
1.183     brouard  1482: { /* Given a function func , and given distinct initial points ax and bx , this routine searches in
                   1483: the downhill direction (defined by the function as evaluated at the initial points) and returns
                   1484: new points ax , bx , cx that bracket a minimum of the function. Also returned are the function
                   1485: values at the three points, fa, fb , and fc such that fa > fb and fb < fc.
                   1486:    */
1.126     brouard  1487:   double ulim,u,r,q, dum;
                   1488:   double fu; 
1.187     brouard  1489: 
                   1490:   double scale=10.;
                   1491:   int iterscale=0;
                   1492: 
                   1493:   *fa=(*func)(*ax); /*  xta[j]=pcom[j]+(*ax)*xicom[j]; fa=f(xta[j])*/
                   1494:   *fb=(*func)(*bx); /*  xtb[j]=pcom[j]+(*bx)*xicom[j]; fb=f(xtb[j]) */
                   1495: 
                   1496: 
                   1497:   /* while(*fb != *fb){ /\* *ax should be ok, reducing distance to *ax *\/ */
                   1498:   /*   printf("Warning mnbrak *fb = %lf, *bx=%lf *ax=%lf *fa==%lf iter=%d\n",*fb, *bx, *ax, *fa, iterscale++); */
                   1499:   /*   *bx = *ax - (*ax - *bx)/scale; */
                   1500:   /*   *fb=(*func)(*bx);  /\*  xtb[j]=pcom[j]+(*bx)*xicom[j]; fb=f(xtb[j]) *\/ */
                   1501:   /* } */
                   1502: 
1.126     brouard  1503:   if (*fb > *fa) { 
                   1504:     SHFT(dum,*ax,*bx,dum) 
1.183     brouard  1505:     SHFT(dum,*fb,*fa,dum) 
                   1506:   } 
1.126     brouard  1507:   *cx=(*bx)+GOLD*(*bx-*ax); 
                   1508:   *fc=(*func)(*cx); 
1.183     brouard  1509: #ifdef DEBUG
                   1510:   printf("mnbrak0 *fb=%.12e *fc=%.12e\n",*fb,*fc);
                   1511:   fprintf(ficlog,"mnbrak0 *fb=%.12e *fc=%.12e\n",*fb,*fc);
                   1512: #endif
                   1513:   while (*fb > *fc) { /* Declining a,b,c with fa> fb > fc */
1.126     brouard  1514:     r=(*bx-*ax)*(*fb-*fc); 
                   1515:     q=(*bx-*cx)*(*fb-*fa); 
                   1516:     u=(*bx)-((*bx-*cx)*q-(*bx-*ax)*r)/ 
1.183     brouard  1517:       (2.0*SIGN(FMAX(fabs(q-r),TINY),q-r)); /* Minimum abscissa of a parabolic estimated from (a,fa), (b,fb) and (c,fc). */
                   1518:     ulim=(*bx)+GLIMIT*(*cx-*bx); /* Maximum abscissa where function should be evaluated */
                   1519:     if ((*bx-u)*(u-*cx) > 0.0) { /* if u_p is between b and c */
1.126     brouard  1520:       fu=(*func)(u); 
1.163     brouard  1521: #ifdef DEBUG
                   1522:       /* f(x)=A(x-u)**2+f(u) */
                   1523:       double A, fparabu; 
                   1524:       A= (*fb - *fa)/(*bx-*ax)/(*bx+*ax-2*u);
                   1525:       fparabu= *fa - A*(*ax-u)*(*ax-u);
                   1526:       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);
                   1527:       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  1528:       /* And thus,it can be that fu > *fc even if fparabu < *fc */
                   1529:       /* mnbrak (*ax=7.666299858533, *fa=299039.693133272231), (*bx=8.595447774979, *fb=298976.598289369489),
                   1530:         (*cx=10.098840694817, *fc=298946.631474258087),  (*u=9.852501168332, fu=298948.773013752128, fparabu=298945.434711494134) */
                   1531:       /* In that case, there is no bracket in the output! Routine is wrong with many consequences.*/
1.163     brouard  1532: #endif 
1.184     brouard  1533: #ifdef MNBRAKORIGINAL
1.183     brouard  1534: #else
1.191     brouard  1535: /*       if (fu > *fc) { */
                   1536: /* #ifdef DEBUG */
                   1537: /*       printf("mnbrak4  fu > fc \n"); */
                   1538: /*       fprintf(ficlog, "mnbrak4 fu > fc\n"); */
                   1539: /* #endif */
                   1540: /*     /\* 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 *\\/  *\/ */
                   1541: /*     /\* SHFT(*fa,*fc,fu,*fc) /\\* (b, u, c) is a bracket while test fb > fc will be fu > fc  will exit *\\/ *\/ */
                   1542: /*     dum=u; /\* Shifting c and u *\/ */
                   1543: /*     u = *cx; */
                   1544: /*     *cx = dum; */
                   1545: /*     dum = fu; */
                   1546: /*     fu = *fc; */
                   1547: /*     *fc =dum; */
                   1548: /*       } else { /\* end *\/ */
                   1549: /* #ifdef DEBUG */
                   1550: /*       printf("mnbrak3  fu < fc \n"); */
                   1551: /*       fprintf(ficlog, "mnbrak3 fu < fc\n"); */
                   1552: /* #endif */
                   1553: /*     dum=u; /\* Shifting c and u *\/ */
                   1554: /*     u = *cx; */
                   1555: /*     *cx = dum; */
                   1556: /*     dum = fu; */
                   1557: /*     fu = *fc; */
                   1558: /*     *fc =dum; */
                   1559: /*       } */
1.183     brouard  1560: #ifdef DEBUG
1.191     brouard  1561:       printf("mnbrak34  fu < or >= fc \n");
                   1562:       fprintf(ficlog, "mnbrak34 fu < fc\n");
1.183     brouard  1563: #endif
1.191     brouard  1564:       dum=u; /* Shifting c and u */
                   1565:       u = *cx;
                   1566:       *cx = dum;
                   1567:       dum = fu;
                   1568:       fu = *fc;
                   1569:       *fc =dum;
1.183     brouard  1570: #endif
1.162     brouard  1571:     } else if ((*cx-u)*(u-ulim) > 0.0) { /* u is after c but before ulim */
1.183     brouard  1572: #ifdef DEBUG
                   1573:       printf("mnbrak2  u after c but before ulim\n");
                   1574:       fprintf(ficlog, "mnbrak2 u after c but before ulim\n");
                   1575: #endif
1.126     brouard  1576:       fu=(*func)(u); 
                   1577:       if (fu < *fc) { 
1.183     brouard  1578: #ifdef DEBUG
                   1579:       printf("mnbrak2  u after c but before ulim AND fu < fc\n");
                   1580:       fprintf(ficlog, "mnbrak2 u after c but before ulim AND fu <fc \n");
                   1581: #endif
1.126     brouard  1582:        SHFT(*bx,*cx,u,*cx+GOLD*(*cx-*bx)) 
1.183     brouard  1583:        SHFT(*fb,*fc,fu,(*func)(u)) 
                   1584:       } 
1.162     brouard  1585:     } else if ((u-ulim)*(ulim-*cx) >= 0.0) { /* u outside ulim (verifying that ulim is beyond c) */
1.183     brouard  1586: #ifdef DEBUG
                   1587:       printf("mnbrak2  u outside ulim (verifying that ulim is beyond c)\n");
                   1588:       fprintf(ficlog, "mnbrak2 u outside ulim (verifying that ulim is beyond c)\n");
                   1589: #endif
1.126     brouard  1590:       u=ulim; 
                   1591:       fu=(*func)(u); 
1.183     brouard  1592:     } else { /* u could be left to b (if r > q parabola has a maximum) */
                   1593: #ifdef DEBUG
                   1594:       printf("mnbrak2  u could be left to b (if r > q parabola has a maximum)\n");
                   1595:       fprintf(ficlog, "mnbrak2  u could be left to b (if r > q parabola has a maximum)\n");
                   1596: #endif
1.126     brouard  1597:       u=(*cx)+GOLD*(*cx-*bx); 
                   1598:       fu=(*func)(u); 
1.183     brouard  1599:     } /* end tests */
1.126     brouard  1600:     SHFT(*ax,*bx,*cx,u) 
1.183     brouard  1601:     SHFT(*fa,*fb,*fc,fu) 
                   1602: #ifdef DEBUG
                   1603:       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);
                   1604:       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);
                   1605: #endif
                   1606:   } /* 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  1607: } 
                   1608: 
                   1609: /*************** linmin ************************/
1.162     brouard  1610: /* Given an n -dimensional point p[1..n] and an n -dimensional direction xi[1..n] , moves and
                   1611: resets p to where the function func(p) takes on a minimum along the direction xi from p ,
                   1612: and replaces xi by the actual vector displacement that p was moved. Also returns as fret
                   1613: the value of func at the returned location p . This is actually all accomplished by calling the
                   1614: routines mnbrak and brent .*/
1.126     brouard  1615: int ncom; 
                   1616: double *pcom,*xicom;
                   1617: double (*nrfunc)(double []); 
                   1618:  
                   1619: void linmin(double p[], double xi[], int n, double *fret,double (*func)(double [])) 
                   1620: { 
                   1621:   double brent(double ax, double bx, double cx, 
                   1622:               double (*f)(double), double tol, double *xmin); 
                   1623:   double f1dim(double x); 
                   1624:   void mnbrak(double *ax, double *bx, double *cx, double *fa, double *fb, 
                   1625:              double *fc, double (*func)(double)); 
                   1626:   int j; 
                   1627:   double xx,xmin,bx,ax; 
                   1628:   double fx,fb,fa;
1.187     brouard  1629: 
1.203     brouard  1630: #ifdef LINMINORIGINAL
                   1631: #else
                   1632:   double scale=10., axs, xxs; /* Scale added for infinity */
                   1633: #endif
                   1634:   
1.126     brouard  1635:   ncom=n; 
                   1636:   pcom=vector(1,n); 
                   1637:   xicom=vector(1,n); 
                   1638:   nrfunc=func; 
                   1639:   for (j=1;j<=n;j++) { 
                   1640:     pcom[j]=p[j]; 
1.202     brouard  1641:     xicom[j]=xi[j]; /* Former scale xi[j] of currrent direction i */
1.126     brouard  1642:   } 
1.187     brouard  1643: 
1.203     brouard  1644: #ifdef LINMINORIGINAL
                   1645:   xx=1.;
                   1646: #else
                   1647:   axs=0.0;
                   1648:   xxs=1.;
                   1649:   do{
                   1650:     xx= xxs;
                   1651: #endif
1.187     brouard  1652:     ax=0.;
                   1653:     mnbrak(&ax,&xx,&bx,&fa,&fx,&fb,f1dim);  /* Outputs: xtx[j]=pcom[j]+(*xx)*xicom[j]; fx=f(xtx[j]) */
                   1654:     /* brackets with inputs ax=0 and xx=1, but points, pcom=p, and directions values, xicom=xi, are sent via f1dim(x) */
                   1655:     /* 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))   */
                   1656:     /* Outputs: fa=f(p(j)) and fx=f(p(j) + xxs * xi(j) ) and f(bx)= f(p(j)+ bx* xi(j)) */
                   1657:     /* Given input ax=axs and xx=xxs, xx might be too far from ax to get a finite f(xx) */
                   1658:     /* Searches on line, outputs (ax, xx, bx) such that fx < min(fa and fb) */
                   1659:     /* 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.203     brouard  1660: #ifdef LINMINORIGINAL
                   1661: #else
                   1662:     if (fx != fx){
                   1663:        xxs=xxs/scale; /* Trying a smaller xx, closer to initial ax=0 */
                   1664:        printf("|");
                   1665:        fprintf(ficlog,"|");
                   1666: #ifdef DEBUGLINMIN
                   1667:        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);
                   1668: #endif
                   1669:     }
                   1670:   }while(fx != fx);
                   1671: #endif
                   1672:   
1.191     brouard  1673: #ifdef DEBUGLINMIN
                   1674:   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);
1.202     brouard  1675:   fprintf(ficlog,"\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);
1.191     brouard  1676: #endif
1.187     brouard  1677:   *fret=brent(ax,xx,bx,f1dim,TOL,&xmin); /* Giving a bracketting triplet (ax, xx, bx), find a minimum, xmin, according to f1dim, *fret(xmin),*/
                   1678:   /* fa = f(p[j] + ax * xi[j]), fx = f(p[j] + xx * xi[j]), fb = f(p[j] + bx * xi[j]) */
                   1679:   /* fmin = f(p[j] + xmin * xi[j]) */
                   1680:   /* P+lambda n in that direction (lambdamin), with TOL between abscisses */
                   1681:   /* f1dim(xmin): for (j=1;j<=ncom;j++) xt[j]=pcom[j]+xmin*xicom[j]; */
1.126     brouard  1682: #ifdef DEBUG
                   1683:   printf("retour brent fret=%.12e xmin=%.12e\n",*fret,xmin);
                   1684:   fprintf(ficlog,"retour brent fret=%.12e xmin=%.12e\n",*fret,xmin);
                   1685: #endif
1.191     brouard  1686: #ifdef DEBUGLINMIN
                   1687:   printf("linmin end ");
1.202     brouard  1688:   fprintf(ficlog,"linmin end ");
1.191     brouard  1689: #endif
1.126     brouard  1690:   for (j=1;j<=n;j++) { 
1.203     brouard  1691: #ifdef LINMINORIGINAL
                   1692:     xi[j] *= xmin; 
                   1693: #else
                   1694: #ifdef DEBUGLINMIN
                   1695:     if(xxs <1.0)
                   1696:       printf(" before xi[%d]=%12.8f", j,xi[j]);
                   1697: #endif
                   1698:     xi[j] *= xmin*xxs; /* xi rescaled by xmin and number of loops: if xmin=-1.237 and xi=(1,0,...,0) xi=(-1.237,0,...,0) */
                   1699: #ifdef DEBUGLINMIN
                   1700:     if(xxs <1.0)
                   1701:       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 );
                   1702: #endif
                   1703: #endif
1.187     brouard  1704:     p[j] += xi[j]; /* Parameters values are updated accordingly */
1.126     brouard  1705:   } 
1.191     brouard  1706: #ifdef DEBUGLINMIN
1.203     brouard  1707:   printf("\n");
1.191     brouard  1708:   printf("Comparing last *frec(xmin=%12.8f)=%12.8f from Brent and frec(0.)=%12.8f \n", xmin, *fret, (*func)(p));
1.202     brouard  1709:   fprintf(ficlog,"Comparing last *frec(xmin=%12.8f)=%12.8f from Brent and frec(0.)=%12.8f \n", xmin, *fret, (*func)(p));
1.191     brouard  1710:   for (j=1;j<=n;j++) { 
1.202     brouard  1711:     printf(" xi[%d]= %14.10f p[%d]= %12.7f",j,xi[j],j,p[j]);
                   1712:     fprintf(ficlog," xi[%d]= %14.10f p[%d]= %12.7f",j,xi[j],j,p[j]);
                   1713:     if(j % ncovmodel == 0){
1.191     brouard  1714:       printf("\n");
1.202     brouard  1715:       fprintf(ficlog,"\n");
                   1716:     }
1.191     brouard  1717:   }
1.203     brouard  1718: #else
1.191     brouard  1719: #endif
1.126     brouard  1720:   free_vector(xicom,1,n); 
                   1721:   free_vector(pcom,1,n); 
                   1722: } 
                   1723: 
                   1724: 
                   1725: /*************** powell ************************/
1.162     brouard  1726: /*
                   1727: Minimization of a function func of n variables. Input consists of an initial starting point
                   1728: p[1..n] ; an initial matrix xi[1..n][1..n] , whose columns contain the initial set of di-
                   1729: rections (usually the n unit vectors); and ftol , the fractional tolerance in the function value
                   1730: such that failure to decrease by more than this amount on one iteration signals doneness. On
                   1731: output, p is set to the best point found, xi is the then-current direction set, fret is the returned
                   1732: function value at p , and iter is the number of iterations taken. The routine linmin is used.
                   1733:  */
1.126     brouard  1734: void powell(double p[], double **xi, int n, double ftol, int *iter, double *fret, 
                   1735:            double (*func)(double [])) 
                   1736: { 
                   1737:   void linmin(double p[], double xi[], int n, double *fret, 
                   1738:              double (*func)(double [])); 
                   1739:   int i,ibig,j; 
                   1740:   double del,t,*pt,*ptt,*xit;
1.181     brouard  1741:   double directest;
1.126     brouard  1742:   double fp,fptt;
                   1743:   double *xits;
                   1744:   int niterf, itmp;
                   1745: 
                   1746:   pt=vector(1,n); 
                   1747:   ptt=vector(1,n); 
                   1748:   xit=vector(1,n); 
                   1749:   xits=vector(1,n); 
                   1750:   *fret=(*func)(p); 
                   1751:   for (j=1;j<=n;j++) pt[j]=p[j]; 
1.202     brouard  1752:   rcurr_time = time(NULL);  
1.126     brouard  1753:   for (*iter=1;;++(*iter)) { 
1.187     brouard  1754:     fp=(*fret); /* From former iteration or initial value */
1.126     brouard  1755:     ibig=0; 
                   1756:     del=0.0; 
1.157     brouard  1757:     rlast_time=rcurr_time;
                   1758:     /* (void) gettimeofday(&curr_time,&tzp); */
                   1759:     rcurr_time = time(NULL);  
                   1760:     curr_time = *localtime(&rcurr_time);
                   1761:     printf("\nPowell iter=%d -2*LL=%.12f %ld sec. %ld sec.",*iter,*fret, rcurr_time-rlast_time, rcurr_time-rstart_time);fflush(stdout);
                   1762:     fprintf(ficlog,"\nPowell iter=%d -2*LL=%.12f %ld sec. %ld sec.",*iter,*fret,rcurr_time-rlast_time, rcurr_time-rstart_time); fflush(ficlog);
                   1763: /*     fprintf(ficrespow,"%d %.12f %ld",*iter,*fret,curr_time.tm_sec-start_time.tm_sec); */
1.192     brouard  1764:     for (i=1;i<=n;i++) {
1.126     brouard  1765:       printf(" %d %.12f",i, p[i]);
                   1766:       fprintf(ficlog," %d %.12lf",i, p[i]);
                   1767:       fprintf(ficrespow," %.12lf", p[i]);
                   1768:     }
                   1769:     printf("\n");
                   1770:     fprintf(ficlog,"\n");
                   1771:     fprintf(ficrespow,"\n");fflush(ficrespow);
                   1772:     if(*iter <=3){
1.157     brouard  1773:       tml = *localtime(&rcurr_time);
                   1774:       strcpy(strcurr,asctime(&tml));
                   1775:       rforecast_time=rcurr_time; 
1.126     brouard  1776:       itmp = strlen(strcurr);
                   1777:       if(strcurr[itmp-1]=='\n')  /* Windows outputs with a new line */
                   1778:        strcurr[itmp-1]='\0';
1.162     brouard  1779:       printf("\nConsidering the time needed for the last iteration #%d: %ld seconds,\n",*iter,rcurr_time-rlast_time);
1.157     brouard  1780:       fprintf(ficlog,"\nConsidering the time needed for this last iteration #%d: %ld seconds,\n",*iter,rcurr_time-rlast_time);
1.126     brouard  1781:       for(niterf=10;niterf<=30;niterf+=10){
1.157     brouard  1782:        rforecast_time=rcurr_time+(niterf-*iter)*(rcurr_time-rlast_time);
                   1783:        forecast_time = *localtime(&rforecast_time);
                   1784:        strcpy(strfor,asctime(&forecast_time));
1.126     brouard  1785:        itmp = strlen(strfor);
                   1786:        if(strfor[itmp-1]=='\n')
                   1787:        strfor[itmp-1]='\0';
1.157     brouard  1788:        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);
                   1789:        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  1790:       }
                   1791:     }
1.187     brouard  1792:     for (i=1;i<=n;i++) { /* For each direction i */
                   1793:       for (j=1;j<=n;j++) xit[j]=xi[j][i]; /* Directions stored from previous iteration with previous scales */
1.126     brouard  1794:       fptt=(*fret); 
                   1795: #ifdef DEBUG
1.203     brouard  1796:       printf("fret=%lf, %lf, %lf \n", *fret, *fret, *fret);
                   1797:       fprintf(ficlog, "fret=%lf, %lf, %lf \n", *fret, *fret, *fret);
1.126     brouard  1798: #endif
1.203     brouard  1799:       printf("%d",i);fflush(stdout); /* print direction (parameter) i */
1.126     brouard  1800:       fprintf(ficlog,"%d",i);fflush(ficlog);
1.188     brouard  1801:       linmin(p,xit,n,fret,func); /* Point p[n]. xit[n] has been loaded for direction i as input.*/
                   1802:                                    /* Outputs are fret(new point p) p is updated and xit rescaled */
                   1803:       if (fabs(fptt-(*fret)) > del) { /* We are keeping the max gain on each of the n directions */
                   1804:        /* because that direction will be replaced unless the gain del is small */
                   1805:        /* in comparison with the 'probable' gain, mu^2, with the last average direction. */
                   1806:        /* Unless the n directions are conjugate some gain in the determinant may be obtained */
                   1807:        /* with the new direction. */
1.126     brouard  1808:        del=fabs(fptt-(*fret)); 
                   1809:        ibig=i; 
                   1810:       } 
                   1811: #ifdef DEBUG
                   1812:       printf("%d %.12e",i,(*fret));
                   1813:       fprintf(ficlog,"%d %.12e",i,(*fret));
                   1814:       for (j=1;j<=n;j++) {
                   1815:        xits[j]=FMAX(fabs(p[j]-pt[j]),1.e-5);
                   1816:        printf(" x(%d)=%.12e",j,xit[j]);
                   1817:        fprintf(ficlog," x(%d)=%.12e",j,xit[j]);
                   1818:       }
                   1819:       for(j=1;j<=n;j++) {
1.162     brouard  1820:        printf(" p(%d)=%.12e",j,p[j]);
                   1821:        fprintf(ficlog," p(%d)=%.12e",j,p[j]);
1.126     brouard  1822:       }
                   1823:       printf("\n");
                   1824:       fprintf(ficlog,"\n");
                   1825: #endif
1.187     brouard  1826:     } /* end loop on each direction i */
                   1827:     /* Convergence test will use last linmin estimation (fret) and compare former iteration (fp) */ 
1.188     brouard  1828:     /* But p and xit have been updated at the end of linmin, *fret corresponds to new p, xit  */
1.187     brouard  1829:     /* New value of last point Pn is not computed, P(n-1) */
1.182     brouard  1830:     if (2.0*fabs(fp-(*fret)) <= ftol*(fabs(fp)+fabs(*fret))) { /* Did we reach enough precision? */
1.188     brouard  1831:       /* We could compare with a chi^2. chisquare(0.95,ddl=1)=3.84 */
                   1832:       /* By adding age*age in a model, the new -2LL should be lower and the difference follows a */
                   1833:       /* a chisquare statistics with 1 degree. To be significant at the 95% level, it should have */
                   1834:       /* decreased of more than 3.84  */
                   1835:       /* By adding age*age and V1*age the gain (-2LL) should be more than 5.99 (ddl=2) */
                   1836:       /* By using V1+V2+V3, the gain should be  7.82, compared with basic 1+age. */
                   1837:       /* By adding 10 parameters more the gain should be 18.31 */
                   1838: 
                   1839:       /* Starting the program with initial values given by a former maximization will simply change */
                   1840:       /* the scales of the directions and the directions, because the are reset to canonical directions */
                   1841:       /* Thus the first calls to linmin will give new points and better maximizations until fp-(*fret) is */
                   1842:       /* under the tolerance value. If the tolerance is very small 1.e-9, it could last long.  */
1.126     brouard  1843: #ifdef DEBUG
                   1844:       int k[2],l;
                   1845:       k[0]=1;
                   1846:       k[1]=-1;
                   1847:       printf("Max: %.12e",(*func)(p));
                   1848:       fprintf(ficlog,"Max: %.12e",(*func)(p));
                   1849:       for (j=1;j<=n;j++) {
                   1850:        printf(" %.12e",p[j]);
                   1851:        fprintf(ficlog," %.12e",p[j]);
                   1852:       }
                   1853:       printf("\n");
                   1854:       fprintf(ficlog,"\n");
                   1855:       for(l=0;l<=1;l++) {
                   1856:        for (j=1;j<=n;j++) {
                   1857:          ptt[j]=p[j]+(p[j]-pt[j])*k[l];
                   1858:          printf("l=%d j=%d ptt=%.12e, xits=%.12e, p=%.12e, xit=%.12e", l,j,ptt[j],xits[j],p[j],xit[j]);
                   1859:          fprintf(ficlog,"l=%d j=%d ptt=%.12e, xits=%.12e, p=%.12e, xit=%.12e", l,j,ptt[j],xits[j],p[j],xit[j]);
                   1860:        }
                   1861:        printf("func(ptt)=%.12e, deriv=%.12e\n",(*func)(ptt),(ptt[j]-p[j])/((*func)(ptt)-(*func)(p)));
                   1862:        fprintf(ficlog,"func(ptt)=%.12e, deriv=%.12e\n",(*func)(ptt),(ptt[j]-p[j])/((*func)(ptt)-(*func)(p)));
                   1863:       }
                   1864: #endif
                   1865: 
                   1866: 
                   1867:       free_vector(xit,1,n); 
                   1868:       free_vector(xits,1,n); 
                   1869:       free_vector(ptt,1,n); 
                   1870:       free_vector(pt,1,n); 
                   1871:       return; 
1.192     brouard  1872:     } /* enough precision */ 
1.126     brouard  1873:     if (*iter == ITMAX) nrerror("powell exceeding maximum iterations."); 
1.181     brouard  1874:     for (j=1;j<=n;j++) { /* Computes the extrapolated point P_0 + 2 (P_n-P_0) */
1.126     brouard  1875:       ptt[j]=2.0*p[j]-pt[j]; 
                   1876:       xit[j]=p[j]-pt[j]; 
                   1877:       pt[j]=p[j]; 
                   1878:     } 
1.181     brouard  1879:     fptt=(*func)(ptt); /* f_3 */
1.192     brouard  1880: #ifdef POWELLF1F3
                   1881: #else
1.161     brouard  1882:     if (fptt < fp) { /* If extrapolated point is better, decide if we keep that new direction or not */
1.192     brouard  1883: #endif
1.162     brouard  1884:       /* (x1 f1=fp), (x2 f2=*fret), (x3 f3=fptt), (xm fm) */
1.161     brouard  1885:       /* From x1 (P0) distance of x2 is at h and x3 is 2h */
1.162     brouard  1886:       /* Let f"(x2) be the 2nd derivative equal everywhere.  */
                   1887:       /* Then the parabolic through (x1,f1), (x2,f2) and (x3,f3) */
                   1888:       /* will reach at f3 = fm + h^2/2 f"m  ; f" = (f1 -2f2 +f3 ) / h**2 */
1.181     brouard  1889:       /* Conditional for using this new direction is that mu^2 = (f1-2f2+f3)^2 /2 < del */
1.161     brouard  1890:       /* t=2.0*(fp-2.0*(*fret)+fptt)*SQR(fp-(*fret)-del)-del*SQR(fp-fptt); */
1.183     brouard  1891: #ifdef NRCORIGINAL
                   1892:       t=2.0*(fp-2.0*(*fret)+fptt)*SQR(fp-(*fret)-del)- del*SQR(fp-fptt); /* Original Numerical Recipes in C*/
                   1893: #else
                   1894:       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  1895:       t= t- del*SQR(fp-fptt);
1.183     brouard  1896: #endif
1.202     brouard  1897:       directest = fp-2.0*(*fret)+fptt - 2.0 * del; /* If delta was big enough we change it for a new direction */
1.161     brouard  1898: #ifdef DEBUG
1.181     brouard  1899:       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);
                   1900:       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  1901:       printf("t3= %.12lf, t4= %.12lf, t3*= %.12lf, t4*= %.12lf\n",SQR(fp-(*fret)-del),SQR(fp-fptt),
                   1902:             (fp-(*fret)-del)*(fp-(*fret)-del),(fp-fptt)*(fp-fptt));
                   1903:       fprintf(ficlog,"t3= %.12lf, t4= %.12lf, t3*= %.12lf, t4*= %.12lf\n",SQR(fp-(*fret)-del),SQR(fp-fptt),
                   1904:             (fp-(*fret)-del)*(fp-(*fret)-del),(fp-fptt)*(fp-fptt));
                   1905:       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);
                   1906:       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);
                   1907: #endif
1.183     brouard  1908: #ifdef POWELLORIGINAL
                   1909:       if (t < 0.0) { /* Then we use it for new direction */
                   1910: #else
1.182     brouard  1911:       if (directest*t < 0.0) { /* Contradiction between both tests */
1.202     brouard  1912:        printf("directest= %.12lf (if <0 we include P0 Pn as new direction), t= %.12lf, f1= %.12lf,f2= %.12lf,f3= %.12lf, del= %.12lf\n",directest, t, fp,(*fret),fptt,del);
1.192     brouard  1913:         printf("f1-2f2+f3= %.12lf, f1-f2-del= %.12lf, f1-f3= %.12lf\n",fp-2.0*(*fret)+fptt, fp -(*fret) -del, fp-fptt);
1.202     brouard  1914:         fprintf(ficlog,"directest= %.12lf (if <0 we include P0 Pn as new direction), t= %.12lf, f1= %.12lf,f2= %.12lf,f3= %.12lf, del= %.12lf\n",directest, t, fp,(*fret),fptt, del);
1.192     brouard  1915:         fprintf(ficlog,"f1-2f2+f3= %.12lf, f1-f2-del= %.12lf, f1-f3= %.12lf\n",fp-2.0*(*fret)+fptt, fp -(*fret) -del, fp-fptt);
                   1916:       } 
1.181     brouard  1917:       if (directest < 0.0) { /* Then we use it for new direction */
                   1918: #endif
1.191     brouard  1919: #ifdef DEBUGLINMIN
                   1920:        printf("Before linmin in direction P%d-P0\n",n);
                   1921:        for (j=1;j<=n;j++) { 
1.202     brouard  1922:          printf(" Before xit[%d]= %12.7f p[%d]= %12.7f",j,xit[j],j,p[j]);
                   1923:          fprintf(ficlog," Before xit[%d]= %12.7f p[%d]= %12.7f",j,xit[j],j,p[j]);
                   1924:          if(j % ncovmodel == 0){
1.191     brouard  1925:            printf("\n");
1.202     brouard  1926:            fprintf(ficlog,"\n");
                   1927:          }
1.191     brouard  1928:        }
                   1929: #endif
1.187     brouard  1930:        linmin(p,xit,n,fret,func); /* computes minimum on the extrapolated direction: changes p and rescales xit.*/
1.191     brouard  1931: #ifdef DEBUGLINMIN
                   1932:        for (j=1;j<=n;j++) { 
                   1933:          printf("After xit[%d]= %12.7f p[%d]= %12.7f",j,xit[j],j,p[j]);
1.202     brouard  1934:          fprintf(ficlog,"After xit[%d]= %12.7f p[%d]= %12.7f",j,xit[j],j,p[j]);
                   1935:          if(j % ncovmodel == 0){
1.191     brouard  1936:            printf("\n");
1.202     brouard  1937:            fprintf(ficlog,"\n");
                   1938:          }
1.191     brouard  1939:        }
                   1940: #endif
1.126     brouard  1941:        for (j=1;j<=n;j++) { 
1.181     brouard  1942:          xi[j][ibig]=xi[j][n]; /* Replace direction with biggest decrease by last direction n */
                   1943:          xi[j][n]=xit[j];      /* and this nth direction by the by the average p_0 p_n */
1.126     brouard  1944:        }
1.181     brouard  1945:        printf("Gaining to use new average direction of P0 P%d instead of biggest increase direction %d :\n",n,ibig);
                   1946:        fprintf(ficlog,"Gaining to use new average direction of P0 P%d instead of biggest increase direction %d :\n",n,ibig);
1.161     brouard  1947: 
1.126     brouard  1948: #ifdef DEBUG
1.164     brouard  1949:        printf("Direction changed  last moved %d in place of ibig=%d, new last is the average:\n",n,ibig);
                   1950:        fprintf(ficlog,"Direction changed  last moved %d in place of ibig=%d, new last is the average:\n",n,ibig);
1.126     brouard  1951:        for(j=1;j<=n;j++){
                   1952:          printf(" %.12e",xit[j]);
                   1953:          fprintf(ficlog," %.12e",xit[j]);
                   1954:        }
                   1955:        printf("\n");
                   1956:        fprintf(ficlog,"\n");
                   1957: #endif
1.192     brouard  1958:       } /* end of t or directest negative */
                   1959: #ifdef POWELLF1F3
                   1960: #else
1.162     brouard  1961:     } /* end if (fptt < fp)  */
1.192     brouard  1962: #endif
                   1963:   } /* loop iteration */ 
1.126     brouard  1964: } 
                   1965: 
                   1966: /**** Prevalence limit (stable or period prevalence)  ****************/
                   1967: 
1.203     brouard  1968: double **prevalim(double **prlim, int nlstate, double x[], double age, double **oldm, double **savm, double ftolpl, int *ncvyear, int ij)
1.126     brouard  1969: {
                   1970:   /* Computes the prevalence limit in each live state at age x by left multiplying the unit
1.203     brouard  1971:      matrix by transitions matrix until convergence is reached with precision ftolpl */
1.206     brouard  1972:   /* Wx= Wx-1 Px-1= Wx-2 Px-2 Px-1  = Wx-n Px-n ... Px-2 Px-1 I */
                   1973:   /* Wx is row vector: population in state 1, population in state 2, population dead */
                   1974:   /* or prevalence in state 1, prevalence in state 2, 0 */
                   1975:   /* newm is the matrix after multiplications, its rows are identical at a factor */
                   1976:   /* Initial matrix pimij */
                   1977:   /* {0.85204250825084937, 0.13044499163996345, 0.017512500109187184, */
                   1978:   /* 0.090851990222114765, 0.88271245433047185, 0.026435555447413338, */
                   1979:   /*  0,                   0                  , 1} */
                   1980:   /*
                   1981:    * and after some iteration: */
                   1982:   /* {0.45504275246439968, 0.42731458730878791, 0.11764266022681241, */
                   1983:   /*  0.45201005341706885, 0.42865420071559901, 0.11933574586733192, */
                   1984:   /*  0,                   0                  , 1} */
                   1985:   /* And prevalence by suppressing the deaths are close to identical rows in prlim: */
                   1986:   /* {0.51571254859325999, 0.4842874514067399, */
                   1987:   /*  0.51326036147820708, 0.48673963852179264} */
                   1988:   /* If we start from prlim again, prlim tends to a constant matrix */
                   1989: 
1.126     brouard  1990:   int i, ii,j,k;
1.209   ! brouard  1991:   double *min, *max, *meandiff, maxmax,sumnew=0.;
1.145     brouard  1992:   /* double **matprod2(); */ /* test */
1.131     brouard  1993:   double **out, cov[NCOVMAX+1], **pmij();
1.126     brouard  1994:   double **newm;
1.209   ! brouard  1995:   double agefin, delaymax=200. ; /* 100 Max number of years to converge */
1.203     brouard  1996:   int ncvloop=0;
1.169     brouard  1997:   
1.209   ! brouard  1998:   min=vector(1,nlstate);
        !          1999:   max=vector(1,nlstate);
        !          2000:   meandiff=vector(1,nlstate);
        !          2001: 
1.126     brouard  2002:   for (ii=1;ii<=nlstate+ndeath;ii++)
                   2003:     for (j=1;j<=nlstate+ndeath;j++){
                   2004:       oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   2005:     }
1.169     brouard  2006:   
                   2007:   cov[1]=1.;
                   2008:   
                   2009:   /* Even if hstepm = 1, at least one multiplication by the unit matrix */
1.202     brouard  2010:   /* Start at agefin= age, computes the matrix of passage and loops decreasing agefin until convergence is reached */
1.126     brouard  2011:   for(agefin=age-stepm/YEARM; agefin>=age-delaymax; agefin=agefin-stepm/YEARM){
1.202     brouard  2012:     ncvloop++;
1.126     brouard  2013:     newm=savm;
                   2014:     /* Covariates have to be included here again */
1.138     brouard  2015:     cov[2]=agefin;
1.187     brouard  2016:     if(nagesqr==1)
                   2017:       cov[3]= agefin*agefin;;
1.138     brouard  2018:     for (k=1; k<=cptcovn;k++) {
1.200     brouard  2019:       /* cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(ij,Tvar[k])]; */
                   2020:       cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(ij,k)];
1.198     brouard  2021:       /* 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  2022:     }
1.186     brouard  2023:     /*wrong? for (k=1; k<=cptcovage;k++) cov[2+Tage[k]]=cov[2+Tage[k]]*cov[2]; */
1.200     brouard  2024:     /* for (k=1; k<=cptcovage;k++) cov[2+nagesqr+Tage[k]]=nbcode[Tvar[k]][codtabm(ij,Tvar[k])]*cov[2]; */
                   2025:     for (k=1; k<=cptcovage;k++) cov[2+nagesqr+Tage[k]]=nbcode[Tvar[k]][codtabm(ij,k)]*cov[2];
1.186     brouard  2026:     for (k=1; k<=cptcovprod;k++) /* Useless */
1.200     brouard  2027:       /* cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,Tvard[k][1])] * nbcode[Tvard[k][2]][codtabm(ij,Tvard[k][2])]; */
                   2028:       cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,k)] * nbcode[Tvard[k][2]][codtabm(ij,k)];
1.138     brouard  2029:     
                   2030:     /*printf("ij=%d cptcovprod=%d tvar=%d ", ij, cptcovprod, Tvar[1]);*/
                   2031:     /*printf("ij=%d cov[3]=%lf cov[4]=%lf \n",ij, cov[3],cov[4]);*/
                   2032:     /*printf("ij=%d cov[3]=%lf \n",ij, cov[3]);*/
1.145     brouard  2033:     /* savm=pmij(pmmij,cov,ncovmodel,x,nlstate); */
                   2034:     /* out=matprod2(newm, pmij(pmmij,cov,ncovmodel,x,nlstate),1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, oldm); /\* Bug Valgrind *\/ */
1.142     brouard  2035:     out=matprod2(newm, pmij(pmmij,cov,ncovmodel,x,nlstate),1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, oldm); /* Bug Valgrind */
1.138     brouard  2036:     
1.126     brouard  2037:     savm=oldm;
                   2038:     oldm=newm;
1.209   ! brouard  2039: 
        !          2040:     for(j=1; j<=nlstate; j++){
        !          2041:       max[j]=0.;
        !          2042:       min[j]=1.;
        !          2043:     }
        !          2044:     for(i=1;i<=nlstate;i++){
        !          2045:       sumnew=0;
        !          2046:       for(k=1; k<=ndeath; k++) sumnew+=newm[i][nlstate+k];
        !          2047:       for(j=1; j<=nlstate; j++){ 
        !          2048:        prlim[i][j]= newm[i][j]/(1-sumnew);
        !          2049:        max[j]=FMAX(max[j],prlim[i][j]);
        !          2050:        min[j]=FMIN(min[j],prlim[i][j]);
        !          2051:       }
        !          2052:     }
        !          2053: 
1.126     brouard  2054:     maxmax=0.;
1.209   ! brouard  2055:     for(j=1; j<=nlstate; j++){
        !          2056:       meandiff[j]=(max[j]-min[j])/(max[j]+min[j])*2.; /* mean difference for each column */
        !          2057:       maxmax=FMAX(maxmax,meandiff[j]);
        !          2058:       /* printf(" age= %d meandiff[%d]=%f, agefin=%d max[%d]=%f min[%d]=%f maxmax=%f\n", (int)age, j, meandiff[j],(int)agefin, j, max[j], j, min[j],maxmax); */
1.169     brouard  2059:     } /* j loop */
1.203     brouard  2060:     *ncvyear= (int)age- (int)agefin;
1.208     brouard  2061:     /* printf("maxmax=%lf maxmin=%lf ncvloop=%d, age=%d, agefin=%d ncvyear=%d \n", maxmax, maxmin, ncvloop, (int)age, (int)agefin, *ncvyear); */
1.126     brouard  2062:     if(maxmax < ftolpl){
1.209   ! brouard  2063:       /* printf("maxmax=%lf ncvloop=%ld, age=%d, agefin=%d ncvyear=%d \n", maxmax, ncvloop, (int)age, (int)agefin, *ncvyear); */
        !          2064:       free_vector(min,1,nlstate);
        !          2065:       free_vector(max,1,nlstate);
        !          2066:       free_vector(meandiff,1,nlstate);
1.126     brouard  2067:       return prlim;
                   2068:     }
1.169     brouard  2069:   } /* age loop */
1.208     brouard  2070:     /* After some age loop it doesn't converge */
1.209   ! brouard  2071:   printf("Warning: the stable prevalence at age %d did not converge with the required precision (%g > ftolpl=%g) within %.0f years. Try to lower 'ftolpl'. \n\
1.208     brouard  2072: Earliest age to start was %d-%d=%d, ncvloop=%d, ncvyear=%d\n", (int)age, maxmax, ftolpl, delaymax, (int)age, (int)delaymax, (int)agefin, ncvloop, *ncvyear);
1.209   ! brouard  2073:   /* Try to lower 'ftol', for example from 1.e-8 to 6.e-9.\n", ftolpl, (int)age, (int)delaymax, (int)agefin, ncvloop, (int)age-(int)agefin); */
        !          2074:   free_vector(min,1,nlstate);
        !          2075:   free_vector(max,1,nlstate);
        !          2076:   free_vector(meandiff,1,nlstate);
1.208     brouard  2077:   
1.169     brouard  2078:   return prlim; /* should not reach here */
1.126     brouard  2079: }
                   2080: 
                   2081: /*************** transition probabilities ***************/ 
                   2082: 
                   2083: double **pmij(double **ps, double *cov, int ncovmodel, double *x, int nlstate )
                   2084: {
1.138     brouard  2085:   /* According to parameters values stored in x and the covariate's values stored in cov,
                   2086:      computes the probability to be observed in state j being in state i by appying the
                   2087:      model to the ncovmodel covariates (including constant and age).
                   2088:      lnpijopii=ln(pij/pii)= aij+bij*age+cij*v1+dij*v2+... = sum_nc=1^ncovmodel xij(nc)*cov[nc]
                   2089:      and, according on how parameters are entered, the position of the coefficient xij(nc) of the
                   2090:      ncth covariate in the global vector x is given by the formula:
                   2091:      j<i nc+((i-1)*(nlstate+ndeath-1)+j-1)*ncovmodel
                   2092:      j>=i nc + ((i-1)*(nlstate+ndeath-1)+(j-2))*ncovmodel
                   2093:      Computes ln(pij/pii) (lnpijopii), deduces pij/pii by exponentiation,
                   2094:      sums on j different of i to get 1-pii/pii, deduces pii, and then all pij.
                   2095:      Outputs ps[i][j] the probability to be observed in j being in j according to
                   2096:      the values of the covariates cov[nc] and corresponding parameter values x[nc+shiftij]
                   2097:   */
                   2098:   double s1, lnpijopii;
1.126     brouard  2099:   /*double t34;*/
1.164     brouard  2100:   int i,j, nc, ii, jj;
1.126     brouard  2101: 
                   2102:     for(i=1; i<= nlstate; i++){
                   2103:       for(j=1; j<i;j++){
1.138     brouard  2104:        for (nc=1, lnpijopii=0.;nc <=ncovmodel; nc++){
                   2105:          /*lnpijopii += param[i][j][nc]*cov[nc];*/
                   2106:          lnpijopii += x[nc+((i-1)*(nlstate+ndeath-1)+j-1)*ncovmodel]*cov[nc];
                   2107: /*      printf("Int j<i s1=%.17e, lnpijopii=%.17e\n",s1,lnpijopii); */
1.126     brouard  2108:        }
1.138     brouard  2109:        ps[i][j]=lnpijopii; /* In fact ln(pij/pii) */
                   2110: /*     printf("s1=%.17e, lnpijopii=%.17e\n",s1,lnpijopii); */
1.126     brouard  2111:       }
                   2112:       for(j=i+1; j<=nlstate+ndeath;j++){
1.138     brouard  2113:        for (nc=1, lnpijopii=0.;nc <=ncovmodel; nc++){
                   2114:          /*lnpijopii += x[(i-1)*nlstate*ncovmodel+(j-2)*ncovmodel+nc+(i-1)*(ndeath-1)*ncovmodel]*cov[nc];*/
                   2115:          lnpijopii += x[nc + ((i-1)*(nlstate+ndeath-1)+(j-2))*ncovmodel]*cov[nc];
                   2116: /*       printf("Int j>i s1=%.17e, lnpijopii=%.17e %lx %lx\n",s1,lnpijopii,s1,lnpijopii); */
1.126     brouard  2117:        }
1.138     brouard  2118:        ps[i][j]=lnpijopii; /* In fact ln(pij/pii) */
1.126     brouard  2119:       }
                   2120:     }
                   2121:     
                   2122:     for(i=1; i<= nlstate; i++){
                   2123:       s1=0;
1.131     brouard  2124:       for(j=1; j<i; j++){
1.138     brouard  2125:        s1+=exp(ps[i][j]); /* In fact sums pij/pii */
1.131     brouard  2126:        /*printf("debug1 %d %d ps=%lf exp(ps)=%lf s1+=%lf\n",i,j,ps[i][j],exp(ps[i][j]),s1); */
                   2127:       }
                   2128:       for(j=i+1; j<=nlstate+ndeath; j++){
1.138     brouard  2129:        s1+=exp(ps[i][j]); /* In fact sums pij/pii */
1.131     brouard  2130:        /*printf("debug2 %d %d ps=%lf exp(ps)=%lf s1+=%lf\n",i,j,ps[i][j],exp(ps[i][j]),s1); */
                   2131:       }
1.138     brouard  2132:       /* s1= sum_{j<>i} pij/pii=(1-pii)/pii and thus pii is known from s1 */
1.126     brouard  2133:       ps[i][i]=1./(s1+1.);
1.138     brouard  2134:       /* Computing other pijs */
1.126     brouard  2135:       for(j=1; j<i; j++)
                   2136:        ps[i][j]= exp(ps[i][j])*ps[i][i];
                   2137:       for(j=i+1; j<=nlstate+ndeath; j++)
                   2138:        ps[i][j]= exp(ps[i][j])*ps[i][i];
                   2139:       /* ps[i][nlstate+1]=1.-s1- ps[i][i];*/ /* Sum should be 1 */
                   2140:     } /* end i */
                   2141:     
                   2142:     for(ii=nlstate+1; ii<= nlstate+ndeath; ii++){
                   2143:       for(jj=1; jj<= nlstate+ndeath; jj++){
                   2144:        ps[ii][jj]=0;
                   2145:        ps[ii][ii]=1;
                   2146:       }
                   2147:     }
                   2148:     
1.145     brouard  2149:     
                   2150:     /* for(ii=1; ii<= nlstate+ndeath; ii++){ */
                   2151:     /*   for(jj=1; jj<= nlstate+ndeath; jj++){ */
                   2152:     /*         printf(" pmij  ps[%d][%d]=%lf ",ii,jj,ps[ii][jj]); */
                   2153:     /*   } */
                   2154:     /*   printf("\n "); */
                   2155:     /* } */
                   2156:     /* printf("\n ");printf("%lf ",cov[2]);*/
                   2157:     /*
1.126     brouard  2158:       for(i=1; i<= npar; i++) printf("%f ",x[i]);
                   2159:       goto end;*/
                   2160:     return ps;
                   2161: }
                   2162: 
                   2163: /**************** Product of 2 matrices ******************/
                   2164: 
1.145     brouard  2165: double **matprod2(double **out, double **in,int nrl, int nrh, int ncl, int nch, int ncolol, int ncoloh, double **b)
1.126     brouard  2166: {
                   2167:   /* Computes the matrix product of in(1,nrh-nrl+1)(1,nch-ncl+1) times
                   2168:      b(1,nch-ncl+1)(1,ncoloh-ncolol+1) into out(...) */
                   2169:   /* in, b, out are matrice of pointers which should have been initialized 
                   2170:      before: only the contents of out is modified. The function returns
                   2171:      a pointer to pointers identical to out */
1.145     brouard  2172:   int i, j, k;
1.126     brouard  2173:   for(i=nrl; i<= nrh; i++)
1.145     brouard  2174:     for(k=ncolol; k<=ncoloh; k++){
                   2175:       out[i][k]=0.;
                   2176:       for(j=ncl; j<=nch; j++)
                   2177:        out[i][k] +=in[i][j]*b[j][k];
                   2178:     }
1.126     brouard  2179:   return out;
                   2180: }
                   2181: 
                   2182: 
                   2183: /************* Higher Matrix Product ***************/
                   2184: 
                   2185: double ***hpxij(double ***po, int nhstepm, double age, int hstepm, double *x, int nlstate, int stepm, double **oldm, double **savm, int ij )
                   2186: {
                   2187:   /* Computes the transition matrix starting at age 'age' over 
                   2188:      'nhstepm*hstepm*stepm' months (i.e. until
                   2189:      age (in years)  age+nhstepm*hstepm*stepm/12) by multiplying 
                   2190:      nhstepm*hstepm matrices. 
                   2191:      Output is stored in matrix po[i][j][h] for h every 'hstepm' step 
                   2192:      (typically every 2 years instead of every month which is too big 
                   2193:      for the memory).
                   2194:      Model is determined by parameters x and covariates have to be 
                   2195:      included manually here. 
                   2196: 
                   2197:      */
                   2198: 
                   2199:   int i, j, d, h, k;
1.131     brouard  2200:   double **out, cov[NCOVMAX+1];
1.126     brouard  2201:   double **newm;
1.187     brouard  2202:   double agexact;
1.126     brouard  2203: 
                   2204:   /* Hstepm could be zero and should return the unit matrix */
                   2205:   for (i=1;i<=nlstate+ndeath;i++)
                   2206:     for (j=1;j<=nlstate+ndeath;j++){
                   2207:       oldm[i][j]=(i==j ? 1.0 : 0.0);
                   2208:       po[i][j][0]=(i==j ? 1.0 : 0.0);
                   2209:     }
                   2210:   /* Even if hstepm = 1, at least one multiplication by the unit matrix */
                   2211:   for(h=1; h <=nhstepm; h++){
                   2212:     for(d=1; d <=hstepm; d++){
                   2213:       newm=savm;
                   2214:       /* Covariates have to be included here again */
                   2215:       cov[1]=1.;
1.187     brouard  2216:       agexact=age+((h-1)*hstepm + (d-1))*stepm/YEARM;
                   2217:       cov[2]=agexact;
                   2218:       if(nagesqr==1)
                   2219:        cov[3]= agexact*agexact;
1.131     brouard  2220:       for (k=1; k<=cptcovn;k++) 
1.200     brouard  2221:        cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(ij,k)];
                   2222:        /* cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(ij,Tvar[k])]; */
1.186     brouard  2223:       for (k=1; k<=cptcovage;k++) /* Should start at cptcovn+1 */
                   2224:        /* cov[2+Tage[k]]=cov[2+Tage[k]]*cov[2]; */
1.200     brouard  2225:        cov[2+nagesqr+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(ij,k)]*cov[2];
                   2226:        /* cov[2+nagesqr+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(ij,Tvar[Tage[k]])]*cov[2]; */
1.145     brouard  2227:       for (k=1; k<=cptcovprod;k++) /* Useless because included in cptcovn */
1.200     brouard  2228:        cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,k)]*nbcode[Tvard[k][2]][codtabm(ij,k)];
                   2229:        /* 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  2230: 
                   2231: 
                   2232:       /*printf("hxi cptcov=%d cptcode=%d\n",cptcov,cptcode);*/
                   2233:       /*printf("h=%d d=%d age=%f cov=%f\n",h,d,age,cov[2]);*/
                   2234:       out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, 
                   2235:                   pmij(pmmij,cov,ncovmodel,x,nlstate));
                   2236:       savm=oldm;
                   2237:       oldm=newm;
                   2238:     }
                   2239:     for(i=1; i<=nlstate+ndeath; i++)
                   2240:       for(j=1;j<=nlstate+ndeath;j++) {
                   2241:        po[i][j][h]=newm[i][j];
1.128     brouard  2242:        /*if(h==nhstepm) printf("po[%d][%d][%d]=%f ",i,j,h,po[i][j][h]);*/
1.126     brouard  2243:       }
1.128     brouard  2244:     /*printf("h=%d ",h);*/
1.126     brouard  2245:   } /* end h */
1.128     brouard  2246: /*     printf("\n H=%d \n",h); */
1.126     brouard  2247:   return po;
                   2248: }
                   2249: 
1.162     brouard  2250: #ifdef NLOPT
                   2251:   double  myfunc(unsigned n, const double *p1, double *grad, void *pd){
                   2252:   double fret;
                   2253:   double *xt;
                   2254:   int j;
                   2255:   myfunc_data *d2 = (myfunc_data *) pd;
                   2256: /* xt = (p1-1); */
                   2257:   xt=vector(1,n); 
                   2258:   for (j=1;j<=n;j++)   xt[j]=p1[j-1]; /* xt[1]=p1[0] */
                   2259: 
                   2260:   fret=(d2->function)(xt); /*  p xt[1]@8 is fine */
                   2261:   /* fret=(*func)(xt); /\*  p xt[1]@8 is fine *\/ */
                   2262:   printf("Function = %.12lf ",fret);
                   2263:   for (j=1;j<=n;j++) printf(" %d %.8lf", j, xt[j]); 
                   2264:   printf("\n");
                   2265:  free_vector(xt,1,n);
                   2266:   return fret;
                   2267: }
                   2268: #endif
1.126     brouard  2269: 
                   2270: /*************** log-likelihood *************/
                   2271: double func( double *x)
                   2272: {
                   2273:   int i, ii, j, k, mi, d, kk;
1.131     brouard  2274:   double l, ll[NLSTATEMAX+1], cov[NCOVMAX+1];
1.126     brouard  2275:   double **out;
                   2276:   double sw; /* Sum of weights */
                   2277:   double lli; /* Individual log likelihood */
                   2278:   int s1, s2;
                   2279:   double bbh, survp;
                   2280:   long ipmx;
1.187     brouard  2281:   double agexact;
1.126     brouard  2282:   /*extern weight */
                   2283:   /* We are differentiating ll according to initial status */
                   2284:   /*  for (i=1;i<=npar;i++) printf("%f ", x[i]);*/
                   2285:   /*for(i=1;i<imx;i++) 
                   2286:     printf(" %d\n",s[4][i]);
                   2287:   */
1.162     brouard  2288: 
                   2289:   ++countcallfunc;
                   2290: 
1.126     brouard  2291:   cov[1]=1.;
                   2292: 
                   2293:   for(k=1; k<=nlstate; k++) ll[k]=0.;
                   2294: 
                   2295:   if(mle==1){
                   2296:     for (i=1,ipmx=0, sw=0.; i<=imx; i++){
1.138     brouard  2297:       /* Computes the values of the ncovmodel covariates of the model
                   2298:         depending if the covariates are fixed or variying (age dependent) and stores them in cov[]
                   2299:         Then computes with function pmij which return a matrix p[i][j] giving the elementary probability
                   2300:         to be observed in j being in i according to the model.
                   2301:        */
1.145     brouard  2302:       for (k=1; k<=cptcovn;k++){ /* Simple and product covariates without age* products */
1.187     brouard  2303:          cov[2+nagesqr+k]=covar[Tvar[k]][i];
1.145     brouard  2304:       }
1.137     brouard  2305:       /* In model V2+V1*V4+age*V3+V3*V2 Tvar[1] is V2, Tvar[2=V1*V4] 
1.138     brouard  2306:         is 6, Tvar[3=age*V3] should not be computed because of age Tvar[4=V3*V2] 
1.137     brouard  2307:         has been calculated etc */
1.126     brouard  2308:       for(mi=1; mi<= wav[i]-1; mi++){
                   2309:        for (ii=1;ii<=nlstate+ndeath;ii++)
                   2310:          for (j=1;j<=nlstate+ndeath;j++){
                   2311:            oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   2312:            savm[ii][j]=(ii==j ? 1.0 : 0.0);
                   2313:          }
                   2314:        for(d=0; d<dh[mi][i]; d++){
                   2315:          newm=savm;
1.187     brouard  2316:          agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;
                   2317:          cov[2]=agexact;
                   2318:          if(nagesqr==1)
                   2319:            cov[3]= agexact*agexact;
1.126     brouard  2320:          for (kk=1; kk<=cptcovage;kk++) {
1.187     brouard  2321:            cov[Tage[kk]+2+nagesqr]=covar[Tvar[Tage[kk]]][i]*agexact; /* Tage[kk] gives the data-covariate associated with age */
1.126     brouard  2322:          }
                   2323:          out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
                   2324:                       1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
                   2325:          savm=oldm;
                   2326:          oldm=newm;
                   2327:        } /* end mult */
                   2328:       
                   2329:        /*lli=log(out[s[mw[mi][i]][i]][s[mw[mi+1][i]][i]]);*/ /* Original formula */
                   2330:        /* But now since version 0.9 we anticipate for bias at large stepm.
                   2331:         * If stepm is larger than one month (smallest stepm) and if the exact delay 
                   2332:         * (in months) between two waves is not a multiple of stepm, we rounded to 
                   2333:         * the nearest (and in case of equal distance, to the lowest) interval but now
                   2334:         * we keep into memory the bias bh[mi][i] and also the previous matrix product
                   2335:         * (i.e to dh[mi][i]-1) saved in 'savm'. Then we inter(extra)polate the
                   2336:         * probability in order to take into account the bias as a fraction of the way
                   2337:         * from savm to out if bh is negative or even beyond if bh is positive. bh varies
                   2338:         * -stepm/2 to stepm/2 .
                   2339:         * For stepm=1 the results are the same as for previous versions of Imach.
                   2340:         * For stepm > 1 the results are less biased than in previous versions. 
                   2341:         */
                   2342:        s1=s[mw[mi][i]][i];
                   2343:        s2=s[mw[mi+1][i]][i];
                   2344:        bbh=(double)bh[mi][i]/(double)stepm; 
                   2345:        /* bias bh is positive if real duration
                   2346:         * is higher than the multiple of stepm and negative otherwise.
                   2347:         */
                   2348:        /* lli= (savm[s1][s2]>1.e-8 ?(1.+bbh)*log(out[s1][s2])- bbh*log(savm[s1][s2]):log((1.+bbh)*out[s1][s2]));*/
                   2349:        if( s2 > nlstate){ 
                   2350:          /* i.e. if s2 is a death state and if the date of death is known 
                   2351:             then the contribution to the likelihood is the probability to 
                   2352:             die between last step unit time and current  step unit time, 
                   2353:             which is also equal to probability to die before dh 
                   2354:             minus probability to die before dh-stepm . 
                   2355:             In version up to 0.92 likelihood was computed
                   2356:        as if date of death was unknown. Death was treated as any other
                   2357:        health state: the date of the interview describes the actual state
                   2358:        and not the date of a change in health state. The former idea was
                   2359:        to consider that at each interview the state was recorded
                   2360:        (healthy, disable or death) and IMaCh was corrected; but when we
                   2361:        introduced the exact date of death then we should have modified
                   2362:        the contribution of an exact death to the likelihood. This new
                   2363:        contribution is smaller and very dependent of the step unit
                   2364:        stepm. It is no more the probability to die between last interview
                   2365:        and month of death but the probability to survive from last
                   2366:        interview up to one month before death multiplied by the
                   2367:        probability to die within a month. Thanks to Chris
                   2368:        Jackson for correcting this bug.  Former versions increased
                   2369:        mortality artificially. The bad side is that we add another loop
                   2370:        which slows down the processing. The difference can be up to 10%
                   2371:        lower mortality.
                   2372:          */
1.183     brouard  2373:        /* If, at the beginning of the maximization mostly, the
                   2374:           cumulative probability or probability to be dead is
                   2375:           constant (ie = 1) over time d, the difference is equal to
                   2376:           0.  out[s1][3] = savm[s1][3]: probability, being at state
                   2377:           s1 at precedent wave, to be dead a month before current
                   2378:           wave is equal to probability, being at state s1 at
                   2379:           precedent wave, to be dead at mont of the current
                   2380:           wave. Then the observed probability (that this person died)
                   2381:           is null according to current estimated parameter. In fact,
                   2382:           it should be very low but not zero otherwise the log go to
                   2383:           infinity.
                   2384:        */
                   2385: /* #ifdef INFINITYORIGINAL */
                   2386: /*         lli=log(out[s1][s2] - savm[s1][s2]); */
                   2387: /* #else */
                   2388: /*       if ((out[s1][s2] - savm[s1][s2]) < mytinydouble)  */
                   2389: /*         lli=log(mytinydouble); */
                   2390: /*       else */
                   2391: /*         lli=log(out[s1][s2] - savm[s1][s2]); */
                   2392: /* #endif */
                   2393:            lli=log(out[s1][s2] - savm[s1][s2]);
1.126     brouard  2394: 
                   2395:        } else if  (s2==-2) {
                   2396:          for (j=1,survp=0. ; j<=nlstate; j++) 
                   2397:            survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j];
                   2398:          /*survp += out[s1][j]; */
                   2399:          lli= log(survp);
                   2400:        }
                   2401:        
                   2402:        else if  (s2==-4) { 
                   2403:          for (j=3,survp=0. ; j<=nlstate; j++)  
                   2404:            survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j];
                   2405:          lli= log(survp); 
                   2406:        } 
                   2407: 
                   2408:        else if  (s2==-5) { 
                   2409:          for (j=1,survp=0. ; j<=2; j++)  
                   2410:            survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j];
                   2411:          lli= log(survp); 
                   2412:        } 
                   2413:        
                   2414:        else{
                   2415:          lli= log((1.+bbh)*out[s1][s2]- bbh*savm[s1][s2]); /* linear interpolation */
                   2416:          /*  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 */
                   2417:        } 
                   2418:        /*lli=(1.+bbh)*log(out[s1][s2])- bbh*log(savm[s1][s2]);*/
                   2419:        /*if(lli ==000.0)*/
                   2420:        /*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); */
                   2421:        ipmx +=1;
                   2422:        sw += weight[i];
                   2423:        ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
1.183     brouard  2424:        /* if (lli < log(mytinydouble)){ */
                   2425:        /*   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); */
                   2426:        /*   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]); */
                   2427:        /* } */
1.126     brouard  2428:       } /* end of wave */
                   2429:     } /* end of individual */
                   2430:   }  else if(mle==2){
                   2431:     for (i=1,ipmx=0, sw=0.; i<=imx; i++){
1.187     brouard  2432:       for (k=1; k<=cptcovn;k++) cov[2+nagesqr+k]=covar[Tvar[k]][i];
1.126     brouard  2433:       for(mi=1; mi<= wav[i]-1; mi++){
                   2434:        for (ii=1;ii<=nlstate+ndeath;ii++)
                   2435:          for (j=1;j<=nlstate+ndeath;j++){
                   2436:            oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   2437:            savm[ii][j]=(ii==j ? 1.0 : 0.0);
                   2438:          }
                   2439:        for(d=0; d<=dh[mi][i]; d++){
                   2440:          newm=savm;
1.187     brouard  2441:          agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;
                   2442:          cov[2]=agexact;
                   2443:          if(nagesqr==1)
                   2444:            cov[3]= agexact*agexact;
1.126     brouard  2445:          for (kk=1; kk<=cptcovage;kk++) {
1.187     brouard  2446:            cov[Tage[kk]+2+nagesqr]=covar[Tvar[Tage[kk]]][i]*agexact;
1.126     brouard  2447:          }
                   2448:          out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
                   2449:                       1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
                   2450:          savm=oldm;
                   2451:          oldm=newm;
                   2452:        } /* end mult */
                   2453:       
                   2454:        s1=s[mw[mi][i]][i];
                   2455:        s2=s[mw[mi+1][i]][i];
                   2456:        bbh=(double)bh[mi][i]/(double)stepm; 
                   2457:        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 */
                   2458:        ipmx +=1;
                   2459:        sw += weight[i];
                   2460:        ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
                   2461:       } /* end of wave */
                   2462:     } /* end of individual */
                   2463:   }  else if(mle==3){  /* exponential inter-extrapolation */
                   2464:     for (i=1,ipmx=0, sw=0.; i<=imx; i++){
1.187     brouard  2465:       for (k=1; k<=cptcovn;k++) cov[2+nagesqr+k]=covar[Tvar[k]][i];
1.126     brouard  2466:       for(mi=1; mi<= wav[i]-1; mi++){
                   2467:        for (ii=1;ii<=nlstate+ndeath;ii++)
                   2468:          for (j=1;j<=nlstate+ndeath;j++){
                   2469:            oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   2470:            savm[ii][j]=(ii==j ? 1.0 : 0.0);
                   2471:          }
                   2472:        for(d=0; d<dh[mi][i]; d++){
                   2473:          newm=savm;
1.187     brouard  2474:          agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;
                   2475:          cov[2]=agexact;
                   2476:          if(nagesqr==1)
                   2477:            cov[3]= agexact*agexact;
1.126     brouard  2478:          for (kk=1; kk<=cptcovage;kk++) {
1.187     brouard  2479:            cov[Tage[kk]+2+nagesqr]=covar[Tvar[Tage[kk]]][i]*agexact;
1.126     brouard  2480:          }
                   2481:          out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
                   2482:                       1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
                   2483:          savm=oldm;
                   2484:          oldm=newm;
                   2485:        } /* end mult */
                   2486:       
                   2487:        s1=s[mw[mi][i]][i];
                   2488:        s2=s[mw[mi+1][i]][i];
                   2489:        bbh=(double)bh[mi][i]/(double)stepm; 
                   2490:        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 */
                   2491:        ipmx +=1;
                   2492:        sw += weight[i];
                   2493:        ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
                   2494:       } /* end of wave */
                   2495:     } /* end of individual */
                   2496:   }else if (mle==4){  /* ml=4 no inter-extrapolation */
                   2497:     for (i=1,ipmx=0, sw=0.; i<=imx; i++){
1.187     brouard  2498:       for (k=1; k<=cptcovn;k++) cov[2+nagesqr+k]=covar[Tvar[k]][i];
1.126     brouard  2499:       for(mi=1; mi<= wav[i]-1; mi++){
                   2500:        for (ii=1;ii<=nlstate+ndeath;ii++)
                   2501:          for (j=1;j<=nlstate+ndeath;j++){
                   2502:            oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   2503:            savm[ii][j]=(ii==j ? 1.0 : 0.0);
                   2504:          }
                   2505:        for(d=0; d<dh[mi][i]; d++){
                   2506:          newm=savm;
1.187     brouard  2507:          agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;
                   2508:          cov[2]=agexact;
                   2509:          if(nagesqr==1)
                   2510:            cov[3]= agexact*agexact;
1.126     brouard  2511:          for (kk=1; kk<=cptcovage;kk++) {
1.187     brouard  2512:            cov[Tage[kk]+2+nagesqr]=covar[Tvar[Tage[kk]]][i]*agexact;
1.126     brouard  2513:          }
                   2514:        
                   2515:          out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
                   2516:                       1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
                   2517:          savm=oldm;
                   2518:          oldm=newm;
                   2519:        } /* end mult */
                   2520:       
                   2521:        s1=s[mw[mi][i]][i];
                   2522:        s2=s[mw[mi+1][i]][i];
                   2523:        if( s2 > nlstate){ 
                   2524:          lli=log(out[s1][s2] - savm[s1][s2]);
                   2525:        }else{
                   2526:          lli=log(out[s[mw[mi][i]][i]][s[mw[mi+1][i]][i]]); /* Original formula */
                   2527:        }
                   2528:        ipmx +=1;
                   2529:        sw += weight[i];
                   2530:        ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
                   2531: /*     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]); */
                   2532:       } /* end of wave */
                   2533:     } /* end of individual */
                   2534:   }else{  /* ml=5 no inter-extrapolation no jackson =0.8a */
                   2535:     for (i=1,ipmx=0, sw=0.; i<=imx; i++){
1.187     brouard  2536:       for (k=1; k<=cptcovn;k++) cov[2+nagesqr+k]=covar[Tvar[k]][i];
1.126     brouard  2537:       for(mi=1; mi<= wav[i]-1; mi++){
                   2538:        for (ii=1;ii<=nlstate+ndeath;ii++)
                   2539:          for (j=1;j<=nlstate+ndeath;j++){
                   2540:            oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   2541:            savm[ii][j]=(ii==j ? 1.0 : 0.0);
                   2542:          }
                   2543:        for(d=0; d<dh[mi][i]; d++){
                   2544:          newm=savm;
1.187     brouard  2545:          agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;
                   2546:          cov[2]=agexact;
                   2547:          if(nagesqr==1)
                   2548:            cov[3]= agexact*agexact;
1.126     brouard  2549:          for (kk=1; kk<=cptcovage;kk++) {
1.187     brouard  2550:            cov[Tage[kk]+2+nagesqr]=covar[Tvar[Tage[kk]]][i]*agexact;
1.126     brouard  2551:          }
                   2552:        
                   2553:          out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
                   2554:                       1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
                   2555:          savm=oldm;
                   2556:          oldm=newm;
                   2557:        } /* end mult */
                   2558:       
                   2559:        s1=s[mw[mi][i]][i];
                   2560:        s2=s[mw[mi+1][i]][i];
                   2561:        lli=log(out[s[mw[mi][i]][i]][s[mw[mi+1][i]][i]]); /* Original formula */
                   2562:        ipmx +=1;
                   2563:        sw += weight[i];
                   2564:        ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
                   2565:        /*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]);*/
                   2566:       } /* end of wave */
                   2567:     } /* end of individual */
                   2568:   } /* End of if */
                   2569:   for(k=1,l=0.; k<=nlstate; k++) l += ll[k];
                   2570:   /* printf("l1=%f l2=%f ",ll[1],ll[2]); */
                   2571:   l= l*ipmx/sw; /* To get the same order of magnitude as if weight=1 for every body */
                   2572:   return -l;
                   2573: }
                   2574: 
                   2575: /*************** log-likelihood *************/
                   2576: double funcone( double *x)
                   2577: {
                   2578:   /* Same as likeli but slower because of a lot of printf and if */
                   2579:   int i, ii, j, k, mi, d, kk;
1.131     brouard  2580:   double l, ll[NLSTATEMAX+1], cov[NCOVMAX+1];
1.126     brouard  2581:   double **out;
                   2582:   double lli; /* Individual log likelihood */
                   2583:   double llt;
                   2584:   int s1, s2;
                   2585:   double bbh, survp;
1.187     brouard  2586:   double agexact;
1.126     brouard  2587:   /*extern weight */
                   2588:   /* We are differentiating ll according to initial status */
                   2589:   /*  for (i=1;i<=npar;i++) printf("%f ", x[i]);*/
                   2590:   /*for(i=1;i<imx;i++) 
                   2591:     printf(" %d\n",s[4][i]);
                   2592:   */
                   2593:   cov[1]=1.;
                   2594: 
                   2595:   for(k=1; k<=nlstate; k++) ll[k]=0.;
                   2596: 
                   2597:   for (i=1,ipmx=0, sw=0.; i<=imx; i++){
1.187     brouard  2598:     for (k=1; k<=cptcovn;k++) cov[2+nagesqr+k]=covar[Tvar[k]][i];
1.126     brouard  2599:     for(mi=1; mi<= wav[i]-1; mi++){
                   2600:       for (ii=1;ii<=nlstate+ndeath;ii++)
                   2601:        for (j=1;j<=nlstate+ndeath;j++){
                   2602:          oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   2603:          savm[ii][j]=(ii==j ? 1.0 : 0.0);
                   2604:        }
                   2605:       for(d=0; d<dh[mi][i]; d++){
                   2606:        newm=savm;
1.187     brouard  2607:        agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;
                   2608:        cov[2]=agexact;
                   2609:        if(nagesqr==1)
                   2610:          cov[3]= agexact*agexact;
1.126     brouard  2611:        for (kk=1; kk<=cptcovage;kk++) {
1.187     brouard  2612:          cov[Tage[kk]+2+nagesqr]=covar[Tvar[Tage[kk]]][i]*agexact;
1.126     brouard  2613:        }
1.187     brouard  2614: 
1.145     brouard  2615:        /* savm=pmij(pmmij,cov,ncovmodel,x,nlstate); */
1.126     brouard  2616:        out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
                   2617:                     1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
1.145     brouard  2618:        /* out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath, */
                   2619:        /*           1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate)); */
1.126     brouard  2620:        savm=oldm;
                   2621:        oldm=newm;
                   2622:       } /* end mult */
                   2623:       
                   2624:       s1=s[mw[mi][i]][i];
                   2625:       s2=s[mw[mi+1][i]][i];
                   2626:       bbh=(double)bh[mi][i]/(double)stepm; 
                   2627:       /* bias is positive if real duration
                   2628:        * is higher than the multiple of stepm and negative otherwise.
                   2629:        */
                   2630:       if( s2 > nlstate && (mle <5) ){  /* Jackson */
                   2631:        lli=log(out[s1][s2] - savm[s1][s2]);
                   2632:       } else if  (s2==-2) {
                   2633:        for (j=1,survp=0. ; j<=nlstate; j++) 
                   2634:          survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j];
                   2635:        lli= log(survp);
                   2636:       }else if (mle==1){
                   2637:        lli= log((1.+bbh)*out[s1][s2]- bbh*savm[s1][s2]); /* linear interpolation */
                   2638:       } else if(mle==2){
                   2639:        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 */
                   2640:       } else if(mle==3){  /* exponential inter-extrapolation */
                   2641:        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 */
                   2642:       } else if (mle==4){  /* mle=4 no inter-extrapolation */
                   2643:        lli=log(out[s1][s2]); /* Original formula */
1.136     brouard  2644:       } else{  /* mle=0 back to 1 */
                   2645:        lli= log((1.+bbh)*out[s1][s2]- bbh*savm[s1][s2]); /* linear interpolation */
                   2646:        /*lli=log(out[s1][s2]); */ /* Original formula */
1.126     brouard  2647:       } /* End of if */
                   2648:       ipmx +=1;
                   2649:       sw += weight[i];
                   2650:       ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
1.132     brouard  2651:       /*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  2652:       if(globpr){
1.205     brouard  2653:        fprintf(ficresilk,"%9ld %6.1f %6d %2d %2d %2d %2d %3d %11.6f %8.4f %8.3f\
1.126     brouard  2654:  %11.6f %11.6f %11.6f ", \
1.205     brouard  2655:                num[i], agexact, i,s1,s2,mi,mw[mi][i],dh[mi][i],exp(lli),weight[i],weight[i]*gipmx/gsw,
1.126     brouard  2656:                2*weight[i]*lli,out[s1][s2],savm[s1][s2]);
                   2657:        for(k=1,llt=0.,l=0.; k<=nlstate; k++){
                   2658:          llt +=ll[k]*gipmx/gsw;
                   2659:          fprintf(ficresilk," %10.6f",-ll[k]*gipmx/gsw);
                   2660:        }
                   2661:        fprintf(ficresilk," %10.6f\n", -llt);
                   2662:       }
                   2663:     } /* end of wave */
                   2664:   } /* end of individual */
                   2665:   for(k=1,l=0.; k<=nlstate; k++) l += ll[k];
                   2666:   /* printf("l1=%f l2=%f ",ll[1],ll[2]); */
                   2667:   l= l*ipmx/sw; /* To get the same order of magnitude as if weight=1 for every body */
                   2668:   if(globpr==0){ /* First time we count the contributions and weights */
                   2669:     gipmx=ipmx;
                   2670:     gsw=sw;
                   2671:   }
                   2672:   return -l;
                   2673: }
                   2674: 
                   2675: 
                   2676: /*************** function likelione ***********/
                   2677: void likelione(FILE *ficres,double p[], int npar, int nlstate, int *globpri, long *ipmx, double *sw, double *fretone, double (*funcone)(double []))
                   2678: {
                   2679:   /* This routine should help understanding what is done with 
                   2680:      the selection of individuals/waves and
                   2681:      to check the exact contribution to the likelihood.
                   2682:      Plotting could be done.
                   2683:    */
                   2684:   int k;
                   2685: 
                   2686:   if(*globpri !=0){ /* Just counts and sums, no printings */
1.201     brouard  2687:     strcpy(fileresilk,"ILK_"); 
1.202     brouard  2688:     strcat(fileresilk,fileresu);
1.126     brouard  2689:     if((ficresilk=fopen(fileresilk,"w"))==NULL) {
                   2690:       printf("Problem with resultfile: %s\n", fileresilk);
                   2691:       fprintf(ficlog,"Problem with resultfile: %s\n", fileresilk);
                   2692:     }
1.205     brouard  2693:     fprintf(ficresilk, "#individual(line's_record) count age s1 s2 wave# effective_wave# number_of_matrices_product pij weight weight/gpw -2ln(pij)*weight 0pij_x 0pij_(x-stepm) cumulating_loglikeli_by_health_state(reweighted=-2ll*weightXnumber_of_contribs/sum_of_weights) and_total\n");
1.207     brouard  2694:     fprintf(ficresilk, "#num_i age i s1 s2 mi mw dh likeli weight %%weight 2wlli out sav ");
1.126     brouard  2695:     /*         i,s1,s2,mi,mw[mi][i],dh[mi][i],exp(lli),weight[i],2*weight[i]*lli,out[s1][s2],savm[s1][s2]); */
                   2696:     for(k=1; k<=nlstate; k++) 
                   2697:       fprintf(ficresilk," -2*gipw/gsw*weight*ll[%d]++",k);
                   2698:     fprintf(ficresilk," -2*gipw/gsw*weight*ll(total)\n");
                   2699:   }
                   2700: 
                   2701:   *fretone=(*funcone)(p);
                   2702:   if(*globpri !=0){
                   2703:     fclose(ficresilk);
1.205     brouard  2704:     if (mle ==0)
                   2705:       fprintf(fichtm,"\n<br>File of contributions to the likelihood computed with initial parameters and mle = %d.",mle);
                   2706:     else if(mle >=1)
                   2707:       fprintf(fichtm,"\n<br>File of contributions to the likelihood computed with optimized parameters mle = %d.",mle);
                   2708:     fprintf(fichtm," You should at least run with mle >= 1 to get starting values corresponding to the optimized parameters in order to visualize the real contribution of each individual/wave: <a href=\"%s\">%s</a><br>\n",subdirf(fileresilk),subdirf(fileresilk));
1.207     brouard  2709:     
1.208     brouard  2710:       
                   2711:     for (k=1; k<= nlstate ; k++) {
                   2712:       fprintf(fichtm,"<br>- Probability p%dj by origin %d and destination j <a href=\"%s-p%dj.png\">%s-p%dj.png</a><br> \
                   2713: <img src=\"%s-p%dj.png\">",k,k,subdirf2(optionfilefiname,"ILK_"),k,subdirf2(optionfilefiname,"ILK_"),k,subdirf2(optionfilefiname,"ILK_"),k);
                   2714:     }
1.207     brouard  2715:     fprintf(fichtm,"<br>- The function drawn is -2Log(L) in Log scale: by state of origin <a href=\"%s-ori.png\">%s-ori.png</a><br> \
1.204     brouard  2716: <img src=\"%s-ori.png\">",subdirf2(optionfilefiname,"ILK_"),subdirf2(optionfilefiname,"ILK_"),subdirf2(optionfilefiname,"ILK_"));
1.207     brouard  2717:     fprintf(fichtm,"<br>- and by state of destination <a href=\"%s-dest.png\">%s-dest.png</a><br> \
1.204     brouard  2718: <img src=\"%s-dest.png\">",subdirf2(optionfilefiname,"ILK_"),subdirf2(optionfilefiname,"ILK_"),subdirf2(optionfilefiname,"ILK_"));
1.207     brouard  2719:     fflush(fichtm);
1.205     brouard  2720:   }
1.126     brouard  2721:   return;
                   2722: }
                   2723: 
                   2724: 
                   2725: /*********** Maximum Likelihood Estimation ***************/
                   2726: 
                   2727: void mlikeli(FILE *ficres,double p[], int npar, int ncovmodel, int nlstate, double ftol, double (*func)(double []))
                   2728: {
1.165     brouard  2729:   int i,j, iter=0;
1.126     brouard  2730:   double **xi;
                   2731:   double fret;
                   2732:   double fretone; /* Only one call to likelihood */
                   2733:   /*  char filerespow[FILENAMELENGTH];*/
1.162     brouard  2734: 
                   2735: #ifdef NLOPT
                   2736:   int creturn;
                   2737:   nlopt_opt opt;
                   2738:   /* double lb[9] = { -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL }; /\* lower bounds *\/ */
                   2739:   double *lb;
                   2740:   double minf; /* the minimum objective value, upon return */
                   2741:   double * p1; /* Shifted parameters from 0 instead of 1 */
                   2742:   myfunc_data dinst, *d = &dinst;
                   2743: #endif
                   2744: 
                   2745: 
1.126     brouard  2746:   xi=matrix(1,npar,1,npar);
                   2747:   for (i=1;i<=npar;i++)
                   2748:     for (j=1;j<=npar;j++)
                   2749:       xi[i][j]=(i==j ? 1.0 : 0.0);
                   2750:   printf("Powell\n");  fprintf(ficlog,"Powell\n");
1.201     brouard  2751:   strcpy(filerespow,"POW_"); 
1.126     brouard  2752:   strcat(filerespow,fileres);
                   2753:   if((ficrespow=fopen(filerespow,"w"))==NULL) {
                   2754:     printf("Problem with resultfile: %s\n", filerespow);
                   2755:     fprintf(ficlog,"Problem with resultfile: %s\n", filerespow);
                   2756:   }
                   2757:   fprintf(ficrespow,"# Powell\n# iter -2*LL");
                   2758:   for (i=1;i<=nlstate;i++)
                   2759:     for(j=1;j<=nlstate+ndeath;j++)
                   2760:       if(j!=i)fprintf(ficrespow," p%1d%1d",i,j);
                   2761:   fprintf(ficrespow,"\n");
1.162     brouard  2762: #ifdef POWELL
1.126     brouard  2763:   powell(p,xi,npar,ftol,&iter,&fret,func);
1.162     brouard  2764: #endif
1.126     brouard  2765: 
1.162     brouard  2766: #ifdef NLOPT
                   2767: #ifdef NEWUOA
                   2768:   opt = nlopt_create(NLOPT_LN_NEWUOA,npar);
                   2769: #else
                   2770:   opt = nlopt_create(NLOPT_LN_BOBYQA,npar);
                   2771: #endif
                   2772:   lb=vector(0,npar-1);
                   2773:   for (i=0;i<npar;i++) lb[i]= -HUGE_VAL;
                   2774:   nlopt_set_lower_bounds(opt, lb);
                   2775:   nlopt_set_initial_step1(opt, 0.1);
                   2776:   
                   2777:   p1= (p+1); /*  p *(p+1)@8 and p *(p1)@8 are equal p1[0]=p[1] */
                   2778:   d->function = func;
                   2779:   printf(" Func %.12lf \n",myfunc(npar,p1,NULL,d));
                   2780:   nlopt_set_min_objective(opt, myfunc, d);
                   2781:   nlopt_set_xtol_rel(opt, ftol);
                   2782:   if ((creturn=nlopt_optimize(opt, p1, &minf)) < 0) {
                   2783:     printf("nlopt failed! %d\n",creturn); 
                   2784:   }
                   2785:   else {
                   2786:     printf("found minimum after %d evaluations (NLOPT=%d)\n", countcallfunc ,NLOPT);
                   2787:     printf("found minimum at f(%g,%g) = %0.10g\n", p[0], p[1], minf);
                   2788:     iter=1; /* not equal */
                   2789:   }
                   2790:   nlopt_destroy(opt);
                   2791: #endif
1.126     brouard  2792:   free_matrix(xi,1,npar,1,npar);
                   2793:   fclose(ficrespow);
1.203     brouard  2794:   printf("\n#Number of iterations & function calls = %d & %d, -2 Log likelihood = %.12f\n",iter, countcallfunc,func(p));
                   2795:   fprintf(ficlog,"\n#Number of iterations & function calls = %d & %d, -2 Log likelihood = %.12f\n",iter, countcallfunc,func(p));
1.180     brouard  2796:   fprintf(ficres,"#Number of iterations & function calls = %d & %d, -2 Log likelihood = %.12f\n",iter, countcallfunc,func(p));
1.126     brouard  2797: 
                   2798: }
                   2799: 
                   2800: /**** Computes Hessian and covariance matrix ***/
1.203     brouard  2801: void hesscov(double **matcov, double **hess, double p[], int npar, double delti[], double ftolhess, double (*func)(double []))
1.126     brouard  2802: {
                   2803:   double  **a,**y,*x,pd;
1.203     brouard  2804:   /* double **hess; */
1.164     brouard  2805:   int i, j;
1.126     brouard  2806:   int *indx;
                   2807: 
                   2808:   double hessii(double p[], double delta, int theta, double delti[],double (*func)(double []),int npar);
1.203     brouard  2809:   double hessij(double p[], double **hess, double delti[], int i, int j,double (*func)(double []),int npar);
1.126     brouard  2810:   void lubksb(double **a, int npar, int *indx, double b[]) ;
                   2811:   void ludcmp(double **a, int npar, int *indx, double *d) ;
                   2812:   double gompertz(double p[]);
1.203     brouard  2813:   /* hess=matrix(1,npar,1,npar); */
1.126     brouard  2814: 
                   2815:   printf("\nCalculation of the hessian matrix. Wait...\n");
                   2816:   fprintf(ficlog,"\nCalculation of the hessian matrix. Wait...\n");
                   2817:   for (i=1;i<=npar;i++){
1.203     brouard  2818:     printf("%d-",i);fflush(stdout);
                   2819:     fprintf(ficlog,"%d-",i);fflush(ficlog);
1.126     brouard  2820:    
                   2821:      hess[i][i]=hessii(p,ftolhess,i,delti,func,npar);
                   2822:     
                   2823:     /*  printf(" %f ",p[i]);
                   2824:        printf(" %lf %lf %lf",hess[i][i],ftolhess,delti[i]);*/
                   2825:   }
                   2826:   
                   2827:   for (i=1;i<=npar;i++) {
                   2828:     for (j=1;j<=npar;j++)  {
                   2829:       if (j>i) { 
1.203     brouard  2830:        printf(".%d-%d",i,j);fflush(stdout);
                   2831:        fprintf(ficlog,".%d-%d",i,j);fflush(ficlog);
                   2832:        hess[i][j]=hessij(p,hess, delti,i,j,func,npar);
1.126     brouard  2833:        
                   2834:        hess[j][i]=hess[i][j];    
                   2835:        /*printf(" %lf ",hess[i][j]);*/
                   2836:       }
                   2837:     }
                   2838:   }
                   2839:   printf("\n");
                   2840:   fprintf(ficlog,"\n");
                   2841: 
                   2842:   printf("\nInverting the hessian to get the covariance matrix. Wait...\n");
                   2843:   fprintf(ficlog,"\nInverting the hessian to get the covariance matrix. Wait...\n");
                   2844:   
                   2845:   a=matrix(1,npar,1,npar);
                   2846:   y=matrix(1,npar,1,npar);
                   2847:   x=vector(1,npar);
                   2848:   indx=ivector(1,npar);
                   2849:   for (i=1;i<=npar;i++)
                   2850:     for (j=1;j<=npar;j++) a[i][j]=hess[i][j];
                   2851:   ludcmp(a,npar,indx,&pd);
                   2852: 
                   2853:   for (j=1;j<=npar;j++) {
                   2854:     for (i=1;i<=npar;i++) x[i]=0;
                   2855:     x[j]=1;
                   2856:     lubksb(a,npar,indx,x);
                   2857:     for (i=1;i<=npar;i++){ 
                   2858:       matcov[i][j]=x[i];
                   2859:     }
                   2860:   }
                   2861: 
                   2862:   printf("\n#Hessian matrix#\n");
                   2863:   fprintf(ficlog,"\n#Hessian matrix#\n");
                   2864:   for (i=1;i<=npar;i++) { 
                   2865:     for (j=1;j<=npar;j++) { 
1.203     brouard  2866:       printf("%.6e ",hess[i][j]);
                   2867:       fprintf(ficlog,"%.6e ",hess[i][j]);
1.126     brouard  2868:     }
                   2869:     printf("\n");
                   2870:     fprintf(ficlog,"\n");
                   2871:   }
                   2872: 
1.203     brouard  2873:   /* printf("\n#Covariance matrix#\n"); */
                   2874:   /* fprintf(ficlog,"\n#Covariance matrix#\n"); */
                   2875:   /* for (i=1;i<=npar;i++) {  */
                   2876:   /*   for (j=1;j<=npar;j++) {  */
                   2877:   /*     printf("%.6e ",matcov[i][j]); */
                   2878:   /*     fprintf(ficlog,"%.6e ",matcov[i][j]); */
                   2879:   /*   } */
                   2880:   /*   printf("\n"); */
                   2881:   /*   fprintf(ficlog,"\n"); */
                   2882:   /* } */
                   2883: 
1.126     brouard  2884:   /* Recompute Inverse */
1.203     brouard  2885:   /* for (i=1;i<=npar;i++) */
                   2886:   /*   for (j=1;j<=npar;j++) a[i][j]=matcov[i][j]; */
                   2887:   /* ludcmp(a,npar,indx,&pd); */
                   2888: 
                   2889:   /*  printf("\n#Hessian matrix recomputed#\n"); */
                   2890: 
                   2891:   /* for (j=1;j<=npar;j++) { */
                   2892:   /*   for (i=1;i<=npar;i++) x[i]=0; */
                   2893:   /*   x[j]=1; */
                   2894:   /*   lubksb(a,npar,indx,x); */
                   2895:   /*   for (i=1;i<=npar;i++){  */
                   2896:   /*     y[i][j]=x[i]; */
                   2897:   /*     printf("%.3e ",y[i][j]); */
                   2898:   /*     fprintf(ficlog,"%.3e ",y[i][j]); */
                   2899:   /*   } */
                   2900:   /*   printf("\n"); */
                   2901:   /*   fprintf(ficlog,"\n"); */
                   2902:   /* } */
                   2903: 
                   2904:   /* Verifying the inverse matrix */
                   2905: #ifdef DEBUGHESS
                   2906:   y=matprod2(y,hess,1,npar,1,npar,1,npar,matcov);
1.126     brouard  2907: 
1.203     brouard  2908:    printf("\n#Verification: multiplying the matrix of covariance by the Hessian matrix, should be unity:#\n");
                   2909:    fprintf(ficlog,"\n#Verification: multiplying the matrix of covariance by the Hessian matrix. Should be unity:#\n");
1.126     brouard  2910: 
                   2911:   for (j=1;j<=npar;j++) {
                   2912:     for (i=1;i<=npar;i++){ 
1.203     brouard  2913:       printf("%.2f ",y[i][j]);
                   2914:       fprintf(ficlog,"%.2f ",y[i][j]);
1.126     brouard  2915:     }
                   2916:     printf("\n");
                   2917:     fprintf(ficlog,"\n");
                   2918:   }
1.203     brouard  2919: #endif
1.126     brouard  2920: 
                   2921:   free_matrix(a,1,npar,1,npar);
                   2922:   free_matrix(y,1,npar,1,npar);
                   2923:   free_vector(x,1,npar);
                   2924:   free_ivector(indx,1,npar);
1.203     brouard  2925:   /* free_matrix(hess,1,npar,1,npar); */
1.126     brouard  2926: 
                   2927: 
                   2928: }
                   2929: 
                   2930: /*************** hessian matrix ****************/
                   2931: double hessii(double x[], double delta, int theta, double delti[], double (*func)(double []), int npar)
1.203     brouard  2932: { /* Around values of x, computes the function func and returns the scales delti and hessian */
1.126     brouard  2933:   int i;
                   2934:   int l=1, lmax=20;
1.203     brouard  2935:   double k1,k2, res, fx;
1.132     brouard  2936:   double p2[MAXPARM+1]; /* identical to x */
1.126     brouard  2937:   double delt=0.0001, delts, nkhi=10.,nkhif=1., khi=1.e-4;
                   2938:   int k=0,kmax=10;
                   2939:   double l1;
                   2940: 
                   2941:   fx=func(x);
                   2942:   for (i=1;i<=npar;i++) p2[i]=x[i];
1.145     brouard  2943:   for(l=0 ; l <=lmax; l++){  /* Enlarging the zone around the Maximum */
1.126     brouard  2944:     l1=pow(10,l);
                   2945:     delts=delt;
                   2946:     for(k=1 ; k <kmax; k=k+1){
                   2947:       delt = delta*(l1*k);
                   2948:       p2[theta]=x[theta] +delt;
1.145     brouard  2949:       k1=func(p2)-fx;   /* Might be negative if too close to the theoretical maximum */
1.126     brouard  2950:       p2[theta]=x[theta]-delt;
                   2951:       k2=func(p2)-fx;
                   2952:       /*res= (k1-2.0*fx+k2)/delt/delt; */
1.203     brouard  2953:       res= (k1+k2)/delt/delt/2.; /* Divided by 2 because L and not 2*L */
1.126     brouard  2954:       
1.203     brouard  2955: #ifdef DEBUGHESSII
1.126     brouard  2956:       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);
                   2957:       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);
                   2958: #endif
                   2959:       /*if(fabs(k1-2.0*fx+k2) <1.e-13){ */
                   2960:       if((k1 <khi/nkhi/2.) || (k2 <khi/nkhi/2.)){
                   2961:        k=kmax;
                   2962:       }
                   2963:       else if((k1 >khi/nkhif) || (k2 >khi/nkhif)){ /* Keeps lastvalue before 3.84/2 KHI2 5% 1d.f. */
1.164     brouard  2964:        k=kmax; l=lmax*10;
1.126     brouard  2965:       }
                   2966:       else if((k1 >khi/nkhi) || (k2 >khi/nkhi)){ 
                   2967:        delts=delt;
                   2968:       }
1.203     brouard  2969:     } /* End loop k */
1.126     brouard  2970:   }
                   2971:   delti[theta]=delts;
                   2972:   return res; 
                   2973:   
                   2974: }
                   2975: 
1.203     brouard  2976: double hessij( double x[], double **hess, double delti[], int thetai,int thetaj,double (*func)(double []),int npar)
1.126     brouard  2977: {
                   2978:   int i;
1.164     brouard  2979:   int l=1, lmax=20;
1.126     brouard  2980:   double k1,k2,k3,k4,res,fx;
1.132     brouard  2981:   double p2[MAXPARM+1];
1.203     brouard  2982:   int k, kmax=1;
                   2983:   double v1, v2, cv12, lc1, lc2;
1.208     brouard  2984: 
                   2985:   int firstime=0;
1.203     brouard  2986:   
1.126     brouard  2987:   fx=func(x);
1.203     brouard  2988:   for (k=1; k<=kmax; k=k+10) {
1.126     brouard  2989:     for (i=1;i<=npar;i++) p2[i]=x[i];
1.203     brouard  2990:     p2[thetai]=x[thetai]+delti[thetai]*k;
                   2991:     p2[thetaj]=x[thetaj]+delti[thetaj]*k;
1.126     brouard  2992:     k1=func(p2)-fx;
                   2993:   
1.203     brouard  2994:     p2[thetai]=x[thetai]+delti[thetai]*k;
                   2995:     p2[thetaj]=x[thetaj]-delti[thetaj]*k;
1.126     brouard  2996:     k2=func(p2)-fx;
                   2997:   
1.203     brouard  2998:     p2[thetai]=x[thetai]-delti[thetai]*k;
                   2999:     p2[thetaj]=x[thetaj]+delti[thetaj]*k;
1.126     brouard  3000:     k3=func(p2)-fx;
                   3001:   
1.203     brouard  3002:     p2[thetai]=x[thetai]-delti[thetai]*k;
                   3003:     p2[thetaj]=x[thetaj]-delti[thetaj]*k;
1.126     brouard  3004:     k4=func(p2)-fx;
1.203     brouard  3005:     res=(k1-k2-k3+k4)/4.0/delti[thetai]/k/delti[thetaj]/k/2.; /* Because of L not 2*L */
                   3006:     if(k1*k2*k3*k4 <0.){
1.208     brouard  3007:       firstime=1;
1.203     brouard  3008:       kmax=kmax+10;
1.208     brouard  3009:     }
                   3010:     if(kmax >=10 || firstime ==1){
1.203     brouard  3011:       printf("Warning: directions %d-%d, you are not estimating the Hessian at the exact maximum likelihood; increase ftol=%.2e\n",thetai,thetaj, ftol);
                   3012:       fprintf(ficlog,"Warning: directions %d-%d, you are not estimating the Hessian at the exact maximum likelihood; increase ftol=%.2e\n",thetai,thetaj, ftol);
                   3013:       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);
                   3014:       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);
                   3015:     }
                   3016: #ifdef DEBUGHESSIJ
                   3017:     v1=hess[thetai][thetai];
                   3018:     v2=hess[thetaj][thetaj];
                   3019:     cv12=res;
                   3020:     /* Computing eigen value of Hessian matrix */
                   3021:     lc1=((v1+v2)+sqrt((v1+v2)*(v1+v2) - 4*(v1*v2-cv12*cv12)))/2.;
                   3022:     lc2=((v1+v2)-sqrt((v1+v2)*(v1+v2) - 4*(v1*v2-cv12*cv12)))/2.;
                   3023:     if ((lc2 <0) || (lc1 <0) ){
                   3024:       printf("Warning: sub Hessian matrix '%d%d' does not have positive eigen values \n",thetai,thetaj);
                   3025:       fprintf(ficlog, "Warning: sub Hessian matrix '%d%d' does not have positive eigen values \n",thetai,thetaj);
                   3026:       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);
                   3027:       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);
                   3028:     }
1.126     brouard  3029: #endif
                   3030:   }
                   3031:   return res;
                   3032: }
                   3033: 
1.203     brouard  3034:     /* Not done yet: Was supposed to fix if not exactly at the maximum */
                   3035: /* double hessij( double x[], double delti[], int thetai,int thetaj,double (*func)(double []),int npar) */
                   3036: /* { */
                   3037: /*   int i; */
                   3038: /*   int l=1, lmax=20; */
                   3039: /*   double k1,k2,k3,k4,res,fx; */
                   3040: /*   double p2[MAXPARM+1]; */
                   3041: /*   double delt=0.0001, delts, nkhi=10.,nkhif=1., khi=1.e-4; */
                   3042: /*   int k=0,kmax=10; */
                   3043: /*   double l1; */
                   3044:   
                   3045: /*   fx=func(x); */
                   3046: /*   for(l=0 ; l <=lmax; l++){  /\* Enlarging the zone around the Maximum *\/ */
                   3047: /*     l1=pow(10,l); */
                   3048: /*     delts=delt; */
                   3049: /*     for(k=1 ; k <kmax; k=k+1){ */
                   3050: /*       delt = delti*(l1*k); */
                   3051: /*       for (i=1;i<=npar;i++) p2[i]=x[i]; */
                   3052: /*       p2[thetai]=x[thetai]+delti[thetai]/k; */
                   3053: /*       p2[thetaj]=x[thetaj]+delti[thetaj]/k; */
                   3054: /*       k1=func(p2)-fx; */
                   3055:       
                   3056: /*       p2[thetai]=x[thetai]+delti[thetai]/k; */
                   3057: /*       p2[thetaj]=x[thetaj]-delti[thetaj]/k; */
                   3058: /*       k2=func(p2)-fx; */
                   3059:       
                   3060: /*       p2[thetai]=x[thetai]-delti[thetai]/k; */
                   3061: /*       p2[thetaj]=x[thetaj]+delti[thetaj]/k; */
                   3062: /*       k3=func(p2)-fx; */
                   3063:       
                   3064: /*       p2[thetai]=x[thetai]-delti[thetai]/k; */
                   3065: /*       p2[thetaj]=x[thetaj]-delti[thetaj]/k; */
                   3066: /*       k4=func(p2)-fx; */
                   3067: /*       res=(k1-k2-k3+k4)/4.0/delti[thetai]*k/delti[thetaj]*k/2.; /\* Because of L not 2*L *\/ */
                   3068: /* #ifdef DEBUGHESSIJ */
                   3069: /*       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); */
                   3070: /*       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); */
                   3071: /* #endif */
                   3072: /*       if((k1 <khi/nkhi/2.) || (k2 <khi/nkhi/2.)|| (k4 <khi/nkhi/2.)|| (k4 <khi/nkhi/2.)){ */
                   3073: /*     k=kmax; */
                   3074: /*       } */
                   3075: /*       else if((k1 >khi/nkhif) || (k2 >khi/nkhif) || (k4 >khi/nkhif) || (k4 >khi/nkhif)){ /\* Keeps lastvalue before 3.84/2 KHI2 5% 1d.f. *\/ */
                   3076: /*     k=kmax; l=lmax*10; */
                   3077: /*       } */
                   3078: /*       else if((k1 >khi/nkhi) || (k2 >khi/nkhi)){  */
                   3079: /*     delts=delt; */
                   3080: /*       } */
                   3081: /*     } /\* End loop k *\/ */
                   3082: /*   } */
                   3083: /*   delti[theta]=delts; */
                   3084: /*   return res;  */
                   3085: /* } */
                   3086: 
                   3087: 
1.126     brouard  3088: /************** Inverse of matrix **************/
                   3089: void ludcmp(double **a, int n, int *indx, double *d) 
                   3090: { 
                   3091:   int i,imax,j,k; 
                   3092:   double big,dum,sum,temp; 
                   3093:   double *vv; 
                   3094:  
                   3095:   vv=vector(1,n); 
                   3096:   *d=1.0; 
                   3097:   for (i=1;i<=n;i++) { 
                   3098:     big=0.0; 
                   3099:     for (j=1;j<=n;j++) 
                   3100:       if ((temp=fabs(a[i][j])) > big) big=temp; 
                   3101:     if (big == 0.0) nrerror("Singular matrix in routine ludcmp"); 
                   3102:     vv[i]=1.0/big; 
                   3103:   } 
                   3104:   for (j=1;j<=n;j++) { 
                   3105:     for (i=1;i<j;i++) { 
                   3106:       sum=a[i][j]; 
                   3107:       for (k=1;k<i;k++) sum -= a[i][k]*a[k][j]; 
                   3108:       a[i][j]=sum; 
                   3109:     } 
                   3110:     big=0.0; 
                   3111:     for (i=j;i<=n;i++) { 
                   3112:       sum=a[i][j]; 
                   3113:       for (k=1;k<j;k++) 
                   3114:        sum -= a[i][k]*a[k][j]; 
                   3115:       a[i][j]=sum; 
                   3116:       if ( (dum=vv[i]*fabs(sum)) >= big) { 
                   3117:        big=dum; 
                   3118:        imax=i; 
                   3119:       } 
                   3120:     } 
                   3121:     if (j != imax) { 
                   3122:       for (k=1;k<=n;k++) { 
                   3123:        dum=a[imax][k]; 
                   3124:        a[imax][k]=a[j][k]; 
                   3125:        a[j][k]=dum; 
                   3126:       } 
                   3127:       *d = -(*d); 
                   3128:       vv[imax]=vv[j]; 
                   3129:     } 
                   3130:     indx[j]=imax; 
                   3131:     if (a[j][j] == 0.0) a[j][j]=TINY; 
                   3132:     if (j != n) { 
                   3133:       dum=1.0/(a[j][j]); 
                   3134:       for (i=j+1;i<=n;i++) a[i][j] *= dum; 
                   3135:     } 
                   3136:   } 
                   3137:   free_vector(vv,1,n);  /* Doesn't work */
                   3138: ;
                   3139: } 
                   3140: 
                   3141: void lubksb(double **a, int n, int *indx, double b[]) 
                   3142: { 
                   3143:   int i,ii=0,ip,j; 
                   3144:   double sum; 
                   3145:  
                   3146:   for (i=1;i<=n;i++) { 
                   3147:     ip=indx[i]; 
                   3148:     sum=b[ip]; 
                   3149:     b[ip]=b[i]; 
                   3150:     if (ii) 
                   3151:       for (j=ii;j<=i-1;j++) sum -= a[i][j]*b[j]; 
                   3152:     else if (sum) ii=i; 
                   3153:     b[i]=sum; 
                   3154:   } 
                   3155:   for (i=n;i>=1;i--) { 
                   3156:     sum=b[i]; 
                   3157:     for (j=i+1;j<=n;j++) sum -= a[i][j]*b[j]; 
                   3158:     b[i]=sum/a[i][i]; 
                   3159:   } 
                   3160: } 
                   3161: 
                   3162: void pstamp(FILE *fichier)
                   3163: {
1.196     brouard  3164:   fprintf(fichier,"# %s.%s\n#IMaCh version %s, %s\n#%s\n# %s", optionfilefiname,optionfilext,version,copyright, fullversion, strstart);
1.126     brouard  3165: }
                   3166: 
                   3167: /************ Frequencies ********************/
                   3168: 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[])
                   3169: {  /* Some frequencies */
                   3170:   
1.164     brouard  3171:   int i, m, jk, j1, bool, z1,j;
1.126     brouard  3172:   int first;
                   3173:   double ***freq; /* Frequencies */
                   3174:   double *pp, **prop;
                   3175:   double pos,posprop, k2, dateintsum=0,k2cpt=0;
                   3176:   char fileresp[FILENAMELENGTH];
                   3177:   
                   3178:   pp=vector(1,nlstate);
                   3179:   prop=matrix(1,nlstate,iagemin,iagemax+3);
1.201     brouard  3180:   strcpy(fileresp,"P_");
                   3181:   strcat(fileresp,fileresu);
1.126     brouard  3182:   if((ficresp=fopen(fileresp,"w"))==NULL) {
                   3183:     printf("Problem with prevalence resultfile: %s\n", fileresp);
                   3184:     fprintf(ficlog,"Problem with prevalence resultfile: %s\n", fileresp);
                   3185:     exit(0);
                   3186:   }
                   3187:   freq= ma3x(-5,nlstate+ndeath,-5,nlstate+ndeath,iagemin,iagemax+3);
                   3188:   j1=0;
                   3189:   
                   3190:   j=cptcoveff;
                   3191:   if (cptcovn<1) {j=1;ncodemax[1]=1;}
                   3192: 
                   3193:   first=1;
                   3194: 
1.169     brouard  3195:   /* for(k1=1; k1<=j ; k1++){ */  /* Loop on covariates */
                   3196:   /*  for(i1=1; i1<=ncodemax[k1];i1++){ */ /* Now it is 2 */
                   3197:   /*    j1++; */
1.145     brouard  3198:   for (j1 = 1; j1 <= (int) pow(2,cptcoveff); j1++){
1.126     brouard  3199:       /*printf("cptcoveff=%d Tvaraff=%d", cptcoveff,Tvaraff[1]);
                   3200:        scanf("%d", i);*/
                   3201:       for (i=-5; i<=nlstate+ndeath; i++)  
                   3202:        for (jk=-5; jk<=nlstate+ndeath; jk++)  
                   3203:          for(m=iagemin; m <= iagemax+3; m++)
                   3204:            freq[i][jk][m]=0;
1.143     brouard  3205:       
                   3206:       for (i=1; i<=nlstate; i++)  
                   3207:        for(m=iagemin; m <= iagemax+3; m++)
                   3208:          prop[i][m]=0;
1.126     brouard  3209:       
                   3210:       dateintsum=0;
                   3211:       k2cpt=0;
                   3212:       for (i=1; i<=imx; i++) {
                   3213:        bool=1;
1.144     brouard  3214:        if  (cptcovn>0) { /* Filter is here: Must be looked at for model=V1+V2+V3+V4 */
                   3215:          for (z1=1; z1<=cptcoveff; z1++)       
1.198     brouard  3216:             if (covar[Tvaraff[z1]][i]!= nbcode[Tvaraff[z1]][codtabm(j1,z1)]){
1.145     brouard  3217:                 /* Tests if the value of each of the covariates of i is equal to filter j1 */
1.144     brouard  3218:               bool=0;
1.198     brouard  3219:               /* 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", 
                   3220:                 bool,i,z1, z1, Tvaraff[z1],i,covar[Tvaraff[z1]][i],j1,z1,codtabm(j1,z1),
                   3221:                 j1,z1,nbcode[Tvaraff[z1]][codtabm(j1,z1)],j1);*/
                   3222:               /* For j1=7 in V1+V2+V3+V4 = 0 1 1 0 and codtabm(7,3)=1 and nbcde[3][?]=1*/
1.144     brouard  3223:             } 
1.126     brouard  3224:        }
1.144     brouard  3225:  
1.126     brouard  3226:        if (bool==1){
                   3227:          for(m=firstpass; m<=lastpass; m++){
                   3228:            k2=anint[m][i]+(mint[m][i]/12.);
                   3229:            /*if ((k2>=dateprev1) && (k2<=dateprev2)) {*/
                   3230:              if(agev[m][i]==0) agev[m][i]=iagemax+1;
                   3231:              if(agev[m][i]==1) agev[m][i]=iagemax+2;
                   3232:              if (s[m][i]>0 && s[m][i]<=nlstate) prop[s[m][i]][(int)agev[m][i]] += weight[i];
                   3233:              if (m<lastpass) {
                   3234:                freq[s[m][i]][s[m+1][i]][(int)agev[m][i]] += weight[i];
                   3235:                freq[s[m][i]][s[m+1][i]][iagemax+3] += weight[i];
                   3236:              }
                   3237:              
                   3238:              if ((agev[m][i]>1) && (agev[m][i]< (iagemax+3))) {
                   3239:                dateintsum=dateintsum+k2;
                   3240:                k2cpt++;
                   3241:              }
                   3242:              /*}*/
                   3243:          }
                   3244:        }
1.145     brouard  3245:       } /* end i */
1.126     brouard  3246:        
                   3247:       /*      fprintf(ficresp, "#Count between %.lf/%.lf/%.lf and %.lf/%.lf/%.lf\n",jprev1, mprev1,anprev1,jprev2, mprev2,anprev2);*/
                   3248:       pstamp(ficresp);
                   3249:       if  (cptcovn>0) {
                   3250:        fprintf(ficresp, "\n#********** Variable "); 
1.198     brouard  3251:        for (z1=1; z1<=cptcoveff; z1++) fprintf(ficresp, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
1.126     brouard  3252:        fprintf(ficresp, "**********\n#");
1.143     brouard  3253:        fprintf(ficlog, "\n#********** Variable "); 
1.198     brouard  3254:        for (z1=1; z1<=cptcoveff; z1++) fprintf(ficlog, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
1.143     brouard  3255:        fprintf(ficlog, "**********\n#");
1.126     brouard  3256:       }
                   3257:       for(i=1; i<=nlstate;i++) 
                   3258:        fprintf(ficresp, " Age Prev(%d) N(%d) N",i,i);
                   3259:       fprintf(ficresp, "\n");
                   3260:       
                   3261:       for(i=iagemin; i <= iagemax+3; i++){
                   3262:        if(i==iagemax+3){
                   3263:          fprintf(ficlog,"Total");
                   3264:        }else{
                   3265:          if(first==1){
                   3266:            first=0;
                   3267:            printf("See log file for details...\n");
                   3268:          }
                   3269:          fprintf(ficlog,"Age %d", i);
                   3270:        }
                   3271:        for(jk=1; jk <=nlstate ; jk++){
                   3272:          for(m=-1, pp[jk]=0; m <=nlstate+ndeath ; m++)
                   3273:            pp[jk] += freq[jk][m][i]; 
                   3274:        }
                   3275:        for(jk=1; jk <=nlstate ; jk++){
                   3276:          for(m=-1, pos=0; m <=0 ; m++)
                   3277:            pos += freq[jk][m][i];
                   3278:          if(pp[jk]>=1.e-10){
                   3279:            if(first==1){
1.132     brouard  3280:              printf(" %d.=%.0f loss[%d]=%.1f%%",jk,pp[jk],jk,100*pos/pp[jk]);
1.126     brouard  3281:            }
                   3282:            fprintf(ficlog," %d.=%.0f loss[%d]=%.1f%%",jk,pp[jk],jk,100*pos/pp[jk]);
                   3283:          }else{
                   3284:            if(first==1)
                   3285:              printf(" %d.=%.0f loss[%d]=NaNQ%%",jk,pp[jk],jk);
                   3286:            fprintf(ficlog," %d.=%.0f loss[%d]=NaNQ%%",jk,pp[jk],jk);
                   3287:          }
                   3288:        }
                   3289: 
                   3290:        for(jk=1; jk <=nlstate ; jk++){
                   3291:          for(m=0, pp[jk]=0; m <=nlstate+ndeath; m++)
                   3292:            pp[jk] += freq[jk][m][i];
                   3293:        }       
                   3294:        for(jk=1,pos=0,posprop=0; jk <=nlstate ; jk++){
                   3295:          pos += pp[jk];
                   3296:          posprop += prop[jk][i];
                   3297:        }
                   3298:        for(jk=1; jk <=nlstate ; jk++){
                   3299:          if(pos>=1.e-5){
                   3300:            if(first==1)
                   3301:              printf(" %d.=%.0f prev[%d]=%.1f%%",jk,pp[jk],jk,100*pp[jk]/pos);
                   3302:            fprintf(ficlog," %d.=%.0f prev[%d]=%.1f%%",jk,pp[jk],jk,100*pp[jk]/pos);
                   3303:          }else{
                   3304:            if(first==1)
                   3305:              printf(" %d.=%.0f prev[%d]=NaNQ%%",jk,pp[jk],jk);
                   3306:            fprintf(ficlog," %d.=%.0f prev[%d]=NaNQ%%",jk,pp[jk],jk);
                   3307:          }
                   3308:          if( i <= iagemax){
                   3309:            if(pos>=1.e-5){
                   3310:              fprintf(ficresp," %d %.5f %.0f %.0f",i,prop[jk][i]/posprop, prop[jk][i],posprop);
                   3311:              /*probs[i][jk][j1]= pp[jk]/pos;*/
                   3312:              /*printf("\ni=%d jk=%d j1=%d %.5f %.0f %.0f %f",i,jk,j1,pp[jk]/pos, pp[jk],pos,probs[i][jk][j1]);*/
                   3313:            }
                   3314:            else
                   3315:              fprintf(ficresp," %d NaNq %.0f %.0f",i,prop[jk][i],posprop);
                   3316:          }
                   3317:        }
                   3318:        
                   3319:        for(jk=-1; jk <=nlstate+ndeath; jk++)
                   3320:          for(m=-1; m <=nlstate+ndeath; m++)
                   3321:            if(freq[jk][m][i] !=0 ) {
                   3322:            if(first==1)
                   3323:              printf(" %d%d=%.0f",jk,m,freq[jk][m][i]);
                   3324:              fprintf(ficlog," %d%d=%.0f",jk,m,freq[jk][m][i]);
                   3325:            }
                   3326:        if(i <= iagemax)
                   3327:          fprintf(ficresp,"\n");
                   3328:        if(first==1)
                   3329:          printf("Others in log...\n");
                   3330:        fprintf(ficlog,"\n");
                   3331:       }
1.145     brouard  3332:       /*}*/
1.126     brouard  3333:   }
                   3334:   dateintmean=dateintsum/k2cpt; 
                   3335:  
                   3336:   fclose(ficresp);
                   3337:   free_ma3x(freq,-5,nlstate+ndeath,-5,nlstate+ndeath, iagemin, iagemax+3);
                   3338:   free_vector(pp,1,nlstate);
                   3339:   free_matrix(prop,1,nlstate,iagemin, iagemax+3);
                   3340:   /* End of Freq */
                   3341: }
                   3342: 
                   3343: /************ Prevalence ********************/
                   3344: 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)
                   3345: {  
                   3346:   /* Compute observed prevalence between dateprev1 and dateprev2 by counting the number of people
                   3347:      in each health status at the date of interview (if between dateprev1 and dateprev2).
                   3348:      We still use firstpass and lastpass as another selection.
                   3349:   */
                   3350:  
1.164     brouard  3351:   int i, m, jk, j1, bool, z1,j;
                   3352: 
                   3353:   double **prop;
                   3354:   double posprop; 
1.126     brouard  3355:   double  y2; /* in fractional years */
                   3356:   int iagemin, iagemax;
1.145     brouard  3357:   int first; /** to stop verbosity which is redirected to log file */
1.126     brouard  3358: 
                   3359:   iagemin= (int) agemin;
                   3360:   iagemax= (int) agemax;
                   3361:   /*pp=vector(1,nlstate);*/
                   3362:   prop=matrix(1,nlstate,iagemin,iagemax+3); 
                   3363:   /*  freq=ma3x(-1,nlstate+ndeath,-1,nlstate+ndeath,iagemin,iagemax+3);*/
                   3364:   j1=0;
                   3365:   
1.145     brouard  3366:   /*j=cptcoveff;*/
1.126     brouard  3367:   if (cptcovn<1) {j=1;ncodemax[1]=1;}
                   3368:   
1.145     brouard  3369:   first=1;
                   3370:   for(j1=1; j1<= (int) pow(2,cptcoveff);j1++){
                   3371:     /*for(i1=1; i1<=ncodemax[k1];i1++){
                   3372:       j1++;*/
1.126     brouard  3373:       
                   3374:       for (i=1; i<=nlstate; i++)  
                   3375:        for(m=iagemin; m <= iagemax+3; m++)
                   3376:          prop[i][m]=0.0;
                   3377:      
                   3378:       for (i=1; i<=imx; i++) { /* Each individual */
                   3379:        bool=1;
                   3380:        if  (cptcovn>0) {
                   3381:          for (z1=1; z1<=cptcoveff; z1++) 
1.198     brouard  3382:            if (covar[Tvaraff[z1]][i]!= nbcode[Tvaraff[z1]][codtabm(j1,z1)]) 
1.126     brouard  3383:              bool=0;
                   3384:        } 
                   3385:        if (bool==1) { 
                   3386:          for(m=firstpass; m<=lastpass; m++){/* Other selection (we can limit to certain interviews*/
                   3387:            y2=anint[m][i]+(mint[m][i]/12.); /* Fractional date in year */
                   3388:            if ((y2>=dateprev1) && (y2<=dateprev2)) { /* Here is the main selection (fractional years) */
                   3389:              if(agev[m][i]==0) agev[m][i]=iagemax+1;
                   3390:              if(agev[m][i]==1) agev[m][i]=iagemax+2;
                   3391:              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); 
                   3392:              if (s[m][i]>0 && s[m][i]<=nlstate) { 
                   3393:                /*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]]);*/
                   3394:                prop[s[m][i]][(int)agev[m][i]] += weight[i];
                   3395:                prop[s[m][i]][iagemax+3] += weight[i]; 
                   3396:              } 
                   3397:            }
                   3398:          } /* end selection of waves */
                   3399:        }
                   3400:       }
                   3401:       for(i=iagemin; i <= iagemax+3; i++){  
                   3402:        for(jk=1,posprop=0; jk <=nlstate ; jk++) { 
                   3403:          posprop += prop[jk][i]; 
                   3404:        } 
1.145     brouard  3405:        
1.126     brouard  3406:        for(jk=1; jk <=nlstate ; jk++){     
                   3407:          if( i <=  iagemax){ 
                   3408:            if(posprop>=1.e-5){ 
                   3409:              probs[i][jk][j1]= prop[jk][i]/posprop;
1.145     brouard  3410:            } else{
                   3411:              if(first==1){
                   3412:                first=0;
                   3413:                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]);
                   3414:              }
                   3415:            }
1.126     brouard  3416:          } 
                   3417:        }/* end jk */ 
                   3418:       }/* end i */ 
1.145     brouard  3419:     /*} *//* end i1 */
                   3420:   } /* end j1 */
1.126     brouard  3421:   
                   3422:   /*  free_ma3x(freq,-1,nlstate+ndeath,-1,nlstate+ndeath, iagemin, iagemax+3);*/
                   3423:   /*free_vector(pp,1,nlstate);*/
                   3424:   free_matrix(prop,1,nlstate, iagemin,iagemax+3);
                   3425: }  /* End of prevalence */
                   3426: 
                   3427: /************* Waves Concatenation ***************/
                   3428: 
                   3429: 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)
                   3430: {
                   3431:   /* Concatenates waves: wav[i] is the number of effective (useful waves) of individual i.
                   3432:      Death is a valid wave (if date is known).
                   3433:      mw[mi][i] is the mi (mi=1 to wav[i])  effective wave of individual i
                   3434:      dh[m][i] or dh[mw[mi][i]][i] is the delay between two effective waves m=mw[mi][i]
                   3435:      and mw[mi+1][i]. dh depends on stepm.
                   3436:      */
                   3437: 
                   3438:   int i, mi, m;
                   3439:   /* int j, k=0,jk, ju, jl,jmin=1e+5, jmax=-1;
                   3440:      double sum=0., jmean=0.;*/
                   3441:   int first;
                   3442:   int j, k=0,jk, ju, jl;
                   3443:   double sum=0.;
                   3444:   first=0;
1.164     brouard  3445:   jmin=100000;
1.126     brouard  3446:   jmax=-1;
                   3447:   jmean=0.;
                   3448:   for(i=1; i<=imx; i++){
                   3449:     mi=0;
                   3450:     m=firstpass;
                   3451:     while(s[m][i] <= nlstate){
                   3452:       if(s[m][i]>=1 || s[m][i]==-2 || s[m][i]==-4 || s[m][i]==-5)
                   3453:        mw[++mi][i]=m;
                   3454:       if(m >=lastpass)
                   3455:        break;
                   3456:       else
                   3457:        m++;
                   3458:     }/* end while */
                   3459:     if (s[m][i] > nlstate){
                   3460:       mi++;    /* Death is another wave */
                   3461:       /* if(mi==0)  never been interviewed correctly before death */
                   3462:         /* Only death is a correct wave */
                   3463:       mw[mi][i]=m;
                   3464:     }
                   3465: 
                   3466:     wav[i]=mi;
                   3467:     if(mi==0){
                   3468:       nbwarn++;
                   3469:       if(first==0){
                   3470:        printf("Warning! No valid information for individual %ld line=%d (skipped) and may be others, see log file\n",num[i],i);
                   3471:        first=1;
                   3472:       }
                   3473:       if(first==1){
                   3474:        fprintf(ficlog,"Warning! No valid information for individual %ld line=%d (skipped)\n",num[i],i);
                   3475:       }
                   3476:     } /* end mi==0 */
                   3477:   } /* End individuals */
                   3478: 
                   3479:   for(i=1; i<=imx; i++){
                   3480:     for(mi=1; mi<wav[i];mi++){
                   3481:       if (stepm <=0)
                   3482:        dh[mi][i]=1;
                   3483:       else{
                   3484:        if (s[mw[mi+1][i]][i] > nlstate) { /* A death */
                   3485:          if (agedc[i] < 2*AGESUP) {
                   3486:            j= rint(agedc[i]*12-agev[mw[mi][i]][i]*12); 
                   3487:            if(j==0) j=1;  /* Survives at least one month after exam */
                   3488:            else if(j<0){
                   3489:              nberr++;
                   3490:              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]);
                   3491:              j=1; /* Temporary Dangerous patch */
                   3492:              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);
                   3493:              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]);
                   3494:              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);
                   3495:            }
                   3496:            k=k+1;
                   3497:            if (j >= jmax){
                   3498:              jmax=j;
                   3499:              ijmax=i;
                   3500:            }
                   3501:            if (j <= jmin){
                   3502:              jmin=j;
                   3503:              ijmin=i;
                   3504:            }
                   3505:            sum=sum+j;
                   3506:            /*if (j<0) printf("j=%d num=%d \n",j,i);*/
                   3507:            /*    printf("%d %d %d %d\n", s[mw[mi][i]][i] ,s[mw[mi+1][i]][i],j,i);*/
                   3508:          }
                   3509:        }
                   3510:        else{
                   3511:          j= rint( (agev[mw[mi+1][i]][i]*12 - agev[mw[mi][i]][i]*12));
                   3512: /*       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]); */
                   3513: 
                   3514:          k=k+1;
                   3515:          if (j >= jmax) {
                   3516:            jmax=j;
                   3517:            ijmax=i;
                   3518:          }
                   3519:          else if (j <= jmin){
                   3520:            jmin=j;
                   3521:            ijmin=i;
                   3522:          }
                   3523:          /*        if (j<10) printf("j=%d jmin=%d num=%d ",j,jmin,i); */
                   3524:          /*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]);*/
                   3525:          if(j<0){
                   3526:            nberr++;
                   3527:            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]);
                   3528:            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]);
                   3529:          }
                   3530:          sum=sum+j;
                   3531:        }
                   3532:        jk= j/stepm;
                   3533:        jl= j -jk*stepm;
                   3534:        ju= j -(jk+1)*stepm;
                   3535:        if(mle <=1){ /* only if we use a the linear-interpoloation pseudo-likelihood */
                   3536:          if(jl==0){
                   3537:            dh[mi][i]=jk;
                   3538:            bh[mi][i]=0;
                   3539:          }else{ /* We want a negative bias in order to only have interpolation ie
1.136     brouard  3540:                  * to avoid the price of an extra matrix product in likelihood */
1.126     brouard  3541:            dh[mi][i]=jk+1;
                   3542:            bh[mi][i]=ju;
                   3543:          }
                   3544:        }else{
                   3545:          if(jl <= -ju){
                   3546:            dh[mi][i]=jk;
                   3547:            bh[mi][i]=jl;       /* bias is positive if real duration
                   3548:                                 * is higher than the multiple of stepm and negative otherwise.
                   3549:                                 */
                   3550:          }
                   3551:          else{
                   3552:            dh[mi][i]=jk+1;
                   3553:            bh[mi][i]=ju;
                   3554:          }
                   3555:          if(dh[mi][i]==0){
                   3556:            dh[mi][i]=1; /* At least one step */
                   3557:            bh[mi][i]=ju; /* At least one step */
                   3558:            /*  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);*/
                   3559:          }
                   3560:        } /* end if mle */
                   3561:       }
                   3562:     } /* end wave */
                   3563:   }
                   3564:   jmean=sum/k;
                   3565:   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  3566:   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  3567:  }
                   3568: 
                   3569: /*********** Tricode ****************************/
1.145     brouard  3570: void tricode(int *Tvar, int **nbcode, int imx, int *Ndum)
1.126     brouard  3571: {
1.144     brouard  3572:   /**< Uses cptcovn+2*cptcovprod as the number of covariates */
                   3573:   /*     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  3574:    * Boring subroutine which should only output nbcode[Tvar[j]][k]
1.145     brouard  3575:    * Tvar[5] in V2+V1+V3*age+V2*V4 is 2 (V2)
1.169     brouard  3576:    * nbcode[Tvar[j]][1]= 
1.144     brouard  3577:   */
1.130     brouard  3578: 
1.145     brouard  3579:   int ij=1, k=0, j=0, i=0, maxncov=NCOVMAX;
1.136     brouard  3580:   int modmaxcovj=0; /* Modality max of covariates j */
1.145     brouard  3581:   int cptcode=0; /* Modality max of covariates j */
                   3582:   int modmincovj=0; /* Modality min of covariates j */
                   3583: 
                   3584: 
1.126     brouard  3585:   cptcoveff=0; 
                   3586:  
1.144     brouard  3587:   for (k=1; k <= maxncov; k++) ncodemax[k]=0; /* Horrible constant again replaced by NCOVMAX */
1.126     brouard  3588: 
1.145     brouard  3589:   /* Loop on covariates without age and products */
1.186     brouard  3590:   for (j=1; j<=(cptcovs); j++) { /* From model V1 + V2*age+ V3 + V3*V4 keeps V1 + V3 = 2 only */
1.192     brouard  3591:     for (k=-1; k < maxncov; k++) Ndum[k]=0;
1.186     brouard  3592:     for (i=1; i<=imx; i++) { /* Loop on individuals: reads the data file to get the maximum value of the 
1.136     brouard  3593:                               modality of this covariate Vj*/ 
1.145     brouard  3594:       ij=(int)(covar[Tvar[j]][i]); /* ij=0 or 1 or -1. Value of the covariate Tvar[j] for individual i
                   3595:                                    * If product of Vn*Vm, still boolean *:
                   3596:                                    * If it was coded 1, 2, 3, 4 should be splitted into 3 boolean variables
                   3597:                                    * 1 => 0 0 0, 2 => 0 0 1, 3 => 0 1 1, 4=1 0 0   */
                   3598:       /* Finds for covariate j, n=Tvar[j] of Vn . ij is the
1.136     brouard  3599:                                      modality of the nth covariate of individual i. */
1.145     brouard  3600:       if (ij > modmaxcovj)
                   3601:         modmaxcovj=ij; 
                   3602:       else if (ij < modmincovj) 
                   3603:        modmincovj=ij; 
                   3604:       if ((ij < -1) && (ij > NCOVMAX)){
                   3605:        printf( "Error: minimal is less than -1 or maximal is bigger than %d. Exiting. \n", NCOVMAX );
                   3606:        exit(1);
                   3607:       }else
1.136     brouard  3608:       Ndum[ij]++; /*counts and stores the occurence of this modality 0, 1, -1*/
1.145     brouard  3609:       /*  If coded 1, 2, 3 , counts the number of 1 Ndum[1], number of 2, Ndum[2], etc */
1.126     brouard  3610:       /*printf("i=%d ij=%d Ndum[ij]=%d imx=%d",i,ij,Ndum[ij],imx);*/
1.136     brouard  3611:       /* getting the maximum value of the modality of the covariate
                   3612:         (should be 0 or 1 now) Tvar[j]. If V=sex and male is coded 0 and
                   3613:         female is 1, then modmaxcovj=1.*/
1.192     brouard  3614:     } /* end for loop on individuals i */
1.145     brouard  3615:     printf(" Minimal and maximal values of %d th covariate V%d: min=%d max=%d \n", j, Tvar[j], modmincovj, modmaxcovj);
1.192     brouard  3616:     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  3617:     cptcode=modmaxcovj;
1.137     brouard  3618:     /* Ndum[0] = frequency of 0 for model-covariate j, Ndum[1] frequency of 1 etc. */
1.145     brouard  3619:    /*for (i=0; i<=cptcode; i++) {*/
1.192     brouard  3620:     for (k=modmincovj;  k<=modmaxcovj; k++) { /* k=-1 ? 0 and 1*//* For each value k of the modality of model-cov j */
                   3621:       printf("Frequencies of covariates %d ie V%d with value %d: %d\n", j, Tvar[j], k, Ndum[k]);
                   3622:       fprintf(ficlog, "Frequencies of covariates %d ie V%d with value %d: %d\n", j, Tvar[j], k, Ndum[k]);
                   3623:       if( Ndum[k] != 0 ){ /* Counts if nobody answered modality k ie empty modality, we skip it and reorder */
                   3624:        if( k != -1){
                   3625:          ncodemax[j]++;  /* ncodemax[j]= Number of modalities of the j th
                   3626:                             covariate for which somebody answered excluding 
                   3627:                             undefined. Usually 2: 0 and 1. */
                   3628:        }
                   3629:        ncodemaxwundef[j]++; /* ncodemax[j]= Number of modalities of the j th
                   3630:                             covariate for which somebody answered including 
                   3631:                             undefined. Usually 3: -1, 0 and 1. */
1.145     brouard  3632:       }
                   3633:       /* In fact  ncodemax[j]=2 (dichotom. variables only) but it could be more for
                   3634:         historical reasons: 3 if coded 1, 2, 3 and 4 and Ndum[2]=0 */
1.131     brouard  3635:     } /* Ndum[-1] number of undefined modalities */
1.126     brouard  3636: 
1.136     brouard  3637:     /* j is a covariate, n=Tvar[j] of Vn; Fills nbcode */
1.186     brouard  3638:     /* For covariate j, modalities could be 1, 2, 3, 4, 5, 6, 7. 
                   3639:        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  3640:        modmincovj=3; modmaxcovj = 7;
1.186     brouard  3641:        There are only 3 modalities non empty 3, 6, 7 (or 2 if 27 is too few) : ncodemax[j]=3;
                   3642:        which will be coded 0, 1, 2 which in binary on 2=3-1 digits are 0=00 1=01, 2=10;
                   3643:        defining two dummy variables: variables V1_1 and V1_2.
1.145     brouard  3644:        nbcode[Tvar[j]][ij]=k;
                   3645:        nbcode[Tvar[j]][1]=0;
                   3646:        nbcode[Tvar[j]][2]=1;
                   3647:        nbcode[Tvar[j]][3]=2;
1.197     brouard  3648:        To be continued (not working yet).
1.145     brouard  3649:     */
1.197     brouard  3650:     ij=0; /* ij is similar to i but can jump over null modalities */
                   3651:     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*/
                   3652:        if (Ndum[i] == 0) { /* If nobody responded to this modality k */
1.192     brouard  3653:          break;
                   3654:        }
                   3655:        ij++;
1.197     brouard  3656:        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  3657:        cptcode = ij; /* New max modality for covar j */
                   3658:     } /* end of loop on modality i=-1 to 1 or more */
                   3659:       
                   3660:     /*   for (k=0; k<= cptcode; k++) { /\* k=-1 ? k=0 to 1 *\//\* Could be 1 to 4 *\//\* cptcode=modmaxcovj *\/ */
                   3661:     /*         /\*recode from 0 *\/ */
                   3662:     /*                                      k is a modality. If we have model=V1+V1*sex  */
                   3663:     /*                                      then: nbcode[1][1]=0 ; nbcode[1][2]=1; nbcode[2][1]=0 ; nbcode[2][2]=1; */
                   3664:     /*                                   But if some modality were not used, it is recoded from 0 to a newer modmaxcovj=cptcode *\/ */
                   3665:     /*         } */
                   3666:     /*         /\* cptcode = ij; *\/ /\* New max modality for covar j *\/ */
                   3667:     /*         if (ij > ncodemax[j]) { */
                   3668:     /*           printf( " Error ij=%d > ncodemax[%d]=%d\n", ij, j, ncodemax[j]);  */
                   3669:     /*           fprintf(ficlog, " Error ij=%d > ncodemax[%d]=%d\n", ij, j, ncodemax[j]); */
                   3670:     /*           break; */
                   3671:     /*         } */
                   3672:     /*   }  /\* end of loop on modality k *\/ */
1.137     brouard  3673:   } /* end of loop on model-covariate j. nbcode[Tvarj][1]=0 and nbcode[Tvarj][2]=1 sets the value of covariate j*/  
                   3674:   
1.145     brouard  3675:  for (k=-1; k< maxncov; k++) Ndum[k]=0; 
1.137     brouard  3676:   
1.187     brouard  3677:   for (i=1; i<=ncovmodel-2-nagesqr; i++) { /* -2, cste and age and eventually age*age */ 
1.145     brouard  3678:    /* Listing of all covariables in statement model to see if some covariates appear twice. For example, V1 appears twice in V1+V1*V2.*/ 
                   3679:    ij=Tvar[i]; /* Tvar might be -1 if status was unknown */ 
1.187     brouard  3680:    Ndum[ij]++; /* Might be supersed V1 + V1*age */
1.145     brouard  3681:  } 
1.126     brouard  3682: 
1.192     brouard  3683:  ij=0;
1.145     brouard  3684:  for (i=0; i<=  maxncov-1; i++) { /* modmaxcovj is unknown here. Only Ndum[2(V2),3(age*V3), 5(V3*V2) 6(V1*V4) */
                   3685:    /*printf("Ndum[%d]=%d\n",i, Ndum[i]);*/
1.126     brouard  3686:    if((Ndum[i]!=0) && (i<=ncovcol)){
1.192     brouard  3687:      ij++;
1.145     brouard  3688:      /*printf("diff Ndum[%d]=%d\n",i, Ndum[i]);*/
                   3689:      Tvaraff[ij]=i; /*For printing (unclear) */
1.192     brouard  3690:    }else{
                   3691:        /* Tvaraff[ij]=0; */
                   3692:    }
1.126     brouard  3693:  }
1.192     brouard  3694:  /* ij--; */
1.144     brouard  3695:  cptcoveff=ij; /*Number of total covariates*/
1.145     brouard  3696: 
1.126     brouard  3697: }
                   3698: 
1.145     brouard  3699: 
1.126     brouard  3700: /*********** Health Expectancies ****************/
                   3701: 
1.127     brouard  3702: 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  3703: 
                   3704: {
                   3705:   /* Health expectancies, no variances */
1.164     brouard  3706:   int i, j, nhstepm, hstepm, h, nstepm;
1.126     brouard  3707:   int nhstepma, nstepma; /* Decreasing with age */
                   3708:   double age, agelim, hf;
                   3709:   double ***p3mat;
                   3710:   double eip;
                   3711: 
                   3712:   pstamp(ficreseij);
                   3713:   fprintf(ficreseij,"# (a) Life expectancies by health status at initial age and (b) health expectancies by health status at initial age\n");
                   3714:   fprintf(ficreseij,"# Age");
                   3715:   for(i=1; i<=nlstate;i++){
                   3716:     for(j=1; j<=nlstate;j++){
                   3717:       fprintf(ficreseij," e%1d%1d ",i,j);
                   3718:     }
                   3719:     fprintf(ficreseij," e%1d. ",i);
                   3720:   }
                   3721:   fprintf(ficreseij,"\n");
                   3722: 
                   3723:   
                   3724:   if(estepm < stepm){
                   3725:     printf ("Problem %d lower than %d\n",estepm, stepm);
                   3726:   }
                   3727:   else  hstepm=estepm;   
                   3728:   /* We compute the life expectancy from trapezoids spaced every estepm months
                   3729:    * This is mainly to measure the difference between two models: for example
                   3730:    * if stepm=24 months pijx are given only every 2 years and by summing them
                   3731:    * we are calculating an estimate of the Life Expectancy assuming a linear 
                   3732:    * progression in between and thus overestimating or underestimating according
                   3733:    * to the curvature of the survival function. If, for the same date, we 
                   3734:    * estimate the model with stepm=1 month, we can keep estepm to 24 months
                   3735:    * to compare the new estimate of Life expectancy with the same linear 
                   3736:    * hypothesis. A more precise result, taking into account a more precise
                   3737:    * curvature will be obtained if estepm is as small as stepm. */
                   3738: 
                   3739:   /* For example we decided to compute the life expectancy with the smallest unit */
                   3740:   /* hstepm beeing the number of stepms, if hstepm=1 the length of hstepm is stepm. 
                   3741:      nhstepm is the number of hstepm from age to agelim 
                   3742:      nstepm is the number of stepm from age to agelin. 
                   3743:      Look at hpijx to understand the reason of that which relies in memory size
                   3744:      and note for a fixed period like estepm months */
                   3745:   /* We decided (b) to get a life expectancy respecting the most precise curvature of the
                   3746:      survival function given by stepm (the optimization length). Unfortunately it
                   3747:      means that if the survival funtion is printed only each two years of age and if
                   3748:      you sum them up and add 1 year (area under the trapezoids) you won't get the same 
                   3749:      results. So we changed our mind and took the option of the best precision.
                   3750:   */
                   3751:   hstepm=hstepm/stepm; /* Typically in stepm units, if stepm=6 & estepm=24 , = 24/6 months = 4 */ 
                   3752: 
                   3753:   agelim=AGESUP;
                   3754:   /* If stepm=6 months */
                   3755:     /* Computed by stepm unit matrices, product of hstepm matrices, stored
                   3756:        in an array of nhstepm length: nhstepm=10, hstepm=4, stepm=6 months */
                   3757:     
                   3758: /* nhstepm age range expressed in number of stepm */
                   3759:   nstepm=(int) rint((agelim-bage)*YEARM/stepm); /* Biggest nstepm */
                   3760:   /* Typically if 20 years nstepm = 20*12/6=40 stepm */ 
                   3761:   /* if (stepm >= YEARM) hstepm=1;*/
                   3762:   nhstepm = nstepm/hstepm;/* Expressed in hstepm, typically nhstepm=40/4=10 */
                   3763:   p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   3764: 
                   3765:   for (age=bage; age<=fage; age ++){ 
                   3766:     nstepma=(int) rint((agelim-bage)*YEARM/stepm); /* Biggest nstepm */
                   3767:     /* Typically if 20 years nstepm = 20*12/6=40 stepm */ 
                   3768:     /* if (stepm >= YEARM) hstepm=1;*/
                   3769:     nhstepma = nstepma/hstepm;/* Expressed in hstepm, typically nhstepma=40/4=10 */
                   3770: 
                   3771:     /* If stepm=6 months */
                   3772:     /* Computed by stepm unit matrices, product of hstepma matrices, stored
                   3773:        in an array of nhstepma length: nhstepma=10, hstepm=4, stepm=6 months */
                   3774:     
                   3775:     hpxij(p3mat,nhstepma,age,hstepm,x,nlstate,stepm,oldm, savm, cij);  
                   3776:     
                   3777:     hf=hstepm*stepm/YEARM;  /* Duration of hstepm expressed in year unit. */
                   3778:     
                   3779:     printf("%d|",(int)age);fflush(stdout);
                   3780:     fprintf(ficlog,"%d|",(int)age);fflush(ficlog);
                   3781:     
                   3782:     /* Computing expectancies */
                   3783:     for(i=1; i<=nlstate;i++)
                   3784:       for(j=1; j<=nlstate;j++)
                   3785:        for (h=0, eij[i][j][(int)age]=0; h<=nhstepm-1; h++){
                   3786:          eij[i][j][(int)age] += (p3mat[i][j][h]+p3mat[i][j][h+1])/2.0*hf;
                   3787:          
                   3788:          /* 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]);*/
                   3789: 
                   3790:        }
                   3791: 
                   3792:     fprintf(ficreseij,"%3.0f",age );
                   3793:     for(i=1; i<=nlstate;i++){
                   3794:       eip=0;
                   3795:       for(j=1; j<=nlstate;j++){
                   3796:        eip +=eij[i][j][(int)age];
                   3797:        fprintf(ficreseij,"%9.4f", eij[i][j][(int)age] );
                   3798:       }
                   3799:       fprintf(ficreseij,"%9.4f", eip );
                   3800:     }
                   3801:     fprintf(ficreseij,"\n");
                   3802:     
                   3803:   }
                   3804:   free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   3805:   printf("\n");
                   3806:   fprintf(ficlog,"\n");
                   3807:   
                   3808: }
                   3809: 
1.127     brouard  3810: 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  3811: 
                   3812: {
                   3813:   /* Covariances of health expectancies eij and of total life expectancies according
                   3814:    to initial status i, ei. .
                   3815:   */
                   3816:   int i, j, nhstepm, hstepm, h, nstepm, k, cptj, cptj2, i2, j2, ij, ji;
                   3817:   int nhstepma, nstepma; /* Decreasing with age */
                   3818:   double age, agelim, hf;
                   3819:   double ***p3matp, ***p3matm, ***varhe;
                   3820:   double **dnewm,**doldm;
                   3821:   double *xp, *xm;
                   3822:   double **gp, **gm;
                   3823:   double ***gradg, ***trgradg;
                   3824:   int theta;
                   3825: 
                   3826:   double eip, vip;
                   3827: 
                   3828:   varhe=ma3x(1,nlstate*nlstate,1,nlstate*nlstate,(int) bage, (int) fage);
                   3829:   xp=vector(1,npar);
                   3830:   xm=vector(1,npar);
                   3831:   dnewm=matrix(1,nlstate*nlstate,1,npar);
                   3832:   doldm=matrix(1,nlstate*nlstate,1,nlstate*nlstate);
                   3833:   
                   3834:   pstamp(ficresstdeij);
                   3835:   fprintf(ficresstdeij,"# Health expectancies with standard errors\n");
                   3836:   fprintf(ficresstdeij,"# Age");
                   3837:   for(i=1; i<=nlstate;i++){
                   3838:     for(j=1; j<=nlstate;j++)
                   3839:       fprintf(ficresstdeij," e%1d%1d (SE)",i,j);
                   3840:     fprintf(ficresstdeij," e%1d. ",i);
                   3841:   }
                   3842:   fprintf(ficresstdeij,"\n");
                   3843: 
                   3844:   pstamp(ficrescveij);
                   3845:   fprintf(ficrescveij,"# Subdiagonal matrix of covariances of health expectancies by age: cov(eij,ekl)\n");
                   3846:   fprintf(ficrescveij,"# Age");
                   3847:   for(i=1; i<=nlstate;i++)
                   3848:     for(j=1; j<=nlstate;j++){
                   3849:       cptj= (j-1)*nlstate+i;
                   3850:       for(i2=1; i2<=nlstate;i2++)
                   3851:        for(j2=1; j2<=nlstate;j2++){
                   3852:          cptj2= (j2-1)*nlstate+i2;
                   3853:          if(cptj2 <= cptj)
                   3854:            fprintf(ficrescveij,"  %1d%1d,%1d%1d",i,j,i2,j2);
                   3855:        }
                   3856:     }
                   3857:   fprintf(ficrescveij,"\n");
                   3858:   
                   3859:   if(estepm < stepm){
                   3860:     printf ("Problem %d lower than %d\n",estepm, stepm);
                   3861:   }
                   3862:   else  hstepm=estepm;   
                   3863:   /* We compute the life expectancy from trapezoids spaced every estepm months
                   3864:    * This is mainly to measure the difference between two models: for example
                   3865:    * if stepm=24 months pijx are given only every 2 years and by summing them
                   3866:    * we are calculating an estimate of the Life Expectancy assuming a linear 
                   3867:    * progression in between and thus overestimating or underestimating according
                   3868:    * to the curvature of the survival function. If, for the same date, we 
                   3869:    * estimate the model with stepm=1 month, we can keep estepm to 24 months
                   3870:    * to compare the new estimate of Life expectancy with the same linear 
                   3871:    * hypothesis. A more precise result, taking into account a more precise
                   3872:    * curvature will be obtained if estepm is as small as stepm. */
                   3873: 
                   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. 
                   3878:      Look at hpijx to understand the reason of that which relies in memory size
                   3879:      and note for a fixed period like estepm months */
                   3880:   /* We decided (b) to get a life expectancy respecting the most precise curvature of the
                   3881:      survival function given by stepm (the optimization length). Unfortunately it
                   3882:      means that if the survival funtion is printed only each two years of age and if
                   3883:      you sum them up and add 1 year (area under the trapezoids) you won't get the same 
                   3884:      results. So we changed our mind and took the option of the best precision.
                   3885:   */
                   3886:   hstepm=hstepm/stepm; /* Typically in stepm units, if stepm=6 & estepm=24 , = 24/6 months = 4 */ 
                   3887: 
                   3888:   /* If stepm=6 months */
                   3889:   /* nhstepm age range expressed in number of stepm */
                   3890:   agelim=AGESUP;
                   3891:   nstepm=(int) rint((agelim-bage)*YEARM/stepm); 
                   3892:   /* Typically if 20 years nstepm = 20*12/6=40 stepm */ 
                   3893:   /* if (stepm >= YEARM) hstepm=1;*/
                   3894:   nhstepm = nstepm/hstepm;/* Expressed in hstepm, typically nhstepm=40/4=10 */
                   3895:   
                   3896:   p3matp=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   3897:   p3matm=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   3898:   gradg=ma3x(0,nhstepm,1,npar,1,nlstate*nlstate);
                   3899:   trgradg =ma3x(0,nhstepm,1,nlstate*nlstate,1,npar);
                   3900:   gp=matrix(0,nhstepm,1,nlstate*nlstate);
                   3901:   gm=matrix(0,nhstepm,1,nlstate*nlstate);
                   3902: 
                   3903:   for (age=bage; age<=fage; age ++){ 
                   3904:     nstepma=(int) rint((agelim-bage)*YEARM/stepm); /* Biggest nstepm */
                   3905:     /* Typically if 20 years nstepm = 20*12/6=40 stepm */ 
                   3906:     /* if (stepm >= YEARM) hstepm=1;*/
                   3907:     nhstepma = nstepma/hstepm;/* Expressed in hstepm, typically nhstepma=40/4=10 */
                   3908: 
                   3909:     /* If stepm=6 months */
                   3910:     /* Computed by stepm unit matrices, product of hstepma matrices, stored
                   3911:        in an array of nhstepma length: nhstepma=10, hstepm=4, stepm=6 months */
                   3912:     
                   3913:     hf=hstepm*stepm/YEARM;  /* Duration of hstepm expressed in year unit. */
                   3914: 
                   3915:     /* Computing  Variances of health expectancies */
                   3916:     /* Gradient is computed with plus gp and minus gm. Code is duplicated in order to
                   3917:        decrease memory allocation */
                   3918:     for(theta=1; theta <=npar; theta++){
                   3919:       for(i=1; i<=npar; i++){ 
                   3920:        xp[i] = x[i] + (i==theta ?delti[theta]:0);
                   3921:        xm[i] = x[i] - (i==theta ?delti[theta]:0);
                   3922:       }
                   3923:       hpxij(p3matp,nhstepm,age,hstepm,xp,nlstate,stepm,oldm,savm, cij);  
                   3924:       hpxij(p3matm,nhstepm,age,hstepm,xm,nlstate,stepm,oldm,savm, cij);  
                   3925:   
                   3926:       for(j=1; j<= nlstate; j++){
                   3927:        for(i=1; i<=nlstate; i++){
                   3928:          for(h=0; h<=nhstepm-1; h++){
                   3929:            gp[h][(j-1)*nlstate + i] = (p3matp[i][j][h]+p3matp[i][j][h+1])/2.;
                   3930:            gm[h][(j-1)*nlstate + i] = (p3matm[i][j][h]+p3matm[i][j][h+1])/2.;
                   3931:          }
                   3932:        }
                   3933:       }
                   3934:      
                   3935:       for(ij=1; ij<= nlstate*nlstate; ij++)
                   3936:        for(h=0; h<=nhstepm-1; h++){
                   3937:          gradg[h][theta][ij]= (gp[h][ij]-gm[h][ij])/2./delti[theta];
                   3938:        }
                   3939:     }/* End theta */
                   3940:     
                   3941:     
                   3942:     for(h=0; h<=nhstepm-1; h++)
                   3943:       for(j=1; j<=nlstate*nlstate;j++)
                   3944:        for(theta=1; theta <=npar; theta++)
                   3945:          trgradg[h][j][theta]=gradg[h][theta][j];
                   3946:     
                   3947: 
                   3948:      for(ij=1;ij<=nlstate*nlstate;ij++)
                   3949:       for(ji=1;ji<=nlstate*nlstate;ji++)
                   3950:        varhe[ij][ji][(int)age] =0.;
                   3951: 
                   3952:      printf("%d|",(int)age);fflush(stdout);
                   3953:      fprintf(ficlog,"%d|",(int)age);fflush(ficlog);
                   3954:      for(h=0;h<=nhstepm-1;h++){
                   3955:       for(k=0;k<=nhstepm-1;k++){
                   3956:        matprod2(dnewm,trgradg[h],1,nlstate*nlstate,1,npar,1,npar,matcov);
                   3957:        matprod2(doldm,dnewm,1,nlstate*nlstate,1,npar,1,nlstate*nlstate,gradg[k]);
                   3958:        for(ij=1;ij<=nlstate*nlstate;ij++)
                   3959:          for(ji=1;ji<=nlstate*nlstate;ji++)
                   3960:            varhe[ij][ji][(int)age] += doldm[ij][ji]*hf*hf;
                   3961:       }
                   3962:     }
                   3963: 
                   3964:     /* Computing expectancies */
                   3965:     hpxij(p3matm,nhstepm,age,hstepm,x,nlstate,stepm,oldm, savm, cij);  
                   3966:     for(i=1; i<=nlstate;i++)
                   3967:       for(j=1; j<=nlstate;j++)
                   3968:        for (h=0, eij[i][j][(int)age]=0; h<=nhstepm-1; h++){
                   3969:          eij[i][j][(int)age] += (p3matm[i][j][h]+p3matm[i][j][h+1])/2.0*hf;
                   3970:          
                   3971:          /* 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]);*/
                   3972: 
                   3973:        }
                   3974: 
                   3975:     fprintf(ficresstdeij,"%3.0f",age );
                   3976:     for(i=1; i<=nlstate;i++){
                   3977:       eip=0.;
                   3978:       vip=0.;
                   3979:       for(j=1; j<=nlstate;j++){
                   3980:        eip += eij[i][j][(int)age];
                   3981:        for(k=1; k<=nlstate;k++) /* Sum on j and k of cov(eij,eik) */
                   3982:          vip += varhe[(j-1)*nlstate+i][(k-1)*nlstate+i][(int)age];
                   3983:        fprintf(ficresstdeij," %9.4f (%.4f)", eij[i][j][(int)age], sqrt(varhe[(j-1)*nlstate+i][(j-1)*nlstate+i][(int)age]) );
                   3984:       }
                   3985:       fprintf(ficresstdeij," %9.4f (%.4f)", eip, sqrt(vip));
                   3986:     }
                   3987:     fprintf(ficresstdeij,"\n");
                   3988: 
                   3989:     fprintf(ficrescveij,"%3.0f",age );
                   3990:     for(i=1; i<=nlstate;i++)
                   3991:       for(j=1; j<=nlstate;j++){
                   3992:        cptj= (j-1)*nlstate+i;
                   3993:        for(i2=1; i2<=nlstate;i2++)
                   3994:          for(j2=1; j2<=nlstate;j2++){
                   3995:            cptj2= (j2-1)*nlstate+i2;
                   3996:            if(cptj2 <= cptj)
                   3997:              fprintf(ficrescveij," %.4f", varhe[cptj][cptj2][(int)age]);
                   3998:          }
                   3999:       }
                   4000:     fprintf(ficrescveij,"\n");
                   4001:    
                   4002:   }
                   4003:   free_matrix(gm,0,nhstepm,1,nlstate*nlstate);
                   4004:   free_matrix(gp,0,nhstepm,1,nlstate*nlstate);
                   4005:   free_ma3x(gradg,0,nhstepm,1,npar,1,nlstate*nlstate);
                   4006:   free_ma3x(trgradg,0,nhstepm,1,nlstate*nlstate,1,npar);
                   4007:   free_ma3x(p3matm,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   4008:   free_ma3x(p3matp,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   4009:   printf("\n");
                   4010:   fprintf(ficlog,"\n");
                   4011: 
                   4012:   free_vector(xm,1,npar);
                   4013:   free_vector(xp,1,npar);
                   4014:   free_matrix(dnewm,1,nlstate*nlstate,1,npar);
                   4015:   free_matrix(doldm,1,nlstate*nlstate,1,nlstate*nlstate);
                   4016:   free_ma3x(varhe,1,nlstate*nlstate,1,nlstate*nlstate,(int) bage, (int)fage);
                   4017: }
                   4018: 
                   4019: /************ Variance ******************/
1.209   ! brouard  4020:  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 *ncvyearp, int ij, int estepm, int cptcov, int cptcod, int popbased, int mobilav, char strstart[])
1.126     brouard  4021: {
                   4022:   /* Variance of health expectancies */
                   4023:   /*  double **prevalim(double **prlim, int nlstate, double *xp, double age, double **oldm, double ** savm,double ftolpl);*/
                   4024:   /* double **newm;*/
1.169     brouard  4025:   /* int movingaverage(double ***probs, double bage,double fage, double ***mobaverage, int mobilav)*/
                   4026:   
                   4027:   int movingaverage();
1.126     brouard  4028:   double **dnewm,**doldm;
                   4029:   double **dnewmp,**doldmp;
                   4030:   int i, j, nhstepm, hstepm, h, nstepm ;
1.164     brouard  4031:   int k;
1.126     brouard  4032:   double *xp;
                   4033:   double **gp, **gm;  /* for var eij */
                   4034:   double ***gradg, ***trgradg; /*for var eij */
                   4035:   double **gradgp, **trgradgp; /* for var p point j */
                   4036:   double *gpp, *gmp; /* for var p point j */
                   4037:   double **varppt; /* for var p point j nlstate to nlstate+ndeath */
                   4038:   double ***p3mat;
                   4039:   double age,agelim, hf;
                   4040:   double ***mobaverage;
                   4041:   int theta;
                   4042:   char digit[4];
                   4043:   char digitp[25];
                   4044: 
                   4045:   char fileresprobmorprev[FILENAMELENGTH];
                   4046: 
                   4047:   if(popbased==1){
                   4048:     if(mobilav!=0)
1.201     brouard  4049:       strcpy(digitp,"-POPULBASED-MOBILAV_");
                   4050:     else strcpy(digitp,"-POPULBASED-NOMOBIL_");
1.126     brouard  4051:   }
                   4052:   else 
1.201     brouard  4053:     strcpy(digitp,"-STABLBASED_");
1.126     brouard  4054: 
                   4055:   if (mobilav!=0) {
                   4056:     mobaverage= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
                   4057:     if (movingaverage(probs, bage, fage, mobaverage,mobilav)!=0){
                   4058:       fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav);
                   4059:       printf(" Error in movingaverage mobilav=%d\n",mobilav);
                   4060:     }
                   4061:   }
                   4062: 
1.201     brouard  4063:   strcpy(fileresprobmorprev,"PRMORPREV-"); 
1.126     brouard  4064:   sprintf(digit,"%-d",ij);
                   4065:   /*printf("DIGIT=%s, ij=%d ijr=%-d|\n",digit, ij,ij);*/
                   4066:   strcat(fileresprobmorprev,digit); /* Tvar to be done */
                   4067:   strcat(fileresprobmorprev,digitp); /* Popbased or not, mobilav or not */
1.202     brouard  4068:   strcat(fileresprobmorprev,fileresu);
1.126     brouard  4069:   if((ficresprobmorprev=fopen(fileresprobmorprev,"w"))==NULL) {
                   4070:     printf("Problem with resultfile: %s\n", fileresprobmorprev);
                   4071:     fprintf(ficlog,"Problem with resultfile: %s\n", fileresprobmorprev);
                   4072:   }
                   4073:   printf("Computing total mortality p.j=w1*p1j+w2*p2j+..: result on file '%s' \n",fileresprobmorprev);
                   4074:   fprintf(ficlog,"Computing total mortality p.j=w1*p1j+w2*p2j+..: result on file '%s' \n",fileresprobmorprev);
                   4075:   pstamp(ficresprobmorprev);
                   4076:   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);
                   4077:   fprintf(ficresprobmorprev,"# Age cov=%-d",ij);
                   4078:   for(j=nlstate+1; j<=(nlstate+ndeath);j++){
                   4079:     fprintf(ficresprobmorprev," p.%-d SE",j);
                   4080:     for(i=1; i<=nlstate;i++)
                   4081:       fprintf(ficresprobmorprev," w%1d p%-d%-d",i,i,j);
                   4082:   }  
                   4083:   fprintf(ficresprobmorprev,"\n");
1.208     brouard  4084:   
1.126     brouard  4085:   fprintf(ficgp,"\n# Routine varevsij");
1.200     brouard  4086:   fprintf(ficgp,"\nunset title \n");
                   4087: /* fprintf(fichtm, "#Local time at start: %s", strstart);*/
1.126     brouard  4088:   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");
                   4089:   fprintf(fichtm,"\n<br>%s  <br>\n",digitp);
                   4090: /*   } */
                   4091:   varppt = matrix(nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);
                   4092:   pstamp(ficresvij);
                   4093:   fprintf(ficresvij,"# Variance and covariance of health expectancies e.j \n#  (weighted average of eij where weights are ");
                   4094:   if(popbased==1)
1.128     brouard  4095:     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  4096:   else
                   4097:     fprintf(ficresvij,"the age specific period (stable) prevalences in each health state \n");
                   4098:   fprintf(ficresvij,"# Age");
                   4099:   for(i=1; i<=nlstate;i++)
                   4100:     for(j=1; j<=nlstate;j++)
                   4101:       fprintf(ficresvij," Cov(e.%1d, e.%1d)",i,j);
                   4102:   fprintf(ficresvij,"\n");
                   4103: 
                   4104:   xp=vector(1,npar);
                   4105:   dnewm=matrix(1,nlstate,1,npar);
                   4106:   doldm=matrix(1,nlstate,1,nlstate);
                   4107:   dnewmp= matrix(nlstate+1,nlstate+ndeath,1,npar);
                   4108:   doldmp= matrix(nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);
                   4109: 
                   4110:   gradgp=matrix(1,npar,nlstate+1,nlstate+ndeath);
                   4111:   gpp=vector(nlstate+1,nlstate+ndeath);
                   4112:   gmp=vector(nlstate+1,nlstate+ndeath);
                   4113:   trgradgp =matrix(nlstate+1,nlstate+ndeath,1,npar); /* mu or p point j*/
                   4114:   
                   4115:   if(estepm < stepm){
                   4116:     printf ("Problem %d lower than %d\n",estepm, stepm);
                   4117:   }
                   4118:   else  hstepm=estepm;   
                   4119:   /* For example we decided to compute the life expectancy with the smallest unit */
                   4120:   /* hstepm beeing the number of stepms, if hstepm=1 the length of hstepm is stepm. 
                   4121:      nhstepm is the number of hstepm from age to agelim 
1.208     brouard  4122:      nstepm is the number of stepm from age to agelim. 
1.209   ! brouard  4123:      Look at function hpijx to understand why because of memory size limitations, 
1.208     brouard  4124:      we decided (b) to get a life expectancy respecting the most precise curvature of the
1.126     brouard  4125:      survival function given by stepm (the optimization length). Unfortunately it
                   4126:      means that if the survival funtion is printed every two years of age and if
                   4127:      you sum them up and add 1 year (area under the trapezoids) you won't get the same 
                   4128:      results. So we changed our mind and took the option of the best precision.
                   4129:   */
                   4130:   hstepm=hstepm/stepm; /* Typically in stepm units, if stepm=6 & estepm=24 , = 24/6 months = 4 */ 
                   4131:   agelim = AGESUP;
                   4132:   for (age=bage; age<=fage; age ++){ /* If stepm=6 months */
                   4133:     nstepm=(int) rint((agelim-age)*YEARM/stepm); /* Typically 20 years = 20*12/6=40 */ 
                   4134:     nhstepm = nstepm/hstepm;/* Expressed in hstepm, typically nhstepm=40/4=10 */
                   4135:     p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   4136:     gradg=ma3x(0,nhstepm,1,npar,1,nlstate);
                   4137:     gp=matrix(0,nhstepm,1,nlstate);
                   4138:     gm=matrix(0,nhstepm,1,nlstate);
                   4139: 
                   4140: 
                   4141:     for(theta=1; theta <=npar; theta++){
                   4142:       for(i=1; i<=npar; i++){ /* Computes gradient x + delta*/
                   4143:        xp[i] = x[i] + (i==theta ?delti[theta]:0);
                   4144:       }
1.209   ! brouard  4145: 
        !          4146:       prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ncvyearp,ij);
1.126     brouard  4147: 
                   4148:       if (popbased==1) {
                   4149:        if(mobilav ==0){
                   4150:          for(i=1; i<=nlstate;i++)
                   4151:            prlim[i][i]=probs[(int)age][i][ij];
                   4152:        }else{ /* mobilav */ 
                   4153:          for(i=1; i<=nlstate;i++)
                   4154:            prlim[i][i]=mobaverage[(int)age][i][ij];
                   4155:        }
                   4156:       }
                   4157:   
1.209   ! brouard  4158:       hpxij(p3mat,nhstepm,age,hstepm,xp,nlstate,stepm,oldm,savm, ij);  /* Returns p3mat[i][j][h] for h=1 to nhstepm */
1.126     brouard  4159:       for(j=1; j<= nlstate; j++){
                   4160:        for(h=0; h<=nhstepm; h++){
                   4161:          for(i=1, gp[h][j]=0.;i<=nlstate;i++)
                   4162:            gp[h][j] += prlim[i][i]*p3mat[i][j][h];
                   4163:        }
                   4164:       }
1.209   ! brouard  4165:       /* Next for computing probability of death (h=1 means
1.126     brouard  4166:          computed over hstepm matrices product = hstepm*stepm months) 
                   4167:          as a weighted average of prlim.
                   4168:       */
                   4169:       for(j=nlstate+1;j<=nlstate+ndeath;j++){
                   4170:        for(i=1,gpp[j]=0.; i<= nlstate; i++)
                   4171:          gpp[j] += prlim[i][i]*p3mat[i][j][1];
                   4172:       }    
                   4173:       /* end probability of death */
                   4174: 
                   4175:       for(i=1; i<=npar; i++) /* Computes gradient x - delta */
                   4176:        xp[i] = x[i] - (i==theta ?delti[theta]:0);
1.209   ! brouard  4177: 
        !          4178:       prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ncvyearp, ij);
1.126     brouard  4179:  
                   4180:       if (popbased==1) {
                   4181:        if(mobilav ==0){
                   4182:          for(i=1; i<=nlstate;i++)
                   4183:            prlim[i][i]=probs[(int)age][i][ij];
                   4184:        }else{ /* mobilav */ 
                   4185:          for(i=1; i<=nlstate;i++)
                   4186:            prlim[i][i]=mobaverage[(int)age][i][ij];
                   4187:        }
                   4188:       }
                   4189: 
1.209   ! brouard  4190:       hpxij(p3mat,nhstepm,age,hstepm,xp,nlstate,stepm,oldm,savm, ij);  
        !          4191: 
1.128     brouard  4192:       for(j=1; j<= nlstate; j++){  /* Sum of wi * eij = e.j */
1.126     brouard  4193:        for(h=0; h<=nhstepm; h++){
                   4194:          for(i=1, gm[h][j]=0.;i<=nlstate;i++)
                   4195:            gm[h][j] += prlim[i][i]*p3mat[i][j][h];
                   4196:        }
                   4197:       }
                   4198:       /* This for computing probability of death (h=1 means
                   4199:          computed over hstepm matrices product = hstepm*stepm months) 
                   4200:          as a weighted average of prlim.
                   4201:       */
                   4202:       for(j=nlstate+1;j<=nlstate+ndeath;j++){
                   4203:        for(i=1,gmp[j]=0.; i<= nlstate; i++)
                   4204:          gmp[j] += prlim[i][i]*p3mat[i][j][1];
                   4205:       }    
                   4206:       /* end probability of death */
                   4207: 
                   4208:       for(j=1; j<= nlstate; j++) /* vareij */
                   4209:        for(h=0; h<=nhstepm; h++){
                   4210:          gradg[h][theta][j]= (gp[h][j]-gm[h][j])/2./delti[theta];
                   4211:        }
                   4212: 
                   4213:       for(j=nlstate+1; j<= nlstate+ndeath; j++){ /* var mu */
                   4214:        gradgp[theta][j]= (gpp[j]-gmp[j])/2./delti[theta];
                   4215:       }
                   4216: 
                   4217:     } /* End theta */
                   4218: 
                   4219:     trgradg =ma3x(0,nhstepm,1,nlstate,1,npar); /* veij */
                   4220: 
                   4221:     for(h=0; h<=nhstepm; h++) /* veij */
                   4222:       for(j=1; j<=nlstate;j++)
                   4223:        for(theta=1; theta <=npar; theta++)
                   4224:          trgradg[h][j][theta]=gradg[h][theta][j];
                   4225: 
                   4226:     for(j=nlstate+1; j<=nlstate+ndeath;j++) /* mu */
                   4227:       for(theta=1; theta <=npar; theta++)
                   4228:        trgradgp[j][theta]=gradgp[theta][j];
                   4229:   
                   4230: 
                   4231:     hf=hstepm*stepm/YEARM;  /* Duration of hstepm expressed in year unit. */
                   4232:     for(i=1;i<=nlstate;i++)
                   4233:       for(j=1;j<=nlstate;j++)
                   4234:        vareij[i][j][(int)age] =0.;
                   4235: 
                   4236:     for(h=0;h<=nhstepm;h++){
                   4237:       for(k=0;k<=nhstepm;k++){
                   4238:        matprod2(dnewm,trgradg[h],1,nlstate,1,npar,1,npar,matcov);
                   4239:        matprod2(doldm,dnewm,1,nlstate,1,npar,1,nlstate,gradg[k]);
                   4240:        for(i=1;i<=nlstate;i++)
                   4241:          for(j=1;j<=nlstate;j++)
                   4242:            vareij[i][j][(int)age] += doldm[i][j]*hf*hf;
                   4243:       }
                   4244:     }
                   4245:   
                   4246:     /* pptj */
                   4247:     matprod2(dnewmp,trgradgp,nlstate+1,nlstate+ndeath,1,npar,1,npar,matcov);
                   4248:     matprod2(doldmp,dnewmp,nlstate+1,nlstate+ndeath,1,npar,nlstate+1,nlstate+ndeath,gradgp);
                   4249:     for(j=nlstate+1;j<=nlstate+ndeath;j++)
                   4250:       for(i=nlstate+1;i<=nlstate+ndeath;i++)
                   4251:        varppt[j][i]=doldmp[j][i];
                   4252:     /* end ppptj */
                   4253:     /*  x centered again */
1.209   ! brouard  4254: 
        !          4255:     prevalim(prlim,nlstate,x,age,oldm,savm,ftolpl,ncvyearp,ij);
1.126     brouard  4256:  
                   4257:     if (popbased==1) {
                   4258:       if(mobilav ==0){
                   4259:        for(i=1; i<=nlstate;i++)
                   4260:          prlim[i][i]=probs[(int)age][i][ij];
                   4261:       }else{ /* mobilav */ 
                   4262:        for(i=1; i<=nlstate;i++)
                   4263:          prlim[i][i]=mobaverage[(int)age][i][ij];
                   4264:       }
                   4265:     }
                   4266:              
                   4267:     /* This for computing probability of death (h=1 means
                   4268:        computed over hstepm (estepm) matrices product = hstepm*stepm months) 
                   4269:        as a weighted average of prlim.
                   4270:     */
1.209   ! brouard  4271:     hpxij(p3mat,nhstepm,age,hstepm,x,nlstate,stepm,oldm,savm, ij);  
1.126     brouard  4272:     for(j=nlstate+1;j<=nlstate+ndeath;j++){
                   4273:       for(i=1,gmp[j]=0.;i<= nlstate; i++) 
                   4274:        gmp[j] += prlim[i][i]*p3mat[i][j][1]; 
                   4275:     }    
                   4276:     /* end probability of death */
                   4277: 
                   4278:     fprintf(ficresprobmorprev,"%3d %d ",(int) age, ij);
                   4279:     for(j=nlstate+1; j<=(nlstate+ndeath);j++){
                   4280:       fprintf(ficresprobmorprev," %11.3e %11.3e",gmp[j], sqrt(varppt[j][j]));
                   4281:       for(i=1; i<=nlstate;i++){
                   4282:        fprintf(ficresprobmorprev," %11.3e %11.3e ",prlim[i][i],p3mat[i][j][1]);
                   4283:       }
                   4284:     } 
                   4285:     fprintf(ficresprobmorprev,"\n");
                   4286: 
                   4287:     fprintf(ficresvij,"%.0f ",age );
                   4288:     for(i=1; i<=nlstate;i++)
                   4289:       for(j=1; j<=nlstate;j++){
                   4290:        fprintf(ficresvij," %.4f", vareij[i][j][(int)age]);
                   4291:       }
                   4292:     fprintf(ficresvij,"\n");
                   4293:     free_matrix(gp,0,nhstepm,1,nlstate);
                   4294:     free_matrix(gm,0,nhstepm,1,nlstate);
                   4295:     free_ma3x(gradg,0,nhstepm,1,npar,1,nlstate);
                   4296:     free_ma3x(trgradg,0,nhstepm,1,nlstate,1,npar);
                   4297:     free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   4298:   } /* End age */
                   4299:   free_vector(gpp,nlstate+1,nlstate+ndeath);
                   4300:   free_vector(gmp,nlstate+1,nlstate+ndeath);
                   4301:   free_matrix(gradgp,1,npar,nlstate+1,nlstate+ndeath);
                   4302:   free_matrix(trgradgp,nlstate+1,nlstate+ndeath,1,npar); /* mu or p point j*/
1.199     brouard  4303:   /* fprintf(ficgp,"\nunset parametric;unset label; set ter png small size 320, 240"); */
                   4304:   fprintf(ficgp,"\nunset parametric;unset label; set ter svg size 640, 480");
1.126     brouard  4305:   /* for(j=nlstate+1; j<= nlstate+ndeath; j++){ *//* Only the first actually */
1.131     brouard  4306:   fprintf(ficgp,"\n set log y; unset log x;set xlabel \"Age\"; set ylabel \"Force of mortality (year-1)\";");
1.201     brouard  4307:   fprintf(ficgp,"\nset out \"%s%s.svg\";",subdirf3(optionfilefiname,"VARMUPTJGR-",digitp),digit);
1.126     brouard  4308: /*   fprintf(ficgp,"\n plot \"%s\"  u 1:($3*%6.3f) not w l 1 ",fileresprobmorprev,YEARM/estepm); */
                   4309: /*   fprintf(ficgp,"\n replot \"%s\"  u 1:(($3+1.96*$4)*%6.3f) t \"95\%% interval\" w l 2 ",fileresprobmorprev,YEARM/estepm); */
                   4310: /*   fprintf(ficgp,"\n replot \"%s\"  u 1:(($3-1.96*$4)*%6.3f) not w l 2 ",fileresprobmorprev,YEARM/estepm); */
1.145     brouard  4311:   fprintf(ficgp,"\n plot \"%s\"  u 1:($3) not w l lt 1 ",subdirf(fileresprobmorprev));
1.170     brouard  4312:   fprintf(ficgp,"\n replot \"%s\"  u 1:(($3+1.96*$4)) t \"95%% interval\" w l lt 2 ",subdirf(fileresprobmorprev));
1.145     brouard  4313:   fprintf(ficgp,"\n replot \"%s\"  u 1:(($3-1.96*$4)) not w l lt 2 ",subdirf(fileresprobmorprev));
1.126     brouard  4314:   fprintf(fichtm,"\n<br> File (multiple files are possible if covariates are present): <A href=\"%s\">%s</a>\n",subdirf(fileresprobmorprev),subdirf(fileresprobmorprev));
1.201     brouard  4315:   fprintf(fichtm,"\n<br> Probability is computed over estepm=%d months. <br> <img src=\"%s%s.svg\"> <br>\n", estepm,subdirf3(optionfilefiname,"VARMUPTJGR-",digitp),digit);
1.199     brouard  4316:   /*  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  4317: */
1.199     brouard  4318: /*   fprintf(ficgp,"\nset out \"varmuptjgr%s%s%s.svg\";replot;",digitp,optionfilefiname,digit); */
1.201     brouard  4319:   fprintf(ficgp,"\nset out;\nset out \"%s%s.svg\";replot;set out;\n",subdirf3(optionfilefiname,"VARMUPTJGR-",digitp),digit);
1.126     brouard  4320: 
                   4321:   free_vector(xp,1,npar);
                   4322:   free_matrix(doldm,1,nlstate,1,nlstate);
                   4323:   free_matrix(dnewm,1,nlstate,1,npar);
                   4324:   free_matrix(doldmp,nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);
                   4325:   free_matrix(dnewmp,nlstate+1,nlstate+ndeath,1,npar);
                   4326:   free_matrix(varppt,nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);
                   4327:   if (mobilav!=0) free_ma3x(mobaverage,1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
                   4328:   fclose(ficresprobmorprev);
                   4329:   fflush(ficgp);
                   4330:   fflush(fichtm); 
                   4331: }  /* end varevsij */
                   4332: 
                   4333: /************ Variance of prevlim ******************/
1.209   ! brouard  4334:  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 *ncvyearp, int ij, char strstart[])
1.126     brouard  4335: {
1.205     brouard  4336:   /* Variance of prevalence limit  for each state ij using current parameters x[] and estimates of neighbourhood give by delti*/
1.126     brouard  4337:   /*  double **prevalim(double **prlim, int nlstate, double *xp, double age, double **oldm, double **savm,double ftolpl);*/
1.164     brouard  4338: 
1.126     brouard  4339:   double **dnewm,**doldm;
                   4340:   int i, j, nhstepm, hstepm;
                   4341:   double *xp;
                   4342:   double *gp, *gm;
                   4343:   double **gradg, **trgradg;
1.208     brouard  4344:   double **mgm, **mgp;
1.126     brouard  4345:   double age,agelim;
                   4346:   int theta;
                   4347:   
                   4348:   pstamp(ficresvpl);
                   4349:   fprintf(ficresvpl,"# Standard deviation of period (stable) prevalences \n");
                   4350:   fprintf(ficresvpl,"# Age");
                   4351:   for(i=1; i<=nlstate;i++)
                   4352:       fprintf(ficresvpl," %1d-%1d",i,i);
                   4353:   fprintf(ficresvpl,"\n");
                   4354: 
                   4355:   xp=vector(1,npar);
                   4356:   dnewm=matrix(1,nlstate,1,npar);
                   4357:   doldm=matrix(1,nlstate,1,nlstate);
                   4358:   
                   4359:   hstepm=1*YEARM; /* Every year of age */
                   4360:   hstepm=hstepm/stepm; /* Typically in stepm units, if j= 2 years, = 2/6 months = 4 */ 
                   4361:   agelim = AGESUP;
                   4362:   for (age=bage; age<=fage; age ++){ /* If stepm=6 months */
                   4363:     nhstepm=(int) rint((agelim-age)*YEARM/stepm); /* Typically 20 years = 20*12/6=40 */ 
                   4364:     if (stepm >= YEARM) hstepm=1;
                   4365:     nhstepm = nhstepm/hstepm; /* Typically 40/4=10 */
                   4366:     gradg=matrix(1,npar,1,nlstate);
1.208     brouard  4367:     mgp=matrix(1,npar,1,nlstate);
                   4368:     mgm=matrix(1,npar,1,nlstate);
1.126     brouard  4369:     gp=vector(1,nlstate);
                   4370:     gm=vector(1,nlstate);
                   4371: 
                   4372:     for(theta=1; theta <=npar; theta++){
                   4373:       for(i=1; i<=npar; i++){ /* Computes gradient */
                   4374:        xp[i] = x[i] + (i==theta ?delti[theta]:0);
                   4375:       }
1.209   ! brouard  4376:       if((int)age==79 ||(int)age== 80 ||(int)age== 81 )
        !          4377:        prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ncvyearp,ij);
        !          4378:       else
        !          4379:        prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ncvyearp,ij);
1.208     brouard  4380:       for(i=1;i<=nlstate;i++){
1.126     brouard  4381:        gp[i] = prlim[i][i];
1.208     brouard  4382:        mgp[theta][i] = prlim[i][i];
                   4383:       }
1.126     brouard  4384:       for(i=1; i<=npar; i++) /* Computes gradient */
                   4385:        xp[i] = x[i] - (i==theta ?delti[theta]:0);
1.209   ! brouard  4386:       if((int)age==79 ||(int)age== 80 ||(int)age== 81 )
        !          4387:        prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ncvyearp,ij);
        !          4388:       else
        !          4389:        prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ncvyearp,ij);
1.208     brouard  4390:       for(i=1;i<=nlstate;i++){
1.126     brouard  4391:        gm[i] = prlim[i][i];
1.208     brouard  4392:        mgm[theta][i] = prlim[i][i];
                   4393:       }
1.126     brouard  4394:       for(i=1;i<=nlstate;i++)
                   4395:        gradg[theta][i]= (gp[i]-gm[i])/2./delti[theta];
1.209   ! brouard  4396:       /* gradg[theta][2]= -gradg[theta][1]; */ /* For testing if nlstate=2 */
1.126     brouard  4397:     } /* End theta */
                   4398: 
                   4399:     trgradg =matrix(1,nlstate,1,npar);
                   4400: 
                   4401:     for(j=1; j<=nlstate;j++)
                   4402:       for(theta=1; theta <=npar; theta++)
                   4403:        trgradg[j][theta]=gradg[theta][j];
1.209   ! brouard  4404:     /* if((int)age==79 ||(int)age== 80 ||(int)age== 81 ){ */
        !          4405:     /*   printf("\nmgm mgp %d ",(int)age); */
        !          4406:     /*   for(j=1; j<=nlstate;j++){ */
        !          4407:     /*         printf(" %d ",j); */
        !          4408:     /*         for(theta=1; theta <=npar; theta++) */
        !          4409:     /*           printf(" %d %lf %lf",theta,mgm[theta][j],mgp[theta][j]); */
        !          4410:     /*         printf("\n "); */
        !          4411:     /*   } */
        !          4412:     /* } */
        !          4413:     /* if((int)age==79 ||(int)age== 80 ||(int)age== 81 ){ */
        !          4414:     /*   printf("\n gradg %d ",(int)age); */
        !          4415:     /*   for(j=1; j<=nlstate;j++){ */
        !          4416:     /*         printf("%d ",j); */
        !          4417:     /*         for(theta=1; theta <=npar; theta++) */
        !          4418:     /*           printf("%d %lf ",theta,gradg[theta][j]); */
        !          4419:     /*         printf("\n "); */
        !          4420:     /*   } */
        !          4421:     /* } */
1.126     brouard  4422: 
                   4423:     for(i=1;i<=nlstate;i++)
                   4424:       varpl[i][(int)age] =0.;
1.209   ! brouard  4425:     if((int)age==79 ||(int)age== 80  ||(int)age== 81){
1.205     brouard  4426:     matprod2(dnewm,trgradg,1,nlstate,1,npar,1,npar,matcov);
                   4427:     matprod2(doldm,dnewm,1,nlstate,1,npar,1,nlstate,gradg);
                   4428:     }else{
1.126     brouard  4429:     matprod2(dnewm,trgradg,1,nlstate,1,npar,1,npar,matcov);
                   4430:     matprod2(doldm,dnewm,1,nlstate,1,npar,1,nlstate,gradg);
1.205     brouard  4431:     }
1.126     brouard  4432:     for(i=1;i<=nlstate;i++)
                   4433:       varpl[i][(int)age] = doldm[i][i]; /* Covariances are useless */
                   4434: 
                   4435:     fprintf(ficresvpl,"%.0f ",age );
                   4436:     for(i=1; i<=nlstate;i++)
                   4437:       fprintf(ficresvpl," %.5f (%.5f)",prlim[i][i],sqrt(varpl[i][(int)age]));
                   4438:     fprintf(ficresvpl,"\n");
                   4439:     free_vector(gp,1,nlstate);
                   4440:     free_vector(gm,1,nlstate);
1.208     brouard  4441:     free_matrix(mgm,1,npar,1,nlstate);
                   4442:     free_matrix(mgp,1,npar,1,nlstate);
1.126     brouard  4443:     free_matrix(gradg,1,npar,1,nlstate);
                   4444:     free_matrix(trgradg,1,nlstate,1,npar);
                   4445:   } /* End age */
                   4446: 
                   4447:   free_vector(xp,1,npar);
                   4448:   free_matrix(doldm,1,nlstate,1,npar);
                   4449:   free_matrix(dnewm,1,nlstate,1,nlstate);
                   4450: 
                   4451: }
                   4452: 
                   4453: /************ Variance of one-step probabilities  ******************/
                   4454: 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[])
                   4455: {
1.164     brouard  4456:   int i, j=0,  k1, l1, tj;
1.126     brouard  4457:   int k2, l2, j1,  z1;
1.164     brouard  4458:   int k=0, l;
1.145     brouard  4459:   int first=1, first1, first2;
1.126     brouard  4460:   double cv12, mu1, mu2, lc1, lc2, v12, v21, v11, v22,v1,v2, c12, tnalp;
                   4461:   double **dnewm,**doldm;
                   4462:   double *xp;
                   4463:   double *gp, *gm;
                   4464:   double **gradg, **trgradg;
                   4465:   double **mu;
1.164     brouard  4466:   double age, cov[NCOVMAX+1];
1.126     brouard  4467:   double std=2.0; /* Number of standard deviation wide of confidence ellipsoids */
                   4468:   int theta;
                   4469:   char fileresprob[FILENAMELENGTH];
                   4470:   char fileresprobcov[FILENAMELENGTH];
                   4471:   char fileresprobcor[FILENAMELENGTH];
                   4472:   double ***varpij;
                   4473: 
1.201     brouard  4474:   strcpy(fileresprob,"PROB_"); 
1.126     brouard  4475:   strcat(fileresprob,fileres);
                   4476:   if((ficresprob=fopen(fileresprob,"w"))==NULL) {
                   4477:     printf("Problem with resultfile: %s\n", fileresprob);
                   4478:     fprintf(ficlog,"Problem with resultfile: %s\n", fileresprob);
                   4479:   }
1.201     brouard  4480:   strcpy(fileresprobcov,"PROBCOV_"); 
1.202     brouard  4481:   strcat(fileresprobcov,fileresu);
1.126     brouard  4482:   if((ficresprobcov=fopen(fileresprobcov,"w"))==NULL) {
                   4483:     printf("Problem with resultfile: %s\n", fileresprobcov);
                   4484:     fprintf(ficlog,"Problem with resultfile: %s\n", fileresprobcov);
                   4485:   }
1.201     brouard  4486:   strcpy(fileresprobcor,"PROBCOR_"); 
1.202     brouard  4487:   strcat(fileresprobcor,fileresu);
1.126     brouard  4488:   if((ficresprobcor=fopen(fileresprobcor,"w"))==NULL) {
                   4489:     printf("Problem with resultfile: %s\n", fileresprobcor);
                   4490:     fprintf(ficlog,"Problem with resultfile: %s\n", fileresprobcor);
                   4491:   }
                   4492:   printf("Computing standard deviation of one-step probabilities: result on file '%s' \n",fileresprob);
                   4493:   fprintf(ficlog,"Computing standard deviation of one-step probabilities: result on file '%s' \n",fileresprob);
                   4494:   printf("Computing matrix of variance covariance of one-step probabilities: result on file '%s' \n",fileresprobcov);
                   4495:   fprintf(ficlog,"Computing matrix of variance covariance of one-step probabilities: result on file '%s' \n",fileresprobcov);
                   4496:   printf("and correlation matrix of one-step probabilities: result on file '%s' \n",fileresprobcor);
                   4497:   fprintf(ficlog,"and correlation matrix of one-step probabilities: result on file '%s' \n",fileresprobcor);
                   4498:   pstamp(ficresprob);
                   4499:   fprintf(ficresprob,"#One-step probabilities and stand. devi in ()\n");
                   4500:   fprintf(ficresprob,"# Age");
                   4501:   pstamp(ficresprobcov);
                   4502:   fprintf(ficresprobcov,"#One-step probabilities and covariance matrix\n");
                   4503:   fprintf(ficresprobcov,"# Age");
                   4504:   pstamp(ficresprobcor);
                   4505:   fprintf(ficresprobcor,"#One-step probabilities and correlation matrix\n");
                   4506:   fprintf(ficresprobcor,"# Age");
                   4507: 
                   4508: 
                   4509:   for(i=1; i<=nlstate;i++)
                   4510:     for(j=1; j<=(nlstate+ndeath);j++){
                   4511:       fprintf(ficresprob," p%1d-%1d (SE)",i,j);
                   4512:       fprintf(ficresprobcov," p%1d-%1d ",i,j);
                   4513:       fprintf(ficresprobcor," p%1d-%1d ",i,j);
                   4514:     }  
                   4515:  /* fprintf(ficresprob,"\n");
                   4516:   fprintf(ficresprobcov,"\n");
                   4517:   fprintf(ficresprobcor,"\n");
                   4518:  */
1.131     brouard  4519:   xp=vector(1,npar);
1.126     brouard  4520:   dnewm=matrix(1,(nlstate)*(nlstate+ndeath),1,npar);
                   4521:   doldm=matrix(1,(nlstate)*(nlstate+ndeath),1,(nlstate)*(nlstate+ndeath));
                   4522:   mu=matrix(1,(nlstate)*(nlstate+ndeath), (int) bage, (int)fage);
                   4523:   varpij=ma3x(1,nlstate*(nlstate+ndeath),1,nlstate*(nlstate+ndeath),(int) bage, (int) fage);
                   4524:   first=1;
                   4525:   fprintf(ficgp,"\n# Routine varprob");
                   4526:   fprintf(fichtm,"\n<li><h4> Computing and drawing one step probabilities with their confidence intervals</h4></li>\n");
                   4527:   fprintf(fichtm,"\n");
                   4528: 
1.200     brouard  4529:   fprintf(fichtm,"\n<li><h4> <a href=\"%s\">Matrix of variance-covariance of one-step probabilities (drawings)</a></h4> this page is important in order to visualize confidence intervals and especially correlation between disability and recovery, or more generally, way in and way back.</li>\n",optionfilehtmcov);
1.197     brouard  4530:   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);
                   4531:   fprintf(fichtmcov,"\nEllipsoids of confidence centered on point (p<inf>ij</inf>, p<inf>kl</inf>) are estimated \
1.126     brouard  4532: and drawn. It helps understanding how is the covariance between two incidences.\
                   4533:  They are expressed in year<sup>-1</sup> in order to be less dependent of stepm.<br>\n");
                   4534:   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. \
                   4535: It can be understood this way: if pij and pkl where uncorrelated the (2x2) matrix of covariance \
                   4536: would have been (1/(var pij), 0 , 0, 1/(var pkl)), and the confidence interval would be 2 \
                   4537: standard deviations wide on each axis. <br>\
                   4538:  Now, if both incidences are correlated (usual case) we diagonalised the inverse of the covariance matrix\
                   4539:  and made the appropriate rotation to look at the uncorrelated principal directions.<br>\
                   4540: To be simple, these graphs help to understand the significativity of each parameter in relation to a second other one.<br> \n");
                   4541: 
                   4542:   cov[1]=1;
1.145     brouard  4543:   /* tj=cptcoveff; */
                   4544:   tj = (int) pow(2,cptcoveff);
1.126     brouard  4545:   if (cptcovn<1) {tj=1;ncodemax[1]=1;}
                   4546:   j1=0;
1.145     brouard  4547:   for(j1=1; j1<=tj;j1++){
                   4548:     /*for(i1=1; i1<=ncodemax[t];i1++){ */
                   4549:     /*j1++;*/
1.126     brouard  4550:       if  (cptcovn>0) {
                   4551:        fprintf(ficresprob, "\n#********** Variable "); 
1.198     brouard  4552:        for (z1=1; z1<=cptcoveff; z1++) fprintf(ficresprob, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
1.126     brouard  4553:        fprintf(ficresprob, "**********\n#\n");
                   4554:        fprintf(ficresprobcov, "\n#********** Variable "); 
1.198     brouard  4555:        for (z1=1; z1<=cptcoveff; z1++) fprintf(ficresprobcov, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
1.126     brouard  4556:        fprintf(ficresprobcov, "**********\n#\n");
                   4557:        
                   4558:        fprintf(ficgp, "\n#********** Variable "); 
1.198     brouard  4559:        for (z1=1; z1<=cptcoveff; z1++) fprintf(ficgp, " V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
1.126     brouard  4560:        fprintf(ficgp, "**********\n#\n");
                   4561:        
                   4562:        
                   4563:        fprintf(fichtmcov, "\n<hr  size=\"2\" color=\"#EC5E5E\">********** Variable "); 
1.198     brouard  4564:        for (z1=1; z1<=cptcoveff; z1++) fprintf(fichtm, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
1.126     brouard  4565:        fprintf(fichtmcov, "**********\n<hr size=\"2\" color=\"#EC5E5E\">");
                   4566:        
                   4567:        fprintf(ficresprobcor, "\n#********** Variable ");    
1.198     brouard  4568:        for (z1=1; z1<=cptcoveff; z1++) fprintf(ficresprobcor, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
1.126     brouard  4569:        fprintf(ficresprobcor, "**********\n#");    
                   4570:       }
                   4571:       
1.145     brouard  4572:       gradg=matrix(1,npar,1,(nlstate)*(nlstate+ndeath));
                   4573:       trgradg=matrix(1,(nlstate)*(nlstate+ndeath),1,npar);
                   4574:       gp=vector(1,(nlstate)*(nlstate+ndeath));
                   4575:       gm=vector(1,(nlstate)*(nlstate+ndeath));
1.126     brouard  4576:       for (age=bage; age<=fage; age ++){ 
                   4577:        cov[2]=age;
1.187     brouard  4578:        if(nagesqr==1)
                   4579:          cov[3]= age*age;
1.126     brouard  4580:        for (k=1; k<=cptcovn;k++) {
1.200     brouard  4581:          cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(j1,k)];
                   4582:          /*cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(j1,Tvar[k])];*//* j1 1 2 3 4
1.145     brouard  4583:                                                         * 1  1 1 1 1
                   4584:                                                         * 2  2 1 1 1
                   4585:                                                         * 3  1 2 1 1
                   4586:                                                         */
                   4587:          /* nbcode[1][1]=0 nbcode[1][2]=1;*/
1.126     brouard  4588:        }
1.186     brouard  4589:        /* for (k=1; k<=cptcovage;k++) cov[2+Tage[k]]=cov[2+Tage[k]]*cov[2]; */
1.200     brouard  4590:        for (k=1; k<=cptcovage;k++) cov[2+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(ij,k)]*cov[2];
1.126     brouard  4591:        for (k=1; k<=cptcovprod;k++)
1.200     brouard  4592:          cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,k)]*nbcode[Tvard[k][2]][codtabm(ij,k)];
1.126     brouard  4593:        
                   4594:     
                   4595:        for(theta=1; theta <=npar; theta++){
                   4596:          for(i=1; i<=npar; i++)
                   4597:            xp[i] = x[i] + (i==theta ?delti[theta]:(double)0);
                   4598:          
                   4599:          pmij(pmmij,cov,ncovmodel,xp,nlstate);
                   4600:          
                   4601:          k=0;
                   4602:          for(i=1; i<= (nlstate); i++){
                   4603:            for(j=1; j<=(nlstate+ndeath);j++){
                   4604:              k=k+1;
                   4605:              gp[k]=pmmij[i][j];
                   4606:            }
                   4607:          }
                   4608:          
                   4609:          for(i=1; i<=npar; i++)
                   4610:            xp[i] = x[i] - (i==theta ?delti[theta]:(double)0);
                   4611:     
                   4612:          pmij(pmmij,cov,ncovmodel,xp,nlstate);
                   4613:          k=0;
                   4614:          for(i=1; i<=(nlstate); i++){
                   4615:            for(j=1; j<=(nlstate+ndeath);j++){
                   4616:              k=k+1;
                   4617:              gm[k]=pmmij[i][j];
                   4618:            }
                   4619:          }
                   4620:      
                   4621:          for(i=1; i<= (nlstate)*(nlstate+ndeath); i++) 
                   4622:            gradg[theta][i]=(gp[i]-gm[i])/(double)2./delti[theta];  
                   4623:        }
                   4624: 
                   4625:        for(j=1; j<=(nlstate)*(nlstate+ndeath);j++)
                   4626:          for(theta=1; theta <=npar; theta++)
                   4627:            trgradg[j][theta]=gradg[theta][j];
                   4628:        
                   4629:        matprod2(dnewm,trgradg,1,(nlstate)*(nlstate+ndeath),1,npar,1,npar,matcov); 
                   4630:        matprod2(doldm,dnewm,1,(nlstate)*(nlstate+ndeath),1,npar,1,(nlstate)*(nlstate+ndeath),gradg);
                   4631: 
                   4632:        pmij(pmmij,cov,ncovmodel,x,nlstate);
                   4633:        
                   4634:        k=0;
                   4635:        for(i=1; i<=(nlstate); i++){
                   4636:          for(j=1; j<=(nlstate+ndeath);j++){
                   4637:            k=k+1;
                   4638:            mu[k][(int) age]=pmmij[i][j];
                   4639:          }
                   4640:        }
                   4641:        for(i=1;i<=(nlstate)*(nlstate+ndeath);i++)
                   4642:          for(j=1;j<=(nlstate)*(nlstate+ndeath);j++)
                   4643:            varpij[i][j][(int)age] = doldm[i][j];
                   4644: 
                   4645:        /*printf("\n%d ",(int)age);
                   4646:          for (i=1; i<=(nlstate)*(nlstate+ndeath);i++){
                   4647:          printf("%e [%e ;%e] ",gm[i],gm[i]-2*sqrt(doldm[i][i]),gm[i]+2*sqrt(doldm[i][i]));
                   4648:          fprintf(ficlog,"%e [%e ;%e] ",gm[i],gm[i]-2*sqrt(doldm[i][i]),gm[i]+2*sqrt(doldm[i][i]));
                   4649:          }*/
                   4650: 
                   4651:        fprintf(ficresprob,"\n%d ",(int)age);
                   4652:        fprintf(ficresprobcov,"\n%d ",(int)age);
                   4653:        fprintf(ficresprobcor,"\n%d ",(int)age);
                   4654: 
                   4655:        for (i=1; i<=(nlstate)*(nlstate+ndeath);i++)
                   4656:          fprintf(ficresprob,"%11.3e (%11.3e) ",mu[i][(int) age],sqrt(varpij[i][i][(int)age]));
                   4657:        for (i=1; i<=(nlstate)*(nlstate+ndeath);i++){
                   4658:          fprintf(ficresprobcov,"%11.3e ",mu[i][(int) age]);
                   4659:          fprintf(ficresprobcor,"%11.3e ",mu[i][(int) age]);
                   4660:        }
                   4661:        i=0;
                   4662:        for (k=1; k<=(nlstate);k++){
                   4663:          for (l=1; l<=(nlstate+ndeath);l++){ 
1.145     brouard  4664:            i++;
1.126     brouard  4665:            fprintf(ficresprobcov,"\n%d %d-%d",(int)age,k,l);
                   4666:            fprintf(ficresprobcor,"\n%d %d-%d",(int)age,k,l);
                   4667:            for (j=1; j<=i;j++){
1.145     brouard  4668:              /* printf(" k=%d l=%d i=%d j=%d\n",k,l,i,j);fflush(stdout); */
1.126     brouard  4669:              fprintf(ficresprobcov," %11.3e",varpij[i][j][(int)age]);
                   4670:              fprintf(ficresprobcor," %11.3e",varpij[i][j][(int) age]/sqrt(varpij[i][i][(int) age])/sqrt(varpij[j][j][(int)age]));
                   4671:            }
                   4672:          }
                   4673:        }/* end of loop for state */
                   4674:       } /* end of loop for age */
1.145     brouard  4675:       free_vector(gp,1,(nlstate+ndeath)*(nlstate+ndeath));
                   4676:       free_vector(gm,1,(nlstate+ndeath)*(nlstate+ndeath));
                   4677:       free_matrix(trgradg,1,(nlstate+ndeath)*(nlstate+ndeath),1,npar);
                   4678:       free_matrix(gradg,1,(nlstate+ndeath)*(nlstate+ndeath),1,npar);
                   4679:       
1.126     brouard  4680:       /* Confidence intervalle of pij  */
                   4681:       /*
1.131     brouard  4682:        fprintf(ficgp,"\nunset parametric;unset label");
1.126     brouard  4683:        fprintf(ficgp,"\nset log y;unset log x; set xlabel \"Age\";set ylabel \"probability (year-1)\"");
                   4684:        fprintf(ficgp,"\nset ter png small\nset size 0.65,0.65");
                   4685:        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);
                   4686:        fprintf(fichtm,"\n<br><img src=\"pijgr%s.png\"> ",optionfilefiname);
                   4687:        fprintf(ficgp,"\nset out \"pijgr%s.png\"",optionfilefiname);
                   4688:        fprintf(ficgp,"\nplot \"%s\" every :::%d::%d u 1:2 \"\%%lf",k1,k2,xfilevarprob);
                   4689:       */
                   4690: 
                   4691:       /* Drawing ellipsoids of confidence of two variables p(k1-l1,k2-l2)*/
1.145     brouard  4692:       first1=1;first2=2;
1.126     brouard  4693:       for (k2=1; k2<=(nlstate);k2++){
                   4694:        for (l2=1; l2<=(nlstate+ndeath);l2++){ 
                   4695:          if(l2==k2) continue;
                   4696:          j=(k2-1)*(nlstate+ndeath)+l2;
                   4697:          for (k1=1; k1<=(nlstate);k1++){
                   4698:            for (l1=1; l1<=(nlstate+ndeath);l1++){ 
                   4699:              if(l1==k1) continue;
                   4700:              i=(k1-1)*(nlstate+ndeath)+l1;
                   4701:              if(i<=j) continue;
                   4702:              for (age=bage; age<=fage; age ++){ 
                   4703:                if ((int)age %5==0){
                   4704:                  v1=varpij[i][i][(int)age]/stepm*YEARM/stepm*YEARM;
                   4705:                  v2=varpij[j][j][(int)age]/stepm*YEARM/stepm*YEARM;
                   4706:                  cv12=varpij[i][j][(int)age]/stepm*YEARM/stepm*YEARM;
                   4707:                  mu1=mu[i][(int) age]/stepm*YEARM ;
                   4708:                  mu2=mu[j][(int) age]/stepm*YEARM;
                   4709:                  c12=cv12/sqrt(v1*v2);
                   4710:                  /* Computing eigen value of matrix of covariance */
                   4711:                  lc1=((v1+v2)+sqrt((v1+v2)*(v1+v2) - 4*(v1*v2-cv12*cv12)))/2.;
                   4712:                  lc2=((v1+v2)-sqrt((v1+v2)*(v1+v2) - 4*(v1*v2-cv12*cv12)))/2.;
1.135     brouard  4713:                  if ((lc2 <0) || (lc1 <0) ){
1.145     brouard  4714:                    if(first2==1){
                   4715:                      first1=0;
                   4716:                    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);
                   4717:                    }
                   4718:                    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);
                   4719:                    /* lc1=fabs(lc1); */ /* If we want to have them positive */
                   4720:                    /* lc2=fabs(lc2); */
1.135     brouard  4721:                  }
                   4722: 
1.126     brouard  4723:                  /* Eigen vectors */
                   4724:                  v11=(1./sqrt(1+(v1-lc1)*(v1-lc1)/cv12/cv12));
                   4725:                  /*v21=sqrt(1.-v11*v11); *//* error */
                   4726:                  v21=(lc1-v1)/cv12*v11;
                   4727:                  v12=-v21;
                   4728:                  v22=v11;
                   4729:                  tnalp=v21/v11;
                   4730:                  if(first1==1){
                   4731:                    first1=0;
                   4732:                    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);
                   4733:                  }
                   4734:                  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);
                   4735:                  /*printf(fignu*/
                   4736:                  /* mu1+ v11*lc1*cost + v12*lc2*sin(t) */
                   4737:                  /* mu2+ v21*lc1*cost + v22*lc2*sin(t) */
                   4738:                  if(first==1){
                   4739:                    first=0;
1.200     brouard  4740:                    fprintf(ficgp,"\n# Ellipsoids of confidence\n#\n");
1.126     brouard  4741:                    fprintf(ficgp,"\nset parametric;unset label");
                   4742:                    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  4743:                    fprintf(ficgp,"\nset ter svg size 640, 480");
1.126     brouard  4744:                    fprintf(fichtmcov,"\n<br>Ellipsoids of confidence cov(p%1d%1d,p%1d%1d) expressed in year<sup>-1</sup>\
1.201     brouard  4745:  :<a href=\"%s_%d%1d%1d-%1d%1d.svg\">\
                   4746: %s_%d%1d%1d-%1d%1d.svg</A>, ",k1,l1,k2,l2,\
                   4747:                            subdirf2(optionfilefiname,"VARPIJGR_"), j1,k1,l1,k2,l2,\
                   4748:                            subdirf2(optionfilefiname,"VARPIJGR_"), j1,k1,l1,k2,l2);
                   4749:                    fprintf(fichtmcov,"\n<br><img src=\"%s_%d%1d%1d-%1d%1d.svg\"> ",subdirf2(optionfilefiname,"VARPIJGR_"), j1,k1,l1,k2,l2);
1.126     brouard  4750:                    fprintf(fichtmcov,"\n<br> Correlation at age %d (%.3f),",(int) age, c12);
1.201     brouard  4751:                    fprintf(ficgp,"\nset out \"%s_%d%1d%1d-%1d%1d.svg\"",subdirf2(optionfilefiname,"VARPIJGR_"), j1,k1,l1,k2,l2);
1.126     brouard  4752:                    fprintf(ficgp,"\nset label \"%d\" at %11.3e,%11.3e center",(int) age, mu1,mu2);
                   4753:                    fprintf(ficgp,"\n# Age %d, p%1d%1d - p%1d%1d",(int) age, k1,l1,k2,l2);
                   4754:                    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",\
                   4755:                            mu1,std,v11,sqrt(lc1),v12,sqrt(lc2),\
                   4756:                            mu2,std,v21,sqrt(lc1),v22,sqrt(lc2));
                   4757:                  }else{
                   4758:                    first=0;
                   4759:                    fprintf(fichtmcov," %d (%.3f),",(int) age, c12);
                   4760:                    fprintf(ficgp,"\n# Age %d, p%1d%1d - p%1d%1d",(int) age, k1,l1,k2,l2);
                   4761:                    fprintf(ficgp,"\nset label \"%d\" at %11.3e,%11.3e center",(int) age, mu1,mu2);
                   4762:                    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",\
                   4763:                            mu1,std,v11,sqrt(lc1),v12,sqrt(lc2),\
                   4764:                            mu2,std,v21,sqrt(lc1),v22,sqrt(lc2));
                   4765:                  }/* if first */
                   4766:                } /* age mod 5 */
                   4767:              } /* end loop age */
1.201     brouard  4768:              fprintf(ficgp,"\nset out;\nset out \"%s_%d%1d%1d-%1d%1d.svg\";replot;set out;",subdirf2(optionfilefiname,"VARPIJGR_"), j1,k1,l1,k2,l2);
1.126     brouard  4769:              first=1;
                   4770:            } /*l12 */
                   4771:          } /* k12 */
                   4772:        } /*l1 */
                   4773:       }/* k1 */
1.169     brouard  4774:       /* } */ /* loop covariates */
1.126     brouard  4775:   }
                   4776:   free_ma3x(varpij,1,nlstate,1,nlstate+ndeath,(int) bage, (int)fage);
                   4777:   free_matrix(mu,1,(nlstate+ndeath)*(nlstate+ndeath),(int) bage, (int)fage);
                   4778:   free_matrix(doldm,1,(nlstate)*(nlstate+ndeath),1,(nlstate)*(nlstate+ndeath));
                   4779:   free_matrix(dnewm,1,(nlstate)*(nlstate+ndeath),1,npar);
                   4780:   free_vector(xp,1,npar);
                   4781:   fclose(ficresprob);
                   4782:   fclose(ficresprobcov);
                   4783:   fclose(ficresprobcor);
                   4784:   fflush(ficgp);
                   4785:   fflush(fichtmcov);
                   4786: }
                   4787: 
                   4788: 
                   4789: /******************* Printing html file ***********/
1.201     brouard  4790: void printinghtml(char fileresu[], char title[], char datafile[], int firstpass, \
1.126     brouard  4791:                  int lastpass, int stepm, int weightopt, char model[],\
                   4792:                  int imx,int jmin, int jmax, double jmeanint,char rfileres[],\
                   4793:                  int popforecast, int estepm ,\
                   4794:                  double jprev1, double mprev1,double anprev1, \
                   4795:                  double jprev2, double mprev2,double anprev2){
                   4796:   int jj1, k1, i1, cpt;
                   4797: 
                   4798:    fprintf(fichtm,"<ul><li><a href='#firstorder'>Result files (first order: no variance)</a>\n \
                   4799:    <li><a href='#secondorder'>Result files (second order (variance)</a>\n \
                   4800: </ul>");
                   4801:    fprintf(fichtm,"<ul><li><h4><a name='firstorder'>Result files (first order: no variance)</a></h4>\n \
                   4802:  - Observed prevalence in each state (during the period defined between %.lf/%.lf/%.lf and %.lf/%.lf/%.lf): <a href=\"%s\">%s</a> <br>\n ",
1.201     brouard  4803:           jprev1, mprev1,anprev1,jprev2, mprev2,anprev2,subdirf2(fileresu,"P_"),subdirf2(fileresu,"P_"));
1.126     brouard  4804:    fprintf(fichtm,"\
                   4805:  - Estimated transition probabilities over %d (stepm) months: <a href=\"%s\">%s</a><br>\n ",
1.201     brouard  4806:           stepm,subdirf2(fileresu,"PIJ_"),subdirf2(fileresu,"PIJ_"));
1.126     brouard  4807:    fprintf(fichtm,"\
                   4808:  - Period (stable) prevalence in each health state: <a href=\"%s\">%s</a> <br>\n",
1.201     brouard  4809:           subdirf2(fileresu,"PL_"),subdirf2(fileresu,"PL_"));
1.126     brouard  4810:    fprintf(fichtm,"\
1.128     brouard  4811:  - (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  4812:    <a href=\"%s\">%s</a> <br>\n",
1.201     brouard  4813:           estepm,subdirf2(fileresu,"E_"),subdirf2(fileresu,"E_"));
1.126     brouard  4814:    fprintf(fichtm,"\
                   4815:  - Population projections by age and states: \
1.201     brouard  4816:    <a href=\"%s\">%s</a> <br>\n</li>", subdirf2(fileresu,"F_"),subdirf2(fileresu,"F_"));
1.126     brouard  4817: 
                   4818: fprintf(fichtm," \n<ul><li><b>Graphs</b></li><p>");
                   4819: 
1.145     brouard  4820:  m=pow(2,cptcoveff);
1.126     brouard  4821:  if (cptcovn < 1) {m=1;ncodemax[1]=1;}
                   4822: 
                   4823:  jj1=0;
                   4824:  for(k1=1; k1<=m;k1++){
1.192     brouard  4825:    /* for(i1=1; i1<=ncodemax[k1];i1++){ */
1.126     brouard  4826:      jj1++;
                   4827:      if (cptcovn > 0) {
                   4828:        fprintf(fichtm,"<hr  size=\"2\" color=\"#EC5E5E\">************ Results for covariates");
1.192     brouard  4829:        for (cpt=1; cpt<=cptcoveff;cpt++){ 
1.198     brouard  4830:         fprintf(fichtm," V%d=%d ",Tvaraff[cpt],nbcode[Tvaraff[cpt]][codtabm(jj1,cpt)]);
                   4831:         printf(" V%d=%d ",Tvaraff[cpt],nbcode[Tvaraff[cpt]][codtabm(jj1,cpt)]);fflush(stdout);
1.192     brouard  4832:        }
1.126     brouard  4833:        fprintf(fichtm," ************\n<hr size=\"2\" color=\"#EC5E5E\">");
                   4834:      }
1.201     brouard  4835:      /* aij, bij */
                   4836:      fprintf(fichtm,"<br>- Logit model, for example: logit(pij)=log(pij/pii)= aij+ bij age + V1 age + etc. as a function of age: <a href=\"%s_%d-1.svg\">%s_%d-1.svg</a><br> \
                   4837: <img src=\"%s_%d-1.svg\">",subdirf2(optionfilefiname,"PE_"),jj1,subdirf2(optionfilefiname,"PE_"),jj1,subdirf2(optionfilefiname,"PE_"),jj1);
1.126     brouard  4838:      /* Pij */
1.202     brouard  4839:      fprintf(fichtm,"<br>\n- Pij or conditional probabilities to be observed in state j being in state i, %d (stepm) months before: <a href=\"%s_%d-2.svg\">%s_%d-2.svg</a><br> \
1.201     brouard  4840: <img src=\"%s_%d-2.svg\">",stepm,subdirf2(optionfilefiname,"PE_"),jj1,subdirf2(optionfilefiname,"PE_"),jj1,subdirf2(optionfilefiname,"PE_"),jj1);     
1.126     brouard  4841:      /* Quasi-incidences */
1.201     brouard  4842:      fprintf(fichtm,"<br>\n- Iij or Conditional probabilities to be observed in state j being in state i %d (stepm) months\
                   4843:  before but expressed in per year i.e. quasi incidences if stepm is small and probabilities too,\
                   4844:  incidence (rates) are the limit when h tends to zero of the ratio of the probability hPij \
                   4845: divided by h: hPij/h : <a href=\"%s_%d-3.svg\">%s_%d-3.svg</a><br> \
                   4846: <img src=\"%s_%d-3.svg\">",stepm,subdirf2(optionfilefiname,"PE_"),jj1,subdirf2(optionfilefiname,"PE_"),jj1,subdirf2(optionfilefiname,"PE_"),jj1); 
                   4847:      /* Survival functions (period) in state j */
                   4848:      for(cpt=1; cpt<=nlstate;cpt++){
                   4849:        fprintf(fichtm,"<br>\n- Survival functions in state %d. Or probability to survive in state %d being in state (1 to %d) at different ages. <a href=\"%s%d_%d.svg\">%s%d_%d.svg</a><br> \
                   4850: <img src=\"%s_%d-%d.svg\">", cpt, cpt, nlstate, subdirf2(optionfilefiname,"LIJ_"),cpt,jj1,subdirf2(optionfilefiname,"LIJ_"),cpt,jj1,subdirf2(optionfilefiname,"LIJ_"),cpt,jj1);
                   4851:      }
                   4852:      /* State specific survival functions (period) */
                   4853:      for(cpt=1; cpt<=nlstate;cpt++){
1.208     brouard  4854:        fprintf(fichtm,"<br>\n- Survival functions from state %d in each live state and total.\
1.201     brouard  4855:  Or probability to survive in various states (1 to %d) being in state %d at different ages.\
                   4856:  <a href=\"%s%d_%d.svg\">%s%d_%d.svg</a><br> <img src=\"%s_%d-%d.svg\">", cpt, nlstate, cpt, subdirf2(optionfilefiname,"LIJT_"),cpt,jj1,subdirf2(optionfilefiname,"LIJT_"),cpt,jj1,subdirf2(optionfilefiname,"LIJT_"),cpt,jj1);
                   4857:      }
                   4858:      /* Period (stable) prevalence in each health state */
                   4859:      for(cpt=1; cpt<=nlstate;cpt++){
                   4860:        fprintf(fichtm,"<br>\n- Convergence to period (stable) prevalence in state %d. Or probability to be in state %d being in state (1 to %d) at different ages. <a href=\"%s%d_%d.svg\">%s%d_%d.svg</a><br> \
                   4861: <img src=\"%s_%d-%d.svg\">", cpt, cpt, nlstate, subdirf2(optionfilefiname,"P_"),cpt,jj1,subdirf2(optionfilefiname,"P_"),cpt,jj1,subdirf2(optionfilefiname,"P_"),cpt,jj1);
                   4862:      }
1.126     brouard  4863:      for(cpt=1; cpt<=nlstate;cpt++) {
1.205     brouard  4864:        fprintf(fichtm,"\n<br>- Life expectancy by health state (%d) at initial age and its decomposition into health expectancies in each alive state (1 to %d) (or area under each survival functions): <a href=\"%s_%d%d.svg\">%s_%d%d.svg</a> <br> \
1.201     brouard  4865: <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  4866:      }
1.192     brouard  4867:    /* } /\* end i1 *\/ */
1.126     brouard  4868:  }/* End k1 */
                   4869:  fprintf(fichtm,"</ul>");
                   4870: 
                   4871:  fprintf(fichtm,"\
                   4872: \n<br><li><h4> <a name='secondorder'>Result files (second order: variances)</a></h4>\n\
1.193     brouard  4873:  - Parameter file with estimated parameters and covariance matrix: <a href=\"%s\">%s</a> <br> \
1.203     brouard  4874:  - 95%% confidence intervals and Wald tests of the estimated parameters are in the log file if optimization has been done (mle != 0).<br> \
1.197     brouard  4875: But because parameters are usually highly correlated (a higher incidence of disability \
                   4876: and a higher incidence of recovery can give very close observed transition) it might \
                   4877: be very useful to look not only at linear confidence intervals estimated from the \
                   4878: variances but at the covariance matrix. And instead of looking at the estimated coefficients \
                   4879: (parameters) of the logistic regression, it might be more meaningful to visualize the \
                   4880: covariance matrix of the one-step probabilities. \
                   4881: See page 'Matrix of variance-covariance of one-step probabilities' below. \n", rfileres,rfileres);
1.126     brouard  4882: 
1.193     brouard  4883:  fprintf(fichtm," - Standard deviation of one-step probabilities: <a href=\"%s\">%s</a> <br>\n",
1.201     brouard  4884:         subdirf2(fileresu,"PROB_"),subdirf2(fileresu,"PROB_"));
1.126     brouard  4885:  fprintf(fichtm,"\
                   4886:  - Variance-covariance of one-step probabilities: <a href=\"%s\">%s</a> <br>\n",
1.201     brouard  4887:         subdirf2(fileresu,"PROBCOV_"),subdirf2(fileresu,"PROBCOV_"));
1.126     brouard  4888: 
                   4889:  fprintf(fichtm,"\
                   4890:  - Correlation matrix of one-step probabilities: <a href=\"%s\">%s</a> <br>\n",
1.201     brouard  4891:         subdirf2(fileresu,"PROBCOR_"),subdirf2(fileresu,"PROBCOR_"));
1.126     brouard  4892:  fprintf(fichtm,"\
                   4893:  - 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): \
                   4894:    <a href=\"%s\">%s</a> <br>\n</li>",
1.201     brouard  4895:           estepm,subdirf2(fileresu,"CVE_"),subdirf2(fileresu,"CVE_"));
1.126     brouard  4896:  fprintf(fichtm,"\
                   4897:  - (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): \
                   4898:    <a href=\"%s\">%s</a> <br>\n</li>",
1.201     brouard  4899:           estepm,subdirf2(fileresu,"STDE_"),subdirf2(fileresu,"STDE_"));
1.126     brouard  4900:  fprintf(fichtm,"\
1.128     brouard  4901:  - Variances and covariances of health expectancies by age. Status (i) based health expectancies (in state j), e<sup>ij</sup> are weighted by the period prevalences in each state i (if popbased=1, an additional computation is done using the cross-sectional prevalences, i.e population based) (estepm=%d months): <a href=\"%s\">%s</a><br>\n",
1.201     brouard  4902:         estepm, subdirf2(fileresu,"V_"),subdirf2(fileresu,"V_"));
1.126     brouard  4903:  fprintf(fichtm,"\
1.128     brouard  4904:  - Total life expectancy and total health expectancies to be spent in each health state e<sup>.j</sup> with their standard errors (if popbased=1, an additional computation is done using the cross-sectional prevalences, i.e population based) (estepm=%d months): <a href=\"%s\">%s</a> <br>\n",
1.201     brouard  4905:         estepm, subdirf2(fileresu,"T_"),subdirf2(fileresu,"T_"));
1.126     brouard  4906:  fprintf(fichtm,"\
                   4907:  - Standard deviation of period (stable) prevalences: <a href=\"%s\">%s</a> <br>\n",\
1.201     brouard  4908:         subdirf2(fileresu,"VPL_"),subdirf2(fileresu,"VPL_"));
1.126     brouard  4909: 
                   4910: /*  if(popforecast==1) fprintf(fichtm,"\n */
                   4911: /*  - Prevalences forecasting: <a href=\"f%s\">f%s</a> <br>\n */
                   4912: /*  - Population forecasting (if popforecast=1): <a href=\"pop%s\">pop%s</a> <br>\n */
                   4913: /*     <br>",fileres,fileres,fileres,fileres); */
                   4914: /*  else  */
                   4915: /*    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); */
                   4916:  fflush(fichtm);
                   4917:  fprintf(fichtm," <ul><li><b>Graphs</b></li><p>");
                   4918: 
1.145     brouard  4919:  m=pow(2,cptcoveff);
1.126     brouard  4920:  if (cptcovn < 1) {m=1;ncodemax[1]=1;}
                   4921: 
                   4922:  jj1=0;
                   4923:  for(k1=1; k1<=m;k1++){
1.192     brouard  4924:    /* for(i1=1; i1<=ncodemax[k1];i1++){ */
1.126     brouard  4925:      jj1++;
                   4926:      if (cptcovn > 0) {
                   4927:        fprintf(fichtm,"<hr  size=\"2\" color=\"#EC5E5E\">************ Results for covariates");
                   4928:        for (cpt=1; cpt<=cptcoveff;cpt++) 
1.198     brouard  4929:         fprintf(fichtm," V%d=%d ",Tvaraff[cpt],nbcode[Tvaraff[cpt]][codtabm(jj1,cpt)]);
1.126     brouard  4930:        fprintf(fichtm," ************\n<hr size=\"2\" color=\"#EC5E5E\">");
                   4931:      }
                   4932:      for(cpt=1; cpt<=nlstate;cpt++) {
                   4933:        fprintf(fichtm,"<br>- Observed (cross-sectional) and period (incidence based) \
1.205     brouard  4934: prevalence (with 95%% confidence interval) in state (%d): <a href=\"%s_%d%d.svg\"> %s_%d-%d.svg <br>\
                   4935: <img src=\"%s_%d-%d.svg\">",cpt,subdirf2(optionfilefiname,"V_"),cpt,jj1,subdirf2(optionfilefiname,"V_"),cpt,jj1,subdirf2(optionfilefiname,"V_"),cpt,jj1);  
1.126     brouard  4936:      }
                   4937:      fprintf(fichtm,"\n<br>- Total life expectancy by age and \
1.128     brouard  4938: health expectancies in states (1) and (2). If popbased=1 the smooth (due to the model) \
                   4939: true period expectancies (those weighted with period prevalences are also\
                   4940:  drawn in addition to the population based expectancies computed using\
1.205     brouard  4941:  observed and cahotic prevalences:  <a href=\"%s_%d.svg\">%s_%d.svg<br>\
                   4942: <img src=\"%s_%d.svg\">",subdirf2(optionfilefiname,"E_"),jj1,subdirf2(optionfilefiname,"E_"),jj1,subdirf2(optionfilefiname,"E_"),jj1);
1.192     brouard  4943:    /* } /\* end i1 *\/ */
1.126     brouard  4944:  }/* End k1 */
                   4945:  fprintf(fichtm,"</ul>");
                   4946:  fflush(fichtm);
                   4947: }
                   4948: 
                   4949: /******************* Gnuplot file **************/
1.201     brouard  4950: void printinggnuplot(char fileresu[], char optionfilefiname[], double ageminpar, double agemaxpar, double fage , char pathc[], double p[]){
1.126     brouard  4951: 
                   4952:   char dirfileres[132],optfileres[132];
1.164     brouard  4953:   int cpt=0,k1=0,i=0,k=0,j=0,jk=0,k2=0,k3=0,ij=0,l=0;
1.130     brouard  4954:   int ng=0;
1.201     brouard  4955:   int vpopbased;
1.126     brouard  4956: /*   if((ficgp=fopen(optionfilegnuplot,"a"))==NULL) { */
                   4957: /*     printf("Problem with file %s",optionfilegnuplot); */
                   4958: /*     fprintf(ficlog,"Problem with file %s",optionfilegnuplot); */
                   4959: /*   } */
                   4960: 
                   4961:   /*#ifdef windows */
                   4962:   fprintf(ficgp,"cd \"%s\" \n",pathc);
                   4963:     /*#endif */
                   4964:   m=pow(2,cptcoveff);
                   4965: 
1.202     brouard  4966:   /* Contribution to likelihood */
                   4967:   /* Plot the probability implied in the likelihood */
                   4968:     fprintf(ficgp,"\n# Contributions to the Likelihood, mle >=1. For mle=4 no interpolation, pure matrix products.\n#\n");
                   4969:     fprintf(ficgp,"\n set log y; unset log x;set xlabel \"Age\"; set ylabel \"Likelihood (-2Log(L))\";");
                   4970:     /* fprintf(ficgp,"\nset ter svg size 640, 480"); */ /* Too big for svg */
1.205     brouard  4971:     fprintf(ficgp,"\nset ter pngcairo size 640, 480");
1.204     brouard  4972: /* nice for mle=4 plot by number of matrix products.
1.202     brouard  4973:    replot  "rrtest1/toto.txt" u 2:($4 == 1 && $5==2 ? $9 : 1/0):5 t "p12" with point lc 1 */
                   4974: /* replot exp(p1+p2*x)/(1+exp(p1+p2*x)+exp(p3+p4*x)+exp(p5+p6*x)) t "p12(x)"  */
                   4975:     /* fprintf(ficgp,"\nset out \"%s.svg\";",subdirf2(optionfilefiname,"ILK_")); */
1.204     brouard  4976:     fprintf(ficgp,"\nset out \"%s-dest.png\";",subdirf2(optionfilefiname,"ILK_"));
1.205     brouard  4977:     fprintf(ficgp,"\nset log y;plot  \"%s\" u 2:(-$12):5 t \"All sample, transitions colored by destination\" with dots lc variable; set out;\n",subdirf(fileresilk));
1.204     brouard  4978:     fprintf(ficgp,"\nset out \"%s-ori.png\";",subdirf2(optionfilefiname,"ILK_"));
1.205     brouard  4979:     fprintf(ficgp,"\nset log y;plot  \"%s\" u 2:(-$12):4 t \"All sample, transitions colored by origin\" with dots lc variable; set out;\n\n",subdirf(fileresilk));
1.204     brouard  4980:     for (i=1; i<= nlstate ; i ++) {
                   4981:       fprintf(ficgp,"\nset out \"%s-p%dj.png\";set ylabel \"Probability for each individual/wave\";",subdirf2(optionfilefiname,"ILK_"),i);
1.205     brouard  4982:       fprintf(ficgp,"unset log;\n# plot weighted, mean weight should have point size of 0.5\n plot  \"%s\"",subdirf(fileresilk));
                   4983:       fprintf(ficgp,"  u  2:($4 == %d && $5==%d ? $9 : 1/0):($11/4.):5 t \"p%d%d\" with points pointtype 7 ps variable lc variable \\\n",i,1,i,1);
1.204     brouard  4984:       for (j=2; j<= nlstate+ndeath ; j ++) {
1.205     brouard  4985:        fprintf(ficgp,",\\\n \"\" u  2:($4 == %d && $5==%d ? $9 : 1/0):($11/4.):5 t \"p%d%d\" with points pointtype 7 ps variable lc variable ",i,j,i,j);
1.204     brouard  4986:       }
                   4987:       fprintf(ficgp,";\nset out; unset ylabel;\n"); 
                   4988:     }
                   4989:     /* unset log; plot  "rrtest1_sorted_4/ILK_rrtest1_sorted_4.txt" u  2:($4 == 1 && $5==2 ? $9 : 1/0):5 t "p12" with points lc variable */             
                   4990:     /* fprintf(ficgp,"\nset log y;plot  \"%s\" u 2:(-$11):3 t \"All sample, all transitions\" with dots lc variable",subdirf(fileresilk)); */
                   4991:     /* fprintf(ficgp,"\nreplot  \"%s\" u 2:($3 <= 3 ? -$11 : 1/0):3 t \"First 3 individuals\" with line lc variable", subdirf(fileresilk)); */
1.203     brouard  4992:     fprintf(ficgp,"\nset out;unset log\n");
1.202     brouard  4993:     /* fprintf(ficgp,"\nset out \"%s.svg\"; replot; set out; # bug gnuplot",subdirf2(optionfilefiname,"ILK_")); */
                   4994: 
1.126     brouard  4995:   strcpy(dirfileres,optionfilefiname);
                   4996:   strcpy(optfileres,"vpl");
                   4997:  /* 1eme*/
1.201     brouard  4998:   fprintf(ficgp,"\n# 1st: Period (stable) prevalence with CI: 'VPL_' files\n");
1.126     brouard  4999:   for (cpt=1; cpt<= nlstate ; cpt ++) {
1.145     brouard  5000:     for (k1=1; k1<= m ; k1 ++) { /* plot [100000000000000000000:-100000000000000000000] "mysbiaspar/vplrmysbiaspar.txt to check */
1.201     brouard  5001:      fprintf(ficgp,"\nset out \"%s_%d-%d.svg\" \n",subdirf2(optionfilefiname,"V_"),cpt,k1);
                   5002:      fprintf(ficgp,"\n#set out \"V_%s_%d-%d.svg\" \n",optionfilefiname,cpt,k1);
1.126     brouard  5003:      fprintf(ficgp,"set xlabel \"Age\" \n\
                   5004: set ylabel \"Probability\" \n\
1.199     brouard  5005: set ter svg size 640, 480\n\
1.201     brouard  5006: plot [%.f:%.f] \"%s\" every :::%d::%d u 1:2 \"%%lf",ageminpar,fage,subdirf2(fileresu,"VPL_"),k1-1,k1-1);
1.126     brouard  5007: 
                   5008:      for (i=1; i<= nlstate ; i ++) {
1.170     brouard  5009:        if (i==cpt) fprintf(ficgp," %%lf (%%lf)");
                   5010:        else        fprintf(ficgp," %%*lf (%%*lf)");
1.126     brouard  5011:      }
1.201     brouard  5012:      fprintf(ficgp,"\" t\"Period (stable) prevalence\" w l lt 0,\"%s\" every :::%d::%d u 1:($2+1.96*$3) \"%%lf",subdirf2(fileresu,"VPL_"),k1-1,k1-1);
1.126     brouard  5013:      for (i=1; i<= nlstate ; i ++) {
1.170     brouard  5014:        if (i==cpt) fprintf(ficgp," %%lf (%%lf)");
                   5015:        else fprintf(ficgp," %%*lf (%%*lf)");
1.126     brouard  5016:      } 
1.201     brouard  5017:      fprintf(ficgp,"\" t\"95%% CI\" w l lt 1,\"%s\" every :::%d::%d u 1:($2-1.96*$3) \"%%lf",subdirf2(fileresu,"VPL_"),k1-1,k1-1); 
1.126     brouard  5018:      for (i=1; i<= nlstate ; i ++) {
1.170     brouard  5019:        if (i==cpt) fprintf(ficgp," %%lf (%%lf)");
                   5020:        else fprintf(ficgp," %%*lf (%%*lf)");
1.126     brouard  5021:      }  
1.201     brouard  5022:      fprintf(ficgp,"\" t\"\" w l lt 1,\"%s\" every :::%d::%d u 1:($%d) t\"Observed prevalence \" w l lt 2",subdirf2(fileresu,"P_"),k1-1,k1-1,2+4*(cpt-1));
                   5023:      fprintf(ficgp,"\nset out \n");
                   5024:     } /* k1 */
                   5025:   } /* cpt */
1.126     brouard  5026:   /*2 eme*/
1.153     brouard  5027:   fprintf(ficgp,"\n# 2nd: Total life expectancy with CI: 't' files\n");
1.126     brouard  5028:   for (k1=1; k1<= m ; k1 ++) { 
1.201     brouard  5029:     fprintf(ficgp,"\nset out \"%s_%d.svg\" \n",subdirf2(optionfilefiname,"E_"),k1);
                   5030:     for(vpopbased=0; vpopbased <= popbased; vpopbased++){ /* Done for vpopbased=0 and vpopbased=1 if popbased==1*/
                   5031:       if(vpopbased==0)
                   5032:        fprintf(ficgp,"set ylabel \"Years\" \nset ter svg size 640, 480\nplot [%.f:%.f] ",ageminpar,fage);
                   5033:       else
                   5034:        fprintf(ficgp,"\nreplot ");
                   5035:       for (i=1; i<= nlstate+1 ; i ++) {
                   5036:        k=2*i;
                   5037:        fprintf(ficgp,"\"%s\" every :::%d::%d u 1:($2==%d && $4!=0 ?$4 : 1/0) \"%%lf %%lf %%lf",subdirf2(fileresu,"T_"),k1-1,k1-1, vpopbased);
                   5038:        for (j=1; j<= nlstate+1 ; j ++) {
                   5039:          if (j==i) fprintf(ficgp," %%lf (%%lf)");
                   5040:          else fprintf(ficgp," %%*lf (%%*lf)");
                   5041:        }   
                   5042:        if (i== 1) fprintf(ficgp,"\" t\"TLE\" w l lt %d, \\\n",i);
                   5043:        else fprintf(ficgp,"\" t\"LE in state (%d)\" w l lt %d, \\\n",i-1,i+1);
                   5044:        fprintf(ficgp,"\"%s\" every :::%d::%d u 1:($2==%d && $4!=0 ? $4-$5*2 : 1/0) \"%%lf %%lf %%lf",subdirf2(fileresu,"T_"),k1-1,k1-1,vpopbased);
                   5045:        for (j=1; j<= nlstate+1 ; j ++) {
                   5046:          if (j==i) fprintf(ficgp," %%lf (%%lf)");
                   5047:          else fprintf(ficgp," %%*lf (%%*lf)");
                   5048:        }   
                   5049:        fprintf(ficgp,"\" t\"\" w l lt 0,");
                   5050:        fprintf(ficgp,"\"%s\" every :::%d::%d u 1:($2==%d && $4!=0 ? $4+$5*2 : 1/0) \"%%lf %%lf %%lf",subdirf2(fileresu,"T_"),k1-1,k1-1,vpopbased);
                   5051:        for (j=1; j<= nlstate+1 ; j ++) {
                   5052:          if (j==i) fprintf(ficgp," %%lf (%%lf)");
                   5053:          else fprintf(ficgp," %%*lf (%%*lf)");
                   5054:        }   
                   5055:        if (i== (nlstate+1)) fprintf(ficgp,"\" t\"\" w l lt 0");
                   5056:        else fprintf(ficgp,"\" t\"\" w l lt 0,\\\n");
                   5057:       } /* state */
                   5058:     } /* vpopbased */
                   5059:     fprintf(ficgp,"\nset out;set out \"%s_%d.svg\"; replot; set out; \n",subdirf2(optionfilefiname,"E_"),k1); /* Buggy gnuplot */
                   5060:   } /* k1 */
1.126     brouard  5061:   /*3eme*/
                   5062:   
                   5063:   for (k1=1; k1<= m ; k1 ++) { 
                   5064:     for (cpt=1; cpt<= nlstate ; cpt ++) {
                   5065:       /*       k=2+nlstate*(2*cpt-2); */
                   5066:       k=2+(nlstate+1)*(cpt-1);
1.201     brouard  5067:       fprintf(ficgp,"\nset out \"%s_%d%d.svg\" \n",subdirf2(optionfilefiname,"EXP_"),cpt,k1);
1.199     brouard  5068:       fprintf(ficgp,"set ter svg size 640, 480\n\
1.201     brouard  5069: plot [%.f:%.f] \"%s\" every :::%d::%d u 1:%d t \"e%d1\" w l",ageminpar,fage,subdirf2(fileresu,"E_"),k1-1,k1-1,k,cpt);
1.126     brouard  5070:       /*fprintf(ficgp,",\"e%s\" every :::%d::%d u 1:($%d-2*$%d) \"\%%lf ",fileres,k1-1,k1-1,k,k+1);
                   5071:        for (i=1; i<= nlstate*2 ; i ++) fprintf(ficgp,"\%%lf (\%%lf) ");
                   5072:        fprintf(ficgp,"\" t \"e%d1\" w l",cpt);
                   5073:        fprintf(ficgp,",\"e%s\" every :::%d::%d u 1:($%d+2*$%d) \"\%%lf ",fileres,k1-1,k1-1,k,k+1);
                   5074:        for (i=1; i<= nlstate*2 ; i ++) fprintf(ficgp,"\%%lf (\%%lf) ");
                   5075:        fprintf(ficgp,"\" t \"e%d1\" w l",cpt);
                   5076:        
                   5077:       */
                   5078:       for (i=1; i< nlstate ; i ++) {
1.201     brouard  5079:        fprintf(ficgp," ,\"%s\" every :::%d::%d u 1:%d t \"e%d%d\" w l",subdirf2(fileresu,"E_"),k1-1,k1-1,k+i,cpt,i+1);
1.126     brouard  5080:        /*      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);*/
                   5081:        
                   5082:       } 
1.201     brouard  5083:       fprintf(ficgp," ,\"%s\" every :::%d::%d u 1:%d t \"e%d.\" w l",subdirf2(fileresu,"E_"),k1-1,k1-1,k+nlstate,cpt);
1.126     brouard  5084:     }
                   5085:   }
                   5086:   
1.201     brouard  5087:   /* Survival functions (period) from state i in state j by initial state i */
                   5088:   for (k1=1; k1<= m ; k1 ++) { /* For each multivariate if any */
                   5089:     for (cpt=1; cpt<=nlstate ; cpt ++) { /* For each life state */
                   5090:       k=3;
                   5091:       fprintf(ficgp,"\n#\n#\n# Survival functions in state j : 'lij' files, cov=%d state=%d",k1, cpt);
                   5092:       fprintf(ficgp,"\nset out \"%s_%d-%d.svg\" \n",subdirf2(optionfilefiname,"LIJ_"),cpt,k1);
                   5093:       fprintf(ficgp,"set xlabel \"Age\" \nset ylabel \"Probability to be alive\" \n\
                   5094: set ter svg size 640, 480\n\
                   5095: unset log y\n\
                   5096: plot [%.f:%.f]  ", ageminpar, agemaxpar);
                   5097:       for (i=1; i<= nlstate ; i ++){
                   5098:        if(i==1)
                   5099:          fprintf(ficgp,"\"%s\"",subdirf2(fileresu,"PIJ_"));
                   5100:        else
                   5101:          fprintf(ficgp,", '' ");
                   5102:        l=(nlstate+ndeath)*(i-1)+1;
                   5103:        fprintf(ficgp," u ($1==%d ? ($3):1/0):($%d/($%d",k1,k+l+(cpt-1),k+l);
                   5104:        for (j=2; j<= nlstate+ndeath ; j ++)
                   5105:          fprintf(ficgp,"+$%d",k+l+j-1);
                   5106:        fprintf(ficgp,")) t \"l(%d,%d)\" w l",i,cpt);
                   5107:       } /* nlstate */
                   5108:       fprintf(ficgp,"\nset out\n");
                   5109:     } /* end cpt state*/ 
                   5110:   } /* end covariate */  
                   5111: 
                   5112:   /* Survival functions (period) from state i in state j by final state j */
1.202     brouard  5113:   for (k1=1; k1<= m ; k1 ++) { /* For each covariate if any */
1.201     brouard  5114:     for (cpt=1; cpt<=nlstate ; cpt ++) { /* For each inital state  */
                   5115:       k=3;
                   5116:       fprintf(ficgp,"\n#\n#\n# Survival functions in state j and all livestates from state i by final state j: 'lij' files, cov=%d state=%d",k1, cpt);
                   5117:       fprintf(ficgp,"\nset out \"%s_%d-%d.svg\" \n",subdirf2(optionfilefiname,"LIJT_"),cpt,k1);
                   5118:       fprintf(ficgp,"set xlabel \"Age\" \nset ylabel \"Probability to be alive\" \n\
                   5119: set ter svg size 640, 480\n\
                   5120: unset log y\n\
                   5121: plot [%.f:%.f]  ", ageminpar, agemaxpar);
                   5122:       for (j=1; j<= nlstate ; j ++){ /* Lived in state j */
                   5123:        if(j==1)
                   5124:          fprintf(ficgp,"\"%s\"",subdirf2(fileresu,"PIJ_"));
                   5125:        else
                   5126:          fprintf(ficgp,", '' ");
                   5127:        l=(nlstate+ndeath)*(cpt-1) +j;
                   5128:        fprintf(ficgp," u (($1==%d && (floor($2)%%5 == 0)) ? ($3):1/0):($%d",k1,k+l);
                   5129:        /* for (i=2; i<= nlstate+ndeath ; i ++) */
                   5130:        /*   fprintf(ficgp,"+$%d",k+l+i-1); */
                   5131:        fprintf(ficgp,") t \"l(%d,%d)\" w l",cpt,j);
                   5132:       } /* nlstate */
                   5133:       fprintf(ficgp,", '' ");
                   5134:       fprintf(ficgp," u (($1==%d && (floor($2)%%5 == 0)) ? ($3):1/0):(",k1);
                   5135:       for (j=1; j<= nlstate ; j ++){ /* Lived in state j */
                   5136:        l=(nlstate+ndeath)*(cpt-1) +j;
                   5137:        if(j < nlstate)
                   5138:          fprintf(ficgp,"$%d +",k+l);
                   5139:        else
                   5140:          fprintf(ficgp,"$%d) t\"l(%d,.)\" w l",k+l,cpt);
                   5141:       }
                   5142:       fprintf(ficgp,"\nset out\n");
                   5143:     } /* end cpt state*/ 
                   5144:   } /* end covariate */  
                   5145: 
1.202     brouard  5146:   /* CV preval stable (period) for each covariate */
                   5147:   for (k1=1; k1<= m ; k1 ++) { /* For each covariate if any */
1.153     brouard  5148:     for (cpt=1; cpt<=nlstate ; cpt ++) { /* For each life state */
1.126     brouard  5149:       k=3;
1.153     brouard  5150:       fprintf(ficgp,"\n#\n#\n#CV preval stable (period): 'pij' files, cov=%d state=%d",k1, cpt);
1.201     brouard  5151:       fprintf(ficgp,"\nset out \"%s_%d-%d.svg\" \n",subdirf2(optionfilefiname,"P_"),cpt,k1);
1.126     brouard  5152:       fprintf(ficgp,"set xlabel \"Age\" \nset ylabel \"Probability\" \n\
1.199     brouard  5153: set ter svg size 640, 480\n\
1.126     brouard  5154: unset log y\n\
1.153     brouard  5155: plot [%.f:%.f]  ", ageminpar, agemaxpar);
                   5156:       for (i=1; i<= nlstate ; i ++){
                   5157:        if(i==1)
1.201     brouard  5158:          fprintf(ficgp,"\"%s\"",subdirf2(fileresu,"PIJ_"));
1.153     brouard  5159:        else
                   5160:          fprintf(ficgp,", '' ");
1.154     brouard  5161:        l=(nlstate+ndeath)*(i-1)+1;
                   5162:        fprintf(ficgp," u ($1==%d ? ($3):1/0):($%d/($%d",k1,k+l+(cpt-1),k+l);
1.201     brouard  5163:        for (j=2; j<= nlstate ; j ++)
                   5164:          fprintf(ficgp,"+$%d",k+l+j-1);
1.153     brouard  5165:        fprintf(ficgp,")) t \"prev(%d,%d)\" w l",i,cpt);
                   5166:       } /* nlstate */
1.201     brouard  5167:       fprintf(ficgp,"\nset out\n");
1.153     brouard  5168:     } /* end cpt state*/ 
                   5169:   } /* end covariate */  
1.201     brouard  5170: 
1.126     brouard  5171:   /* proba elementaires */
1.187     brouard  5172:   fprintf(ficgp,"\n##############\n#MLE estimated parameters\n#############\n");
1.126     brouard  5173:   for(i=1,jk=1; i <=nlstate; i++){
1.187     brouard  5174:     fprintf(ficgp,"# initial state %d\n",i);
1.126     brouard  5175:     for(k=1; k <=(nlstate+ndeath); k++){
                   5176:       if (k != i) {
1.187     brouard  5177:        fprintf(ficgp,"#   current state %d\n",k);
1.126     brouard  5178:        for(j=1; j <=ncovmodel; j++){
1.187     brouard  5179:          fprintf(ficgp,"p%d=%f; ",jk,p[jk]);
1.126     brouard  5180:          jk++; 
                   5181:        }
1.187     brouard  5182:        fprintf(ficgp,"\n");
1.126     brouard  5183:       }
                   5184:     }
                   5185:    }
1.187     brouard  5186:   fprintf(ficgp,"##############\n#\n");
                   5187: 
1.145     brouard  5188:   /*goto avoid;*/
1.200     brouard  5189:   fprintf(ficgp,"\n##############\n#Graphics of probabilities or incidences\n#############\n");
1.187     brouard  5190:   fprintf(ficgp,"# logi(p12/p11)=a12+b12*age+c12age*age+d12*V1+e12*V1*age\n");
                   5191:   fprintf(ficgp,"# logi(p12/p11)=p1 +p2*age +p3*age*age+ p4*V1+ p5*V1*age\n");
                   5192:   fprintf(ficgp,"# logi(p13/p11)=a13+b13*age+c13age*age+d13*V1+e13*V1*age\n");
                   5193:   fprintf(ficgp,"# logi(p13/p11)=p6 +p7*age +p8*age*age+ p9*V1+ p10*V1*age\n");
                   5194:   fprintf(ficgp,"# p12+p13+p14+p11=1=p11(1+exp(a12+b12*age+c12age*age+d12*V1+e12*V1*age)\n");
                   5195:   fprintf(ficgp,"#                      +exp(a13+b13*age+c13age*age+d13*V1+e13*V1*age)+...)\n");
                   5196:   fprintf(ficgp,"# p11=1/(1+exp(a12+b12*age+c12age*age+d12*V1+e12*V1*age)\n");
                   5197:   fprintf(ficgp,"#                      +exp(a13+b13*age+c13age*age+d13*V1+e13*V1*age)+...)\n");
                   5198:   fprintf(ficgp,"# p12=exp(a12+b12*age+c12age*age+d12*V1+e12*V1*age)/\n");
                   5199:   fprintf(ficgp,"#     (1+exp(a12+b12*age+c12age*age+d12*V1+e12*V1*age)\n");
                   5200:   fprintf(ficgp,"#       +exp(a13+b13*age+c13age*age+d13*V1+e13*V1*age))\n");
                   5201:   fprintf(ficgp,"#       +exp(a14+b14*age+c14age*age+d14*V1+e14*V1*age)+...)\n");
                   5202:   fprintf(ficgp,"#\n");
1.201     brouard  5203:    for(ng=1; ng<=3;ng++){ /* Number of graphics: first is logit, 2nd is probabilities, third is incidences per year*/
1.187     brouard  5204:      fprintf(ficgp,"# ng=%d\n",ng);
                   5205:      fprintf(ficgp,"#   jk=1 to 2^%d=%d\n",cptcoveff,m);
1.126     brouard  5206:      for(jk=1; jk <=m; jk++) {
1.187     brouard  5207:        fprintf(ficgp,"#    jk=%d\n",jk);
1.201     brouard  5208:        fprintf(ficgp,"\nset out \"%s_%d-%d.svg\" ",subdirf2(optionfilefiname,"PE_"),jk,ng);
                   5209:        fprintf(ficgp,"\nset ter svg size 640, 480 ");
                   5210:        if (ng==1){
                   5211:         fprintf(ficgp,"\nset ylabel \"Value of the logit of the model\"\n"); /* exp(a12+b12*x) could be nice */
                   5212:         fprintf(ficgp,"\nunset log y");
                   5213:        }else if (ng==2){
                   5214:         fprintf(ficgp,"\nset ylabel \"Probability\"\n");
                   5215:         fprintf(ficgp,"\nset log y");
                   5216:        }else if (ng==3){
1.126     brouard  5217:         fprintf(ficgp,"\nset ylabel \"Quasi-incidence per year\"\n");
1.201     brouard  5218:         fprintf(ficgp,"\nset log y");
                   5219:        }else
                   5220:         fprintf(ficgp,"\nunset title ");
                   5221:        fprintf(ficgp,"\nplot  [%.f:%.f] ",ageminpar,agemaxpar);
1.126     brouard  5222:        i=1;
                   5223:        for(k2=1; k2<=nlstate; k2++) {
                   5224:         k3=i;
                   5225:         for(k=1; k<=(nlstate+ndeath); k++) {
                   5226:           if (k != k2){
1.201     brouard  5227:             switch( ng) {
                   5228:             case 1:
1.187     brouard  5229:               if(nagesqr==0)
1.201     brouard  5230:                 fprintf(ficgp," p%d+p%d*x",i,i+1);
1.187     brouard  5231:               else /* nagesqr =1 */
1.201     brouard  5232:                 fprintf(ficgp," p%d+p%d*x+p%d*x*x",i,i+1,i+1+nagesqr);
                   5233:               break;
                   5234:             case 2: /* ng=2 */
1.187     brouard  5235:               if(nagesqr==0)
                   5236:                 fprintf(ficgp," exp(p%d+p%d*x",i,i+1);
                   5237:               else /* nagesqr =1 */
1.201     brouard  5238:                   fprintf(ficgp," exp(p%d+p%d*x+p%d*x*x",i,i+1,i+1+nagesqr);
                   5239:               break;
                   5240:             case 3:
                   5241:               if(nagesqr==0)
                   5242:                 fprintf(ficgp," %f*exp(p%d+p%d*x",YEARM/stepm,i,i+1);
                   5243:               else /* nagesqr =1 */
                   5244:                 fprintf(ficgp," %f*exp(p%d+p%d*x+p%d*x*x",YEARM/stepm,i,i+1,i+1+nagesqr);
                   5245:               break;
                   5246:             }
1.141     brouard  5247:             ij=1;/* To be checked else nbcode[0][0] wrong */
1.187     brouard  5248:             for(j=3; j <=ncovmodel-nagesqr; j++) {
1.197     brouard  5249:               /* printf("Tage[%d]=%d, j=%d\n", ij, Tage[ij], j); */
                   5250:               if(ij <=cptcovage) { /* Bug valgrind */
                   5251:                 if((j-2)==Tage[ij]) { /* Bug valgrind */
1.200     brouard  5252:                   fprintf(ficgp,"+p%d*%d*x",i+j+nagesqr-1,nbcode[Tvar[j-2]][codtabm(jk,j-2)]);
                   5253:                   /* fprintf(ficgp,"+p%d*%d*x",i+j+nagesqr-1,nbcode[Tvar[j-2]][codtabm(jk,Tvar[j-2])]); */
1.197     brouard  5254:                   ij++;
                   5255:                 }
1.186     brouard  5256:               }
                   5257:               else
1.198     brouard  5258:                 fprintf(ficgp,"+p%d*%d",i+j+nagesqr-1,nbcode[Tvar[j-2]][codtabm(jk,j-2)]);
1.126     brouard  5259:             }
1.201     brouard  5260:             if(ng != 1){
                   5261:               fprintf(ficgp,")/(1");
1.126     brouard  5262:             
1.201     brouard  5263:               for(k1=1; k1 <=nlstate; k1++){ 
                   5264:                 if(nagesqr==0)
                   5265:                   fprintf(ficgp,"+exp(p%d+p%d*x",k3+(k1-1)*ncovmodel,k3+(k1-1)*ncovmodel+1);
                   5266:                 else /* nagesqr =1 */
                   5267:                   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);
                   5268:                 
                   5269:                 ij=1;
                   5270:                 for(j=3; j <=ncovmodel-nagesqr; j++){
                   5271:                   if(ij <=cptcovage) { /* Bug valgrind */
                   5272:                     if((j-2)==Tage[ij]) { /* Bug valgrind */
                   5273:                       fprintf(ficgp,"+p%d*%d*x",k3+(k1-1)*ncovmodel+1+j-2+nagesqr,nbcode[Tvar[j-2]][codtabm(jk,j-2)]);
                   5274:                       /* fprintf(ficgp,"+p%d*%d*x",k3+(k1-1)*ncovmodel+1+j-2+nagesqr,nbcode[Tvar[j-2]][codtabm(jk,Tvar[j-2])]); */
                   5275:                       ij++;
                   5276:                     }
1.197     brouard  5277:                   }
1.201     brouard  5278:                   else
                   5279:                     fprintf(ficgp,"+p%d*%d",k3+(k1-1)*ncovmodel+1+j-2+nagesqr,nbcode[Tvar[j-2]][codtabm(jk,j-2)]);
1.186     brouard  5280:                 }
1.201     brouard  5281:                 fprintf(ficgp,")");
1.126     brouard  5282:               }
                   5283:               fprintf(ficgp,")");
1.201     brouard  5284:               if(ng ==2)
                   5285:                 fprintf(ficgp," t \"p%d%d\" ", k2,k);
                   5286:               else /* ng= 3 */
                   5287:                 fprintf(ficgp," t \"i%d%d\" ", k2,k);
                   5288:             }else{ /* end ng <> 1 */
                   5289:               fprintf(ficgp," t \"logit(p%d%d)\" ", k2,k);
1.126     brouard  5290:             }
                   5291:             if ((k+k2)!= (nlstate*2+ndeath)) fprintf(ficgp,",");
                   5292:             i=i+ncovmodel;
                   5293:           }
                   5294:         } /* end k */
                   5295:        } /* end k2 */
1.201     brouard  5296:        fprintf(ficgp,"\n set out\n");
1.126     brouard  5297:      } /* end jk */
                   5298:    } /* end ng */
1.164     brouard  5299:  /* avoid: */
1.126     brouard  5300:    fflush(ficgp); 
                   5301: }  /* end gnuplot */
                   5302: 
                   5303: 
                   5304: /*************** Moving average **************/
                   5305: int movingaverage(double ***probs, double bage,double fage, double ***mobaverage, int mobilav){
                   5306: 
                   5307:   int i, cpt, cptcod;
                   5308:   int modcovmax =1;
                   5309:   int mobilavrange, mob;
                   5310:   double age;
                   5311: 
                   5312:   modcovmax=2*cptcoveff;/* Max number of modalities. We suppose 
                   5313:                           a covariate has 2 modalities */
                   5314:   if (cptcovn<1) modcovmax=1; /* At least 1 pass */
                   5315: 
                   5316:   if(mobilav==1||mobilav ==3 ||mobilav==5 ||mobilav== 7){
                   5317:     if(mobilav==1) mobilavrange=5; /* default */
                   5318:     else mobilavrange=mobilav;
                   5319:     for (age=bage; age<=fage; age++)
                   5320:       for (i=1; i<=nlstate;i++)
                   5321:        for (cptcod=1;cptcod<=modcovmax;cptcod++)
                   5322:          mobaverage[(int)age][i][cptcod]=probs[(int)age][i][cptcod];
                   5323:     /* We keep the original values on the extreme ages bage, fage and for 
                   5324:        fage+1 and bage-1 we use a 3 terms moving average; for fage+2 bage+2
                   5325:        we use a 5 terms etc. until the borders are no more concerned. 
                   5326:     */ 
                   5327:     for (mob=3;mob <=mobilavrange;mob=mob+2){
                   5328:       for (age=bage+(mob-1)/2; age<=fage-(mob-1)/2; age++){
                   5329:        for (i=1; i<=nlstate;i++){
                   5330:          for (cptcod=1;cptcod<=modcovmax;cptcod++){
                   5331:            mobaverage[(int)age][i][cptcod] =probs[(int)age][i][cptcod];
                   5332:              for (cpt=1;cpt<=(mob-1)/2;cpt++){
                   5333:                mobaverage[(int)age][i][cptcod] +=probs[(int)age-cpt][i][cptcod];
                   5334:                mobaverage[(int)age][i][cptcod] +=probs[(int)age+cpt][i][cptcod];
                   5335:              }
                   5336:            mobaverage[(int)age][i][cptcod]=mobaverage[(int)age][i][cptcod]/mob;
                   5337:          }
                   5338:        }
                   5339:       }/* end age */
                   5340:     }/* end mob */
                   5341:   }else return -1;
                   5342:   return 0;
                   5343: }/* End movingaverage */
                   5344: 
                   5345: 
                   5346: /************** Forecasting ******************/
1.169     brouard  5347: 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  5348:   /* proj1, year, month, day of starting projection 
                   5349:      agemin, agemax range of age
                   5350:      dateprev1 dateprev2 range of dates during which prevalence is computed
                   5351:      anproj2 year of en of projection (same day and month as proj1).
                   5352:   */
1.164     brouard  5353:   int yearp, stepsize, hstepm, nhstepm, j, k, cptcod, i, h, i1;
1.126     brouard  5354:   double agec; /* generic age */
                   5355:   double agelim, ppij, yp,yp1,yp2,jprojmean,mprojmean,anprojmean;
                   5356:   double *popeffectif,*popcount;
                   5357:   double ***p3mat;
                   5358:   double ***mobaverage;
                   5359:   char fileresf[FILENAMELENGTH];
                   5360: 
                   5361:   agelim=AGESUP;
                   5362:   prevalence(probs, ageminpar, agemax, s, agev, nlstate, imx, Tvar, nbcode, ncodemax, mint, anint, dateprev1, dateprev2, firstpass, lastpass);
                   5363:  
1.201     brouard  5364:   strcpy(fileresf,"F_"); 
                   5365:   strcat(fileresf,fileresu);
1.126     brouard  5366:   if((ficresf=fopen(fileresf,"w"))==NULL) {
                   5367:     printf("Problem with forecast resultfile: %s\n", fileresf);
                   5368:     fprintf(ficlog,"Problem with forecast resultfile: %s\n", fileresf);
                   5369:   }
                   5370:   printf("Computing forecasting: result on file '%s' \n", fileresf);
                   5371:   fprintf(ficlog,"Computing forecasting: result on file '%s' \n", fileresf);
                   5372: 
                   5373:   if (cptcoveff==0) ncodemax[cptcoveff]=1;
                   5374: 
                   5375:   if (mobilav!=0) {
                   5376:     mobaverage= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
                   5377:     if (movingaverage(probs, ageminpar, fage, mobaverage,mobilav)!=0){
                   5378:       fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav);
                   5379:       printf(" Error in movingaverage mobilav=%d\n",mobilav);
                   5380:     }
                   5381:   }
                   5382: 
                   5383:   stepsize=(int) (stepm+YEARM-1)/YEARM;
                   5384:   if (stepm<=12) stepsize=1;
                   5385:   if(estepm < stepm){
                   5386:     printf ("Problem %d lower than %d\n",estepm, stepm);
                   5387:   }
                   5388:   else  hstepm=estepm;   
                   5389: 
                   5390:   hstepm=hstepm/stepm; 
                   5391:   yp1=modf(dateintmean,&yp);/* extracts integral of datemean in yp  and
                   5392:                                fractional in yp1 */
                   5393:   anprojmean=yp;
                   5394:   yp2=modf((yp1*12),&yp);
                   5395:   mprojmean=yp;
                   5396:   yp1=modf((yp2*30.5),&yp);
                   5397:   jprojmean=yp;
                   5398:   if(jprojmean==0) jprojmean=1;
                   5399:   if(mprojmean==0) jprojmean=1;
                   5400: 
                   5401:   i1=cptcoveff;
                   5402:   if (cptcovn < 1){i1=1;}
                   5403:   
                   5404:   fprintf(ficresf,"# Mean day of interviews %.lf/%.lf/%.lf (%.2f) between %.2f and %.2f \n",jprojmean,mprojmean,anprojmean,dateintmean,dateprev1,dateprev2); 
                   5405:   
                   5406:   fprintf(ficresf,"#****** Routine prevforecast **\n");
                   5407: 
                   5408: /*           if (h==(int)(YEARM*yearp)){ */
                   5409:   for(cptcov=1, k=0;cptcov<=i1;cptcov++){
                   5410:     for(cptcod=1;cptcod<=ncodemax[cptcoveff];cptcod++){
                   5411:       k=k+1;
                   5412:       fprintf(ficresf,"\n#******");
                   5413:       for(j=1;j<=cptcoveff;j++) {
1.198     brouard  5414:        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  5415:       }
                   5416:       fprintf(ficresf,"******\n");
                   5417:       fprintf(ficresf,"# Covariate valuofcovar yearproj age");
                   5418:       for(j=1; j<=nlstate+ndeath;j++){ 
                   5419:        for(i=1; i<=nlstate;i++)              
                   5420:           fprintf(ficresf," p%d%d",i,j);
                   5421:        fprintf(ficresf," p.%d",j);
                   5422:       }
                   5423:       for (yearp=0; yearp<=(anproj2-anproj1);yearp +=stepsize) { 
                   5424:        fprintf(ficresf,"\n");
                   5425:        fprintf(ficresf,"\n# Forecasting at date %.lf/%.lf/%.lf ",jproj1,mproj1,anproj1+yearp);   
                   5426: 
                   5427:        for (agec=fage; agec>=(ageminpar-1); agec--){ 
                   5428:          nhstepm=(int) rint((agelim-agec)*YEARM/stepm); 
                   5429:          nhstepm = nhstepm/hstepm; 
                   5430:          p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   5431:          oldm=oldms;savm=savms;
                   5432:          hpxij(p3mat,nhstepm,agec,hstepm,p,nlstate,stepm,oldm,savm, k);  
                   5433:        
                   5434:          for (h=0; h<=nhstepm; h++){
                   5435:            if (h*hstepm/YEARM*stepm ==yearp) {
                   5436:               fprintf(ficresf,"\n");
                   5437:               for(j=1;j<=cptcoveff;j++) 
1.198     brouard  5438:                 fprintf(ficresf,"%d %d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
1.126     brouard  5439:              fprintf(ficresf,"%.f %.f ",anproj1+yearp,agec+h*hstepm/YEARM*stepm);
                   5440:            } 
                   5441:            for(j=1; j<=nlstate+ndeath;j++) {
                   5442:              ppij=0.;
                   5443:              for(i=1; i<=nlstate;i++) {
                   5444:                if (mobilav==1) 
                   5445:                  ppij=ppij+p3mat[i][j][h]*mobaverage[(int)agec][i][cptcod];
                   5446:                else {
                   5447:                  ppij=ppij+p3mat[i][j][h]*probs[(int)(agec)][i][cptcod];
                   5448:                }
                   5449:                if (h*hstepm/YEARM*stepm== yearp) {
                   5450:                  fprintf(ficresf," %.3f", p3mat[i][j][h]);
                   5451:                }
                   5452:              } /* end i */
                   5453:              if (h*hstepm/YEARM*stepm==yearp) {
                   5454:                fprintf(ficresf," %.3f", ppij);
                   5455:              }
                   5456:            }/* end j */
                   5457:          } /* end h */
                   5458:          free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   5459:        } /* end agec */
                   5460:       } /* end yearp */
                   5461:     } /* end cptcod */
                   5462:   } /* end  cptcov */
                   5463:        
                   5464:   if (mobilav!=0) free_ma3x(mobaverage,1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
                   5465: 
                   5466:   fclose(ficresf);
                   5467: }
                   5468: 
                   5469: /************** Forecasting *****not tested NB*************/
1.169     brouard  5470: 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  5471:   
                   5472:   int cpt, stepsize, hstepm, nhstepm, j,k,c, cptcod, i,h;
                   5473:   int *popage;
                   5474:   double calagedatem, agelim, kk1, kk2;
                   5475:   double *popeffectif,*popcount;
                   5476:   double ***p3mat,***tabpop,***tabpopprev;
                   5477:   double ***mobaverage;
                   5478:   char filerespop[FILENAMELENGTH];
                   5479: 
                   5480:   tabpop= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
                   5481:   tabpopprev= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
                   5482:   agelim=AGESUP;
                   5483:   calagedatem=(anpyram+mpyram/12.+jpyram/365.-dateintmean)*YEARM;
                   5484:   
                   5485:   prevalence(probs, ageminpar, agemax, s, agev, nlstate, imx, Tvar, nbcode, ncodemax, mint, anint, dateprev1, dateprev2, firstpass, lastpass);
                   5486:   
                   5487:   
1.201     brouard  5488:   strcpy(filerespop,"POP_"); 
                   5489:   strcat(filerespop,fileresu);
1.126     brouard  5490:   if((ficrespop=fopen(filerespop,"w"))==NULL) {
                   5491:     printf("Problem with forecast resultfile: %s\n", filerespop);
                   5492:     fprintf(ficlog,"Problem with forecast resultfile: %s\n", filerespop);
                   5493:   }
                   5494:   printf("Computing forecasting: result on file '%s' \n", filerespop);
                   5495:   fprintf(ficlog,"Computing forecasting: result on file '%s' \n", filerespop);
                   5496: 
                   5497:   if (cptcoveff==0) ncodemax[cptcoveff]=1;
                   5498: 
                   5499:   if (mobilav!=0) {
                   5500:     mobaverage= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
                   5501:     if (movingaverage(probs, ageminpar, fage, mobaverage,mobilav)!=0){
                   5502:       fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav);
                   5503:       printf(" Error in movingaverage mobilav=%d\n",mobilav);
                   5504:     }
                   5505:   }
                   5506: 
                   5507:   stepsize=(int) (stepm+YEARM-1)/YEARM;
                   5508:   if (stepm<=12) stepsize=1;
                   5509:   
                   5510:   agelim=AGESUP;
                   5511:   
                   5512:   hstepm=1;
                   5513:   hstepm=hstepm/stepm; 
                   5514:   
                   5515:   if (popforecast==1) {
                   5516:     if((ficpop=fopen(popfile,"r"))==NULL) {
                   5517:       printf("Problem with population file : %s\n",popfile);exit(0);
                   5518:       fprintf(ficlog,"Problem with population file : %s\n",popfile);exit(0);
                   5519:     } 
                   5520:     popage=ivector(0,AGESUP);
                   5521:     popeffectif=vector(0,AGESUP);
                   5522:     popcount=vector(0,AGESUP);
                   5523:     
                   5524:     i=1;   
                   5525:     while ((c=fscanf(ficpop,"%d %lf\n",&popage[i],&popcount[i])) != EOF) i=i+1;
                   5526:    
                   5527:     imx=i;
                   5528:     for (i=1; i<imx;i++) popeffectif[popage[i]]=popcount[i];
                   5529:   }
                   5530: 
                   5531:   for(cptcov=1,k=0;cptcov<=i2;cptcov++){
                   5532:    for(cptcod=1;cptcod<=ncodemax[cptcoveff];cptcod++){
                   5533:       k=k+1;
                   5534:       fprintf(ficrespop,"\n#******");
                   5535:       for(j=1;j<=cptcoveff;j++) {
1.198     brouard  5536:        fprintf(ficrespop," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
1.126     brouard  5537:       }
                   5538:       fprintf(ficrespop,"******\n");
                   5539:       fprintf(ficrespop,"# Age");
                   5540:       for(j=1; j<=nlstate+ndeath;j++) fprintf(ficrespop," P.%d",j);
                   5541:       if (popforecast==1)  fprintf(ficrespop," [Population]");
                   5542:       
                   5543:       for (cpt=0; cpt<=0;cpt++) { 
                   5544:        fprintf(ficrespop,"\n\n# Forecasting at date %.lf/%.lf/%.lf ",jpyram,mpyram,anpyram+cpt);   
                   5545:        
                   5546:        for (agedeb=(fage-((int)calagedatem %12/12.)); agedeb>=(ageminpar-((int)calagedatem %12)/12.); agedeb--){ 
                   5547:          nhstepm=(int) rint((agelim-agedeb)*YEARM/stepm); 
                   5548:          nhstepm = nhstepm/hstepm; 
                   5549:          
                   5550:          p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   5551:          oldm=oldms;savm=savms;
                   5552:          hpxij(p3mat,nhstepm,agedeb,hstepm,p,nlstate,stepm,oldm,savm, k);  
                   5553:        
                   5554:          for (h=0; h<=nhstepm; h++){
                   5555:            if (h==(int) (calagedatem+YEARM*cpt)) {
                   5556:              fprintf(ficrespop,"\n %3.f ",agedeb+h*hstepm/YEARM*stepm);
                   5557:            } 
                   5558:            for(j=1; j<=nlstate+ndeath;j++) {
                   5559:              kk1=0.;kk2=0;
                   5560:              for(i=1; i<=nlstate;i++) {              
                   5561:                if (mobilav==1) 
                   5562:                  kk1=kk1+p3mat[i][j][h]*mobaverage[(int)agedeb+1][i][cptcod];
                   5563:                else {
                   5564:                  kk1=kk1+p3mat[i][j][h]*probs[(int)(agedeb+1)][i][cptcod];
                   5565:                }
                   5566:              }
                   5567:              if (h==(int)(calagedatem+12*cpt)){
                   5568:                tabpop[(int)(agedeb)][j][cptcod]=kk1;
                   5569:                  /*fprintf(ficrespop," %.3f", kk1);
                   5570:                    if (popforecast==1) fprintf(ficrespop," [%.f]", kk1*popeffectif[(int)agedeb+1]);*/
                   5571:              }
                   5572:            }
                   5573:            for(i=1; i<=nlstate;i++){
                   5574:              kk1=0.;
                   5575:                for(j=1; j<=nlstate;j++){
                   5576:                  kk1= kk1+tabpop[(int)(agedeb)][j][cptcod]; 
                   5577:                }
                   5578:                  tabpopprev[(int)(agedeb)][i][cptcod]=tabpop[(int)(agedeb)][i][cptcod]/kk1*popeffectif[(int)(agedeb+(calagedatem+12*cpt)*hstepm/YEARM*stepm-1)];
                   5579:            }
                   5580: 
                   5581:            if (h==(int)(calagedatem+12*cpt)) for(j=1; j<=nlstate;j++) 
                   5582:              fprintf(ficrespop," %15.2f",tabpopprev[(int)(agedeb+1)][j][cptcod]);
                   5583:          }
                   5584:          free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   5585:        }
                   5586:       }
                   5587:  
                   5588:   /******/
                   5589: 
                   5590:       for (cpt=1; cpt<=(anpyram1-anpyram);cpt++) { 
                   5591:        fprintf(ficrespop,"\n\n# Forecasting at date %.lf/%.lf/%.lf ",jpyram,mpyram,anpyram+cpt);   
                   5592:        for (agedeb=(fage-((int)calagedatem %12/12.)); agedeb>=(ageminpar-((int)calagedatem %12)/12.); agedeb--){ 
                   5593:          nhstepm=(int) rint((agelim-agedeb)*YEARM/stepm); 
                   5594:          nhstepm = nhstepm/hstepm; 
                   5595:          
                   5596:          p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   5597:          oldm=oldms;savm=savms;
                   5598:          hpxij(p3mat,nhstepm,agedeb,hstepm,p,nlstate,stepm,oldm,savm, k);  
                   5599:          for (h=0; h<=nhstepm; h++){
                   5600:            if (h==(int) (calagedatem+YEARM*cpt)) {
                   5601:              fprintf(ficresf,"\n %3.f ",agedeb+h*hstepm/YEARM*stepm);
                   5602:            } 
                   5603:            for(j=1; j<=nlstate+ndeath;j++) {
                   5604:              kk1=0.;kk2=0;
                   5605:              for(i=1; i<=nlstate;i++) {              
                   5606:                kk1=kk1+p3mat[i][j][h]*tabpopprev[(int)agedeb+1][i][cptcod];    
                   5607:              }
                   5608:              if (h==(int)(calagedatem+12*cpt)) fprintf(ficresf," %15.2f", kk1);        
                   5609:            }
                   5610:          }
                   5611:          free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   5612:        }
                   5613:       }
                   5614:    } 
                   5615:   }
                   5616:  
                   5617:   if (mobilav!=0) free_ma3x(mobaverage,1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
                   5618: 
                   5619:   if (popforecast==1) {
                   5620:     free_ivector(popage,0,AGESUP);
                   5621:     free_vector(popeffectif,0,AGESUP);
                   5622:     free_vector(popcount,0,AGESUP);
                   5623:   }
                   5624:   free_ma3x(tabpop,1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
                   5625:   free_ma3x(tabpopprev,1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
                   5626:   fclose(ficrespop);
                   5627: } /* End of popforecast */
                   5628: 
                   5629: int fileappend(FILE *fichier, char *optionfich)
                   5630: {
                   5631:   if((fichier=fopen(optionfich,"a"))==NULL) {
                   5632:     printf("Problem with file: %s\n", optionfich);
                   5633:     fprintf(ficlog,"Problem with file: %s\n", optionfich);
                   5634:     return (0);
                   5635:   }
                   5636:   fflush(fichier);
                   5637:   return (1);
                   5638: }
                   5639: 
                   5640: 
                   5641: /**************** function prwizard **********************/
                   5642: void prwizard(int ncovmodel, int nlstate, int ndeath,  char model[], FILE *ficparo)
                   5643: {
                   5644: 
                   5645:   /* Wizard to print covariance matrix template */
                   5646: 
1.164     brouard  5647:   char ca[32], cb[32];
                   5648:   int i,j, k, li, lj, lk, ll, jj, npar, itimes;
1.126     brouard  5649:   int numlinepar;
                   5650: 
                   5651:   printf("# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
                   5652:   fprintf(ficparo,"# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
                   5653:   for(i=1; i <=nlstate; i++){
                   5654:     jj=0;
                   5655:     for(j=1; j <=nlstate+ndeath; j++){
                   5656:       if(j==i) continue;
                   5657:       jj++;
                   5658:       /*ca[0]= k+'a'-1;ca[1]='\0';*/
                   5659:       printf("%1d%1d",i,j);
                   5660:       fprintf(ficparo,"%1d%1d",i,j);
                   5661:       for(k=1; k<=ncovmodel;k++){
                   5662:        /*        printf(" %lf",param[i][j][k]); */
                   5663:        /*        fprintf(ficparo," %lf",param[i][j][k]); */
                   5664:        printf(" 0.");
                   5665:        fprintf(ficparo," 0.");
                   5666:       }
                   5667:       printf("\n");
                   5668:       fprintf(ficparo,"\n");
                   5669:     }
                   5670:   }
                   5671:   printf("# Scales (for hessian or gradient estimation)\n");
                   5672:   fprintf(ficparo,"# Scales (for hessian or gradient estimation)\n");
                   5673:   npar= (nlstate+ndeath-1)*nlstate*ncovmodel; /* Number of parameters*/ 
                   5674:   for(i=1; i <=nlstate; i++){
                   5675:     jj=0;
                   5676:     for(j=1; j <=nlstate+ndeath; j++){
                   5677:       if(j==i) continue;
                   5678:       jj++;
                   5679:       fprintf(ficparo,"%1d%1d",i,j);
                   5680:       printf("%1d%1d",i,j);
                   5681:       fflush(stdout);
                   5682:       for(k=1; k<=ncovmodel;k++){
                   5683:        /*      printf(" %le",delti3[i][j][k]); */
                   5684:        /*      fprintf(ficparo," %le",delti3[i][j][k]); */
                   5685:        printf(" 0.");
                   5686:        fprintf(ficparo," 0.");
                   5687:       }
                   5688:       numlinepar++;
                   5689:       printf("\n");
                   5690:       fprintf(ficparo,"\n");
                   5691:     }
                   5692:   }
                   5693:   printf("# Covariance matrix\n");
                   5694: /* # 121 Var(a12)\n\ */
                   5695: /* # 122 Cov(b12,a12) Var(b12)\n\ */
                   5696: /* # 131 Cov(a13,a12) Cov(a13,b12, Var(a13)\n\ */
                   5697: /* # 132 Cov(b13,a12) Cov(b13,b12, Cov(b13,a13) Var(b13)\n\ */
                   5698: /* # 212 Cov(a21,a12) Cov(a21,b12, Cov(a21,a13) Cov(a21,b13) Var(a21)\n\ */
                   5699: /* # 212 Cov(b21,a12) Cov(b21,b12, Cov(b21,a13) Cov(b21,b13) Cov(b21,a21) Var(b21)\n\ */
                   5700: /* # 232 Cov(a23,a12) Cov(a23,b12, Cov(a23,a13) Cov(a23,b13) Cov(a23,a21) Cov(a23,b21) Var(a23)\n\ */
                   5701: /* # 232 Cov(b23,a12) Cov(b23,b12) ... Var (b23)\n" */
                   5702:   fflush(stdout);
                   5703:   fprintf(ficparo,"# Covariance matrix\n");
                   5704:   /* # 121 Var(a12)\n\ */
                   5705:   /* # 122 Cov(b12,a12) Var(b12)\n\ */
                   5706:   /* #   ...\n\ */
                   5707:   /* # 232 Cov(b23,a12)  Cov(b23,b12) ... Var (b23)\n" */
                   5708:   
                   5709:   for(itimes=1;itimes<=2;itimes++){
                   5710:     jj=0;
                   5711:     for(i=1; i <=nlstate; i++){
                   5712:       for(j=1; j <=nlstate+ndeath; j++){
                   5713:        if(j==i) continue;
                   5714:        for(k=1; k<=ncovmodel;k++){
                   5715:          jj++;
                   5716:          ca[0]= k+'a'-1;ca[1]='\0';
                   5717:          if(itimes==1){
                   5718:            printf("#%1d%1d%d",i,j,k);
                   5719:            fprintf(ficparo,"#%1d%1d%d",i,j,k);
                   5720:          }else{
                   5721:            printf("%1d%1d%d",i,j,k);
                   5722:            fprintf(ficparo,"%1d%1d%d",i,j,k);
                   5723:            /*  printf(" %.5le",matcov[i][j]); */
                   5724:          }
                   5725:          ll=0;
                   5726:          for(li=1;li <=nlstate; li++){
                   5727:            for(lj=1;lj <=nlstate+ndeath; lj++){
                   5728:              if(lj==li) continue;
                   5729:              for(lk=1;lk<=ncovmodel;lk++){
                   5730:                ll++;
                   5731:                if(ll<=jj){
                   5732:                  cb[0]= lk +'a'-1;cb[1]='\0';
                   5733:                  if(ll<jj){
                   5734:                    if(itimes==1){
                   5735:                      printf(" Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
                   5736:                      fprintf(ficparo," Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
                   5737:                    }else{
                   5738:                      printf(" 0.");
                   5739:                      fprintf(ficparo," 0.");
                   5740:                    }
                   5741:                  }else{
                   5742:                    if(itimes==1){
                   5743:                      printf(" Var(%s%1d%1d)",ca,i,j);
                   5744:                      fprintf(ficparo," Var(%s%1d%1d)",ca,i,j);
                   5745:                    }else{
                   5746:                      printf(" 0.");
                   5747:                      fprintf(ficparo," 0.");
                   5748:                    }
                   5749:                  }
                   5750:                }
                   5751:              } /* end lk */
                   5752:            } /* end lj */
                   5753:          } /* end li */
                   5754:          printf("\n");
                   5755:          fprintf(ficparo,"\n");
                   5756:          numlinepar++;
                   5757:        } /* end k*/
                   5758:       } /*end j */
                   5759:     } /* end i */
                   5760:   } /* end itimes */
                   5761: 
                   5762: } /* end of prwizard */
                   5763: /******************* Gompertz Likelihood ******************************/
                   5764: double gompertz(double x[])
                   5765: { 
                   5766:   double A,B,L=0.0,sump=0.,num=0.;
                   5767:   int i,n=0; /* n is the size of the sample */
                   5768: 
                   5769:   for (i=0;i<=imx-1 ; i++) {
                   5770:     sump=sump+weight[i];
                   5771:     /*    sump=sump+1;*/
                   5772:     num=num+1;
                   5773:   }
                   5774:  
                   5775:  
                   5776:   /* for (i=0; i<=imx; i++) 
                   5777:      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]);*/
                   5778: 
                   5779:   for (i=1;i<=imx ; i++)
                   5780:     {
                   5781:       if (cens[i] == 1 && wav[i]>1)
                   5782:        A=-x[1]/(x[2])*(exp(x[2]*(agecens[i]-agegomp))-exp(x[2]*(ageexmed[i]-agegomp)));
                   5783:       
                   5784:       if (cens[i] == 0 && wav[i]>1)
                   5785:        A=-x[1]/(x[2])*(exp(x[2]*(agedc[i]-agegomp))-exp(x[2]*(ageexmed[i]-agegomp)))
                   5786:             +log(x[1]/YEARM)+x[2]*(agedc[i]-agegomp)+log(YEARM);  
                   5787:       
                   5788:       /*if (wav[i] > 1 && agecens[i] > 15) {*/ /* ??? */
                   5789:       if (wav[i] > 1 ) { /* ??? */
                   5790:        L=L+A*weight[i];
                   5791:        /*      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]);*/
                   5792:       }
                   5793:     }
                   5794: 
                   5795:  /*printf("x1=%2.9f x2=%2.9f x3=%2.9f L=%f\n",x[1],x[2],x[3],L);*/
                   5796:  
                   5797:   return -2*L*num/sump;
                   5798: }
                   5799: 
1.136     brouard  5800: #ifdef GSL
                   5801: /******************* Gompertz_f Likelihood ******************************/
                   5802: double gompertz_f(const gsl_vector *v, void *params)
                   5803: { 
                   5804:   double A,B,LL=0.0,sump=0.,num=0.;
                   5805:   double *x= (double *) v->data;
                   5806:   int i,n=0; /* n is the size of the sample */
                   5807: 
                   5808:   for (i=0;i<=imx-1 ; i++) {
                   5809:     sump=sump+weight[i];
                   5810:     /*    sump=sump+1;*/
                   5811:     num=num+1;
                   5812:   }
                   5813:  
                   5814:  
                   5815:   /* for (i=0; i<=imx; i++) 
                   5816:      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]);*/
                   5817:   printf("x[0]=%lf x[1]=%lf\n",x[0],x[1]);
                   5818:   for (i=1;i<=imx ; i++)
                   5819:     {
                   5820:       if (cens[i] == 1 && wav[i]>1)
                   5821:        A=-x[0]/(x[1])*(exp(x[1]*(agecens[i]-agegomp))-exp(x[1]*(ageexmed[i]-agegomp)));
                   5822:       
                   5823:       if (cens[i] == 0 && wav[i]>1)
                   5824:        A=-x[0]/(x[1])*(exp(x[1]*(agedc[i]-agegomp))-exp(x[1]*(ageexmed[i]-agegomp)))
                   5825:             +log(x[0]/YEARM)+x[1]*(agedc[i]-agegomp)+log(YEARM);  
                   5826:       
                   5827:       /*if (wav[i] > 1 && agecens[i] > 15) {*/ /* ??? */
                   5828:       if (wav[i] > 1 ) { /* ??? */
                   5829:        LL=LL+A*weight[i];
                   5830:        /*      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]);*/
                   5831:       }
                   5832:     }
                   5833: 
                   5834:  /*printf("x1=%2.9f x2=%2.9f x3=%2.9f L=%f\n",x[1],x[2],x[3],L);*/
                   5835:   printf("x[0]=%lf x[1]=%lf -2*LL*num/sump=%lf\n",x[0],x[1],-2*LL*num/sump);
                   5836:  
                   5837:   return -2*LL*num/sump;
                   5838: }
                   5839: #endif
                   5840: 
1.126     brouard  5841: /******************* Printing html file ***********/
1.201     brouard  5842: void printinghtmlmort(char fileresu[], char title[], char datafile[], int firstpass, \
1.126     brouard  5843:                  int lastpass, int stepm, int weightopt, char model[],\
                   5844:                  int imx,  double p[],double **matcov,double agemortsup){
                   5845:   int i,k;
                   5846: 
                   5847:   fprintf(fichtm,"<ul><li><h4>Result files </h4>\n Force of mortality. Parameters of the Gompertz fit (with confidence interval in brackets):<br>");
                   5848:   fprintf(fichtm,"  mu(age) =%lf*exp(%lf*(age-%d)) per year<br><br>",p[1],p[2],agegomp);
                   5849:   for (i=1;i<=2;i++) 
                   5850:     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  5851:   fprintf(fichtm,"<br><br><img src=\"graphmort.svg\">");
1.126     brouard  5852:   fprintf(fichtm,"</ul>");
                   5853: 
                   5854: fprintf(fichtm,"<ul><li><h4>Life table</h4>\n <br>");
                   5855: 
                   5856:  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>");
                   5857: 
                   5858:  for (k=agegomp;k<(agemortsup-2);k++) 
                   5859:    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]);
                   5860: 
                   5861:  
                   5862:   fflush(fichtm);
                   5863: }
                   5864: 
                   5865: /******************* Gnuplot file **************/
1.201     brouard  5866: void printinggnuplotmort(char fileresu[], char optionfilefiname[], double ageminpar, double agemaxpar, double fage , char pathc[], double p[]){
1.126     brouard  5867: 
                   5868:   char dirfileres[132],optfileres[132];
1.164     brouard  5869: 
1.126     brouard  5870:   int ng;
                   5871: 
                   5872: 
                   5873:   /*#ifdef windows */
                   5874:   fprintf(ficgp,"cd \"%s\" \n",pathc);
                   5875:     /*#endif */
                   5876: 
                   5877: 
                   5878:   strcpy(dirfileres,optionfilefiname);
                   5879:   strcpy(optfileres,"vpl");
1.199     brouard  5880:   fprintf(ficgp,"set out \"graphmort.svg\"\n "); 
1.126     brouard  5881:   fprintf(ficgp,"set xlabel \"Age\"\n set ylabel \"Force of mortality (per year)\" \n "); 
1.199     brouard  5882:   fprintf(ficgp, "set ter svg size 640, 480\n set log y\n"); 
1.145     brouard  5883:   /* fprintf(ficgp, "set size 0.65,0.65\n"); */
1.126     brouard  5884:   fprintf(ficgp,"plot [%d:100] %lf*exp(%lf*(x-%d))",agegomp,p[1],p[2],agegomp);
                   5885: 
                   5886: } 
                   5887: 
1.136     brouard  5888: int readdata(char datafile[], int firstobs, int lastobs, int *imax)
                   5889: {
1.126     brouard  5890: 
1.136     brouard  5891:   /*-------- data file ----------*/
                   5892:   FILE *fic;
                   5893:   char dummy[]="                         ";
1.164     brouard  5894:   int i=0, j=0, n=0;
1.136     brouard  5895:   int linei, month, year,iout;
                   5896:   char line[MAXLINE], linetmp[MAXLINE];
1.164     brouard  5897:   char stra[MAXLINE], strb[MAXLINE];
1.136     brouard  5898:   char *stratrunc;
                   5899:   int lstra;
1.126     brouard  5900: 
                   5901: 
1.136     brouard  5902:   if((fic=fopen(datafile,"r"))==NULL)    {
1.195     brouard  5903:     printf("Problem while opening datafile: %s\n", datafile);fflush(stdout);
                   5904:     fprintf(ficlog,"Problem while opening datafile: %s\n", datafile);fflush(ficlog);return 1;
1.136     brouard  5905:   }
1.126     brouard  5906: 
1.136     brouard  5907:   i=1;
                   5908:   linei=0;
                   5909:   while ((fgets(line, MAXLINE, fic) != NULL) &&((i >= firstobs) && (i <=lastobs))) {
                   5910:     linei=linei+1;
                   5911:     for(j=strlen(line); j>=0;j--){  /* Untabifies line */
                   5912:       if(line[j] == '\t')
                   5913:        line[j] = ' ';
                   5914:     }
                   5915:     for(j=strlen(line)-1; (line[j]==' ')||(line[j]==10)||(line[j]==13);j--){
                   5916:       ;
                   5917:     };
                   5918:     line[j+1]=0;  /* Trims blanks at end of line */
                   5919:     if(line[0]=='#'){
                   5920:       fprintf(ficlog,"Comment line\n%s\n",line);
                   5921:       printf("Comment line\n%s\n",line);
                   5922:       continue;
                   5923:     }
                   5924:     trimbb(linetmp,line); /* Trims multiple blanks in line */
1.164     brouard  5925:     strcpy(line, linetmp);
1.136     brouard  5926:   
1.126     brouard  5927: 
1.136     brouard  5928:     for (j=maxwav;j>=1;j--){
1.137     brouard  5929:       cutv(stra, strb, line, ' '); 
1.136     brouard  5930:       if(strb[0]=='.') { /* Missing status */
                   5931:        lval=-1;
                   5932:       }else{
                   5933:        errno=0;
                   5934:        lval=strtol(strb,&endptr,10); 
                   5935:       /*       if (errno == ERANGE && (lval == LONG_MAX || lval == LONG_MIN))*/
                   5936:        if( strb[0]=='\0' || (*endptr != '\0')){
1.141     brouard  5937:          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);
                   5938:          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  5939:          return 1;
                   5940:        }
                   5941:       }
                   5942:       s[j][i]=lval;
                   5943:       
                   5944:       strcpy(line,stra);
                   5945:       cutv(stra, strb,line,' ');
1.169     brouard  5946:       if( (iout=sscanf(strb,"%d/%d",&month, &year)) != 0){
1.136     brouard  5947:       }
1.169     brouard  5948:       else  if( (iout=sscanf(strb,"%s.",dummy)) != 0){
1.136     brouard  5949:        month=99;
                   5950:        year=9999;
                   5951:       }else{
1.141     brouard  5952:        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);
                   5953:        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  5954:        return 1;
                   5955:       }
                   5956:       anint[j][i]= (double) year; 
                   5957:       mint[j][i]= (double)month; 
                   5958:       strcpy(line,stra);
                   5959:     } /* ENd Waves */
                   5960:     
                   5961:     cutv(stra, strb,line,' '); 
1.169     brouard  5962:     if( (iout=sscanf(strb,"%d/%d",&month, &year)) != 0){
1.136     brouard  5963:     }
1.169     brouard  5964:     else  if( (iout=sscanf(strb,"%s.",dummy)) != 0){
1.136     brouard  5965:       month=99;
                   5966:       year=9999;
                   5967:     }else{
1.141     brouard  5968:       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);
                   5969:        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  5970:        return 1;
                   5971:     }
                   5972:     andc[i]=(double) year; 
                   5973:     moisdc[i]=(double) month; 
                   5974:     strcpy(line,stra);
                   5975:     
                   5976:     cutv(stra, strb,line,' '); 
1.169     brouard  5977:     if( (iout=sscanf(strb,"%d/%d",&month, &year)) != 0){
1.136     brouard  5978:     }
1.169     brouard  5979:     else  if( (iout=sscanf(strb,"%s.", dummy)) != 0){
1.136     brouard  5980:       month=99;
                   5981:       year=9999;
                   5982:     }else{
1.141     brouard  5983:       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);
                   5984:       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  5985:        return 1;
                   5986:     }
                   5987:     if (year==9999) {
1.141     brouard  5988:       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);
                   5989:       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  5990:        return 1;
1.126     brouard  5991: 
1.136     brouard  5992:     }
                   5993:     annais[i]=(double)(year);
                   5994:     moisnais[i]=(double)(month); 
                   5995:     strcpy(line,stra);
                   5996:     
                   5997:     cutv(stra, strb,line,' '); 
                   5998:     errno=0;
                   5999:     dval=strtod(strb,&endptr); 
                   6000:     if( strb[0]=='\0' || (*endptr != '\0')){
1.141     brouard  6001:       printf("Error reading data around '%f' at line number %d, \"%s\" for individual %d\nShould be a weight.  Exiting.\n",dval, i,line,linei);
                   6002:       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  6003:       fflush(ficlog);
                   6004:       return 1;
                   6005:     }
                   6006:     weight[i]=dval; 
                   6007:     strcpy(line,stra);
                   6008:     
                   6009:     for (j=ncovcol;j>=1;j--){
                   6010:       cutv(stra, strb,line,' '); 
                   6011:       if(strb[0]=='.') { /* Missing status */
                   6012:        lval=-1;
                   6013:       }else{
                   6014:        errno=0;
                   6015:        lval=strtol(strb,&endptr,10); 
                   6016:        if( strb[0]=='\0' || (*endptr != '\0')){
1.141     brouard  6017:          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);
                   6018:          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  6019:          return 1;
                   6020:        }
                   6021:       }
                   6022:       if(lval <-1 || lval >1){
1.141     brouard  6023:        printf("Error reading data around '%ld' at line number %d for individual %d, '%s'\n \
1.136     brouard  6024:  Should be a value of %d(nth) covariate (0 should be the value for the reference and 1\n \
                   6025:  for the alternative. IMaCh does not build design variables automatically, do it yourself.\n \
                   6026:  For example, for multinomial values like 1, 2 and 3,\n \
                   6027:  build V1=0 V2=0 for the reference value (1),\n \
                   6028:         V1=1 V2=0 for (2) \n \
                   6029:  and V1=0 V2=1 for (3). V1=1 V2=1 should not exist and the corresponding\n \
                   6030:  output of IMaCh is often meaningless.\n \
                   6031:  Exiting.\n",lval,linei, i,line,j);
1.141     brouard  6032:        fprintf(ficlog,"Error reading data around '%ld' at line number %d for individual %d, '%s'\n \
1.136     brouard  6033:  Should be a value of %d(nth) covariate (0 should be the value for the reference and 1\n \
                   6034:  for the alternative. IMaCh does not build design variables automatically, do it yourself.\n \
                   6035:  For example, for multinomial values like 1, 2 and 3,\n \
                   6036:  build V1=0 V2=0 for the reference value (1),\n \
                   6037:         V1=1 V2=0 for (2) \n \
                   6038:  and V1=0 V2=1 for (3). V1=1 V2=1 should not exist and the corresponding\n \
                   6039:  output of IMaCh is often meaningless.\n \
                   6040:  Exiting.\n",lval,linei, i,line,j);fflush(ficlog);
                   6041:        return 1;
                   6042:       }
                   6043:       covar[j][i]=(double)(lval);
                   6044:       strcpy(line,stra);
                   6045:     }  
                   6046:     lstra=strlen(stra);
                   6047:      
                   6048:     if(lstra > 9){ /* More than 2**32 or max of what printf can write with %ld */
                   6049:       stratrunc = &(stra[lstra-9]);
                   6050:       num[i]=atol(stratrunc);
                   6051:     }
                   6052:     else
                   6053:       num[i]=atol(stra);
                   6054:     /*if((s[2][i]==2) && (s[3][i]==-1)&&(s[4][i]==9)){
                   6055:       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;}*/
                   6056:     
                   6057:     i=i+1;
                   6058:   } /* End loop reading  data */
1.126     brouard  6059: 
1.136     brouard  6060:   *imax=i-1; /* Number of individuals */
                   6061:   fclose(fic);
                   6062:  
                   6063:   return (0);
1.164     brouard  6064:   /* endread: */
1.136     brouard  6065:     printf("Exiting readdata: ");
                   6066:     fclose(fic);
                   6067:     return (1);
1.126     brouard  6068: 
                   6069: 
                   6070: 
1.136     brouard  6071: }
1.145     brouard  6072: void removespace(char *str) {
                   6073:   char *p1 = str, *p2 = str;
                   6074:   do
                   6075:     while (*p2 == ' ')
                   6076:       p2++;
1.169     brouard  6077:   while (*p1++ == *p2++);
1.145     brouard  6078: }
                   6079: 
                   6080: int decodemodel ( char model[], int lastobs) /**< This routine decode the model and returns:
1.187     brouard  6081:    * Model  V1+V2+V3+V8+V7*V8+V5*V6+V8*age+V3*age+age*age
                   6082:    * - nagesqr = 1 if age*age in the model, otherwise 0.
                   6083:    * - cptcovt total number of covariates of the model nbocc(+)+1 = 8 excepting constant and age and age*age
                   6084:    * - cptcovn or number of covariates k of the models excluding age*products =6 and age*age
1.145     brouard  6085:    * - cptcovage number of covariates with age*products =2
                   6086:    * - cptcovs number of simple covariates
                   6087:    * - 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
                   6088:    *     which is a new column after the 9 (ncovcol) variables. 
                   6089:    * - if k is a product Vn*Vm covar[k][i] is filled with correct values for each individual
                   6090:    * - Tprod[l] gives the kth covariates of the product Vn*Vm l=1 to cptcovprod-cptcovage
                   6091:    *    Tprod[1]@2 {5, 6}: position of first product V7*V8 is 5, and second V5*V6 is 6.
                   6092:    * - Tvard[k]  p Tvard[1][1]@4 {7, 8, 5, 6} for V7*V8 and V5*V6 .
                   6093:  */
1.136     brouard  6094: {
1.145     brouard  6095:   int i, j, k, ks;
1.164     brouard  6096:   int  j1, k1, k2;
1.136     brouard  6097:   char modelsav[80];
1.145     brouard  6098:   char stra[80], strb[80], strc[80], strd[80],stre[80];
1.187     brouard  6099:   char *strpt;
1.136     brouard  6100: 
1.145     brouard  6101:   /*removespace(model);*/
1.136     brouard  6102:   if (strlen(model) >1){ /* If there is at least 1 covariate */
1.145     brouard  6103:     j=0, j1=0, k1=0, k2=-1, ks=0, cptcovn=0;
1.137     brouard  6104:     if (strstr(model,"AGE") !=0){
1.192     brouard  6105:       printf("Error. AGE must be in lower case 'age' model=1+age+%s. ",model);
                   6106:       fprintf(ficlog,"Error. AGE must be in lower case model=1+age+%s. ",model);fflush(ficlog);
1.136     brouard  6107:       return 1;
                   6108:     }
1.141     brouard  6109:     if (strstr(model,"v") !=0){
                   6110:       printf("Error. 'v' must be in upper case 'V' model=%s ",model);
                   6111:       fprintf(ficlog,"Error. 'v' must be in upper case model=%s ",model);fflush(ficlog);
                   6112:       return 1;
                   6113:     }
1.187     brouard  6114:     strcpy(modelsav,model); 
                   6115:     if ((strpt=strstr(model,"age*age")) !=0){
                   6116:       printf(" strpt=%s, model=%s\n",strpt, model);
                   6117:       if(strpt != model){
                   6118:       printf("Error in model: 'model=%s'; 'age*age' should in first place before other covariates\n \
1.192     brouard  6119:  'model=1+age+age*age+V1.' or 'model=1+age+age*age+V1+V1*age.', please swap as well as \n \
1.187     brouard  6120:  corresponding column of parameters.\n",model);
                   6121:       fprintf(ficlog,"Error in model: 'model=%s'; 'age*age' should in first place before other covariates\n \
1.192     brouard  6122:  'model=1+age+age*age+V1.' or 'model=1+age+age*age+V1+V1*age.', please swap as well as \n \
1.187     brouard  6123:  corresponding column of parameters.\n",model); fflush(ficlog);
                   6124:       return 1;
                   6125:     }
                   6126: 
                   6127:       nagesqr=1;
                   6128:       if (strstr(model,"+age*age") !=0)
                   6129:        substrchaine(modelsav, model, "+age*age");
                   6130:       else if (strstr(model,"age*age+") !=0)
                   6131:        substrchaine(modelsav, model, "age*age+");
                   6132:       else 
                   6133:        substrchaine(modelsav, model, "age*age");
                   6134:     }else
                   6135:       nagesqr=0;
                   6136:     if (strlen(modelsav) >1){
                   6137:       j=nbocc(modelsav,'+'); /**< j=Number of '+' */
                   6138:       j1=nbocc(modelsav,'*'); /**< j1=Number of '*' */
                   6139:       cptcovs=j+1-j1; /**<  Number of simple covariates V1+V1*age+V3 +V3*V4+age*age=> V1 + V3 =2  */
                   6140:       cptcovt= j+1; /* Number of total covariates in the model, not including
                   6141:                   * cst, age and age*age 
                   6142:                   * V1+V1*age+ V3 + V3*V4+age*age=> 4*/
                   6143:                   /* including age products which are counted in cptcovage.
                   6144:                  * but the covariates which are products must be treated 
                   6145:                  * separately: ncovn=4- 2=2 (V1+V3). */
                   6146:       cptcovprod=j1; /**< Number of products  V1*V2 +v3*age = 2 */
                   6147:       cptcovprodnoage=0; /**< Number of covariate products without age: V3*V4 =1  */
                   6148: 
                   6149:     
                   6150:       /*   Design
                   6151:        *  V1   V2   V3   V4  V5  V6  V7  V8  V9 Weight
                   6152:        *  <          ncovcol=8                >
                   6153:        * Model V2 + V1 + V3*age + V3 + V5*V6 + V7*V8 + V8*age + V8
                   6154:        *   k=  1    2      3       4     5       6      7        8
                   6155:        *  cptcovn number of covariates (not including constant and age ) = # of + plus 1 = 7+1=8
                   6156:        *  covar[k,i], value of kth covariate if not including age for individual i:
                   6157:        *       covar[1][i]= (V2), covar[4][i]=(V3), covar[8][i]=(V8)
                   6158:        *  Tvar[k] # of the kth covariate:  Tvar[1]=2  Tvar[4]=3 Tvar[8]=8
                   6159:        *       if multiplied by age: V3*age Tvar[3=V3*age]=3 (V3) Tvar[7]=8 and 
                   6160:        *  Tage[++cptcovage]=k
                   6161:        *       if products, new covar are created after ncovcol with k1
                   6162:        *  Tvar[k]=ncovcol+k1; # of the kth covariate product:  Tvar[5]=ncovcol+1=10  Tvar[6]=ncovcol+1=11
                   6163:        *  Tprod[k1]=k; Tprod[1]=5 Tprod[2]= 6; gives the position of the k1th product
                   6164:        *  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
                   6165:        *  Tvar[cptcovn+k2]=Tvard[k1][1];Tvar[cptcovn+k2+1]=Tvard[k1][2];
                   6166:        *  Tvar[8+1]=5;Tvar[8+2]=6;Tvar[8+3]=7;Tvar[8+4]=8 inverted
                   6167:        *  V1   V2   V3   V4  V5  V6  V7  V8  V9  V10  V11
                   6168:        *  <          ncovcol=8                >
                   6169:        *       Model V2 + V1 + V3*age + V3 + V5*V6 + V7*V8 + V8*age + V8    d1   d1   d2  d2
                   6170:        *          k=  1    2      3       4     5       6      7        8    9   10   11  12
                   6171:        *     Tvar[k]= 2    1      3       3    10      11      8        8    5    6    7   8
                   6172:        * p Tvar[1]@12={2,   1,     3,      3,   11,     10,     8,       8,   7,   8,   5,  6}
                   6173:        * p Tprod[1]@2={                         6, 5}
                   6174:        *p Tvard[1][1]@4= {7, 8, 5, 6}
                   6175:        * covar[k][i]= V2   V1      ?      V3    V5*V6?   V7*V8?  ?       V8   
                   6176:        *  cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*cov[2];
                   6177:        *How to reorganize?
                   6178:        * Model V1 + V2 + V3 + V8 + V5*V6 + V7*V8 + V3*age + V8*age
                   6179:        * Tvars {2,   1,     3,      3,   11,     10,     8,       8,   7,   8,   5,  6}
                   6180:        *       {2,   1,     4,      8,    5,      6,     3,       7}
                   6181:        * Struct []
                   6182:        */
1.145     brouard  6183: 
1.187     brouard  6184:       /* This loop fills the array Tvar from the string 'model'.*/
                   6185:       /* j is the number of + signs in the model V1+V2+V3 j=2 i=3 to 1 */
                   6186:       /*   modelsav=V2+V1+V4+age*V3 strb=age*V3 stra=V2+V1+V4  */
                   6187:       /*       k=4 (age*V3) Tvar[k=4]= 3 (from V3) Tage[cptcovage=1]=4 */
                   6188:       /*       k=3 V4 Tvar[k=3]= 4 (from V4) */
                   6189:       /*       k=2 V1 Tvar[k=2]= 1 (from V1) */
                   6190:       /*       k=1 Tvar[1]=2 (from V2) */
                   6191:       /*       k=5 Tvar[5] */
                   6192:       /* for (k=1; k<=cptcovn;k++) { */
1.198     brouard  6193:       /*       cov[2+k]=nbcode[Tvar[k]][codtabm(ij,Tvar[k])]; */
1.187     brouard  6194:       /*       } */
1.198     brouard  6195:       /* for (k=1; k<=cptcovage;k++) cov[2+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(ij,Tvar[Tage[k])]]*cov[2]; */
1.187     brouard  6196:       /*
                   6197:        * Treating invertedly V2+V1+V3*age+V2*V4 is as if written V2*V4 +V3*age + V1 + V2 */
                   6198:       for(k=cptcovt; k>=1;k--) /**< Number of covariates */
1.145     brouard  6199:         Tvar[k]=0;
1.187     brouard  6200:       cptcovage=0;
                   6201:       for(k=1; k<=cptcovt;k++){ /* Loop on total covariates of the model */
                   6202:        cutl(stra,strb,modelsav,'+'); /* keeps in strb after the first '+' 
                   6203:                                         modelsav==V2+V1+V4+V3*age strb=V3*age stra=V2+V1+V4 */ 
                   6204:        if (nbocc(modelsav,'+')==0) strcpy(strb,modelsav); /* and analyzes it */
                   6205:        /*      printf("i=%d a=%s b=%s sav=%s\n",i, stra,strb,modelsav);*/
                   6206:        /*scanf("%d",i);*/
                   6207:        if (strchr(strb,'*')) {  /**< Model includes a product V2+V1+V4+V3*age strb=V3*age */
                   6208:          cutl(strc,strd,strb,'*'); /**< strd*strc  Vm*Vn: strb=V3*age(input) strc=age strd=V3 ; V3*V2 strc=V2, strd=V3 */
                   6209:          if (strcmp(strc,"age")==0) { /**< Model includes age: Vn*age */
                   6210:            /* covar is not filled and then is empty */
                   6211:            cptcovprod--;
                   6212:            cutl(stre,strb,strd,'V'); /* strd=V3(input): stre="3" */
                   6213:            Tvar[k]=atoi(stre);  /* V2+V1+V4+V3*age Tvar[4]=3 ; V1+V2*age Tvar[2]=2; V1+V1*age Tvar[2]=1 */
                   6214:            cptcovage++; /* Sums the number of covariates which include age as a product */
                   6215:            Tage[cptcovage]=k;  /* Tvar[4]=3, Tage[1] = 4 or V1+V1*age Tvar[2]=1, Tage[1]=2 */
                   6216:            /*printf("stre=%s ", stre);*/
                   6217:          } else if (strcmp(strd,"age")==0) { /* or age*Vn */
                   6218:            cptcovprod--;
                   6219:            cutl(stre,strb,strc,'V');
                   6220:            Tvar[k]=atoi(stre);
                   6221:            cptcovage++;
                   6222:            Tage[cptcovage]=k;
                   6223:          } else {  /* Age is not in the model product V2+V1+V1*V4+V3*age+V3*V2  strb=V3*V2*/
                   6224:            /* loops on k1=1 (V3*V2) and k1=2 V4*V3 */
                   6225:            cptcovn++;
                   6226:            cptcovprodnoage++;k1++;
                   6227:            cutl(stre,strb,strc,'V'); /* strc= Vn, stre is n; strb=V3*V2 stre=3 strc=*/
                   6228:            Tvar[k]=ncovcol+k1; /* For model-covariate k tells which data-covariate to use but
                   6229:                                   because this model-covariate is a construction we invent a new column
                   6230:                                   ncovcol + k1
                   6231:                                   If already ncovcol=4 and model=V2+V1+V1*V4+age*V3+V3*V2
                   6232:                                   Tvar[3=V1*V4]=4+1 Tvar[5=V3*V2]=4 + 2= 6, etc */
                   6233:            cutl(strc,strb,strd,'V'); /* strd was Vm, strc is m */
                   6234:            Tprod[k1]=k;  /* Tprod[1]=3(=V1*V4) for V2+V1+V1*V4+age*V3+V3*V2  */
                   6235:            Tvard[k1][1] =atoi(strc); /* m 1 for V1*/
                   6236:            Tvard[k1][2] =atoi(stre); /* n 4 for V4*/
                   6237:            k2=k2+2;
                   6238:            Tvar[cptcovt+k2]=Tvard[k1][1]; /* Tvar[(cptcovt=4+k2=1)=5]= 1 (V1) */
                   6239:            Tvar[cptcovt+k2+1]=Tvard[k1][2];  /* Tvar[(cptcovt=4+(k2=1)+1)=6]= 4 (V4) */
                   6240:            for (i=1; i<=lastobs;i++){
                   6241:              /* Computes the new covariate which is a product of
                   6242:                 covar[n][i]* covar[m][i] and stores it at ncovol+k1 May not be defined */
                   6243:              covar[ncovcol+k1][i]=covar[atoi(stre)][i]*covar[atoi(strc)][i];
                   6244:            }
                   6245:          } /* End age is not in the model */
                   6246:        } /* End if model includes a product */
                   6247:        else { /* no more sum */
                   6248:          /*printf("d=%s c=%s b=%s\n", strd,strc,strb);*/
                   6249:          /*  scanf("%d",i);*/
                   6250:          cutl(strd,strc,strb,'V');
                   6251:          ks++; /**< Number of simple covariates */
1.145     brouard  6252:          cptcovn++;
1.187     brouard  6253:          Tvar[k]=atoi(strd);
                   6254:        }
                   6255:        strcpy(modelsav,stra);  /* modelsav=V2+V1+V4 stra=V2+V1+V4 */ 
                   6256:        /*printf("a=%s b=%s sav=%s\n", stra,strb,modelsav);
                   6257:          scanf("%d",i);*/
                   6258:       } /* end of loop + on total covariates */
                   6259:     } /* end if strlen(modelsave == 0) age*age might exist */
                   6260:   } /* end if strlen(model == 0) */
1.136     brouard  6261:   
                   6262:   /*The number n of Vn is stored in Tvar. cptcovage =number of age covariate. Tage gives the position of age. cptcovprod= number of products.
                   6263:     If model=V1+V1*age then Tvar[1]=1 Tvar[2]=1 cptcovage=1 Tage[1]=2 cptcovprod=0*/
                   6264: 
                   6265:   /* printf("tvar1=%d tvar2=%d tvar3=%d cptcovage=%d Tage=%d",Tvar[1],Tvar[2],Tvar[3],cptcovage,Tage[1]);
                   6266:   printf("cptcovprod=%d ", cptcovprod);
                   6267:   fprintf(ficlog,"cptcovprod=%d ", cptcovprod);
                   6268: 
                   6269:   scanf("%d ",i);*/
                   6270: 
                   6271: 
1.137     brouard  6272:   return (0); /* with covar[new additional covariate if product] and Tage if age */ 
1.164     brouard  6273:   /*endread:*/
1.136     brouard  6274:     printf("Exiting decodemodel: ");
                   6275:     return (1);
                   6276: }
                   6277: 
1.169     brouard  6278: int calandcheckages(int imx, int maxwav, double *agemin, double *agemax, int *nberr, int *nbwarn )
1.136     brouard  6279: {
                   6280:   int i, m;
                   6281: 
                   6282:   for (i=1; i<=imx; i++) {
                   6283:     for(m=2; (m<= maxwav); m++) {
                   6284:       if (((int)mint[m][i]== 99) && (s[m][i] <= nlstate)){
                   6285:        anint[m][i]=9999;
                   6286:        s[m][i]=-1;
                   6287:       }
                   6288:       if((int)moisdc[i]==99 && (int)andc[i]==9999 && s[m][i]>nlstate){
1.169     brouard  6289:        *nberr = *nberr + 1;
                   6290:        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);
                   6291:        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  6292:        s[m][i]=-1;
                   6293:       }
                   6294:       if((int)moisdc[i]==99 && (int)andc[i]!=9999 && s[m][i]>nlstate){
1.169     brouard  6295:        (*nberr)++;
1.136     brouard  6296:        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]); 
                   6297:        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]); 
                   6298:        s[m][i]=-1; /* We prefer to skip it (and to skip it in version 0.8a1 too */
                   6299:       }
                   6300:     }
                   6301:   }
                   6302: 
                   6303:   for (i=1; i<=imx; i++)  {
                   6304:     agedc[i]=(moisdc[i]/12.+andc[i])-(moisnais[i]/12.+annais[i]);
                   6305:     for(m=firstpass; (m<= lastpass); m++){
                   6306:       if(s[m][i] >0 || s[m][i]==-2 || s[m][i]==-4 || s[m][i]==-5){
                   6307:        if (s[m][i] >= nlstate+1) {
1.169     brouard  6308:          if(agedc[i]>0){
                   6309:            if((int)moisdc[i]!=99 && (int)andc[i]!=9999){
1.136     brouard  6310:              agev[m][i]=agedc[i];
                   6311:          /*if(moisdc[i]==99 && andc[i]==9999) s[m][i]=-1;*/
1.169     brouard  6312:            }else {
1.136     brouard  6313:              if ((int)andc[i]!=9999){
                   6314:                nbwarn++;
                   6315:                printf("Warning negative age at death: %ld line:%d\n",num[i],i);
                   6316:                fprintf(ficlog,"Warning negative age at death: %ld line:%d\n",num[i],i);
                   6317:                agev[m][i]=-1;
                   6318:              }
                   6319:            }
1.169     brouard  6320:          } /* agedc > 0 */
1.136     brouard  6321:        }
                   6322:        else if(s[m][i] !=9){ /* Standard case, age in fractional
                   6323:                                 years but with the precision of a month */
                   6324:          agev[m][i]=(mint[m][i]/12.+1./24.+anint[m][i])-(moisnais[i]/12.+1./24.+annais[i]);
                   6325:          if((int)mint[m][i]==99 || (int)anint[m][i]==9999)
                   6326:            agev[m][i]=1;
                   6327:          else if(agev[m][i] < *agemin){ 
                   6328:            *agemin=agev[m][i];
                   6329:            printf(" Min anint[%d][%d]=%.2f annais[%d]=%.2f, agemin=%.2f\n",m,i,anint[m][i], i,annais[i], *agemin);
                   6330:          }
                   6331:          else if(agev[m][i] >*agemax){
                   6332:            *agemax=agev[m][i];
1.156     brouard  6333:            /* printf(" Max anint[%d][%d]=%.0f annais[%d]=%.0f, agemax=%.2f\n",m,i,anint[m][i], i,annais[i], *agemax);*/
1.136     brouard  6334:          }
                   6335:          /*agev[m][i]=anint[m][i]-annais[i];*/
                   6336:          /*     agev[m][i] = age[i]+2*m;*/
                   6337:        }
                   6338:        else { /* =9 */
                   6339:          agev[m][i]=1;
                   6340:          s[m][i]=-1;
                   6341:        }
                   6342:       }
                   6343:       else /*= 0 Unknown */
                   6344:        agev[m][i]=1;
                   6345:     }
                   6346:     
                   6347:   }
                   6348:   for (i=1; i<=imx; i++)  {
                   6349:     for(m=firstpass; (m<=lastpass); m++){
                   6350:       if (s[m][i] > (nlstate+ndeath)) {
1.169     brouard  6351:        (*nberr)++;
1.136     brouard  6352:        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);     
                   6353:        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);     
                   6354:        return 1;
                   6355:       }
                   6356:     }
                   6357:   }
                   6358: 
                   6359:   /*for (i=1; i<=imx; i++){
                   6360:   for (m=firstpass; (m<lastpass); m++){
                   6361:      printf("%ld %d %.lf %d %d\n", num[i],(covar[1][i]),agev[m][i],s[m][i],s[m+1][i]);
                   6362: }
                   6363: 
                   6364: }*/
                   6365: 
                   6366: 
1.139     brouard  6367:   printf("Total number of individuals= %d, Agemin = %.2f, Agemax= %.2f\n\n", imx, *agemin, *agemax);
                   6368:   fprintf(ficlog,"Total number of individuals= %d, Agemin = %.2f, Agemax= %.2f\n\n", imx, *agemin, *agemax); 
1.136     brouard  6369: 
                   6370:   return (0);
1.164     brouard  6371:  /* endread:*/
1.136     brouard  6372:     printf("Exiting calandcheckages: ");
                   6373:     return (1);
                   6374: }
                   6375: 
1.172     brouard  6376: #if defined(_MSC_VER)
                   6377: /*printf("Visual C++ compiler: %s \n;", _MSC_FULL_VER);*/
                   6378: /*fprintf(ficlog, "Visual C++ compiler: %s \n;", _MSC_FULL_VER);*/
                   6379: //#include "stdafx.h"
                   6380: //#include <stdio.h>
                   6381: //#include <tchar.h>
                   6382: //#include <windows.h>
                   6383: //#include <iostream>
                   6384: typedef BOOL(WINAPI *LPFN_ISWOW64PROCESS) (HANDLE, PBOOL);
                   6385: 
                   6386: LPFN_ISWOW64PROCESS fnIsWow64Process;
                   6387: 
                   6388: BOOL IsWow64()
                   6389: {
                   6390:        BOOL bIsWow64 = FALSE;
                   6391: 
                   6392:        //typedef BOOL (APIENTRY *LPFN_ISWOW64PROCESS)
                   6393:        //  (HANDLE, PBOOL);
                   6394: 
                   6395:        //LPFN_ISWOW64PROCESS fnIsWow64Process;
                   6396: 
                   6397:        HMODULE module = GetModuleHandle(_T("kernel32"));
                   6398:        const char funcName[] = "IsWow64Process";
                   6399:        fnIsWow64Process = (LPFN_ISWOW64PROCESS)
                   6400:                GetProcAddress(module, funcName);
                   6401: 
                   6402:        if (NULL != fnIsWow64Process)
                   6403:        {
                   6404:                if (!fnIsWow64Process(GetCurrentProcess(),
                   6405:                        &bIsWow64))
                   6406:                        //throw std::exception("Unknown error");
                   6407:                        printf("Unknown error\n");
                   6408:        }
                   6409:        return bIsWow64 != FALSE;
                   6410: }
                   6411: #endif
1.177     brouard  6412: 
1.191     brouard  6413: void syscompilerinfo(int logged)
1.167     brouard  6414:  {
                   6415:    /* #include "syscompilerinfo.h"*/
1.185     brouard  6416:    /* command line Intel compiler 32bit windows, XP compatible:*/
                   6417:    /* /GS /W3 /Gy
                   6418:       /Zc:wchar_t /Zi /O2 /Fd"Release\vc120.pdb" /D "WIN32" /D "NDEBUG" /D
                   6419:       "_CONSOLE" /D "_LIB" /D "_USING_V110_SDK71_" /D "_UNICODE" /D
                   6420:       "UNICODE" /Qipo /Zc:forScope /Gd /Oi /MT /Fa"Release\" /EHsc /nologo
1.186     brouard  6421:       /Fo"Release\" /Qprof-dir "Release\" /Fp"Release\IMaCh.pch"
                   6422:    */ 
                   6423:    /* 64 bits */
1.185     brouard  6424:    /*
                   6425:      /GS /W3 /Gy
                   6426:      /Zc:wchar_t /Zi /O2 /Fd"x64\Release\vc120.pdb" /D "WIN32" /D "NDEBUG"
                   6427:      /D "_CONSOLE" /D "_LIB" /D "_UNICODE" /D "UNICODE" /Qipo /Zc:forScope
                   6428:      /Oi /MD /Fa"x64\Release\" /EHsc /nologo /Fo"x64\Release\" /Qprof-dir
                   6429:      "x64\Release\" /Fp"x64\Release\IMaCh.pch" */
                   6430:    /* Optimization are useless and O3 is slower than O2 */
                   6431:    /*
                   6432:      /GS /W3 /Gy /Zc:wchar_t /Zi /O3 /Fd"x64\Release\vc120.pdb" /D "WIN32" 
                   6433:      /D "NDEBUG" /D "_CONSOLE" /D "_LIB" /D "_UNICODE" /D "UNICODE" /Qipo 
                   6434:      /Zc:forScope /Oi /MD /Fa"x64\Release\" /EHsc /nologo /Qparallel 
                   6435:      /Fo"x64\Release\" /Qprof-dir "x64\Release\" /Fp"x64\Release\IMaCh.pch" 
                   6436:    */
1.186     brouard  6437:    /* Link is */ /* /OUT:"visual studio
1.185     brouard  6438:       2013\Projects\IMaCh\Release\IMaCh.exe" /MANIFEST /NXCOMPAT
                   6439:       /PDB:"visual studio
                   6440:       2013\Projects\IMaCh\Release\IMaCh.pdb" /DYNAMICBASE
                   6441:       "kernel32.lib" "user32.lib" "gdi32.lib" "winspool.lib"
                   6442:       "comdlg32.lib" "advapi32.lib" "shell32.lib" "ole32.lib"
                   6443:       "oleaut32.lib" "uuid.lib" "odbc32.lib" "odbccp32.lib"
                   6444:       /MACHINE:X86 /OPT:REF /SAFESEH /INCREMENTAL:NO
                   6445:       /SUBSYSTEM:CONSOLE",5.01" /MANIFESTUAC:"level='asInvoker'
                   6446:       uiAccess='false'"
                   6447:       /ManifestFile:"Release\IMaCh.exe.intermediate.manifest" /OPT:ICF
                   6448:       /NOLOGO /TLBID:1
                   6449:    */
1.177     brouard  6450: #if defined __INTEL_COMPILER
1.178     brouard  6451: #if defined(__GNUC__)
                   6452:        struct utsname sysInfo;  /* For Intel on Linux and OS/X */
                   6453: #endif
1.177     brouard  6454: #elif defined(__GNUC__) 
1.179     brouard  6455: #ifndef  __APPLE__
1.174     brouard  6456: #include <gnu/libc-version.h>  /* Only on gnu */
1.179     brouard  6457: #endif
1.177     brouard  6458:    struct utsname sysInfo;
1.178     brouard  6459:    int cross = CROSS;
                   6460:    if (cross){
                   6461:           printf("Cross-");
1.191     brouard  6462:           if(logged) fprintf(ficlog, "Cross-");
1.178     brouard  6463:    }
1.174     brouard  6464: #endif
                   6465: 
1.171     brouard  6466: #include <stdint.h>
1.178     brouard  6467: 
1.191     brouard  6468:    printf("Compiled with:");if(logged)fprintf(ficlog,"Compiled with:");
1.169     brouard  6469: #if defined(__clang__)
1.191     brouard  6470:    printf(" Clang/LLVM");if(logged)fprintf(ficlog," Clang/LLVM");      /* Clang/LLVM. ---------------------------------------------- */
1.169     brouard  6471: #endif
                   6472: #if defined(__ICC) || defined(__INTEL_COMPILER)
1.191     brouard  6473:    printf(" Intel ICC/ICPC");if(logged)fprintf(ficlog," Intel ICC/ICPC");/* Intel ICC/ICPC. ------------------------------------------ */
1.169     brouard  6474: #endif
                   6475: #if defined(__GNUC__) || defined(__GNUG__)
1.191     brouard  6476:    printf(" GNU GCC/G++");if(logged)fprintf(ficlog," GNU GCC/G++");/* GNU GCC/G++. --------------------------------------------- */
1.169     brouard  6477: #endif
                   6478: #if defined(__HP_cc) || defined(__HP_aCC)
1.191     brouard  6479:    printf(" Hewlett-Packard C/aC++");if(logged)fprintf(fcilog," Hewlett-Packard C/aC++"); /* Hewlett-Packard C/aC++. ---------------------------------- */
1.169     brouard  6480: #endif
                   6481: #if defined(__IBMC__) || defined(__IBMCPP__)
1.191     brouard  6482:    printf(" IBM XL C/C++"); if(logged) fprintf(ficlog," IBM XL C/C++");/* IBM XL C/C++. -------------------------------------------- */
1.169     brouard  6483: #endif
                   6484: #if defined(_MSC_VER)
1.191     brouard  6485:    printf(" Microsoft Visual Studio");if(logged)fprintf(ficlog," Microsoft Visual Studio");/* Microsoft Visual Studio. --------------------------------- */
1.169     brouard  6486: #endif
                   6487: #if defined(__PGI)
1.191     brouard  6488:    printf(" Portland Group PGCC/PGCPP");if(logged) fprintf(ficlog," Portland Group PGCC/PGCPP");/* Portland Group PGCC/PGCPP. ------------------------------- */
1.169     brouard  6489: #endif
                   6490: #if defined(__SUNPRO_C) || defined(__SUNPRO_CC)
1.191     brouard  6491:    printf(" Oracle Solaris Studio");if(logged)fprintf(ficlog," Oracle Solaris Studio\n");/* Oracle Solaris Studio. ----------------------------------- */
1.167     brouard  6492: #endif
1.191     brouard  6493:    printf(" for "); if (logged) fprintf(ficlog, " for ");
1.169     brouard  6494:    
1.167     brouard  6495: // http://stackoverflow.com/questions/4605842/how-to-identify-platform-compiler-from-preprocessor-macros
                   6496: #ifdef _WIN32 // note the underscore: without it, it's not msdn official!
                   6497:     // Windows (x64 and x86)
1.191     brouard  6498:    printf("Windows (x64 and x86) ");if(logged) fprintf(ficlog,"Windows (x64 and x86) ");
1.167     brouard  6499: #elif __unix__ // all unices, not all compilers
                   6500:     // Unix
1.191     brouard  6501:    printf("Unix ");if(logged) fprintf(ficlog,"Unix ");
1.167     brouard  6502: #elif __linux__
                   6503:     // linux
1.191     brouard  6504:    printf("linux ");if(logged) fprintf(ficlog,"linux ");
1.167     brouard  6505: #elif __APPLE__
1.174     brouard  6506:     // Mac OS, not sure if this is covered by __posix__ and/or __unix__ though..
1.191     brouard  6507:    printf("Mac OS ");if(logged) fprintf(ficlog,"Mac OS ");
1.167     brouard  6508: #endif
                   6509: 
                   6510: /*  __MINGW32__          */
                   6511: /*  __CYGWIN__  */
                   6512: /* __MINGW64__  */
                   6513: // http://msdn.microsoft.com/en-us/library/b0084kay.aspx
                   6514: /* _MSC_VER  //the Visual C++ compiler is 17.00.51106.1, the _MSC_VER macro evaluates to 1700. Type cl /?  */
                   6515: /* _MSC_FULL_VER //the Visual C++ compiler is 15.00.20706.01, the _MSC_FULL_VER macro evaluates to 150020706 */
                   6516: /* _WIN64  // Defined for applications for Win64. */
                   6517: /* _M_X64 // Defined for compilations that target x64 processors. */
                   6518: /* _DEBUG // Defined when you compile with /LDd, /MDd, and /MTd. */
1.171     brouard  6519: 
1.167     brouard  6520: #if UINTPTR_MAX == 0xffffffff
1.191     brouard  6521:    printf(" 32-bit"); if(logged) fprintf(ficlog," 32-bit");/* 32-bit */
1.167     brouard  6522: #elif UINTPTR_MAX == 0xffffffffffffffff
1.191     brouard  6523:    printf(" 64-bit"); if(logged) fprintf(ficlog," 64-bit");/* 64-bit */
1.167     brouard  6524: #else
1.191     brouard  6525:    printf(" wtf-bit"); if(logged) fprintf(ficlog," wtf-bit");/* wtf */
1.167     brouard  6526: #endif
                   6527: 
1.169     brouard  6528: #if defined(__GNUC__)
                   6529: # if defined(__GNUC_PATCHLEVEL__)
                   6530: #  define __GNUC_VERSION__ (__GNUC__ * 10000 \
                   6531:                             + __GNUC_MINOR__ * 100 \
                   6532:                             + __GNUC_PATCHLEVEL__)
                   6533: # else
                   6534: #  define __GNUC_VERSION__ (__GNUC__ * 10000 \
                   6535:                             + __GNUC_MINOR__ * 100)
                   6536: # endif
1.174     brouard  6537:    printf(" using GNU C version %d.\n", __GNUC_VERSION__);
1.191     brouard  6538:    if(logged) fprintf(ficlog, " using GNU C version %d.\n", __GNUC_VERSION__);
1.176     brouard  6539: 
                   6540:    if (uname(&sysInfo) != -1) {
                   6541:      printf("Running on: %s %s %s %s %s\n",sysInfo.sysname, sysInfo.nodename, sysInfo.release, sysInfo.version, sysInfo.machine);
1.191     brouard  6542:         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  6543:    }
                   6544:    else
                   6545:       perror("uname() error");
1.179     brouard  6546:    //#ifndef __INTEL_COMPILER 
                   6547: #if !defined (__INTEL_COMPILER) && !defined(__APPLE__)
1.174     brouard  6548:    printf("GNU libc version: %s\n", gnu_get_libc_version()); 
1.191     brouard  6549:    if(logged) fprintf(ficlog,"GNU libc version: %s\n", gnu_get_libc_version());
1.177     brouard  6550: #endif
1.169     brouard  6551: #endif
1.172     brouard  6552: 
                   6553:    //   void main()
                   6554:    //   {
1.169     brouard  6555: #if defined(_MSC_VER)
1.174     brouard  6556:    if (IsWow64()){
1.191     brouard  6557:           printf("\nThe program (probably compiled for 32bit) is running under WOW64 (64bit) emulation.\n");
                   6558:           if (logged) fprintf(ficlog, "\nThe program (probably compiled for 32bit) is running under WOW64 (64bit) emulation.\n");
1.174     brouard  6559:    }
                   6560:    else{
1.191     brouard  6561:           printf("\nThe program is not running under WOW64 (i.e probably on a 64bit Windows).\n");
                   6562:           if (logged) fprintf(ficlog, "\nThe programm is not running under WOW64 (i.e probably on a 64bit Windows).\n");
1.174     brouard  6563:    }
1.172     brouard  6564:    //     printf("\nPress Enter to continue...");
                   6565:    //     getchar();
                   6566:    //   }
                   6567: 
1.169     brouard  6568: #endif
                   6569:    
1.167     brouard  6570: 
                   6571:  }
1.136     brouard  6572: 
1.209   ! brouard  6573:  int prevalence_limit(double *p, double **prlim, double ageminpar, double agemaxpar, double ftolpl, int *ncvyearp){
1.180     brouard  6574:   /*--------------- Prevalence limit  (period or stable prevalence) --------------*/
                   6575:   int i, j, k, i1 ;
1.202     brouard  6576:   /* double ftolpl = 1.e-10; */
1.180     brouard  6577:   double age, agebase, agelim;
1.203     brouard  6578:   double tot;
1.180     brouard  6579: 
1.202     brouard  6580:   strcpy(filerespl,"PL_");
                   6581:   strcat(filerespl,fileresu);
                   6582:   if((ficrespl=fopen(filerespl,"w"))==NULL) {
                   6583:     printf("Problem with period (stable) prevalence resultfile: %s\n", filerespl);return 1;
                   6584:     fprintf(ficlog,"Problem with period (stable) prevalence resultfile: %s\n", filerespl);return 1;
                   6585:   }
                   6586:   printf("Computing period (stable) prevalence: result on file '%s' \n", filerespl);
                   6587:   fprintf(ficlog,"Computing period (stable) prevalence: result on file '%s' \n", filerespl);
                   6588:   pstamp(ficrespl);
1.203     brouard  6589:   fprintf(ficrespl,"# Period (stable) prevalence. Precision given by ftolpl=%g \n", ftolpl);
1.202     brouard  6590:   fprintf(ficrespl,"#Age ");
                   6591:   for(i=1; i<=nlstate;i++) fprintf(ficrespl,"%d-%d ",i,i);
                   6592:   fprintf(ficrespl,"\n");
1.180     brouard  6593:   
                   6594:     /* prlim=matrix(1,nlstate,1,nlstate);*/ /* back in main */
                   6595: 
                   6596:     agebase=ageminpar;
                   6597:     agelim=agemaxpar;
                   6598: 
                   6599:     i1=pow(2,cptcoveff);
                   6600:     if (cptcovn < 1){i1=1;}
                   6601: 
                   6602:     for(cptcov=1,k=0;cptcov<=i1;cptcov++){
                   6603:     /* for(cptcov=1,k=0;cptcov<=1;cptcov++){ */
                   6604:       //for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){
                   6605:        k=k+1;
                   6606:        /* to clean */
1.198     brouard  6607:        //printf("cptcov=%d cptcod=%d codtab=%d\n",cptcov, cptcod,codtabm(cptcod,cptcov));
1.200     brouard  6608:        fprintf(ficrespl,"#******");
                   6609:        printf("#******");
                   6610:        fprintf(ficlog,"#******");
1.180     brouard  6611:        for(j=1;j<=cptcoveff;j++) {
1.198     brouard  6612:          fprintf(ficrespl," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
                   6613:          printf(" V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
                   6614:          fprintf(ficlog," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
1.180     brouard  6615:        }
                   6616:        fprintf(ficrespl,"******\n");
                   6617:        printf("******\n");
                   6618:        fprintf(ficlog,"******\n");
                   6619: 
                   6620:        fprintf(ficrespl,"#Age ");
                   6621:        for(j=1;j<=cptcoveff;j++) {
1.200     brouard  6622:          fprintf(ficrespl,"V%d %d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
1.180     brouard  6623:        }
1.203     brouard  6624:        for(i=1; i<=nlstate;i++) fprintf(ficrespl,"  %d-%d   ",i,i);
                   6625:        fprintf(ficrespl,"Total Years_to_converge\n");
1.180     brouard  6626:        
                   6627:        for (age=agebase; age<=agelim; age++){
                   6628:        /* for (age=agebase; age<=agebase; age++){ */
1.209   ! brouard  6629:          prevalim(prlim, nlstate, p, age, oldm, savm, ftolpl, ncvyearp, k);
1.180     brouard  6630:          fprintf(ficrespl,"%.0f ",age );
                   6631:          for(j=1;j<=cptcoveff;j++)
1.198     brouard  6632:            fprintf(ficrespl,"%d %d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
1.203     brouard  6633:          tot=0.;
                   6634:          for(i=1; i<=nlstate;i++){
                   6635:            tot +=  prlim[i][i];
1.180     brouard  6636:            fprintf(ficrespl," %.5f", prlim[i][i]);
1.203     brouard  6637:          }
1.209   ! brouard  6638:          fprintf(ficrespl," %.3f %d\n", tot, *ncvyearp);
1.180     brouard  6639:        } /* Age */
                   6640:        /* was end of cptcod */
                   6641:     } /* cptcov */
1.184     brouard  6642:        return 0;
1.180     brouard  6643: }
                   6644: 
                   6645: int hPijx(double *p, int bage, int fage){
                   6646:     /*------------- h Pij x at various ages ------------*/
                   6647: 
                   6648:   int stepsize;
                   6649:   int agelim;
                   6650:   int hstepm;
                   6651:   int nhstepm;
                   6652:   int h, i, i1, j, k;
                   6653: 
                   6654:   double agedeb;
                   6655:   double ***p3mat;
                   6656: 
1.201     brouard  6657:     strcpy(filerespij,"PIJ_");  strcat(filerespij,fileresu);
1.180     brouard  6658:     if((ficrespij=fopen(filerespij,"w"))==NULL) {
                   6659:       printf("Problem with Pij resultfile: %s\n", filerespij); return 1;
                   6660:       fprintf(ficlog,"Problem with Pij resultfile: %s\n", filerespij); return 1;
                   6661:     }
                   6662:     printf("Computing pij: result on file '%s' \n", filerespij);
                   6663:     fprintf(ficlog,"Computing pij: result on file '%s' \n", filerespij);
                   6664:   
                   6665:     stepsize=(int) (stepm+YEARM-1)/YEARM;
                   6666:     /*if (stepm<=24) stepsize=2;*/
                   6667: 
                   6668:     agelim=AGESUP;
                   6669:     hstepm=stepsize*YEARM; /* Every year of age */
                   6670:     hstepm=hstepm/stepm; /* Typically 2 years, = 2/6 months = 4 */ 
                   6671: 
                   6672:     /* hstepm=1;   aff par mois*/
                   6673:     pstamp(ficrespij);
                   6674:     fprintf(ficrespij,"#****** h Pij x Probability to be in state j at age x+h being in i at x ");
                   6675:     i1= pow(2,cptcoveff);
1.183     brouard  6676:    /* for(cptcov=1,k=0;cptcov<=i1;cptcov++){ */
                   6677:    /*    /\*for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){*\/ */
                   6678:    /*          k=k+1;  */
                   6679:     for (k=1; k <= (int) pow(2,cptcoveff); k++){
                   6680:       fprintf(ficrespij,"\n#****** ");
                   6681:       for(j=1;j<=cptcoveff;j++) 
1.198     brouard  6682:        fprintf(ficrespij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
1.183     brouard  6683:       fprintf(ficrespij,"******\n");
                   6684:       
                   6685:       for (agedeb=fage; agedeb>=bage; agedeb--){ /* If stepm=6 months */
                   6686:        nhstepm=(int) rint((agelim-agedeb)*YEARM/stepm); /* Typically 20 years = 20*12/6=40 */ 
                   6687:        nhstepm = nhstepm/hstepm; /* Typically 40/4=10 */
                   6688:        
                   6689:        /*        nhstepm=nhstepm*YEARM; aff par mois*/
1.180     brouard  6690:        
1.183     brouard  6691:        p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   6692:        oldm=oldms;savm=savms;
                   6693:        hpxij(p3mat,nhstepm,agedeb,hstepm,p,nlstate,stepm,oldm,savm, k);  
                   6694:        fprintf(ficrespij,"# Cov Agex agex+h hpijx with i,j=");
                   6695:        for(i=1; i<=nlstate;i++)
                   6696:          for(j=1; j<=nlstate+ndeath;j++)
                   6697:            fprintf(ficrespij," %1d-%1d",i,j);
                   6698:        fprintf(ficrespij,"\n");
                   6699:        for (h=0; h<=nhstepm; h++){
                   6700:          /*agedebphstep = agedeb + h*hstepm/YEARM*stepm;*/
                   6701:          fprintf(ficrespij,"%d %3.f %3.f",k, agedeb, agedeb + h*hstepm/YEARM*stepm );
1.180     brouard  6702:          for(i=1; i<=nlstate;i++)
                   6703:            for(j=1; j<=nlstate+ndeath;j++)
1.183     brouard  6704:              fprintf(ficrespij," %.5f", p3mat[i][j][h]);
1.180     brouard  6705:          fprintf(ficrespij,"\n");
                   6706:        }
1.183     brouard  6707:        free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   6708:        fprintf(ficrespij,"\n");
                   6709:       }
1.180     brouard  6710:       /*}*/
                   6711:     }
1.184     brouard  6712:        return 0;
1.180     brouard  6713: }
                   6714: 
                   6715: 
1.136     brouard  6716: /***********************************************/
                   6717: /**************** Main Program *****************/
                   6718: /***********************************************/
                   6719: 
                   6720: int main(int argc, char *argv[])
                   6721: {
                   6722: #ifdef GSL
                   6723:   const gsl_multimin_fminimizer_type *T;
                   6724:   size_t iteri = 0, it;
                   6725:   int rval = GSL_CONTINUE;
                   6726:   int status = GSL_SUCCESS;
                   6727:   double ssval;
                   6728: #endif
                   6729:   int movingaverage(double ***probs, double bage,double fage, double ***mobaverage, int mobilav);
1.164     brouard  6730:   int i,j, k, n=MAXN,iter=0,m,size=100, cptcod;
1.209   ! brouard  6731:   int ncvyear=0; /* Number of years needed for the period prevalence to converge */
1.164     brouard  6732:   int jj, ll, li, lj, lk;
1.136     brouard  6733:   int numlinepar=0; /* Current linenumber of parameter file */
1.197     brouard  6734:   int num_filled;
1.136     brouard  6735:   int itimes;
                   6736:   int NDIM=2;
                   6737:   int vpopbased=0;
                   6738: 
1.164     brouard  6739:   char ca[32], cb[32];
1.136     brouard  6740:   /*  FILE *fichtm; *//* Html File */
                   6741:   /* FILE *ficgp;*/ /*Gnuplot File */
                   6742:   struct stat info;
1.191     brouard  6743:   double agedeb=0.;
1.194     brouard  6744: 
                   6745:   double ageminpar=AGEOVERFLOW,agemin=AGEOVERFLOW, agemaxpar=-AGEOVERFLOW, agemax=-AGEOVERFLOW;
1.136     brouard  6746: 
1.165     brouard  6747:   double fret;
1.191     brouard  6748:   double dum=0.; /* Dummy variable */
1.136     brouard  6749:   double ***p3mat;
                   6750:   double ***mobaverage;
1.164     brouard  6751: 
                   6752:   char line[MAXLINE];
1.197     brouard  6753:   char path[MAXLINE],pathc[MAXLINE],pathcd[MAXLINE],pathtot[MAXLINE];
                   6754: 
                   6755:   char model[MAXLINE], modeltemp[MAXLINE];
1.136     brouard  6756:   char pathr[MAXLINE], pathimach[MAXLINE]; 
1.164     brouard  6757:   char *tok, *val; /* pathtot */
1.136     brouard  6758:   int firstobs=1, lastobs=10;
1.195     brouard  6759:   int c,  h , cpt, c2;
1.191     brouard  6760:   int jl=0;
                   6761:   int i1, j1, jk, stepsize=0;
1.194     brouard  6762:   int count=0;
                   6763: 
1.164     brouard  6764:   int *tab; 
1.136     brouard  6765:   int mobilavproj=0 , prevfcast=0 ; /* moving average of prev, If prevfcast=1 prevalence projection */
                   6766:   int mobilav=0,popforecast=0;
1.191     brouard  6767:   int hstepm=0, nhstepm=0;
1.136     brouard  6768:   int agemortsup;
                   6769:   float  sumlpop=0.;
                   6770:   double jprev1=1, mprev1=1,anprev1=2000,jprev2=1, mprev2=1,anprev2=2000;
                   6771:   double jpyram=1, mpyram=1,anpyram=2000,jpyram1=1, mpyram1=1,anpyram1=2000;
                   6772: 
1.191     brouard  6773:   double bage=0, fage=110., age, agelim=0., agebase=0.;
1.136     brouard  6774:   double ftolpl=FTOL;
                   6775:   double **prlim;
                   6776:   double ***param; /* Matrix of parameters */
                   6777:   double  *p;
                   6778:   double **matcov; /* Matrix of covariance */
1.203     brouard  6779:   double **hess; /* Hessian matrix */
1.136     brouard  6780:   double ***delti3; /* Scale */
                   6781:   double *delti; /* Scale */
                   6782:   double ***eij, ***vareij;
                   6783:   double **varpl; /* Variances of prevalence limits by age */
                   6784:   double *epj, vepp;
1.164     brouard  6785: 
1.136     brouard  6786:   double dateprev1, dateprev2,jproj1=1,mproj1=1,anproj1=2000,jproj2=1,mproj2=1,anproj2=2000;
                   6787:   double **ximort;
1.145     brouard  6788:   char *alph[]={"a","a","b","c","d","e"}, str[4]="1234";
1.136     brouard  6789:   int *dcwave;
                   6790: 
1.164     brouard  6791:   char z[1]="c";
1.136     brouard  6792: 
                   6793:   /*char  *strt;*/
                   6794:   char strtend[80];
1.126     brouard  6795: 
1.164     brouard  6796: 
1.126     brouard  6797: /*   setlocale (LC_ALL, ""); */
                   6798: /*   bindtextdomain (PACKAGE, LOCALEDIR); */
                   6799: /*   textdomain (PACKAGE); */
                   6800: /*   setlocale (LC_CTYPE, ""); */
                   6801: /*   setlocale (LC_MESSAGES, ""); */
                   6802: 
                   6803:   /*   gettimeofday(&start_time, (struct timezone*)0); */ /* at first time */
1.157     brouard  6804:   rstart_time = time(NULL);  
                   6805:   /*  (void) gettimeofday(&start_time,&tzp);*/
                   6806:   start_time = *localtime(&rstart_time);
1.126     brouard  6807:   curr_time=start_time;
1.157     brouard  6808:   /*tml = *localtime(&start_time.tm_sec);*/
                   6809:   /* strcpy(strstart,asctime(&tml)); */
                   6810:   strcpy(strstart,asctime(&start_time));
1.126     brouard  6811: 
                   6812: /*  printf("Localtime (at start)=%s",strstart); */
1.157     brouard  6813: /*  tp.tm_sec = tp.tm_sec +86400; */
                   6814: /*  tm = *localtime(&start_time.tm_sec); */
1.126     brouard  6815: /*   tmg.tm_year=tmg.tm_year +dsign*dyear; */
                   6816: /*   tmg.tm_mon=tmg.tm_mon +dsign*dmonth; */
                   6817: /*   tmg.tm_hour=tmg.tm_hour + 1; */
1.157     brouard  6818: /*   tp.tm_sec = mktime(&tmg); */
1.126     brouard  6819: /*   strt=asctime(&tmg); */
                   6820: /*   printf("Time(after) =%s",strstart);  */
                   6821: /*  (void) time (&time_value);
                   6822: *  printf("time=%d,t-=%d\n",time_value,time_value-86400);
                   6823: *  tm = *localtime(&time_value);
                   6824: *  strstart=asctime(&tm);
                   6825: *  printf("tim_value=%d,asctime=%s\n",time_value,strstart); 
                   6826: */
                   6827: 
                   6828:   nberr=0; /* Number of errors and warnings */
                   6829:   nbwarn=0;
1.184     brouard  6830: #ifdef WIN32
                   6831:   _getcwd(pathcd, size);
                   6832: #else
1.126     brouard  6833:   getcwd(pathcd, size);
1.184     brouard  6834: #endif
1.191     brouard  6835:   syscompilerinfo(0);
1.196     brouard  6836:   printf("\nIMaCh version %s, %s\n%s",version, copyright, fullversion);
1.126     brouard  6837:   if(argc <=1){
                   6838:     printf("\nEnter the parameter file name: ");
1.205     brouard  6839:     if(!fgets(pathr,FILENAMELENGTH,stdin)){
                   6840:       printf("ERROR Empty parameter file name\n");
                   6841:       goto end;
                   6842:     }
1.126     brouard  6843:     i=strlen(pathr);
                   6844:     if(pathr[i-1]=='\n')
                   6845:       pathr[i-1]='\0';
1.156     brouard  6846:     i=strlen(pathr);
1.205     brouard  6847:     if(i >= 1 && pathr[i-1]==' ') {/* This may happen when dragging on oS/X! */
1.156     brouard  6848:       pathr[i-1]='\0';
1.205     brouard  6849:     }
                   6850:     i=strlen(pathr);
                   6851:     if( i==0 ){
                   6852:       printf("ERROR Empty parameter file name\n");
                   6853:       goto end;
                   6854:     }
                   6855:     for (tok = pathr; tok != NULL; ){
1.126     brouard  6856:       printf("Pathr |%s|\n",pathr);
                   6857:       while ((val = strsep(&tok, "\"" )) != NULL && *val == '\0');
                   6858:       printf("val= |%s| pathr=%s\n",val,pathr);
                   6859:       strcpy (pathtot, val);
                   6860:       if(pathr[0] == '\0') break; /* Dirty */
                   6861:     }
                   6862:   }
                   6863:   else{
                   6864:     strcpy(pathtot,argv[1]);
                   6865:   }
                   6866:   /*if(getcwd(pathcd, MAXLINE)!= NULL)printf ("Error pathcd\n");*/
                   6867:   /*cygwin_split_path(pathtot,path,optionfile);
                   6868:     printf("pathtot=%s, path=%s, optionfile=%s\n",pathtot,path,optionfile);*/
                   6869:   /* cutv(path,optionfile,pathtot,'\\');*/
                   6870: 
                   6871:   /* Split argv[0], imach program to get pathimach */
                   6872:   printf("\nargv[0]=%s argv[1]=%s, \n",argv[0],argv[1]);
                   6873:   split(argv[0],pathimach,optionfile,optionfilext,optionfilefiname);
                   6874:   printf("\nargv[0]=%s pathimach=%s, \noptionfile=%s \noptionfilext=%s \noptionfilefiname=%s\n",argv[0],pathimach,optionfile,optionfilext,optionfilefiname);
                   6875:  /*   strcpy(pathimach,argv[0]); */
                   6876:   /* Split argv[1]=pathtot, parameter file name to get path, optionfile, extension and name */
                   6877:   split(pathtot,path,optionfile,optionfilext,optionfilefiname);
                   6878:   printf("\npathtot=%s,\npath=%s,\noptionfile=%s \noptionfilext=%s \noptionfilefiname=%s\n",pathtot,path,optionfile,optionfilext,optionfilefiname);
1.184     brouard  6879: #ifdef WIN32
                   6880:   _chdir(path); /* Can be a relative path */
                   6881:   if(_getcwd(pathcd,MAXLINE) > 0) /* So pathcd is the full path */
                   6882: #else
1.126     brouard  6883:   chdir(path); /* Can be a relative path */
1.184     brouard  6884:   if (getcwd(pathcd, MAXLINE) > 0) /* So pathcd is the full path */
                   6885: #endif
                   6886:   printf("Current directory %s!\n",pathcd);
1.126     brouard  6887:   strcpy(command,"mkdir ");
                   6888:   strcat(command,optionfilefiname);
                   6889:   if((outcmd=system(command)) != 0){
1.169     brouard  6890:     printf("Directory already exists (or can't create it) %s%s, err=%d\n",path,optionfilefiname,outcmd);
1.126     brouard  6891:     /* fprintf(ficlog,"Problem creating directory %s%s\n",path,optionfilefiname); */
                   6892:     /* fclose(ficlog); */
                   6893: /*     exit(1); */
                   6894:   }
                   6895: /*   if((imk=mkdir(optionfilefiname))<0){ */
                   6896: /*     perror("mkdir"); */
                   6897: /*   } */
                   6898: 
                   6899:   /*-------- arguments in the command line --------*/
                   6900: 
1.186     brouard  6901:   /* Main Log file */
1.126     brouard  6902:   strcat(filelog, optionfilefiname);
                   6903:   strcat(filelog,".log");    /* */
                   6904:   if((ficlog=fopen(filelog,"w"))==NULL)    {
                   6905:     printf("Problem with logfile %s\n",filelog);
                   6906:     goto end;
                   6907:   }
                   6908:   fprintf(ficlog,"Log filename:%s\n",filelog);
1.197     brouard  6909:   fprintf(ficlog,"Version %s %s",version,fullversion);
1.126     brouard  6910:   fprintf(ficlog,"\nEnter the parameter file name: \n");
                   6911:   fprintf(ficlog,"pathimach=%s\npathtot=%s\n\
                   6912:  path=%s \n\
                   6913:  optionfile=%s\n\
                   6914:  optionfilext=%s\n\
1.156     brouard  6915:  optionfilefiname='%s'\n",pathimach,pathtot,path,optionfile,optionfilext,optionfilefiname);
1.126     brouard  6916: 
1.197     brouard  6917:   syscompilerinfo(1);
1.167     brouard  6918: 
1.126     brouard  6919:   printf("Local time (at start):%s",strstart);
                   6920:   fprintf(ficlog,"Local time (at start): %s",strstart);
                   6921:   fflush(ficlog);
                   6922: /*   (void) gettimeofday(&curr_time,&tzp); */
1.157     brouard  6923: /*   printf("Elapsed time %d\n", asc_diff_time(curr_time.tm_sec-start_time.tm_sec,tmpout)); */
1.126     brouard  6924: 
                   6925:   /* */
                   6926:   strcpy(fileres,"r");
                   6927:   strcat(fileres, optionfilefiname);
1.201     brouard  6928:   strcat(fileresu, optionfilefiname); /* Without r in front */
1.126     brouard  6929:   strcat(fileres,".txt");    /* Other files have txt extension */
1.201     brouard  6930:   strcat(fileresu,".txt");    /* Other files have txt extension */
1.126     brouard  6931: 
1.186     brouard  6932:   /* Main ---------arguments file --------*/
1.126     brouard  6933: 
                   6934:   if((ficpar=fopen(optionfile,"r"))==NULL)    {
1.155     brouard  6935:     printf("Problem with optionfile '%s' with errno='%s'\n",optionfile,strerror(errno));
                   6936:     fprintf(ficlog,"Problem with optionfile '%s' with errno='%s'\n",optionfile,strerror(errno));
1.126     brouard  6937:     fflush(ficlog);
1.149     brouard  6938:     /* goto end; */
                   6939:     exit(70); 
1.126     brouard  6940:   }
                   6941: 
                   6942: 
                   6943: 
                   6944:   strcpy(filereso,"o");
1.201     brouard  6945:   strcat(filereso,fileresu);
1.126     brouard  6946:   if((ficparo=fopen(filereso,"w"))==NULL) { /* opened on subdirectory */
                   6947:     printf("Problem with Output resultfile: %s\n", filereso);
                   6948:     fprintf(ficlog,"Problem with Output resultfile: %s\n", filereso);
                   6949:     fflush(ficlog);
                   6950:     goto end;
                   6951:   }
                   6952: 
                   6953:   /* Reads comments: lines beginning with '#' */
                   6954:   numlinepar=0;
1.197     brouard  6955: 
                   6956:     /* First parameter line */
                   6957:   while(fgets(line, MAXLINE, ficpar)) {
                   6958:     /* If line starts with a # it is a comment */
                   6959:     if (line[0] == '#') {
                   6960:       numlinepar++;
                   6961:       fputs(line,stdout);
                   6962:       fputs(line,ficparo);
                   6963:       fputs(line,ficlog);
                   6964:       continue;
                   6965:     }else
                   6966:       break;
                   6967:   }
                   6968:   if((num_filled=sscanf(line,"title=%s datafile=%s lastobs=%d firstpass=%d lastpass=%d\n", \
                   6969:                        title, datafile, &lastobs, &firstpass,&lastpass)) !=EOF){
                   6970:     if (num_filled != 5) {
                   6971:       printf("Should be 5 parameters\n");
                   6972:     }
1.126     brouard  6973:     numlinepar++;
1.197     brouard  6974:     printf("title=%s datafile=%s lastobs=%d firstpass=%d lastpass=%d\n", title, datafile, lastobs, firstpass,lastpass);
                   6975:   }
                   6976:   /* Second parameter line */
                   6977:   while(fgets(line, MAXLINE, ficpar)) {
                   6978:     /* If line starts with a # it is a comment */
                   6979:     if (line[0] == '#') {
                   6980:       numlinepar++;
                   6981:       fputs(line,stdout);
                   6982:       fputs(line,ficparo);
                   6983:       fputs(line,ficlog);
                   6984:       continue;
                   6985:     }else
                   6986:       break;
                   6987:   }
                   6988:   if((num_filled=sscanf(line,"ftol=%lf stepm=%d ncovcol=%d nlstate=%d ndeath=%d maxwav=%d mle=%d weight=%d\n", \
                   6989:                        &ftol, &stepm, &ncovcol, &nlstate, &ndeath, &maxwav, &mle, &weightopt)) !=EOF){
                   6990:     if (num_filled != 8) {
1.209   ! brouard  6991:       printf("Not 8 parameters, for example:ftol=1.e-8 stepm=12 ncovcol=2 nlstate=2 ndeath=1 maxwav=3 mle=1 weight=1\n");
        !          6992:       printf("but line=%s\n",line);
1.197     brouard  6993:     }
                   6994:     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  6995:   }
1.203     brouard  6996:   /* ftolpl=6*ftol*1.e5; /\* 6.e-3 make convergences in less than 80 loops for the prevalence limit *\/ */
1.209   ! brouard  6997:   /*ftolpl=6.e-4; *//* 6.e-3 make convergences in less than 80 loops for the prevalence limit */
1.197     brouard  6998:   /* Third parameter line */
                   6999:   while(fgets(line, MAXLINE, ficpar)) {
                   7000:     /* If line starts with a # it is a comment */
                   7001:     if (line[0] == '#') {
                   7002:       numlinepar++;
                   7003:       fputs(line,stdout);
                   7004:       fputs(line,ficparo);
                   7005:       fputs(line,ficlog);
                   7006:       continue;
                   7007:     }else
                   7008:       break;
                   7009:   }
1.201     brouard  7010:   if((num_filled=sscanf(line,"model=1+age%[^.\n]", model)) !=EOF){
                   7011:     if (num_filled == 0)
                   7012:             model[0]='\0';
                   7013:     else if (num_filled != 1){
1.197     brouard  7014:       printf("ERROR %d: Model should be at minimum 'model=1+age.' %s\n",num_filled, line);
                   7015:       fprintf(ficlog,"ERROR %d: Model should be at minimum 'model=1+age.' %s\n",num_filled, line);
                   7016:       model[0]='\0';
                   7017:       goto end;
                   7018:     }
                   7019:     else{
                   7020:       if (model[0]=='+'){
                   7021:        for(i=1; i<=strlen(model);i++)
                   7022:          modeltemp[i-1]=model[i];
1.201     brouard  7023:        strcpy(model,modeltemp); 
1.197     brouard  7024:       }
                   7025:     }
1.199     brouard  7026:     /* printf(" model=1+age%s modeltemp= %s, model=%s\n",model, modeltemp, model);fflush(stdout); */
1.203     brouard  7027:     printf("model=1+age+%s\n",model);fflush(stdout);
1.197     brouard  7028:   }
                   7029:   /* 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); */
                   7030:   /* numlinepar=numlinepar+3; /\* In general *\/ */
                   7031:   /* 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.203     brouard  7032:   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);
                   7033:   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  7034:   fflush(ficlog);
1.190     brouard  7035:   /* if(model[0]=='#'|| model[0]== '\0'){ */
                   7036:   if(model[0]=='#'){
1.187     brouard  7037:     printf("Error in 'model' line: model should start with 'model=1+age+' and end with '.' \n \
                   7038:  'model=1+age+.' or 'model=1+age+V1.' or 'model=1+age+age*age+V1+V1*age.' or \n \
                   7039:  'model=1+age+V1+V2.' or 'model=1+age+V1+V2+V1*V2.' etc. \n");         \
                   7040:     if(mle != -1){
                   7041:       printf("Fix the model line and run imach with mle=-1 to get a correct template of the parameter file.\n");
                   7042:       exit(1);
                   7043:     }
                   7044:   }
1.126     brouard  7045:   while((c=getc(ficpar))=='#' && c!= EOF){
                   7046:     ungetc(c,ficpar);
                   7047:     fgets(line, MAXLINE, ficpar);
                   7048:     numlinepar++;
1.195     brouard  7049:     if(line[1]=='q'){ /* This #q will quit imach (the answer is q) */
                   7050:       z[0]=line[1];
                   7051:     }
                   7052:     /* printf("****line [1] = %c \n",line[1]); */
1.141     brouard  7053:     fputs(line, stdout);
                   7054:     //puts(line);
1.126     brouard  7055:     fputs(line,ficparo);
                   7056:     fputs(line,ficlog);
                   7057:   }
                   7058:   ungetc(c,ficpar);
                   7059: 
                   7060:    
1.145     brouard  7061:   covar=matrix(0,NCOVMAX,1,n);  /**< used in readdata */
1.136     brouard  7062:   cptcovn=0; /*Number of covariates, i.e. number of '+' in model statement plus one, indepently of n in Vn*/
                   7063:   /* v1+v2+v3+v2*v4+v5*age makes cptcovn = 5
                   7064:      v1+v2*age+v2*v3 makes cptcovn = 3
                   7065:   */
                   7066:   if (strlen(model)>1) 
1.187     brouard  7067:     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  7068:   else
1.187     brouard  7069:     ncovmodel=2; /* Constant and age */
1.133     brouard  7070:   nforce= (nlstate+ndeath-1)*nlstate; /* Number of forces ij from state i to j */
                   7071:   npar= nforce*ncovmodel; /* Number of parameters like aij*/
1.131     brouard  7072:   if(npar >MAXPARM || nlstate >NLSTATEMAX || ndeath >NDEATHMAX || ncovmodel>NCOVMAX){
                   7073:     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);
                   7074:     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);
                   7075:     fflush(stdout);
                   7076:     fclose (ficlog);
                   7077:     goto end;
                   7078:   }
1.126     brouard  7079:   delti3= ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel);
                   7080:   delti=delti3[1][1];
                   7081:   /*delti=vector(1,npar); *//* Scale of each paramater (output from hesscov)*/
                   7082:   if(mle==-1){ /* Print a wizard for help writing covariance matrix */
                   7083:     prwizard(ncovmodel, nlstate, ndeath, model, ficparo);
1.191     brouard  7084:     printf(" You chose mle=-1, look at file %s for a template of covariance matrix \n",filereso);
                   7085:     fprintf(ficlog," You chose mle=-1, look at file %s for a template of covariance matrix \n",filereso);
1.126     brouard  7086:     free_ma3x(delti3,1,nlstate,1, nlstate+ndeath-1,1,ncovmodel); 
                   7087:     fclose (ficparo);
                   7088:     fclose (ficlog);
                   7089:     goto end;
                   7090:     exit(0);
                   7091:   }
1.186     brouard  7092:   else if(mle==-3) { /* Main Wizard */
1.126     brouard  7093:     prwizard(ncovmodel, nlstate, ndeath, model, ficparo);
1.192     brouard  7094:     printf(" You chose mle=-3, look at file %s for a template of covariance matrix \n",filereso);
                   7095:     fprintf(ficlog," You chose mle=-3, look at file %s for a template of covariance matrix \n",filereso);
1.126     brouard  7096:     param= ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel);
                   7097:     matcov=matrix(1,npar,1,npar);
1.203     brouard  7098:     hess=matrix(1,npar,1,npar);
1.126     brouard  7099:   }
                   7100:   else{
1.145     brouard  7101:     /* Read guessed parameters */
1.126     brouard  7102:     /* Reads comments: lines beginning with '#' */
                   7103:     while((c=getc(ficpar))=='#' && c!= EOF){
                   7104:       ungetc(c,ficpar);
                   7105:       fgets(line, MAXLINE, ficpar);
                   7106:       numlinepar++;
1.141     brouard  7107:       fputs(line,stdout);
1.126     brouard  7108:       fputs(line,ficparo);
                   7109:       fputs(line,ficlog);
                   7110:     }
                   7111:     ungetc(c,ficpar);
                   7112:     
                   7113:     param= ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel);
                   7114:     for(i=1; i <=nlstate; i++){
                   7115:       j=0;
                   7116:       for(jj=1; jj <=nlstate+ndeath; jj++){
                   7117:        if(jj==i) continue;
                   7118:        j++;
                   7119:        fscanf(ficpar,"%1d%1d",&i1,&j1);
1.193     brouard  7120:        if ((i1 != i) || (j1 != jj)){
1.126     brouard  7121:          printf("Error in line parameters number %d, %1d%1d instead of %1d%1d \n \
                   7122: It might be a problem of design; if ncovcol and the model are correct\n \
                   7123: run imach with mle=-1 to get a correct template of the parameter file.\n",numlinepar, i,j, i1, j1);
                   7124:          exit(1);
                   7125:        }
                   7126:        fprintf(ficparo,"%1d%1d",i1,j1);
                   7127:        if(mle==1)
1.193     brouard  7128:          printf("%1d%1d",i,jj);
                   7129:        fprintf(ficlog,"%1d%1d",i,jj);
1.126     brouard  7130:        for(k=1; k<=ncovmodel;k++){
                   7131:          fscanf(ficpar," %lf",&param[i][j][k]);
                   7132:          if(mle==1){
                   7133:            printf(" %lf",param[i][j][k]);
                   7134:            fprintf(ficlog," %lf",param[i][j][k]);
                   7135:          }
                   7136:          else
                   7137:            fprintf(ficlog," %lf",param[i][j][k]);
                   7138:          fprintf(ficparo," %lf",param[i][j][k]);
                   7139:        }
                   7140:        fscanf(ficpar,"\n");
                   7141:        numlinepar++;
                   7142:        if(mle==1)
                   7143:          printf("\n");
                   7144:        fprintf(ficlog,"\n");
                   7145:        fprintf(ficparo,"\n");
                   7146:       }
                   7147:     }  
                   7148:     fflush(ficlog);
                   7149: 
1.145     brouard  7150:     /* Reads scales values */
1.126     brouard  7151:     p=param[1][1];
                   7152:     
                   7153:     /* Reads comments: lines beginning with '#' */
                   7154:     while((c=getc(ficpar))=='#' && c!= EOF){
                   7155:       ungetc(c,ficpar);
                   7156:       fgets(line, MAXLINE, ficpar);
                   7157:       numlinepar++;
1.141     brouard  7158:       fputs(line,stdout);
1.126     brouard  7159:       fputs(line,ficparo);
                   7160:       fputs(line,ficlog);
                   7161:     }
                   7162:     ungetc(c,ficpar);
                   7163: 
                   7164:     for(i=1; i <=nlstate; i++){
                   7165:       for(j=1; j <=nlstate+ndeath-1; j++){
                   7166:        fscanf(ficpar,"%1d%1d",&i1,&j1);
1.164     brouard  7167:        if ( (i1-i) * (j1-j) != 0){
1.126     brouard  7168:          printf("Error in line parameters number %d, %1d%1d instead of %1d%1d \n",numlinepar, i,j, i1, j1);
                   7169:          exit(1);
                   7170:        }
                   7171:        printf("%1d%1d",i,j);
                   7172:        fprintf(ficparo,"%1d%1d",i1,j1);
                   7173:        fprintf(ficlog,"%1d%1d",i1,j1);
                   7174:        for(k=1; k<=ncovmodel;k++){
                   7175:          fscanf(ficpar,"%le",&delti3[i][j][k]);
                   7176:          printf(" %le",delti3[i][j][k]);
                   7177:          fprintf(ficparo," %le",delti3[i][j][k]);
                   7178:          fprintf(ficlog," %le",delti3[i][j][k]);
                   7179:        }
                   7180:        fscanf(ficpar,"\n");
                   7181:        numlinepar++;
                   7182:        printf("\n");
                   7183:        fprintf(ficparo,"\n");
                   7184:        fprintf(ficlog,"\n");
                   7185:       }
                   7186:     }
                   7187:     fflush(ficlog);
                   7188: 
1.145     brouard  7189:     /* Reads covariance matrix */
1.126     brouard  7190:     delti=delti3[1][1];
                   7191: 
                   7192: 
                   7193:     /* free_ma3x(delti3,1,nlstate,1,nlstate+ndeath-1,1,ncovmodel); */ /* Hasn't to to freed here otherwise delti is no more allocated */
                   7194:   
                   7195:     /* Reads comments: lines beginning with '#' */
                   7196:     while((c=getc(ficpar))=='#' && c!= EOF){
                   7197:       ungetc(c,ficpar);
                   7198:       fgets(line, MAXLINE, ficpar);
                   7199:       numlinepar++;
1.141     brouard  7200:       fputs(line,stdout);
1.126     brouard  7201:       fputs(line,ficparo);
                   7202:       fputs(line,ficlog);
                   7203:     }
                   7204:     ungetc(c,ficpar);
                   7205:   
                   7206:     matcov=matrix(1,npar,1,npar);
1.203     brouard  7207:     hess=matrix(1,npar,1,npar);
1.131     brouard  7208:     for(i=1; i <=npar; i++)
                   7209:       for(j=1; j <=npar; j++) matcov[i][j]=0.;
                   7210:       
1.194     brouard  7211:     /* Scans npar lines */
1.126     brouard  7212:     for(i=1; i <=npar; i++){
1.194     brouard  7213:       count=fscanf(ficpar,"%1d%1d%1d",&i1,&j1,&jk);
                   7214:       if(count != 3){
                   7215:        printf("Error! Error in parameter file %s at line %d after line starting with %1d%1d%1d\n\
                   7216: This is probably because your covariance matrix doesn't \n  contain exactly %d lines corresponding to your model line '1+age+%s'.\n\
                   7217: Please run with mle=-1 to get a correct covariance matrix.\n",optionfile,numlinepar, i1,j1,jk, npar, model);
                   7218:        fprintf(ficlog,"Error! Error in parameter file %s at line %d after line starting with %1d%1d%1d\n\
                   7219: This is probably because your covariance matrix doesn't \n  contain exactly %d lines corresponding to your model line '1+age+%s'.\n\
                   7220: Please run with mle=-1 to get a correct covariance matrix.\n",optionfile,numlinepar, i1,j1,jk, npar, model);
                   7221:        exit(1);
                   7222:       }else
1.126     brouard  7223:       if(mle==1)
1.194     brouard  7224:        printf("%1d%1d%1d",i1,j1,jk);
                   7225:       fprintf(ficlog,"%1d%1d%1d",i1,j1,jk);
                   7226:       fprintf(ficparo,"%1d%1d%1d",i1,j1,jk);
1.126     brouard  7227:       for(j=1; j <=i; j++){
                   7228:        fscanf(ficpar," %le",&matcov[i][j]);
                   7229:        if(mle==1){
                   7230:          printf(" %.5le",matcov[i][j]);
                   7231:        }
                   7232:        fprintf(ficlog," %.5le",matcov[i][j]);
                   7233:        fprintf(ficparo," %.5le",matcov[i][j]);
                   7234:       }
                   7235:       fscanf(ficpar,"\n");
                   7236:       numlinepar++;
                   7237:       if(mle==1)
                   7238:        printf("\n");
                   7239:       fprintf(ficlog,"\n");
                   7240:       fprintf(ficparo,"\n");
                   7241:     }
1.194     brouard  7242:     /* End of read covariance matrix npar lines */
1.126     brouard  7243:     for(i=1; i <=npar; i++)
                   7244:       for(j=i+1;j<=npar;j++)
                   7245:        matcov[i][j]=matcov[j][i];
                   7246:     
                   7247:     if(mle==1)
                   7248:       printf("\n");
                   7249:     fprintf(ficlog,"\n");
                   7250:     
                   7251:     fflush(ficlog);
                   7252:     
                   7253:     /*-------- Rewriting parameter file ----------*/
                   7254:     strcpy(rfileres,"r");    /* "Rparameterfile */
                   7255:     strcat(rfileres,optionfilefiname);    /* Parameter file first name*/
                   7256:     strcat(rfileres,".");    /* */
                   7257:     strcat(rfileres,optionfilext);    /* Other files have txt extension */
                   7258:     if((ficres =fopen(rfileres,"w"))==NULL) {
1.201     brouard  7259:       printf("Problem writing new parameter file: %s\n", rfileres);goto end;
                   7260:       fprintf(ficlog,"Problem writing new parameter file: %s\n", rfileres);goto end;
1.126     brouard  7261:     }
                   7262:     fprintf(ficres,"#%s\n",version);
                   7263:   }    /* End of mle != -3 */
                   7264: 
1.186     brouard  7265:   /*  Main data
                   7266:    */
1.126     brouard  7267:   n= lastobs;
                   7268:   num=lvector(1,n);
                   7269:   moisnais=vector(1,n);
                   7270:   annais=vector(1,n);
                   7271:   moisdc=vector(1,n);
                   7272:   andc=vector(1,n);
                   7273:   agedc=vector(1,n);
                   7274:   cod=ivector(1,n);
                   7275:   weight=vector(1,n);
                   7276:   for(i=1;i<=n;i++) weight[i]=1.0; /* Equal weights, 1 by default */
                   7277:   mint=matrix(1,maxwav,1,n);
                   7278:   anint=matrix(1,maxwav,1,n);
1.131     brouard  7279:   s=imatrix(1,maxwav+1,1,n); /* s[i][j] health state for wave i and individual j */ 
1.126     brouard  7280:   tab=ivector(1,NCOVMAX);
1.144     brouard  7281:   ncodemax=ivector(1,NCOVMAX); /* Number of code per covariate; if O and 1 only, 2**ncov; V1+V2+V3+V4=>16 */
1.192     brouard  7282:   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  7283: 
1.136     brouard  7284:   /* Reads data from file datafile */
                   7285:   if (readdata(datafile, firstobs, lastobs, &imx)==1)
                   7286:     goto end;
                   7287: 
                   7288:   /* Calculation of the number of parameters from char model */
1.137     brouard  7289:     /*    modelsav=V2+V1+V4+age*V3 strb=age*V3 stra=V2+V1+V4 
                   7290:        k=4 (age*V3) Tvar[k=4]= 3 (from V3) Tag[cptcovage=1]=4
                   7291:        k=3 V4 Tvar[k=3]= 4 (from V4)
                   7292:        k=2 V1 Tvar[k=2]= 1 (from V1)
                   7293:        k=1 Tvar[1]=2 (from V2)
                   7294:     */
                   7295:   Tvar=ivector(1,NCOVMAX); /* Was 15 changed to NCOVMAX. */
                   7296:   /*  V2+V1+V4+age*V3 is a model with 4 covariates (3 plus signs). 
                   7297:       For each model-covariate stores the data-covariate id. Tvar[1]=2, Tvar[2]=1, Tvar[3]=4, 
                   7298:       Tvar[4=age*V3] is 3 and 'age' is recorded in Tage.
                   7299:   */
                   7300:   /* For model-covariate k tells which data-covariate to use but
                   7301:     because this model-covariate is a construction we invent a new column
                   7302:     ncovcol + k1
                   7303:     If already ncovcol=4 and model=V2+V1+V1*V4+age*V3
                   7304:     Tvar[3=V1*V4]=4+1 etc */
1.145     brouard  7305:   Tprod=ivector(1,NCOVMAX); /* Gives the position of a product */
1.137     brouard  7306:   /* Tprod[k1=1]=3(=V1*V4) for V2+V1+V1*V4+age*V3
                   7307:      if  V2+V1+V1*V4+age*V3+V3*V2   TProd[k1=2]=5 (V3*V2)
                   7308:   */
1.145     brouard  7309:   Tvaraff=ivector(1,NCOVMAX); /* Unclear */
                   7310:   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  7311:                            * For V3*V2 (in V2+V1+V1*V4+age*V3+V3*V2), V3*V2 position is 2nd. 
                   7312:                            * Tvard[k1=2][1]=3 (V3) Tvard[k1=2][2]=2(V2) */
1.145     brouard  7313:   Tage=ivector(1,NCOVMAX); /* Gives the covariate id of covariates associated with age: V2 + V1 + age*V4 + V3*age
1.137     brouard  7314:                         4 covariates (3 plus signs)
                   7315:                         Tage[1=V3*age]= 4; Tage[2=age*V4] = 3
                   7316:                      */  
1.136     brouard  7317: 
1.186     brouard  7318: /* Main decodemodel */
                   7319: 
1.187     brouard  7320: 
1.136     brouard  7321:   if(decodemodel(model, lastobs) == 1)
                   7322:     goto end;
                   7323: 
1.137     brouard  7324:   if((double)(lastobs-imx)/(double)imx > 1.10){
                   7325:     nbwarn++;
                   7326:     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); 
                   7327:     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); 
                   7328:   }
1.136     brouard  7329:     /*  if(mle==1){*/
1.137     brouard  7330:   if (weightopt != 1) { /* Maximisation without weights. We can have weights different from 1 but want no weight*/
                   7331:     for(i=1;i<=imx;i++) weight[i]=1.0; /* changed to imx */
1.136     brouard  7332:   }
                   7333: 
                   7334:     /*-calculation of age at interview from date of interview and age at death -*/
                   7335:   agev=matrix(1,maxwav,1,imx);
                   7336: 
                   7337:   if(calandcheckages(imx, maxwav, &agemin, &agemax, &nberr, &nbwarn) == 1)
                   7338:     goto end;
                   7339: 
1.126     brouard  7340: 
1.136     brouard  7341:   agegomp=(int)agemin;
                   7342:   free_vector(moisnais,1,n);
                   7343:   free_vector(annais,1,n);
1.126     brouard  7344:   /* free_matrix(mint,1,maxwav,1,n);
                   7345:      free_matrix(anint,1,maxwav,1,n);*/
                   7346:   free_vector(moisdc,1,n);
                   7347:   free_vector(andc,1,n);
1.145     brouard  7348:   /* */
                   7349:   
1.126     brouard  7350:   wav=ivector(1,imx);
                   7351:   dh=imatrix(1,lastpass-firstpass+1,1,imx);
                   7352:   bh=imatrix(1,lastpass-firstpass+1,1,imx);
                   7353:   mw=imatrix(1,lastpass-firstpass+1,1,imx);
                   7354:    
                   7355:   /* Concatenates waves */
                   7356:   concatwav(wav, dh, bh, mw, s, agedc, agev,  firstpass, lastpass, imx, nlstate, stepm);
1.145     brouard  7357:   /* */
                   7358:  
1.126     brouard  7359:   /* Routine tricode is to calculate cptcoveff (real number of unique covariates) and to associate covariable number and modality */
                   7360: 
                   7361:   nbcode=imatrix(0,NCOVMAX,0,NCOVMAX); 
                   7362:   ncodemax[1]=1;
1.145     brouard  7363:   Ndum =ivector(-1,NCOVMAX);  
1.187     brouard  7364:   if (ncovmodel-nagesqr > 2 ) /* That is if covariate other than cst, age and age*age */
1.145     brouard  7365:     tricode(Tvar,nbcode,imx, Ndum); /**< Fills nbcode[Tvar[j]][l]; */
1.186     brouard  7366:   /* Nbcode gives the value of the lth modality of jth covariate, in
                   7367:      V2+V1*age, there are 3 covariates Tvar[2]=1 (V1).*/
                   7368:   /* 1 to ncodemax[j] is the maximum value of this jth covariate */
1.145     brouard  7369: 
1.200     brouard  7370:   /*  codtab=imatrix(1,100,1,10);*/ /* codtab[h,k]=( (h-1) - mod(k-1,2**(k-1) )/2**(k-1) */
1.198     brouard  7371:   /*printf(" codtab[1,1],codtab[100,10]=%d,%d\n", codtab[1][1],codtabm(100,10));*/
1.186     brouard  7372:   /* codtab gives the value 1 or 2 of the hth combination of k covariates (1 or 2).*/
1.145     brouard  7373:   h=0;
                   7374: 
                   7375: 
                   7376:   /*if (cptcovn > 0) */
1.126     brouard  7377:       
1.145     brouard  7378:  
1.126     brouard  7379:   m=pow(2,cptcoveff);
                   7380:  
1.144     brouard  7381:          /**< codtab(h,k)  k   = codtab[h,k]=( (h-1) - mod(k-1,2**(k-1) )/2**(k-1) + 1
1.186     brouard  7382:           * For k=4 covariates, h goes from 1 to 2**k
                   7383:           * codtabm(h,k)=  1 & (h-1) >> (k-1) ;
                   7384:           *     h\k   1     2     3     4
1.143     brouard  7385:           *______________________________  
                   7386:           *     1 i=1 1 i=1 1 i=1 1 i=1 1
                   7387:           *     2     2     1     1     1
                   7388:           *     3 i=2 1     2     1     1
                   7389:           *     4     2     2     1     1
                   7390:           *     5 i=3 1 i=2 1     2     1
                   7391:           *     6     2     1     2     1
                   7392:           *     7 i=4 1     2     2     1
                   7393:           *     8     2     2     2     1
1.197     brouard  7394:           *     9 i=5 1 i=3 1 i=2 1     2
                   7395:           *    10     2     1     1     2
                   7396:           *    11 i=6 1     2     1     2
                   7397:           *    12     2     2     1     2
                   7398:           *    13 i=7 1 i=4 1     2     2    
                   7399:           *    14     2     1     2     2
                   7400:           *    15 i=8 1     2     2     2
                   7401:           *    16     2     2     2     2
1.143     brouard  7402:           */
1.202     brouard  7403:   /* /\* for(h=1; h <=100 ;h++){  *\/ */
                   7404:   /*   /\* printf("h=%2d ", h); *\/ */
                   7405:   /*    /\* for(k=1; k <=10; k++){ *\/ */
                   7406:   /*      /\* printf("k=%d %d ",k,codtabm(h,k)); *\/ */
                   7407:   /*    /\*   codtab[h][k]=codtabm(h,k); *\/ */
                   7408:   /*    /\* } *\/ */
                   7409:   /*    /\* printf("\n"); *\/ */
                   7410:   /* } */
1.197     brouard  7411:   /* for(k=1;k<=cptcoveff; k++){ /\* scans any effective covariate *\/ */
                   7412:   /*   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 *\/  */
                   7413:   /*     for(j=1; j <= ncodemax[k]; j++){ /\* For each modality of this covariate ncodemax=2*\/ */
                   7414:   /*   for(cpt=1; cpt <=pow(2,k-1); cpt++){  /\* cpt=1 to 8/2**(3+1-1 or 3+1-3) =1 or 4 *\/  */
                   7415:   /*     h++; */
                   7416:   /*     if (h>m)  */
                   7417:   /*       h=1; */
                   7418:   /*     codtab[h][k]=j; */
                   7419:   /*     /\* codtab[12][3]=1; *\/ */
                   7420:   /*     /\*codtab[h][Tvar[k]]=j;*\/ */
                   7421:   /*     /\* 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]]); *\/ */
                   7422:   /*   }  */
                   7423:   /*     } */
                   7424:   /*   } */
                   7425:   /* }  */
1.126     brouard  7426:   /* printf("codtab[1][2]=%d codtab[2][2]=%d",codtab[1][2],codtab[2][2]); 
                   7427:      codtab[1][2]=1;codtab[2][2]=2; */
1.197     brouard  7428:   /* for(i=1; i <=m ;i++){  */
                   7429:   /*    for(k=1; k <=cptcovn; k++){ */
                   7430:   /*      printf("i=%d k=%d %d %d ",i,k,codtab[i][k], cptcoveff); */
                   7431:   /*    } */
                   7432:   /*    printf("\n"); */
                   7433:   /* } */
                   7434:   /*   scanf("%d",i);*/
1.145     brouard  7435: 
                   7436:  free_ivector(Ndum,-1,NCOVMAX);
                   7437: 
                   7438: 
1.126     brouard  7439:     
1.186     brouard  7440:   /* Initialisation of ----------- gnuplot -------------*/
1.126     brouard  7441:   strcpy(optionfilegnuplot,optionfilefiname);
                   7442:   if(mle==-3)
1.201     brouard  7443:     strcat(optionfilegnuplot,"-MORT_");
1.126     brouard  7444:   strcat(optionfilegnuplot,".gp");
                   7445: 
                   7446:   if((ficgp=fopen(optionfilegnuplot,"w"))==NULL) {
                   7447:     printf("Problem with file %s",optionfilegnuplot);
                   7448:   }
                   7449:   else{
1.204     brouard  7450:     fprintf(ficgp,"\n# IMaCh-%s\n", version); 
1.126     brouard  7451:     fprintf(ficgp,"# %s\n", optionfilegnuplot); 
1.141     brouard  7452:     //fprintf(ficgp,"set missing 'NaNq'\n");
                   7453:     fprintf(ficgp,"set datafile missing 'NaNq'\n");
1.126     brouard  7454:   }
                   7455:   /*  fclose(ficgp);*/
1.186     brouard  7456: 
                   7457: 
                   7458:   /* Initialisation of --------- index.htm --------*/
1.126     brouard  7459: 
                   7460:   strcpy(optionfilehtm,optionfilefiname); /* Main html file */
                   7461:   if(mle==-3)
1.201     brouard  7462:     strcat(optionfilehtm,"-MORT_");
1.126     brouard  7463:   strcat(optionfilehtm,".htm");
                   7464:   if((fichtm=fopen(optionfilehtm,"w"))==NULL)    {
1.131     brouard  7465:     printf("Problem with %s \n",optionfilehtm);
                   7466:     exit(0);
1.126     brouard  7467:   }
                   7468: 
                   7469:   strcpy(optionfilehtmcov,optionfilefiname); /* Only for matrix of covariance */
                   7470:   strcat(optionfilehtmcov,"-cov.htm");
                   7471:   if((fichtmcov=fopen(optionfilehtmcov,"w"))==NULL)    {
                   7472:     printf("Problem with %s \n",optionfilehtmcov), exit(0);
                   7473:   }
                   7474:   else{
                   7475:   fprintf(fichtmcov,"<html><head>\n<title>IMaCh Cov %s</title></head>\n <body><font size=\"2\">%s <br> %s</font> \
                   7476: <hr size=\"2\" color=\"#EC5E5E\"> \n\
1.204     brouard  7477: Title=%s <br>Datafile=%s Firstpass=%d Lastpass=%d Stepm=%d Weight=%d Model=1+age+%s<br>\n",\
1.126     brouard  7478:          optionfilehtmcov,version,fullversion,title,datafile,firstpass,lastpass,stepm, weightopt, model);
                   7479:   }
                   7480: 
1.204     brouard  7481:   fprintf(fichtm,"<html><head>\n<head>\n<meta charset=\"utf-8\"/><meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\" />\n<title>IMaCh %s</title></head>\n <body><font size=\"7\"><a href=http:/euroreves.ined.fr/imach>IMaCh for Interpolated Markov Chain</a> </font><br>\n<font size=\"3\">Sponsored by Copyright (C)  2002-2015 <a href=http://www.ined.fr>INED</a>-EUROREVES-Institut de longévité-Japan Society for the Promotion of Sciences 日本学術振興会 (<a href=https://www.jsps.go.jp/english/e-grants/>Grant-in-Aid for Scientific Research 25293121</a>) - <a href=https://software.intel.com/en-us>Intel Software 2015</a></font><br>  \
                   7482: <hr size=\"2\" color=\"#EC5E5E\"> \n\
                   7483: <font size=\"2\">IMaCh-%s <br> %s</font> \
1.126     brouard  7484: <hr size=\"2\" color=\"#EC5E5E\"> \n\
1.204     brouard  7485: Title=%s <br>Datafile=%s Firstpass=%d Lastpass=%d Stepm=%d Weight=%d Model=1+age+%s<br>\n\
1.126     brouard  7486: \n\
                   7487: <hr  size=\"2\" color=\"#EC5E5E\">\
                   7488:  <ul><li><h4>Parameter files</h4>\n\
                   7489:  - Parameter file: <a href=\"%s.%s\">%s.%s</a><br>\n\
                   7490:  - Copy of the parameter file: <a href=\"o%s\">o%s</a><br>\n\
                   7491:  - Log file of the run: <a href=\"%s\">%s</a><br>\n\
                   7492:  - Gnuplot file name: <a href=\"%s\">%s</a><br>\n\
                   7493:  - Date and time at start: %s</ul>\n",\
                   7494:          optionfilehtm,version,fullversion,title,datafile,firstpass,lastpass,stepm, weightopt, model,\
                   7495:          optionfilefiname,optionfilext,optionfilefiname,optionfilext,\
                   7496:          fileres,fileres,\
                   7497:          filelog,filelog,optionfilegnuplot,optionfilegnuplot,strstart);
                   7498:   fflush(fichtm);
                   7499: 
                   7500:   strcpy(pathr,path);
                   7501:   strcat(pathr,optionfilefiname);
1.184     brouard  7502: #ifdef WIN32
                   7503:   _chdir(optionfilefiname); /* Move to directory named optionfile */
                   7504: #else
1.126     brouard  7505:   chdir(optionfilefiname); /* Move to directory named optionfile */
1.184     brouard  7506: #endif
                   7507:          
1.126     brouard  7508:   
                   7509:   /* Calculates basic frequencies. Computes observed prevalence at single age
                   7510:      and prints on file fileres'p'. */
                   7511:   freqsummary(fileres, agemin, agemax, s, agev, nlstate, imx,Tvaraff,nbcode, ncodemax,mint,anint,strstart);
                   7512: 
                   7513:   fprintf(fichtm,"\n");
                   7514:   fprintf(fichtm,"<br>Total number of observations=%d <br>\n\
                   7515: Youngest age at first (selected) pass %.2f, oldest age %.2f<br>\n\
                   7516: Interval (in months) between two waves: Min=%d Max=%d Mean=%.2lf<br>\n",\
                   7517:          imx,agemin,agemax,jmin,jmax,jmean);
                   7518:   pmmij= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
                   7519:     oldms= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
                   7520:     newms= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
                   7521:     savms= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
                   7522:     oldm=oldms; newm=newms; savm=savms; /* Keeps fixed addresses to free */
                   7523:     
                   7524:    
                   7525:   /* For Powell, parameters are in a vector p[] starting at p[1]
                   7526:      so we point p on param[1][1] so that p[1] maps on param[1][1][1] */
                   7527:   p=param[1][1]; /* *(*(*(param +1)+1)+0) */
                   7528: 
                   7529:   globpr=0; /* To get the number ipmx of contributions and the sum of weights*/
1.186     brouard  7530:   /* For mortality only */
1.126     brouard  7531:   if (mle==-3){
1.136     brouard  7532:     ximort=matrix(1,NDIM,1,NDIM); 
1.186     brouard  7533:     /*     ximort=gsl_matrix_alloc(1,NDIM,1,NDIM); */
1.126     brouard  7534:     cens=ivector(1,n);
                   7535:     ageexmed=vector(1,n);
                   7536:     agecens=vector(1,n);
                   7537:     dcwave=ivector(1,n);
                   7538:  
                   7539:     for (i=1; i<=imx; i++){
                   7540:       dcwave[i]=-1;
                   7541:       for (m=firstpass; m<=lastpass; m++)
                   7542:        if (s[m][i]>nlstate) {
                   7543:          dcwave[i]=m;
                   7544:          /*    printf("i=%d j=%d s=%d dcwave=%d\n",i,j, s[j][i],dcwave[i]);*/
                   7545:          break;
                   7546:        }
                   7547:     }
                   7548: 
                   7549:     for (i=1; i<=imx; i++) {
                   7550:       if (wav[i]>0){
                   7551:        ageexmed[i]=agev[mw[1][i]][i];
                   7552:        j=wav[i];
                   7553:        agecens[i]=1.; 
                   7554: 
                   7555:        if (ageexmed[i]> 1 && wav[i] > 0){
                   7556:          agecens[i]=agev[mw[j][i]][i];
                   7557:          cens[i]= 1;
                   7558:        }else if (ageexmed[i]< 1) 
                   7559:          cens[i]= -1;
                   7560:        if (agedc[i]< AGESUP && agedc[i]>1 && dcwave[i]>firstpass && dcwave[i]<=lastpass)
                   7561:          cens[i]=0 ;
                   7562:       }
                   7563:       else cens[i]=-1;
                   7564:     }
                   7565:     
                   7566:     for (i=1;i<=NDIM;i++) {
                   7567:       for (j=1;j<=NDIM;j++)
                   7568:        ximort[i][j]=(i == j ? 1.0 : 0.0);
                   7569:     }
                   7570:     
1.145     brouard  7571:     /*p[1]=0.0268; p[NDIM]=0.083;*/
1.126     brouard  7572:     /*printf("%lf %lf", p[1], p[2]);*/
                   7573:     
                   7574:     
1.136     brouard  7575: #ifdef GSL
                   7576:     printf("GSL optimization\n");  fprintf(ficlog,"Powell\n");
1.162     brouard  7577: #else
1.126     brouard  7578:     printf("Powell\n");  fprintf(ficlog,"Powell\n");
1.136     brouard  7579: #endif
1.201     brouard  7580:     strcpy(filerespow,"POW-MORT_"); 
                   7581:     strcat(filerespow,fileresu);
1.126     brouard  7582:     if((ficrespow=fopen(filerespow,"w"))==NULL) {
                   7583:       printf("Problem with resultfile: %s\n", filerespow);
                   7584:       fprintf(ficlog,"Problem with resultfile: %s\n", filerespow);
                   7585:     }
1.136     brouard  7586: #ifdef GSL
                   7587:     fprintf(ficrespow,"# GSL optimization\n# iter -2*LL");
1.162     brouard  7588: #else
1.126     brouard  7589:     fprintf(ficrespow,"# Powell\n# iter -2*LL");
1.136     brouard  7590: #endif
1.126     brouard  7591:     /*  for (i=1;i<=nlstate;i++)
                   7592:        for(j=1;j<=nlstate+ndeath;j++)
                   7593:        if(j!=i)fprintf(ficrespow," p%1d%1d",i,j);
                   7594:     */
                   7595:     fprintf(ficrespow,"\n");
1.136     brouard  7596: #ifdef GSL
                   7597:     /* gsl starts here */ 
                   7598:     T = gsl_multimin_fminimizer_nmsimplex;
                   7599:     gsl_multimin_fminimizer *sfm = NULL;
                   7600:     gsl_vector *ss, *x;
                   7601:     gsl_multimin_function minex_func;
                   7602: 
                   7603:     /* Initial vertex size vector */
                   7604:     ss = gsl_vector_alloc (NDIM);
                   7605:     
                   7606:     if (ss == NULL){
                   7607:       GSL_ERROR_VAL ("failed to allocate space for ss", GSL_ENOMEM, 0);
                   7608:     }
                   7609:     /* Set all step sizes to 1 */
                   7610:     gsl_vector_set_all (ss, 0.001);
                   7611: 
                   7612:     /* Starting point */
1.126     brouard  7613:     
1.136     brouard  7614:     x = gsl_vector_alloc (NDIM);
                   7615:     
                   7616:     if (x == NULL){
                   7617:       gsl_vector_free(ss);
                   7618:       GSL_ERROR_VAL ("failed to allocate space for x", GSL_ENOMEM, 0);
                   7619:     }
                   7620:   
                   7621:     /* Initialize method and iterate */
                   7622:     /*     p[1]=0.0268; p[NDIM]=0.083; */
1.186     brouard  7623:     /*     gsl_vector_set(x, 0, 0.0268); */
                   7624:     /*     gsl_vector_set(x, 1, 0.083); */
1.136     brouard  7625:     gsl_vector_set(x, 0, p[1]);
                   7626:     gsl_vector_set(x, 1, p[2]);
                   7627: 
                   7628:     minex_func.f = &gompertz_f;
                   7629:     minex_func.n = NDIM;
                   7630:     minex_func.params = (void *)&p; /* ??? */
                   7631:     
                   7632:     sfm = gsl_multimin_fminimizer_alloc (T, NDIM);
                   7633:     gsl_multimin_fminimizer_set (sfm, &minex_func, x, ss);
                   7634:     
                   7635:     printf("Iterations beginning .....\n\n");
                   7636:     printf("Iter. #    Intercept       Slope     -Log Likelihood     Simplex size\n");
                   7637: 
                   7638:     iteri=0;
                   7639:     while (rval == GSL_CONTINUE){
                   7640:       iteri++;
                   7641:       status = gsl_multimin_fminimizer_iterate(sfm);
                   7642:       
                   7643:       if (status) printf("error: %s\n", gsl_strerror (status));
                   7644:       fflush(0);
                   7645:       
                   7646:       if (status) 
                   7647:         break;
                   7648:       
                   7649:       rval = gsl_multimin_test_size (gsl_multimin_fminimizer_size (sfm), 1e-6);
                   7650:       ssval = gsl_multimin_fminimizer_size (sfm);
                   7651:       
                   7652:       if (rval == GSL_SUCCESS)
                   7653:         printf ("converged to a local maximum at\n");
                   7654:       
                   7655:       printf("%5d ", iteri);
                   7656:       for (it = 0; it < NDIM; it++){
                   7657:        printf ("%10.5f ", gsl_vector_get (sfm->x, it));
                   7658:       }
                   7659:       printf("f() = %-10.5f ssize = %.7f\n", sfm->fval, ssval);
                   7660:     }
                   7661:     
                   7662:     printf("\n\n Please note: Program should be run many times with varying starting points to detemine global maximum\n\n");
                   7663:     
                   7664:     gsl_vector_free(x); /* initial values */
                   7665:     gsl_vector_free(ss); /* inital step size */
                   7666:     for (it=0; it<NDIM; it++){
                   7667:       p[it+1]=gsl_vector_get(sfm->x,it);
                   7668:       fprintf(ficrespow," %.12lf", p[it]);
                   7669:     }
                   7670:     gsl_multimin_fminimizer_free (sfm); /* p *(sfm.x.data) et p *(sfm.x.data+1)  */
                   7671: #endif
                   7672: #ifdef POWELL
                   7673:      powell(p,ximort,NDIM,ftol,&iter,&fret,gompertz);
                   7674: #endif  
1.126     brouard  7675:     fclose(ficrespow);
                   7676:     
1.203     brouard  7677:     hesscov(matcov, hess, p, NDIM, delti, 1e-4, gompertz); 
1.126     brouard  7678: 
                   7679:     for(i=1; i <=NDIM; i++)
                   7680:       for(j=i+1;j<=NDIM;j++)
                   7681:        matcov[i][j]=matcov[j][i];
                   7682:     
                   7683:     printf("\nCovariance matrix\n ");
1.203     brouard  7684:     fprintf(ficlog,"\nCovariance matrix\n ");
1.126     brouard  7685:     for(i=1; i <=NDIM; i++) {
                   7686:       for(j=1;j<=NDIM;j++){ 
                   7687:        printf("%f ",matcov[i][j]);
1.203     brouard  7688:        fprintf(ficlog,"%f ",matcov[i][j]);
1.126     brouard  7689:       }
1.203     brouard  7690:       printf("\n ");  fprintf(ficlog,"\n ");
1.126     brouard  7691:     }
                   7692:     
                   7693:     printf("iter=%d MLE=%f Eq=%lf*exp(%lf*(age-%d))\n",iter,-gompertz(p),p[1],p[2],agegomp);
1.193     brouard  7694:     for (i=1;i<=NDIM;i++) {
1.126     brouard  7695:       printf("%f [%f ; %f]\n",p[i],p[i]-2*sqrt(matcov[i][i]),p[i]+2*sqrt(matcov[i][i]));
1.193     brouard  7696:       fprintf(ficlog,"%f [%f ; %f]\n",p[i],p[i]-2*sqrt(matcov[i][i]),p[i]+2*sqrt(matcov[i][i]));
                   7697:     }
1.126     brouard  7698:     lsurv=vector(1,AGESUP);
                   7699:     lpop=vector(1,AGESUP);
                   7700:     tpop=vector(1,AGESUP);
                   7701:     lsurv[agegomp]=100000;
                   7702:     
                   7703:     for (k=agegomp;k<=AGESUP;k++) {
                   7704:       agemortsup=k;
                   7705:       if (p[1]*exp(p[2]*(k-agegomp))>1) break;
                   7706:     }
                   7707:     
                   7708:     for (k=agegomp;k<agemortsup;k++)
                   7709:       lsurv[k+1]=lsurv[k]-lsurv[k]*(p[1]*exp(p[2]*(k-agegomp)));
                   7710:     
                   7711:     for (k=agegomp;k<agemortsup;k++){
                   7712:       lpop[k]=(lsurv[k]+lsurv[k+1])/2.;
                   7713:       sumlpop=sumlpop+lpop[k];
                   7714:     }
                   7715:     
                   7716:     tpop[agegomp]=sumlpop;
                   7717:     for (k=agegomp;k<(agemortsup-3);k++){
                   7718:       /*  tpop[k+1]=2;*/
                   7719:       tpop[k+1]=tpop[k]-lpop[k];
                   7720:     }
                   7721:     
                   7722:     
                   7723:     printf("\nAge   lx     qx    dx    Lx     Tx     e(x)\n");
                   7724:     for (k=agegomp;k<(agemortsup-2);k++) 
                   7725:       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]);
                   7726:     
                   7727:     
                   7728:     replace_back_to_slash(pathc,pathcd); /* Even gnuplot wants a / */
1.194     brouard  7729:     if(ageminpar == AGEOVERFLOW ||agemaxpar == AGEOVERFLOW){
                   7730:        printf("Warning! Error in gnuplot file with ageminpar %f or agemaxpar %f overflow\n\
                   7731: This is probably because your parameter file doesn't \n  contain the exact number of lines (or columns) corresponding to your model line.\n\
                   7732: Please run with mle=-1 to get a correct covariance matrix.\n",ageminpar,agemaxpar);
                   7733:        fprintf(ficlog,"Warning! Error in gnuplot file with ageminpar %f or agemaxpar %f overflow\n\
                   7734: This is probably because your parameter file doesn't \n  contain the exact number of lines (or columns) corresponding to your model line.\n\
                   7735: Please run with mle=-1 to get a correct covariance matrix.\n",ageminpar,agemaxpar);
                   7736:     }else
1.201     brouard  7737:       printinggnuplotmort(fileresu, optionfilefiname,ageminpar,agemaxpar,fage, pathc,p);
                   7738:     printinghtmlmort(fileresu,title,datafile, firstpass, lastpass, \
1.126     brouard  7739:                     stepm, weightopt,\
                   7740:                     model,imx,p,matcov,agemortsup);
                   7741:     
                   7742:     free_vector(lsurv,1,AGESUP);
                   7743:     free_vector(lpop,1,AGESUP);
                   7744:     free_vector(tpop,1,AGESUP);
1.136     brouard  7745: #ifdef GSL
                   7746:     free_ivector(cens,1,n);
                   7747:     free_vector(agecens,1,n);
                   7748:     free_ivector(dcwave,1,n);
                   7749:     free_matrix(ximort,1,NDIM,1,NDIM);
                   7750: #endif
1.186     brouard  7751:   } /* Endof if mle==-3 mortality only */
1.205     brouard  7752:   /* Standard  */
                   7753:   else{ /* For mle !=- 3, could be 0 or 1 or 4 etc. */
                   7754:     globpr=0;/* Computes sum of likelihood for globpr=1 and funcone */
                   7755:     /* Computes likelihood for initial parameters, uses funcone to compute gpimx and gsw */
1.132     brouard  7756:     likelione(ficres, p, npar, nlstate, &globpr, &ipmx, &sw, &fretone, funcone); /* Prints the contributions to the likelihood */
1.126     brouard  7757:     printf("First Likeli=%12.6f ipmx=%ld sw=%12.6f",fretone,ipmx,sw);
                   7758:     for (k=1; k<=npar;k++)
                   7759:       printf(" %d %8.5f",k,p[k]);
                   7760:     printf("\n");
1.205     brouard  7761:     if(mle>=1){ /* Could be 1 or 2, Real Maximization */
                   7762:       /* mlikeli uses func not funcone */
                   7763:       mlikeli(ficres,p, npar, ncovmodel, nlstate, ftol, func);
                   7764:     }
                   7765:     if(mle==0) {/* No optimization, will print the likelihoods for the datafile */
                   7766:       globpr=0;/* Computes sum of likelihood for globpr=1 and funcone */
                   7767:       /* Computes likelihood for initial parameters, uses funcone to compute gpimx and gsw */
                   7768:       likelione(ficres, p, npar, nlstate, &globpr, &ipmx, &sw, &fretone, funcone); /* Prints the contributions to the likelihood */
                   7769:     }
                   7770:     globpr=1; /* again, to print the individual contributions using computed gpimx and gsw */
1.126     brouard  7771:     likelione(ficres, p, npar, nlstate, &globpr, &ipmx, &sw, &fretone, funcone); /* Prints the contributions to the likelihood */
                   7772:     printf("Second Likeli=%12.6f ipmx=%ld sw=%12.6f",fretone,ipmx,sw);
                   7773:     for (k=1; k<=npar;k++)
                   7774:       printf(" %d %8.5f",k,p[k]);
                   7775:     printf("\n");
                   7776:     
                   7777:     /*--------- results files --------------*/
1.192     brouard  7778:     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  7779:     
                   7780:     
                   7781:     fprintf(ficres,"# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
                   7782:     printf("# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
                   7783:     fprintf(ficlog,"# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
                   7784:     for(i=1,jk=1; i <=nlstate; i++){
                   7785:       for(k=1; k <=(nlstate+ndeath); k++){
                   7786:        if (k != i) {
                   7787:          printf("%d%d ",i,k);
                   7788:          fprintf(ficlog,"%d%d ",i,k);
                   7789:          fprintf(ficres,"%1d%1d ",i,k);
                   7790:          for(j=1; j <=ncovmodel; j++){
1.190     brouard  7791:            printf("%12.7f ",p[jk]);
                   7792:            fprintf(ficlog,"%12.7f ",p[jk]);
                   7793:            fprintf(ficres,"%12.7f ",p[jk]);
1.126     brouard  7794:            jk++; 
                   7795:          }
                   7796:          printf("\n");
                   7797:          fprintf(ficlog,"\n");
                   7798:          fprintf(ficres,"\n");
                   7799:        }
                   7800:       }
                   7801:     }
1.203     brouard  7802:     if(mle != 0){
                   7803:       /* Computing hessian and covariance matrix only at a peak of the Likelihood, that is after optimization */
1.126     brouard  7804:       ftolhess=ftol; /* Usually correct */
1.203     brouard  7805:       hesscov(matcov, hess, p, npar, delti, ftolhess, func);
                   7806:       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");
                   7807:       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");
                   7808:       for(i=1,jk=1; i <=nlstate; i++){
                   7809:        for(k=1; k <=(nlstate+ndeath); k++){
                   7810:          if (k != i) {
                   7811:            printf("%d%d ",i,k);
                   7812:            fprintf(ficlog,"%d%d ",i,k);
                   7813:            for(j=1; j <=ncovmodel; j++){
                   7814:              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]));
                   7815:              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]));
                   7816:              jk++; 
                   7817:            }
                   7818:            printf("\n");
                   7819:            fprintf(ficlog,"\n");
1.193     brouard  7820:          }
                   7821:        }
                   7822:       }
1.203     brouard  7823:     } /* end of hesscov and Wald tests */
1.193     brouard  7824: 
1.203     brouard  7825:     /*  */
1.126     brouard  7826:     fprintf(ficres,"# Scales (for hessian or gradient estimation)\n");
                   7827:     printf("# Scales (for hessian or gradient estimation)\n");
                   7828:     fprintf(ficlog,"# Scales (for hessian or gradient estimation)\n");
                   7829:     for(i=1,jk=1; i <=nlstate; i++){
                   7830:       for(j=1; j <=nlstate+ndeath; j++){
                   7831:        if (j!=i) {
                   7832:          fprintf(ficres,"%1d%1d",i,j);
                   7833:          printf("%1d%1d",i,j);
                   7834:          fprintf(ficlog,"%1d%1d",i,j);
                   7835:          for(k=1; k<=ncovmodel;k++){
                   7836:            printf(" %.5e",delti[jk]);
                   7837:            fprintf(ficlog," %.5e",delti[jk]);
                   7838:            fprintf(ficres," %.5e",delti[jk]);
                   7839:            jk++;
                   7840:          }
                   7841:          printf("\n");
                   7842:          fprintf(ficlog,"\n");
                   7843:          fprintf(ficres,"\n");
                   7844:        }
                   7845:       }
                   7846:     }
                   7847:     
                   7848:     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");
1.203     brouard  7849:     if(mle >= 1) /* To big for the screen */
1.126     brouard  7850:       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");
                   7851:     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");
                   7852:     /* # 121 Var(a12)\n\ */
                   7853:     /* # 122 Cov(b12,a12) Var(b12)\n\ */
                   7854:     /* # 131 Cov(a13,a12) Cov(a13,b12, Var(a13)\n\ */
                   7855:     /* # 132 Cov(b13,a12) Cov(b13,b12, Cov(b13,a13) Var(b13)\n\ */
                   7856:     /* # 212 Cov(a21,a12) Cov(a21,b12, Cov(a21,a13) Cov(a21,b13) Var(a21)\n\ */
                   7857:     /* # 212 Cov(b21,a12) Cov(b21,b12, Cov(b21,a13) Cov(b21,b13) Cov(b21,a21) Var(b21)\n\ */
                   7858:     /* # 232 Cov(a23,a12) Cov(a23,b12, Cov(a23,a13) Cov(a23,b13) Cov(a23,a21) Cov(a23,b21) Var(a23)\n\ */
                   7859:     /* # 232 Cov(b23,a12) Cov(b23,b12) ... Var (b23)\n" */
                   7860:     
                   7861:     
                   7862:     /* Just to have a covariance matrix which will be more understandable
                   7863:        even is we still don't want to manage dictionary of variables
                   7864:     */
                   7865:     for(itimes=1;itimes<=2;itimes++){
                   7866:       jj=0;
                   7867:       for(i=1; i <=nlstate; i++){
                   7868:        for(j=1; j <=nlstate+ndeath; j++){
                   7869:          if(j==i) continue;
                   7870:          for(k=1; k<=ncovmodel;k++){
                   7871:            jj++;
                   7872:            ca[0]= k+'a'-1;ca[1]='\0';
                   7873:            if(itimes==1){
                   7874:              if(mle>=1)
                   7875:                printf("#%1d%1d%d",i,j,k);
                   7876:              fprintf(ficlog,"#%1d%1d%d",i,j,k);
                   7877:              fprintf(ficres,"#%1d%1d%d",i,j,k);
                   7878:            }else{
                   7879:              if(mle>=1)
                   7880:                printf("%1d%1d%d",i,j,k);
                   7881:              fprintf(ficlog,"%1d%1d%d",i,j,k);
                   7882:              fprintf(ficres,"%1d%1d%d",i,j,k);
                   7883:            }
                   7884:            ll=0;
                   7885:            for(li=1;li <=nlstate; li++){
                   7886:              for(lj=1;lj <=nlstate+ndeath; lj++){
                   7887:                if(lj==li) continue;
                   7888:                for(lk=1;lk<=ncovmodel;lk++){
                   7889:                  ll++;
                   7890:                  if(ll<=jj){
                   7891:                    cb[0]= lk +'a'-1;cb[1]='\0';
                   7892:                    if(ll<jj){
                   7893:                      if(itimes==1){
                   7894:                        if(mle>=1)
                   7895:                          printf(" Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
                   7896:                        fprintf(ficlog," Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
                   7897:                        fprintf(ficres," Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
                   7898:                      }else{
                   7899:                        if(mle>=1)
                   7900:                          printf(" %.5e",matcov[jj][ll]); 
                   7901:                        fprintf(ficlog," %.5e",matcov[jj][ll]); 
                   7902:                        fprintf(ficres," %.5e",matcov[jj][ll]); 
                   7903:                      }
                   7904:                    }else{
                   7905:                      if(itimes==1){
                   7906:                        if(mle>=1)
                   7907:                          printf(" Var(%s%1d%1d)",ca,i,j);
                   7908:                        fprintf(ficlog," Var(%s%1d%1d)",ca,i,j);
                   7909:                        fprintf(ficres," Var(%s%1d%1d)",ca,i,j);
                   7910:                      }else{
                   7911:                        if(mle>=1)
1.203     brouard  7912:                          printf(" %.7e",matcov[jj][ll]); 
                   7913:                        fprintf(ficlog," %.7e",matcov[jj][ll]); 
                   7914:                        fprintf(ficres," %.7e",matcov[jj][ll]); 
1.126     brouard  7915:                      }
                   7916:                    }
                   7917:                  }
                   7918:                } /* end lk */
                   7919:              } /* end lj */
                   7920:            } /* end li */
                   7921:            if(mle>=1)
                   7922:              printf("\n");
                   7923:            fprintf(ficlog,"\n");
                   7924:            fprintf(ficres,"\n");
                   7925:            numlinepar++;
                   7926:          } /* end k*/
                   7927:        } /*end j */
                   7928:       } /* end i */
                   7929:     } /* end itimes */
                   7930:     
                   7931:     fflush(ficlog);
                   7932:     fflush(ficres);
1.209   ! brouard  7933:       while(fgets(line, MAXLINE, ficpar)) {
        !          7934:     /* If line starts with a # it is a comment */
        !          7935:     if (line[0] == '#') {
        !          7936:       numlinepar++;
1.141     brouard  7937:       fputs(line,stdout);
1.126     brouard  7938:       fputs(line,ficparo);
1.209   ! brouard  7939:       fputs(line,ficlog);
        !          7940:       continue;
        !          7941:     }else
        !          7942:       break;
        !          7943:   }
        !          7944: 
        !          7945:     /* while((c=getc(ficpar))=='#' && c!= EOF){ */
        !          7946:     /*   ungetc(c,ficpar); */
        !          7947:     /*   fgets(line, MAXLINE, ficpar); */
        !          7948:     /*   fputs(line,stdout); */
        !          7949:     /*   fputs(line,ficparo); */
        !          7950:     /* } */
        !          7951:     /* ungetc(c,ficpar); */
1.126     brouard  7952:     
                   7953:     estepm=0;
1.209   ! brouard  7954:     if((num_filled=sscanf(line,"agemin=%lf agemax=%lf bage=%lf fage=%lf estepm=%d ftolpl=%lf\n",&ageminpar,&agemaxpar, &bage, &fage, &estepm, &ftolpl)) !=EOF){
        !          7955: 
        !          7956:     if (num_filled != 6) {
        !          7957:       printf("Not 6 parameters in line, for example:agemin=60 agemax=95 bage=55 fage=95 estepm=24 ftolpl=6e-4\n");
        !          7958:       printf("but line=%s\n",line);
        !          7959:       goto end;
        !          7960:     }
        !          7961:     printf("agemin=%lf agemax=%lf bage=%lf fage=%lf estepm=%d ftolpl=%lf\n",ageminpar,agemaxpar, bage, fage, estepm, ftolpl);
        !          7962:   }
        !          7963:   /* ftolpl=6*ftol*1.e5; /\* 6.e-3 make convergences in less than 80 loops for the prevalence limit *\/ */
        !          7964:   /*ftolpl=6.e-4;*/ /* 6.e-3 make convergences in less than 80 loops for the prevalence limit */
        !          7965: 
        !          7966:     /* fscanf(ficpar,"agemin=%lf agemax=%lf bage=%lf fage=%lf estepm=%d ftolpl=%\n",&ageminpar,&agemaxpar, &bage, &fage, &estepm); */
1.126     brouard  7967:     if (estepm==0 || estepm < stepm) estepm=stepm;
                   7968:     if (fage <= 2) {
                   7969:       bage = ageminpar;
                   7970:       fage = agemaxpar;
                   7971:     }
                   7972:     
                   7973:     fprintf(ficres,"# agemin agemax for life expectancy, bage fage (if mle==0 ie no data nor Max likelihood).\n");
                   7974:     fprintf(ficres,"agemin=%.0f agemax=%.0f bage=%.0f fage=%.0f estepm=%d\n",ageminpar,agemaxpar,bage,fage, estepm);
                   7975:     fprintf(ficparo,"agemin=%.0f agemax=%.0f bage=%.0f fage=%.0f estepm=%d\n",ageminpar,agemaxpar,bage,fage, estepm);
1.186     brouard  7976: 
                   7977:     /* Other stuffs, more or less useful */    
1.126     brouard  7978:     while((c=getc(ficpar))=='#' && c!= EOF){
                   7979:       ungetc(c,ficpar);
                   7980:       fgets(line, MAXLINE, ficpar);
1.141     brouard  7981:       fputs(line,stdout);
1.126     brouard  7982:       fputs(line,ficparo);
                   7983:     }
                   7984:     ungetc(c,ficpar);
                   7985:     
                   7986:     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);
                   7987:     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);
                   7988:     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);
                   7989:     printf("begin-prev-date=%.lf/%.lf/%.lf end-prev-date=%.lf/%.lf/%.lf mov_average=%d\n",jprev1, mprev1,anprev1,jprev2, mprev2,anprev2,mobilav);
                   7990:     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);
                   7991:     
                   7992:     while((c=getc(ficpar))=='#' && c!= EOF){
                   7993:       ungetc(c,ficpar);
                   7994:       fgets(line, MAXLINE, ficpar);
1.141     brouard  7995:       fputs(line,stdout);
1.126     brouard  7996:       fputs(line,ficparo);
                   7997:     }
                   7998:     ungetc(c,ficpar);
                   7999:     
                   8000:     
                   8001:     dateprev1=anprev1+(mprev1-1)/12.+(jprev1-1)/365.;
                   8002:     dateprev2=anprev2+(mprev2-1)/12.+(jprev2-1)/365.;
                   8003:     
                   8004:     fscanf(ficpar,"pop_based=%d\n",&popbased);
1.193     brouard  8005:     fprintf(ficlog,"pop_based=%d\n",popbased);
1.126     brouard  8006:     fprintf(ficparo,"pop_based=%d\n",popbased);   
                   8007:     fprintf(ficres,"pop_based=%d\n",popbased);   
                   8008:     
                   8009:     while((c=getc(ficpar))=='#' && c!= EOF){
                   8010:       ungetc(c,ficpar);
                   8011:       fgets(line, MAXLINE, ficpar);
1.141     brouard  8012:       fputs(line,stdout);
1.126     brouard  8013:       fputs(line,ficparo);
                   8014:     }
                   8015:     ungetc(c,ficpar);
                   8016:     
                   8017:     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);
                   8018:     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);
                   8019:     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);
                   8020:     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);
                   8021:     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);
                   8022:     /* day and month of proj2 are not used but only year anproj2.*/
                   8023:     
                   8024:     
                   8025:     
1.145     brouard  8026:      /* freqsummary(fileres, agemin, agemax, s, agev, nlstate, imx,Tvaraff,nbcode, ncodemax,mint,anint); */
                   8027:     /* ,dateprev1,dateprev2,jprev1, mprev1,anprev1,jprev2, mprev2,anprev2); */
1.126     brouard  8028:     
                   8029:     replace_back_to_slash(pathc,pathcd); /* Even gnuplot wants a / */
1.194     brouard  8030:     if(ageminpar == AGEOVERFLOW ||agemaxpar == -AGEOVERFLOW){
                   8031:        printf("Warning! Error in gnuplot file with ageminpar %f or agemaxpar %f overflow\n\
                   8032: This is probably because your parameter file doesn't \n  contain the exact number of lines (or columns) corresponding to your model line.\n\
                   8033: Please run with mle=-1 to get a correct covariance matrix.\n",ageminpar,agemaxpar);
                   8034:        fprintf(ficlog,"Warning! Error in gnuplot file with ageminpar %f or agemaxpar %f overflow\n\
                   8035: This is probably because your parameter file doesn't \n  contain the exact number of lines (or columns) corresponding to your model line.\n\
                   8036: Please run with mle=-1 to get a correct covariance matrix.\n",ageminpar,agemaxpar);
                   8037:     }else
1.201     brouard  8038:       printinggnuplot(fileresu, optionfilefiname,ageminpar,agemaxpar,fage, pathc,p);
1.126     brouard  8039:     
1.201     brouard  8040:     printinghtml(fileresu,title,datafile, firstpass, lastpass, stepm, weightopt,\
1.126     brouard  8041:                 model,imx,jmin,jmax,jmean,rfileres,popforecast,estepm,\
                   8042:                 jprev1,mprev1,anprev1,jprev2,mprev2,anprev2);
                   8043:       
                   8044:    /*------------ free_vector  -------------*/
                   8045:    /*  chdir(path); */
                   8046:  
                   8047:     free_ivector(wav,1,imx);
                   8048:     free_imatrix(dh,1,lastpass-firstpass+1,1,imx);
                   8049:     free_imatrix(bh,1,lastpass-firstpass+1,1,imx);
                   8050:     free_imatrix(mw,1,lastpass-firstpass+1,1,imx);   
                   8051:     free_lvector(num,1,n);
                   8052:     free_vector(agedc,1,n);
                   8053:     /*free_matrix(covar,0,NCOVMAX,1,n);*/
                   8054:     /*free_matrix(covar,1,NCOVMAX,1,n);*/
                   8055:     fclose(ficparo);
                   8056:     fclose(ficres);
                   8057: 
                   8058: 
1.186     brouard  8059:     /* Other results (useful)*/
                   8060: 
                   8061: 
1.126     brouard  8062:     /*--------------- Prevalence limit  (period or stable prevalence) --------------*/
1.180     brouard  8063:     /*#include "prevlim.h"*/  /* Use ficrespl, ficlog */
                   8064:     prlim=matrix(1,nlstate,1,nlstate);
1.209   ! brouard  8065:     prevalence_limit(p, prlim,  ageminpar, agemaxpar, ftolpl, &ncvyear);
1.126     brouard  8066:     fclose(ficrespl);
                   8067: 
1.145     brouard  8068: #ifdef FREEEXIT2
                   8069: #include "freeexit2.h"
                   8070: #endif
                   8071: 
1.126     brouard  8072:     /*------------- h Pij x at various ages ------------*/
1.180     brouard  8073:     /*#include "hpijx.h"*/
                   8074:     hPijx(p, bage, fage);
1.145     brouard  8075:     fclose(ficrespij);
1.126     brouard  8076: 
1.145     brouard  8077:   /*-------------- Variance of one-step probabilities---*/
                   8078:     k=1;
1.126     brouard  8079:     varprob(optionfilefiname, matcov, p, delti, nlstate, bage, fage,k,Tvar,nbcode, ncodemax,strstart);
                   8080: 
                   8081: 
                   8082:     probs= ma3x(1,AGESUP,1,NCOVMAX, 1,NCOVMAX);
                   8083:     for(i=1;i<=AGESUP;i++)
                   8084:       for(j=1;j<=NCOVMAX;j++)
                   8085:        for(k=1;k<=NCOVMAX;k++)
                   8086:          probs[i][j][k]=0.;
                   8087: 
                   8088:     /*---------- Forecasting ------------------*/
                   8089:     /*if((stepm == 1) && (strcmp(model,".")==0)){*/
                   8090:     if(prevfcast==1){
                   8091:       /*    if(stepm ==1){*/
1.201     brouard  8092:       prevforecast(fileresu, anproj1, mproj1, jproj1, agemin, agemax, dateprev1, dateprev2, mobilavproj, bage, fage, firstpass, lastpass, anproj2, p, cptcoveff);
1.126     brouard  8093:       /* (popforecast==1) populforecast(fileres, anpyram,mpyram,jpyram, agemin,agemax, dateprev1, dateprev2,mobilav, agedeb, fage, popforecast, popfile, anpyram1,p, i1);*/
                   8094:       /*      }  */
                   8095:       /*      else{ */
                   8096:       /*        erreur=108; */
                   8097:       /*        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); */
                   8098:       /*        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); */
                   8099:       /*      } */
                   8100:     }
1.186     brouard  8101:  
                   8102:     /* ------ Other prevalence ratios------------ */
1.126     brouard  8103: 
1.127     brouard  8104:     /* Computes prevalence between agemin (i.e minimal age computed) and no more ageminpar */
                   8105: 
                   8106:     prevalence(probs, agemin, agemax, s, agev, nlstate, imx, Tvar, nbcode, ncodemax, mint, anint, dateprev1, dateprev2, firstpass, lastpass);
                   8107:     /*  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",\
                   8108:        ageminpar, agemax, s[lastpass][imx], agev[lastpass][imx], nlstate, imx, mint[lastpass][imx],anint[lastpass][imx], dateprev1, dateprev2, firstpass, lastpass);
                   8109:     */
1.126     brouard  8110: 
1.127     brouard  8111:     if (mobilav!=0) {
                   8112:       mobaverage= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
                   8113:       if (movingaverage(probs, bage, fage, mobaverage,mobilav)!=0){
                   8114:        fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav);
                   8115:        printf(" Error in movingaverage mobilav=%d\n",mobilav);
                   8116:       }
1.126     brouard  8117:     }
                   8118: 
                   8119: 
1.127     brouard  8120:     /*---------- Health expectancies, no variances ------------*/
                   8121: 
1.201     brouard  8122:     strcpy(filerese,"E_");
                   8123:     strcat(filerese,fileresu);
1.126     brouard  8124:     if((ficreseij=fopen(filerese,"w"))==NULL) {
                   8125:       printf("Problem with Health Exp. resultfile: %s\n", filerese); exit(0);
                   8126:       fprintf(ficlog,"Problem with Health Exp. resultfile: %s\n", filerese); exit(0);
                   8127:     }
1.208     brouard  8128:     printf("Computing Health Expectancies: result on file '%s' ...", filerese);fflush(stdout);
                   8129:     fprintf(ficlog,"Computing Health Expectancies: result on file '%s' ...", filerese);fflush(ficlog);
1.145     brouard  8130:     /*for(cptcov=1,k=0;cptcov<=i1;cptcov++){
                   8131:       for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){*/
                   8132:           
                   8133:     for (k=1; k <= (int) pow(2,cptcoveff); k++){
1.127     brouard  8134:        fprintf(ficreseij,"\n#****** ");
                   8135:        for(j=1;j<=cptcoveff;j++) {
1.200     brouard  8136:          fprintf(ficreseij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
1.127     brouard  8137:        }
                   8138:        fprintf(ficreseij,"******\n");
                   8139: 
                   8140:        eij=ma3x(1,nlstate,1,nlstate,(int) bage, (int) fage);
                   8141:        oldm=oldms;savm=savms;
                   8142:        evsij(eij, p, nlstate, stepm, (int) bage, (int)fage, oldm, savm, k, estepm, strstart);  
                   8143:       
                   8144:        free_ma3x(eij,1,nlstate,1,nlstate,(int) bage, (int)fage);
1.145     brouard  8145:       /*}*/
1.127     brouard  8146:     }
                   8147:     fclose(ficreseij);
1.208     brouard  8148:     printf("done evsij\n");fflush(stdout);
                   8149:     fprintf(ficlog,"done evsij\n");fflush(ficlog);
1.127     brouard  8150: 
                   8151:     /*---------- Health expectancies and variances ------------*/
                   8152: 
                   8153: 
1.201     brouard  8154:     strcpy(filerest,"T_");
                   8155:     strcat(filerest,fileresu);
1.127     brouard  8156:     if((ficrest=fopen(filerest,"w"))==NULL) {
                   8157:       printf("Problem with total LE resultfile: %s\n", filerest);goto end;
                   8158:       fprintf(ficlog,"Problem with total LE resultfile: %s\n", filerest);goto end;
                   8159:     }
1.208     brouard  8160:     printf("Computing Total Life expectancies with their standard errors: file '%s' ...\n", filerest); fflush(stdout);
                   8161:     fprintf(ficlog,"Computing Total Life expectancies with their standard errors: file '%s' ...\n", filerest); fflush(ficlog);
1.127     brouard  8162: 
1.126     brouard  8163: 
1.201     brouard  8164:     strcpy(fileresstde,"STDE_");
                   8165:     strcat(fileresstde,fileresu);
1.126     brouard  8166:     if((ficresstdeij=fopen(fileresstde,"w"))==NULL) {
                   8167:       printf("Problem with Health Exp. and std errors resultfile: %s\n", fileresstde); exit(0);
                   8168:       fprintf(ficlog,"Problem with Health Exp. and std errors resultfile: %s\n", fileresstde); exit(0);
                   8169:     }
1.208     brouard  8170:     printf("  Computing Health Expectancies and standard errors: result on file '%s' \n", fileresstde);
                   8171:     fprintf(ficlog,"  Computing Health Expectancies and standard errors: result on file '%s' \n", fileresstde);
1.126     brouard  8172: 
1.201     brouard  8173:     strcpy(filerescve,"CVE_");
                   8174:     strcat(filerescve,fileresu);
1.126     brouard  8175:     if((ficrescveij=fopen(filerescve,"w"))==NULL) {
                   8176:       printf("Problem with Covar. Health Exp. resultfile: %s\n", filerescve); exit(0);
                   8177:       fprintf(ficlog,"Problem with Covar. Health Exp. resultfile: %s\n", filerescve); exit(0);
                   8178:     }
1.208     brouard  8179:     printf("    Computing Covar. of Health Expectancies: result on file '%s' \n", filerescve);
                   8180:     fprintf(ficlog,"    Computing Covar. of Health Expectancies: result on file '%s' \n", filerescve);
1.126     brouard  8181: 
1.201     brouard  8182:     strcpy(fileresv,"V_");
                   8183:     strcat(fileresv,fileresu);
1.126     brouard  8184:     if((ficresvij=fopen(fileresv,"w"))==NULL) {
                   8185:       printf("Problem with variance resultfile: %s\n", fileresv);exit(0);
                   8186:       fprintf(ficlog,"Problem with variance resultfile: %s\n", fileresv);exit(0);
                   8187:     }
1.208     brouard  8188:     printf("      Computing Variance-covariance of DFLEs: file '%s' ... ", fileresv);fflush(stdout);
                   8189:     fprintf(ficlog,"      Computing Variance-covariance of DFLEs: file '%s' ... ", fileresv);fflush(ficlog);
1.126     brouard  8190: 
1.145     brouard  8191:     /*for(cptcov=1,k=0;cptcov<=i1;cptcov++){
                   8192:       for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){*/
                   8193:           
                   8194:     for (k=1; k <= (int) pow(2,cptcoveff); k++){
1.208     brouard  8195:       fprintf(ficrest,"\n#****** ");
                   8196:       for(j=1;j<=cptcoveff;j++) 
                   8197:        fprintf(ficrest,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
                   8198:       fprintf(ficrest,"******\n");
                   8199:       
                   8200:       fprintf(ficresstdeij,"\n#****** ");
                   8201:       fprintf(ficrescveij,"\n#****** ");
                   8202:       for(j=1;j<=cptcoveff;j++) {
                   8203:        fprintf(ficresstdeij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
                   8204:        fprintf(ficrescveij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
                   8205:       }
                   8206:       fprintf(ficresstdeij,"******\n");
                   8207:       fprintf(ficrescveij,"******\n");
                   8208:       
                   8209:       fprintf(ficresvij,"\n#****** ");
                   8210:       for(j=1;j<=cptcoveff;j++) 
                   8211:        fprintf(ficresvij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
                   8212:       fprintf(ficresvij,"******\n");
                   8213:       
                   8214:       eij=ma3x(1,nlstate,1,nlstate,(int) bage, (int) fage);
                   8215:       oldm=oldms;savm=savms;
                   8216:       printf(" cvevsij %d, ",k);
                   8217:       fprintf(ficlog, " cvevsij %d, ",k);
                   8218:       cvevsij(eij, p, nlstate, stepm, (int) bage, (int)fage, oldm, savm, k, estepm, delti, matcov, strstart);
                   8219:       printf(" end cvevsij \n ");
                   8220:       fprintf(ficlog, " end cvevsij \n ");
                   8221:       
                   8222:       /*
                   8223:        */
                   8224:       /* goto endfree; */
                   8225:       
                   8226:       vareij=ma3x(1,nlstate,1,nlstate,(int) bage, (int) fage);
                   8227:       pstamp(ficrest);
                   8228:       
                   8229:       
                   8230:       for(vpopbased=0; vpopbased <= popbased; vpopbased++){ /* Done for vpopbased=0 and vpopbased=1 if popbased==1*/
                   8231:        oldm=oldms;savm=savms; /* ZZ Segmentation fault */
                   8232:        cptcod= 0; /* To be deleted */
                   8233:        printf("varevsij %d \n",vpopbased);
                   8234:        fprintf(ficlog, "varevsij %d \n",vpopbased);
1.209   ! brouard  8235:        varevsij(optionfilefiname, vareij, matcov, p, delti, nlstate, stepm, (int) bage, (int) fage, oldm, savm, prlim, ftolpl, &ncvyear, k, estepm, cptcov,cptcod,vpopbased,mobilav, strstart); /* cptcod not initialized Intel */
1.208     brouard  8236:        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 ");
                   8237:        if(vpopbased==1)
                   8238:          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);
                   8239:        else
                   8240:          fprintf(ficrest,"the age specific period (stable) prevalences in each health state \n");
                   8241:        fprintf(ficrest,"# Age popbased mobilav e.. (std) ");
                   8242:        for (i=1;i<=nlstate;i++) fprintf(ficrest,"e.%d (std) ",i);
                   8243:        fprintf(ficrest,"\n");
                   8244:        /* printf("Which p?\n"); for(i=1;i<=npar;i++)printf("p[i=%d]=%lf,",i,p[i]);printf("\n"); */
                   8245:        epj=vector(1,nlstate+1);
                   8246:        printf("Computing age specific period (stable) prevalences in each health state \n");
                   8247:        fprintf(ficlog,"Computing age specific period (stable) prevalences in each health state \n");
                   8248:        for(age=bage; age <=fage ;age++){
1.209   ! brouard  8249:          prevalim(prlim, nlstate, p, age, oldm, savm, ftolpl, &ncvyear, k); /*ZZ Is it the correct prevalim */
1.208     brouard  8250:          if (vpopbased==1) {
                   8251:            if(mobilav ==0){
                   8252:              for(i=1; i<=nlstate;i++)
                   8253:                prlim[i][i]=probs[(int)age][i][k];
                   8254:            }else{ /* mobilav */ 
                   8255:              for(i=1; i<=nlstate;i++)
                   8256:                prlim[i][i]=mobaverage[(int)age][i][k];
1.126     brouard  8257:            }
1.208     brouard  8258:          }
                   8259:          
                   8260:          fprintf(ficrest," %4.0f %d %d",age, vpopbased, mobilav);
                   8261:          /* fprintf(ficrest," %4.0f %d %d %d %d",age, vpopbased, mobilav,Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]); */ /* to be done */
                   8262:          /* printf(" age %4.0f ",age); */
                   8263:          for(j=1, epj[nlstate+1]=0.;j <=nlstate;j++){
                   8264:            for(i=1, epj[j]=0.;i <=nlstate;i++) {
                   8265:              epj[j] += prlim[i][i]*eij[i][j][(int)age];
                   8266:              /*ZZZ  printf("%lf %lf ", prlim[i][i] ,eij[i][j][(int)age]);*/
                   8267:              /* printf("%lf %lf ", prlim[i][i] ,eij[i][j][(int)age]); */
1.126     brouard  8268:            }
1.208     brouard  8269:            epj[nlstate+1] +=epj[j];
                   8270:          }
                   8271:          /* printf(" age %4.0f \n",age); */
                   8272:          
                   8273:          for(i=1, vepp=0.;i <=nlstate;i++)
                   8274:            for(j=1;j <=nlstate;j++)
                   8275:              vepp += vareij[i][j][(int)age];
                   8276:          fprintf(ficrest," %7.3f (%7.3f)", epj[nlstate+1],sqrt(vepp));
                   8277:          for(j=1;j <=nlstate;j++){
                   8278:            fprintf(ficrest," %7.3f (%7.3f)", epj[j],sqrt(vareij[j][j][(int)age]));
1.126     brouard  8279:          }
1.208     brouard  8280:          fprintf(ficrest,"\n");
1.126     brouard  8281:        }
1.208     brouard  8282:       } /* End vpopbased */
                   8283:       free_ma3x(eij,1,nlstate,1,nlstate,(int) bage, (int)fage);
                   8284:       free_ma3x(vareij,1,nlstate,1,nlstate,(int) bage, (int)fage);
                   8285:       free_vector(epj,1,nlstate+1);
                   8286:       printf("done \n");fflush(stdout);
                   8287:       fprintf(ficlog,"done\n");fflush(ficlog);
                   8288:       
1.145     brouard  8289:       /*}*/
1.208     brouard  8290:     } /* End k */
1.126     brouard  8291:     free_vector(weight,1,n);
1.145     brouard  8292:     free_imatrix(Tvard,1,NCOVMAX,1,2);
1.126     brouard  8293:     free_imatrix(s,1,maxwav+1,1,n);
                   8294:     free_matrix(anint,1,maxwav,1,n); 
                   8295:     free_matrix(mint,1,maxwav,1,n);
                   8296:     free_ivector(cod,1,n);
                   8297:     free_ivector(tab,1,NCOVMAX);
                   8298:     fclose(ficresstdeij);
                   8299:     fclose(ficrescveij);
                   8300:     fclose(ficresvij);
                   8301:     fclose(ficrest);
1.208     brouard  8302:     printf("done Health expectancies\n");fflush(stdout);
                   8303:     fprintf(ficlog,"done Health expectancies\n");fflush(ficlog);
1.126     brouard  8304:     fclose(ficpar);
                   8305:   
                   8306:     /*------- Variance of period (stable) prevalence------*/   
                   8307: 
1.201     brouard  8308:     strcpy(fileresvpl,"VPL_");
                   8309:     strcat(fileresvpl,fileresu);
1.126     brouard  8310:     if((ficresvpl=fopen(fileresvpl,"w"))==NULL) {
                   8311:       printf("Problem with variance of period (stable) prevalence  resultfile: %s\n", fileresvpl);
                   8312:       exit(0);
                   8313:     }
1.208     brouard  8314:     printf("Computing Variance-covariance of period (stable) prevalence: file '%s' ...", fileresvpl);fflush(stdout);
                   8315:     fprintf(ficlog, "Computing Variance-covariance of period (stable) prevalence: file '%s' ...", fileresvpl);fflush(ficlog);
1.126     brouard  8316: 
1.145     brouard  8317:     /*for(cptcov=1,k=0;cptcov<=i1;cptcov++){
                   8318:       for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){*/
                   8319:           
                   8320:     for (k=1; k <= (int) pow(2,cptcoveff); k++){
                   8321:        fprintf(ficresvpl,"\n#****** ");
1.126     brouard  8322:        for(j=1;j<=cptcoveff;j++) 
1.200     brouard  8323:          fprintf(ficresvpl,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
1.126     brouard  8324:        fprintf(ficresvpl,"******\n");
                   8325:       
                   8326:        varpl=matrix(1,nlstate,(int) bage, (int) fage);
                   8327:        oldm=oldms;savm=savms;
1.209   ! brouard  8328:        varprevlim(fileres, varpl, matcov, p, delti, nlstate, stepm, (int) bage, (int) fage, oldm, savm, prlim, ftolpl, &ncvyear, k, strstart);
1.126     brouard  8329:        free_matrix(varpl,1,nlstate,(int) bage, (int)fage);
1.145     brouard  8330:       /*}*/
1.126     brouard  8331:     }
                   8332: 
                   8333:     fclose(ficresvpl);
1.208     brouard  8334:     printf("done variance-covariance of period prevalence\n");fflush(stdout);
                   8335:     fprintf(ficlog,"done variance-covariance of period prevalence\n");fflush(ficlog);
1.126     brouard  8336: 
                   8337:     /*---------- End : free ----------------*/
                   8338:     if (mobilav!=0) free_ma3x(mobaverage,1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
                   8339:     free_ma3x(probs,1,AGESUP,1,NCOVMAX, 1,NCOVMAX);
                   8340:   }  /* mle==-3 arrives here for freeing */
1.164     brouard  8341:  /* endfree:*/
1.141     brouard  8342:     free_matrix(prlim,1,nlstate,1,nlstate); /*here or after loop ? */
1.126     brouard  8343:     free_matrix(pmmij,1,nlstate+ndeath,1,nlstate+ndeath);
                   8344:     free_matrix(oldms, 1,nlstate+ndeath,1,nlstate+ndeath);
                   8345:     free_matrix(newms, 1,nlstate+ndeath,1,nlstate+ndeath);
                   8346:     free_matrix(savms, 1,nlstate+ndeath,1,nlstate+ndeath);
                   8347:     free_matrix(covar,0,NCOVMAX,1,n);
                   8348:     free_matrix(matcov,1,npar,1,npar);
1.203     brouard  8349:     free_matrix(hess,1,npar,1,npar);
1.126     brouard  8350:     /*free_vector(delti,1,npar);*/
                   8351:     free_ma3x(delti3,1,nlstate,1, nlstate+ndeath-1,1,ncovmodel); 
                   8352:     free_matrix(agev,1,maxwav,1,imx);
                   8353:     free_ma3x(param,1,nlstate,1, nlstate+ndeath-1,1,ncovmodel);
                   8354: 
1.145     brouard  8355:     free_ivector(ncodemax,1,NCOVMAX);
1.192     brouard  8356:     free_ivector(ncodemaxwundef,1,NCOVMAX);
1.145     brouard  8357:     free_ivector(Tvar,1,NCOVMAX);
                   8358:     free_ivector(Tprod,1,NCOVMAX);
                   8359:     free_ivector(Tvaraff,1,NCOVMAX);
                   8360:     free_ivector(Tage,1,NCOVMAX);
1.126     brouard  8361: 
                   8362:     free_imatrix(nbcode,0,NCOVMAX,0,NCOVMAX);
1.200     brouard  8363:     /* free_imatrix(codtab,1,100,1,10); */
1.126     brouard  8364:   fflush(fichtm);
                   8365:   fflush(ficgp);
                   8366:   
                   8367: 
                   8368:   if((nberr >0) || (nbwarn>0)){
                   8369:     printf("End of Imach with %d errors and/or %d warnings\n",nberr,nbwarn);
                   8370:     fprintf(ficlog,"End of Imach with %d errors and/or warnings %d\n",nberr,nbwarn);
                   8371:   }else{
                   8372:     printf("End of Imach\n");
                   8373:     fprintf(ficlog,"End of Imach\n");
                   8374:   }
                   8375:   printf("See log file on %s\n",filelog);
                   8376:   /*  gettimeofday(&end_time, (struct timezone*)0);*/  /* after time */
1.157     brouard  8377:   /*(void) gettimeofday(&end_time,&tzp);*/
                   8378:   rend_time = time(NULL);  
                   8379:   end_time = *localtime(&rend_time);
                   8380:   /* tml = *localtime(&end_time.tm_sec); */
                   8381:   strcpy(strtend,asctime(&end_time));
1.126     brouard  8382:   printf("Local time at start %s\nLocal time at end   %s",strstart, strtend); 
                   8383:   fprintf(ficlog,"Local time at start %s\nLocal time at end   %s\n",strstart, strtend); 
1.157     brouard  8384:   printf("Total time used %s\n", asc_diff_time(rend_time -rstart_time,tmpout));
1.126     brouard  8385: 
1.157     brouard  8386:   printf("Total time was %.0lf Sec.\n", difftime(rend_time,rstart_time));
                   8387:   fprintf(ficlog,"Total time used %s\n", asc_diff_time(rend_time -rstart_time,tmpout));
                   8388:   fprintf(ficlog,"Total time was %.0lf Sec.\n", difftime(rend_time,rstart_time));
1.126     brouard  8389:   /*  printf("Total time was %d uSec.\n", total_usecs);*/
                   8390: /*   if(fileappend(fichtm,optionfilehtm)){ */
                   8391:   fprintf(fichtm,"<br>Local time at start %s<br>Local time at end   %s<br>\n</body></html>",strstart, strtend);
                   8392:   fclose(fichtm);
                   8393:   fprintf(fichtmcov,"<br>Local time at start %s<br>Local time at end   %s<br>\n</body></html>",strstart, strtend);
                   8394:   fclose(fichtmcov);
                   8395:   fclose(ficgp);
                   8396:   fclose(ficlog);
                   8397:   /*------ End -----------*/
                   8398: 
                   8399: 
                   8400:    printf("Before Current directory %s!\n",pathcd);
1.184     brouard  8401: #ifdef WIN32
                   8402:    if (_chdir(pathcd) != 0)
                   8403:           printf("Can't move to directory %s!\n",path);
                   8404:    if(_getcwd(pathcd,MAXLINE) > 0)
                   8405: #else
1.126     brouard  8406:    if(chdir(pathcd) != 0)
1.184     brouard  8407:           printf("Can't move to directory %s!\n", path);
                   8408:    if (getcwd(pathcd, MAXLINE) > 0)
                   8409: #endif 
1.126     brouard  8410:     printf("Current directory %s!\n",pathcd);
                   8411:   /*strcat(plotcmd,CHARSEPARATOR);*/
                   8412:   sprintf(plotcmd,"gnuplot");
1.157     brouard  8413: #ifdef _WIN32
1.126     brouard  8414:   sprintf(plotcmd,"\"%sgnuplot.exe\"",pathimach);
                   8415: #endif
                   8416:   if(!stat(plotcmd,&info)){
1.158     brouard  8417:     printf("Error or gnuplot program not found: '%s'\n",plotcmd);fflush(stdout);
1.126     brouard  8418:     if(!stat(getenv("GNUPLOTBIN"),&info)){
1.158     brouard  8419:       printf("Error or gnuplot program not found: '%s' Environment GNUPLOTBIN not set.\n",plotcmd);fflush(stdout);
1.126     brouard  8420:     }else
                   8421:       strcpy(pplotcmd,plotcmd);
1.157     brouard  8422: #ifdef __unix
1.126     brouard  8423:     strcpy(plotcmd,GNUPLOTPROGRAM);
                   8424:     if(!stat(plotcmd,&info)){
1.158     brouard  8425:       printf("Error gnuplot program not found: '%s'\n",plotcmd);fflush(stdout);
1.126     brouard  8426:     }else
                   8427:       strcpy(pplotcmd,plotcmd);
                   8428: #endif
                   8429:   }else
                   8430:     strcpy(pplotcmd,plotcmd);
                   8431:   
                   8432:   sprintf(plotcmd,"%s %s",pplotcmd, optionfilegnuplot);
1.158     brouard  8433:   printf("Starting graphs with: '%s'\n",plotcmd);fflush(stdout);
1.126     brouard  8434: 
                   8435:   if((outcmd=system(plotcmd)) != 0){
1.158     brouard  8436:     printf("gnuplot command might not be in your path: '%s', err=%d\n", plotcmd, outcmd);
1.154     brouard  8437:     printf("\n Trying if gnuplot resides on the same directory that IMaCh\n");
1.152     brouard  8438:     sprintf(plotcmd,"%sgnuplot %s", pathimach, optionfilegnuplot);
1.150     brouard  8439:     if((outcmd=system(plotcmd)) != 0)
1.153     brouard  8440:       printf("\n Still a problem with gnuplot command %s, err=%d\n", plotcmd, outcmd);
1.126     brouard  8441:   }
1.158     brouard  8442:   printf(" Successful, please wait...");
1.126     brouard  8443:   while (z[0] != 'q') {
                   8444:     /* chdir(path); */
1.154     brouard  8445:     printf("\nType e to edit results with your browser, g to graph again and q for exit: ");
1.126     brouard  8446:     scanf("%s",z);
                   8447: /*     if (z[0] == 'c') system("./imach"); */
                   8448:     if (z[0] == 'e') {
1.158     brouard  8449: #ifdef __APPLE__
1.152     brouard  8450:       sprintf(pplotcmd, "open %s", optionfilehtm);
1.157     brouard  8451: #elif __linux
                   8452:       sprintf(pplotcmd, "xdg-open %s", optionfilehtm);
1.153     brouard  8453: #else
1.152     brouard  8454:       sprintf(pplotcmd, "%s", optionfilehtm);
1.153     brouard  8455: #endif
                   8456:       printf("Starting browser with: %s",pplotcmd);fflush(stdout);
                   8457:       system(pplotcmd);
1.126     brouard  8458:     }
                   8459:     else if (z[0] == 'g') system(plotcmd);
                   8460:     else if (z[0] == 'q') exit(0);
                   8461:   }
                   8462:   end:
                   8463:   while (z[0] != 'q') {
1.195     brouard  8464:     printf("\nType  q for exiting: "); fflush(stdout);
1.126     brouard  8465:     scanf("%s",z);
                   8466:   }
                   8467: }

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