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

1.211   ! brouard     1: /* $Id: imach.c,v 1.210 2015/11/18 17:41:20 brouard Exp $
1.126     brouard     2:   $State: Exp $
1.163     brouard     3:   $Log: imach.c,v $
1.211   ! brouard     4:   Revision 1.210  2015/11/18 17:41:20  brouard
        !             5:   Summary: Start working on projected prevalences
        !             6: 
1.210     brouard     7:   Revision 1.209  2015/11/17 22:12:03  brouard
                      8:   Summary: Adding ftolpl parameter
                      9:   Author: N Brouard
                     10: 
                     11:   We had difficulties to get smoothed confidence intervals. It was due
                     12:   to the period prevalence which wasn't computed accurately. The inner
                     13:   parameter ftolpl is now an outer parameter of the .imach parameter
                     14:   file after estepm. If ftolpl is small 1.e-4 and estepm too,
                     15:   computation are long.
                     16: 
1.209     brouard    17:   Revision 1.208  2015/11/17 14:31:57  brouard
                     18:   Summary: temporary
                     19: 
1.208     brouard    20:   Revision 1.207  2015/10/27 17:36:57  brouard
                     21:   *** empty log message ***
                     22: 
1.207     brouard    23:   Revision 1.206  2015/10/24 07:14:11  brouard
                     24:   *** empty log message ***
                     25: 
1.206     brouard    26:   Revision 1.205  2015/10/23 15:50:53  brouard
                     27:   Summary: 0.98r3 some clarification for graphs on likelihood contributions
                     28: 
1.205     brouard    29:   Revision 1.204  2015/10/01 16:20:26  brouard
                     30:   Summary: Some new graphs of contribution to likelihood
                     31: 
1.204     brouard    32:   Revision 1.203  2015/09/30 17:45:14  brouard
                     33:   Summary: looking at better estimation of the hessian
                     34: 
                     35:   Also a better criteria for convergence to the period prevalence And
                     36:   therefore adding the number of years needed to converge. (The
                     37:   prevalence in any alive state shold sum to one
                     38: 
1.203     brouard    39:   Revision 1.202  2015/09/22 19:45:16  brouard
                     40:   Summary: Adding some overall graph on contribution to likelihood. Might change
                     41: 
1.202     brouard    42:   Revision 1.201  2015/09/15 17:34:58  brouard
                     43:   Summary: 0.98r0
                     44: 
                     45:   - Some new graphs like suvival functions
                     46:   - Some bugs fixed like model=1+age+V2.
                     47: 
1.201     brouard    48:   Revision 1.200  2015/09/09 16:53:55  brouard
                     49:   Summary: Big bug thanks to Flavia
                     50: 
                     51:   Even model=1+age+V2. did not work anymore
                     52: 
1.200     brouard    53:   Revision 1.199  2015/09/07 14:09:23  brouard
                     54:   Summary: 0.98q6 changing default small png format for graph to vectorized svg.
                     55: 
1.199     brouard    56:   Revision 1.198  2015/09/03 07:14:39  brouard
                     57:   Summary: 0.98q5 Flavia
                     58: 
1.198     brouard    59:   Revision 1.197  2015/09/01 18:24:39  brouard
                     60:   *** empty log message ***
                     61: 
1.197     brouard    62:   Revision 1.196  2015/08/18 23:17:52  brouard
                     63:   Summary: 0.98q5
                     64: 
1.196     brouard    65:   Revision 1.195  2015/08/18 16:28:39  brouard
                     66:   Summary: Adding a hack for testing purpose
                     67: 
                     68:   After reading the title, ftol and model lines, if the comment line has
                     69:   a q, starting with #q, the answer at the end of the run is quit. It
                     70:   permits to run test files in batch with ctest. The former workaround was
                     71:   $ echo q | imach foo.imach
                     72: 
1.195     brouard    73:   Revision 1.194  2015/08/18 13:32:00  brouard
                     74:   Summary:  Adding error when the covariance matrix doesn't contain the exact number of lines required by the model line.
                     75: 
1.194     brouard    76:   Revision 1.193  2015/08/04 07:17:42  brouard
                     77:   Summary: 0.98q4
                     78: 
1.193     brouard    79:   Revision 1.192  2015/07/16 16:49:02  brouard
                     80:   Summary: Fixing some outputs
                     81: 
1.192     brouard    82:   Revision 1.191  2015/07/14 10:00:33  brouard
                     83:   Summary: Some fixes
                     84: 
1.191     brouard    85:   Revision 1.190  2015/05/05 08:51:13  brouard
                     86:   Summary: Adding digits in output parameters (7 digits instead of 6)
                     87: 
                     88:   Fix 1+age+.
                     89: 
1.190     brouard    90:   Revision 1.189  2015/04/30 14:45:16  brouard
                     91:   Summary: 0.98q2
                     92: 
1.189     brouard    93:   Revision 1.188  2015/04/30 08:27:53  brouard
                     94:   *** empty log message ***
                     95: 
1.188     brouard    96:   Revision 1.187  2015/04/29 09:11:15  brouard
                     97:   *** empty log message ***
                     98: 
1.187     brouard    99:   Revision 1.186  2015/04/23 12:01:52  brouard
                    100:   Summary: V1*age is working now, version 0.98q1
                    101: 
                    102:   Some codes had been disabled in order to simplify and Vn*age was
                    103:   working in the optimization phase, ie, giving correct MLE parameters,
                    104:   but, as usual, outputs were not correct and program core dumped.
                    105: 
1.186     brouard   106:   Revision 1.185  2015/03/11 13:26:42  brouard
                    107:   Summary: Inclusion of compile and links command line for Intel Compiler
                    108: 
1.185     brouard   109:   Revision 1.184  2015/03/11 11:52:39  brouard
                    110:   Summary: Back from Windows 8. Intel Compiler
                    111: 
1.184     brouard   112:   Revision 1.183  2015/03/10 20:34:32  brouard
                    113:   Summary: 0.98q0, trying with directest, mnbrak fixed
                    114: 
                    115:   We use directest instead of original Powell test; probably no
                    116:   incidence on the results, but better justifications;
                    117:   We fixed Numerical Recipes mnbrak routine which was wrong and gave
                    118:   wrong results.
                    119: 
1.183     brouard   120:   Revision 1.182  2015/02/12 08:19:57  brouard
                    121:   Summary: Trying to keep directest which seems simpler and more general
                    122:   Author: Nicolas Brouard
                    123: 
1.182     brouard   124:   Revision 1.181  2015/02/11 23:22:24  brouard
                    125:   Summary: Comments on Powell added
                    126: 
                    127:   Author:
                    128: 
1.181     brouard   129:   Revision 1.180  2015/02/11 17:33:45  brouard
                    130:   Summary: Finishing move from main to function (hpijx and prevalence_limit)
                    131: 
1.180     brouard   132:   Revision 1.179  2015/01/04 09:57:06  brouard
                    133:   Summary: back to OS/X
                    134: 
1.179     brouard   135:   Revision 1.178  2015/01/04 09:35:48  brouard
                    136:   *** empty log message ***
                    137: 
1.178     brouard   138:   Revision 1.177  2015/01/03 18:40:56  brouard
                    139:   Summary: Still testing ilc32 on OSX
                    140: 
1.177     brouard   141:   Revision 1.176  2015/01/03 16:45:04  brouard
                    142:   *** empty log message ***
                    143: 
1.176     brouard   144:   Revision 1.175  2015/01/03 16:33:42  brouard
                    145:   *** empty log message ***
                    146: 
1.175     brouard   147:   Revision 1.174  2015/01/03 16:15:49  brouard
                    148:   Summary: Still in cross-compilation
                    149: 
1.174     brouard   150:   Revision 1.173  2015/01/03 12:06:26  brouard
                    151:   Summary: trying to detect cross-compilation
                    152: 
1.173     brouard   153:   Revision 1.172  2014/12/27 12:07:47  brouard
                    154:   Summary: Back from Visual Studio and Intel, options for compiling for Windows XP
                    155: 
1.172     brouard   156:   Revision 1.171  2014/12/23 13:26:59  brouard
                    157:   Summary: Back from Visual C
                    158: 
                    159:   Still problem with utsname.h on Windows
                    160: 
1.171     brouard   161:   Revision 1.170  2014/12/23 11:17:12  brouard
                    162:   Summary: Cleaning some \%% back to %%
                    163: 
                    164:   The escape was mandatory for a specific compiler (which one?), but too many warnings.
                    165: 
1.170     brouard   166:   Revision 1.169  2014/12/22 23:08:31  brouard
                    167:   Summary: 0.98p
                    168: 
                    169:   Outputs some informations on compiler used, OS etc. Testing on different platforms.
                    170: 
1.169     brouard   171:   Revision 1.168  2014/12/22 15:17:42  brouard
1.170     brouard   172:   Summary: update
1.169     brouard   173: 
1.168     brouard   174:   Revision 1.167  2014/12/22 13:50:56  brouard
                    175:   Summary: Testing uname and compiler version and if compiled 32 or 64
                    176: 
                    177:   Testing on Linux 64
                    178: 
1.167     brouard   179:   Revision 1.166  2014/12/22 11:40:47  brouard
                    180:   *** empty log message ***
                    181: 
1.166     brouard   182:   Revision 1.165  2014/12/16 11:20:36  brouard
                    183:   Summary: After compiling on Visual C
                    184: 
                    185:   * imach.c (Module): Merging 1.61 to 1.162
                    186: 
1.165     brouard   187:   Revision 1.164  2014/12/16 10:52:11  brouard
                    188:   Summary: Merging with Visual C after suppressing some warnings for unused variables. Also fixing Saito's bug 0.98Xn
                    189: 
                    190:   * imach.c (Module): Merging 1.61 to 1.162
                    191: 
1.164     brouard   192:   Revision 1.163  2014/12/16 10:30:11  brouard
                    193:   * imach.c (Module): Merging 1.61 to 1.162
                    194: 
1.163     brouard   195:   Revision 1.162  2014/09/25 11:43:39  brouard
                    196:   Summary: temporary backup 0.99!
                    197: 
1.162     brouard   198:   Revision 1.1  2014/09/16 11:06:58  brouard
                    199:   Summary: With some code (wrong) for nlopt
                    200: 
                    201:   Author:
                    202: 
                    203:   Revision 1.161  2014/09/15 20:41:41  brouard
                    204:   Summary: Problem with macro SQR on Intel compiler
                    205: 
1.161     brouard   206:   Revision 1.160  2014/09/02 09:24:05  brouard
                    207:   *** empty log message ***
                    208: 
1.160     brouard   209:   Revision 1.159  2014/09/01 10:34:10  brouard
                    210:   Summary: WIN32
                    211:   Author: Brouard
                    212: 
1.159     brouard   213:   Revision 1.158  2014/08/27 17:11:51  brouard
                    214:   *** empty log message ***
                    215: 
1.158     brouard   216:   Revision 1.157  2014/08/27 16:26:55  brouard
                    217:   Summary: Preparing windows Visual studio version
                    218:   Author: Brouard
                    219: 
                    220:   In order to compile on Visual studio, time.h is now correct and time_t
                    221:   and tm struct should be used. difftime should be used but sometimes I
                    222:   just make the differences in raw time format (time(&now).
                    223:   Trying to suppress #ifdef LINUX
                    224:   Add xdg-open for __linux in order to open default browser.
                    225: 
1.157     brouard   226:   Revision 1.156  2014/08/25 20:10:10  brouard
                    227:   *** empty log message ***
                    228: 
1.156     brouard   229:   Revision 1.155  2014/08/25 18:32:34  brouard
                    230:   Summary: New compile, minor changes
                    231:   Author: Brouard
                    232: 
1.155     brouard   233:   Revision 1.154  2014/06/20 17:32:08  brouard
                    234:   Summary: Outputs now all graphs of convergence to period prevalence
                    235: 
1.154     brouard   236:   Revision 1.153  2014/06/20 16:45:46  brouard
                    237:   Summary: If 3 live state, convergence to period prevalence on same graph
                    238:   Author: Brouard
                    239: 
1.153     brouard   240:   Revision 1.152  2014/06/18 17:54:09  brouard
                    241:   Summary: open browser, use gnuplot on same dir than imach if not found in the path
                    242: 
1.152     brouard   243:   Revision 1.151  2014/06/18 16:43:30  brouard
                    244:   *** empty log message ***
                    245: 
1.151     brouard   246:   Revision 1.150  2014/06/18 16:42:35  brouard
                    247:   Summary: If gnuplot is not in the path try on same directory than imach binary (OSX)
                    248:   Author: brouard
                    249: 
1.150     brouard   250:   Revision 1.149  2014/06/18 15:51:14  brouard
                    251:   Summary: Some fixes in parameter files errors
                    252:   Author: Nicolas Brouard
                    253: 
1.149     brouard   254:   Revision 1.148  2014/06/17 17:38:48  brouard
                    255:   Summary: Nothing new
                    256:   Author: Brouard
                    257: 
                    258:   Just a new packaging for OS/X version 0.98nS
                    259: 
1.148     brouard   260:   Revision 1.147  2014/06/16 10:33:11  brouard
                    261:   *** empty log message ***
                    262: 
1.147     brouard   263:   Revision 1.146  2014/06/16 10:20:28  brouard
                    264:   Summary: Merge
                    265:   Author: Brouard
                    266: 
                    267:   Merge, before building revised version.
                    268: 
1.146     brouard   269:   Revision 1.145  2014/06/10 21:23:15  brouard
                    270:   Summary: Debugging with valgrind
                    271:   Author: Nicolas Brouard
                    272: 
                    273:   Lot of changes in order to output the results with some covariates
                    274:   After the Edimburgh REVES conference 2014, it seems mandatory to
                    275:   improve the code.
                    276:   No more memory valgrind error but a lot has to be done in order to
                    277:   continue the work of splitting the code into subroutines.
                    278:   Also, decodemodel has been improved. Tricode is still not
                    279:   optimal. nbcode should be improved. Documentation has been added in
                    280:   the source code.
                    281: 
1.144     brouard   282:   Revision 1.143  2014/01/26 09:45:38  brouard
                    283:   Summary: Version 0.98nR (to be improved, but gives same optimization results as 0.98k. Nice, promising
                    284: 
                    285:   * imach.c (Module): Trying to merge old staffs together while being at Tokyo. Not tested...
                    286:   (Module): Version 0.98nR Running ok, but output format still only works for three covariates.
                    287: 
1.143     brouard   288:   Revision 1.142  2014/01/26 03:57:36  brouard
                    289:   Summary: gnuplot changed plot w l 1 has to be changed to plot w l lt 2
                    290: 
                    291:   * imach.c (Module): Trying to merge old staffs together while being at Tokyo. Not tested...
                    292: 
1.142     brouard   293:   Revision 1.141  2014/01/26 02:42:01  brouard
                    294:   * imach.c (Module): Trying to merge old staffs together while being at Tokyo. Not tested...
                    295: 
1.141     brouard   296:   Revision 1.140  2011/09/02 10:37:54  brouard
                    297:   Summary: times.h is ok with mingw32 now.
                    298: 
1.140     brouard   299:   Revision 1.139  2010/06/14 07:50:17  brouard
                    300:   After the theft of my laptop, I probably lost some lines of codes which were not uploaded to the CVS tree.
                    301:   I remember having already fixed agemin agemax which are pointers now but not cvs saved.
                    302: 
1.139     brouard   303:   Revision 1.138  2010/04/30 18:19:40  brouard
                    304:   *** empty log message ***
                    305: 
1.138     brouard   306:   Revision 1.137  2010/04/29 18:11:38  brouard
                    307:   (Module): Checking covariates for more complex models
                    308:   than V1+V2. A lot of change to be done. Unstable.
                    309: 
1.137     brouard   310:   Revision 1.136  2010/04/26 20:30:53  brouard
                    311:   (Module): merging some libgsl code. Fixing computation
                    312:   of likelione (using inter/intrapolation if mle = 0) in order to
                    313:   get same likelihood as if mle=1.
                    314:   Some cleaning of code and comments added.
                    315: 
1.136     brouard   316:   Revision 1.135  2009/10/29 15:33:14  brouard
                    317:   (Module): Now imach stops if date of birth, at least year of birth, is not given. Some cleaning of the code.
                    318: 
1.135     brouard   319:   Revision 1.134  2009/10/29 13:18:53  brouard
                    320:   (Module): Now imach stops if date of birth, at least year of birth, is not given. Some cleaning of the code.
                    321: 
1.134     brouard   322:   Revision 1.133  2009/07/06 10:21:25  brouard
                    323:   just nforces
                    324: 
1.133     brouard   325:   Revision 1.132  2009/07/06 08:22:05  brouard
                    326:   Many tings
                    327: 
1.132     brouard   328:   Revision 1.131  2009/06/20 16:22:47  brouard
                    329:   Some dimensions resccaled
                    330: 
1.131     brouard   331:   Revision 1.130  2009/05/26 06:44:34  brouard
                    332:   (Module): Max Covariate is now set to 20 instead of 8. A
                    333:   lot of cleaning with variables initialized to 0. Trying to make
                    334:   V2+V3*age+V1+V4 strb=V3*age+V1+V4 working better.
                    335: 
1.130     brouard   336:   Revision 1.129  2007/08/31 13:49:27  lievre
                    337:   Modification of the way of exiting when the covariate is not binary in order to see on the window the error message before exiting
                    338: 
1.129     lievre    339:   Revision 1.128  2006/06/30 13:02:05  brouard
                    340:   (Module): Clarifications on computing e.j
                    341: 
1.128     brouard   342:   Revision 1.127  2006/04/28 18:11:50  brouard
                    343:   (Module): Yes the sum of survivors was wrong since
                    344:   imach-114 because nhstepm was no more computed in the age
                    345:   loop. Now we define nhstepma in the age loop.
                    346:   (Module): In order to speed up (in case of numerous covariates) we
                    347:   compute health expectancies (without variances) in a first step
                    348:   and then all the health expectancies with variances or standard
                    349:   deviation (needs data from the Hessian matrices) which slows the
                    350:   computation.
                    351:   In the future we should be able to stop the program is only health
                    352:   expectancies and graph are needed without standard deviations.
                    353: 
1.127     brouard   354:   Revision 1.126  2006/04/28 17:23:28  brouard
                    355:   (Module): Yes the sum of survivors was wrong since
                    356:   imach-114 because nhstepm was no more computed in the age
                    357:   loop. Now we define nhstepma in the age loop.
                    358:   Version 0.98h
                    359: 
1.126     brouard   360:   Revision 1.125  2006/04/04 15:20:31  lievre
                    361:   Errors in calculation of health expectancies. Age was not initialized.
                    362:   Forecasting file added.
                    363: 
                    364:   Revision 1.124  2006/03/22 17:13:53  lievre
                    365:   Parameters are printed with %lf instead of %f (more numbers after the comma).
                    366:   The log-likelihood is printed in the log file
                    367: 
                    368:   Revision 1.123  2006/03/20 10:52:43  brouard
                    369:   * imach.c (Module): <title> changed, corresponds to .htm file
                    370:   name. <head> headers where missing.
                    371: 
                    372:   * imach.c (Module): Weights can have a decimal point as for
                    373:   English (a comma might work with a correct LC_NUMERIC environment,
                    374:   otherwise the weight is truncated).
                    375:   Modification of warning when the covariates values are not 0 or
                    376:   1.
                    377:   Version 0.98g
                    378: 
                    379:   Revision 1.122  2006/03/20 09:45:41  brouard
                    380:   (Module): Weights can have a decimal point as for
                    381:   English (a comma might work with a correct LC_NUMERIC environment,
                    382:   otherwise the weight is truncated).
                    383:   Modification of warning when the covariates values are not 0 or
                    384:   1.
                    385:   Version 0.98g
                    386: 
                    387:   Revision 1.121  2006/03/16 17:45:01  lievre
                    388:   * imach.c (Module): Comments concerning covariates added
                    389: 
                    390:   * imach.c (Module): refinements in the computation of lli if
                    391:   status=-2 in order to have more reliable computation if stepm is
                    392:   not 1 month. Version 0.98f
                    393: 
                    394:   Revision 1.120  2006/03/16 15:10:38  lievre
                    395:   (Module): refinements in the computation of lli if
                    396:   status=-2 in order to have more reliable computation if stepm is
                    397:   not 1 month. Version 0.98f
                    398: 
                    399:   Revision 1.119  2006/03/15 17:42:26  brouard
                    400:   (Module): Bug if status = -2, the loglikelihood was
                    401:   computed as likelihood omitting the logarithm. Version O.98e
                    402: 
                    403:   Revision 1.118  2006/03/14 18:20:07  brouard
                    404:   (Module): varevsij Comments added explaining the second
                    405:   table of variances if popbased=1 .
                    406:   (Module): Covariances of eij, ekl added, graphs fixed, new html link.
                    407:   (Module): Function pstamp added
                    408:   (Module): Version 0.98d
                    409: 
                    410:   Revision 1.117  2006/03/14 17:16:22  brouard
                    411:   (Module): varevsij Comments added explaining the second
                    412:   table of variances if popbased=1 .
                    413:   (Module): Covariances of eij, ekl added, graphs fixed, new html link.
                    414:   (Module): Function pstamp added
                    415:   (Module): Version 0.98d
                    416: 
                    417:   Revision 1.116  2006/03/06 10:29:27  brouard
                    418:   (Module): Variance-covariance wrong links and
                    419:   varian-covariance of ej. is needed (Saito).
                    420: 
                    421:   Revision 1.115  2006/02/27 12:17:45  brouard
                    422:   (Module): One freematrix added in mlikeli! 0.98c
                    423: 
                    424:   Revision 1.114  2006/02/26 12:57:58  brouard
                    425:   (Module): Some improvements in processing parameter
                    426:   filename with strsep.
                    427: 
                    428:   Revision 1.113  2006/02/24 14:20:24  brouard
                    429:   (Module): Memory leaks checks with valgrind and:
                    430:   datafile was not closed, some imatrix were not freed and on matrix
                    431:   allocation too.
                    432: 
                    433:   Revision 1.112  2006/01/30 09:55:26  brouard
                    434:   (Module): Back to gnuplot.exe instead of wgnuplot.exe
                    435: 
                    436:   Revision 1.111  2006/01/25 20:38:18  brouard
                    437:   (Module): Lots of cleaning and bugs added (Gompertz)
                    438:   (Module): Comments can be added in data file. Missing date values
                    439:   can be a simple dot '.'.
                    440: 
                    441:   Revision 1.110  2006/01/25 00:51:50  brouard
                    442:   (Module): Lots of cleaning and bugs added (Gompertz)
                    443: 
                    444:   Revision 1.109  2006/01/24 19:37:15  brouard
                    445:   (Module): Comments (lines starting with a #) are allowed in data.
                    446: 
                    447:   Revision 1.108  2006/01/19 18:05:42  lievre
                    448:   Gnuplot problem appeared...
                    449:   To be fixed
                    450: 
                    451:   Revision 1.107  2006/01/19 16:20:37  brouard
                    452:   Test existence of gnuplot in imach path
                    453: 
                    454:   Revision 1.106  2006/01/19 13:24:36  brouard
                    455:   Some cleaning and links added in html output
                    456: 
                    457:   Revision 1.105  2006/01/05 20:23:19  lievre
                    458:   *** empty log message ***
                    459: 
                    460:   Revision 1.104  2005/09/30 16:11:43  lievre
                    461:   (Module): sump fixed, loop imx fixed, and simplifications.
                    462:   (Module): If the status is missing at the last wave but we know
                    463:   that the person is alive, then we can code his/her status as -2
                    464:   (instead of missing=-1 in earlier versions) and his/her
                    465:   contributions to the likelihood is 1 - Prob of dying from last
                    466:   health status (= 1-p13= p11+p12 in the easiest case of somebody in
                    467:   the healthy state at last known wave). Version is 0.98
                    468: 
                    469:   Revision 1.103  2005/09/30 15:54:49  lievre
                    470:   (Module): sump fixed, loop imx fixed, and simplifications.
                    471: 
                    472:   Revision 1.102  2004/09/15 17:31:30  brouard
                    473:   Add the possibility to read data file including tab characters.
                    474: 
                    475:   Revision 1.101  2004/09/15 10:38:38  brouard
                    476:   Fix on curr_time
                    477: 
                    478:   Revision 1.100  2004/07/12 18:29:06  brouard
                    479:   Add version for Mac OS X. Just define UNIX in Makefile
                    480: 
                    481:   Revision 1.99  2004/06/05 08:57:40  brouard
                    482:   *** empty log message ***
                    483: 
                    484:   Revision 1.98  2004/05/16 15:05:56  brouard
                    485:   New version 0.97 . First attempt to estimate force of mortality
                    486:   directly from the data i.e. without the need of knowing the health
                    487:   state at each age, but using a Gompertz model: log u =a + b*age .
                    488:   This is the basic analysis of mortality and should be done before any
                    489:   other analysis, in order to test if the mortality estimated from the
                    490:   cross-longitudinal survey is different from the mortality estimated
                    491:   from other sources like vital statistic data.
                    492: 
                    493:   The same imach parameter file can be used but the option for mle should be -3.
                    494: 
1.133     brouard   495:   Agnès, who wrote this part of the code, tried to keep most of the
1.126     brouard   496:   former routines in order to include the new code within the former code.
                    497: 
                    498:   The output is very simple: only an estimate of the intercept and of
                    499:   the slope with 95% confident intervals.
                    500: 
                    501:   Current limitations:
                    502:   A) Even if you enter covariates, i.e. with the
                    503:   model= V1+V2 equation for example, the programm does only estimate a unique global model without covariates.
                    504:   B) There is no computation of Life Expectancy nor Life Table.
                    505: 
                    506:   Revision 1.97  2004/02/20 13:25:42  lievre
                    507:   Version 0.96d. Population forecasting command line is (temporarily)
                    508:   suppressed.
                    509: 
                    510:   Revision 1.96  2003/07/15 15:38:55  brouard
                    511:   * imach.c (Repository): Errors in subdirf, 2, 3 while printing tmpout is
                    512:   rewritten within the same printf. Workaround: many printfs.
                    513: 
                    514:   Revision 1.95  2003/07/08 07:54:34  brouard
                    515:   * imach.c (Repository):
                    516:   (Repository): Using imachwizard code to output a more meaningful covariance
                    517:   matrix (cov(a12,c31) instead of numbers.
                    518: 
                    519:   Revision 1.94  2003/06/27 13:00:02  brouard
                    520:   Just cleaning
                    521: 
                    522:   Revision 1.93  2003/06/25 16:33:55  brouard
                    523:   (Module): On windows (cygwin) function asctime_r doesn't
                    524:   exist so I changed back to asctime which exists.
                    525:   (Module): Version 0.96b
                    526: 
                    527:   Revision 1.92  2003/06/25 16:30:45  brouard
                    528:   (Module): On windows (cygwin) function asctime_r doesn't
                    529:   exist so I changed back to asctime which exists.
                    530: 
                    531:   Revision 1.91  2003/06/25 15:30:29  brouard
                    532:   * imach.c (Repository): Duplicated warning errors corrected.
                    533:   (Repository): Elapsed time after each iteration is now output. It
                    534:   helps to forecast when convergence will be reached. Elapsed time
                    535:   is stamped in powell.  We created a new html file for the graphs
                    536:   concerning matrix of covariance. It has extension -cov.htm.
                    537: 
                    538:   Revision 1.90  2003/06/24 12:34:15  brouard
                    539:   (Module): Some bugs corrected for windows. Also, when
                    540:   mle=-1 a template is output in file "or"mypar.txt with the design
                    541:   of the covariance matrix to be input.
                    542: 
                    543:   Revision 1.89  2003/06/24 12:30:52  brouard
                    544:   (Module): Some bugs corrected for windows. Also, when
                    545:   mle=-1 a template is output in file "or"mypar.txt with the design
                    546:   of the covariance matrix to be input.
                    547: 
                    548:   Revision 1.88  2003/06/23 17:54:56  brouard
                    549:   * 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.
                    550: 
                    551:   Revision 1.87  2003/06/18 12:26:01  brouard
                    552:   Version 0.96
                    553: 
                    554:   Revision 1.86  2003/06/17 20:04:08  brouard
                    555:   (Module): Change position of html and gnuplot routines and added
                    556:   routine fileappend.
                    557: 
                    558:   Revision 1.85  2003/06/17 13:12:43  brouard
                    559:   * imach.c (Repository): Check when date of death was earlier that
                    560:   current date of interview. It may happen when the death was just
                    561:   prior to the death. In this case, dh was negative and likelihood
                    562:   was wrong (infinity). We still send an "Error" but patch by
                    563:   assuming that the date of death was just one stepm after the
                    564:   interview.
                    565:   (Repository): Because some people have very long ID (first column)
                    566:   we changed int to long in num[] and we added a new lvector for
                    567:   memory allocation. But we also truncated to 8 characters (left
                    568:   truncation)
                    569:   (Repository): No more line truncation errors.
                    570: 
                    571:   Revision 1.84  2003/06/13 21:44:43  brouard
                    572:   * imach.c (Repository): Replace "freqsummary" at a correct
                    573:   place. It differs from routine "prevalence" which may be called
                    574:   many times. Probs is memory consuming and must be used with
                    575:   parcimony.
                    576:   Version 0.95a3 (should output exactly the same maximization than 0.8a2)
                    577: 
                    578:   Revision 1.83  2003/06/10 13:39:11  lievre
                    579:   *** empty log message ***
                    580: 
                    581:   Revision 1.82  2003/06/05 15:57:20  brouard
                    582:   Add log in  imach.c and  fullversion number is now printed.
                    583: 
                    584: */
                    585: /*
                    586:    Interpolated Markov Chain
                    587: 
                    588:   Short summary of the programme:
                    589:   
                    590:   This program computes Healthy Life Expectancies from
                    591:   cross-longitudinal data. Cross-longitudinal data consist in: -1- a
                    592:   first survey ("cross") where individuals from different ages are
                    593:   interviewed on their health status or degree of disability (in the
                    594:   case of a health survey which is our main interest) -2- at least a
                    595:   second wave of interviews ("longitudinal") which measure each change
                    596:   (if any) in individual health status.  Health expectancies are
                    597:   computed from the time spent in each health state according to a
                    598:   model. More health states you consider, more time is necessary to reach the
                    599:   Maximum Likelihood of the parameters involved in the model.  The
                    600:   simplest model is the multinomial logistic model where pij is the
                    601:   probability to be observed in state j at the second wave
                    602:   conditional to be observed in state i at the first wave. Therefore
                    603:   the model is: log(pij/pii)= aij + bij*age+ cij*sex + etc , where
                    604:   'age' is age and 'sex' is a covariate. If you want to have a more
                    605:   complex model than "constant and age", you should modify the program
                    606:   where the markup *Covariates have to be included here again* invites
                    607:   you to do it.  More covariates you add, slower the
                    608:   convergence.
                    609: 
                    610:   The advantage of this computer programme, compared to a simple
                    611:   multinomial logistic model, is clear when the delay between waves is not
                    612:   identical for each individual. Also, if a individual missed an
                    613:   intermediate interview, the information is lost, but taken into
                    614:   account using an interpolation or extrapolation.  
                    615: 
                    616:   hPijx is the probability to be observed in state i at age x+h
                    617:   conditional to the observed state i at age x. The delay 'h' can be
                    618:   split into an exact number (nh*stepm) of unobserved intermediate
                    619:   states. This elementary transition (by month, quarter,
                    620:   semester or year) is modelled as a multinomial logistic.  The hPx
                    621:   matrix is simply the matrix product of nh*stepm elementary matrices
                    622:   and the contribution of each individual to the likelihood is simply
                    623:   hPijx.
                    624: 
                    625:   Also this programme outputs the covariance matrix of the parameters but also
                    626:   of the life expectancies. It also computes the period (stable) prevalence. 
                    627:   
1.133     brouard   628:   Authors: Nicolas Brouard (brouard@ined.fr) and Agnès Lièvre (lievre@ined.fr).
                    629:            Institut national d'études démographiques, Paris.
1.126     brouard   630:   This software have been partly granted by Euro-REVES, a concerted action
                    631:   from the European Union.
                    632:   It is copyrighted identically to a GNU software product, ie programme and
                    633:   software can be distributed freely for non commercial use. Latest version
                    634:   can be accessed at http://euroreves.ined.fr/imach .
                    635: 
                    636:   Help to debug: LD_PRELOAD=/usr/local/lib/libnjamd.so ./imach foo.imach
                    637:   or better on gdb : set env LD_PRELOAD=/usr/local/lib/libnjamd.so
                    638:   
                    639:   **********************************************************************/
                    640: /*
                    641:   main
                    642:   read parameterfile
                    643:   read datafile
                    644:   concatwav
                    645:   freqsummary
                    646:   if (mle >= 1)
                    647:     mlikeli
                    648:   print results files
                    649:   if mle==1 
                    650:      computes hessian
                    651:   read end of parameter file: agemin, agemax, bage, fage, estepm
                    652:       begin-prev-date,...
                    653:   open gnuplot file
                    654:   open html file
1.145     brouard   655:   period (stable) prevalence      | pl_nom    1-1 2-2 etc by covariate
                    656:    for age prevalim()             | #****** V1=0  V2=1  V3=1  V4=0 ******
                    657:                                   | 65 1 0 2 1 3 1 4 0  0.96326 0.03674
                    658:     freexexit2 possible for memory heap.
                    659: 
                    660:   h Pij x                         | pij_nom  ficrestpij
                    661:    # Cov Agex agex+h hpijx with i,j= 1-1 1-2     1-3     2-1     2-2     2-3
                    662:        1  85   85    1.00000             0.00000 0.00000 0.00000 1.00000 0.00000
                    663:        1  85   86    0.68299             0.22291 0.09410 0.71093 0.00000 0.28907
                    664: 
                    665:        1  65   99    0.00364             0.00322 0.99314 0.00350 0.00310 0.99340
                    666:        1  65  100    0.00214             0.00204 0.99581 0.00206 0.00196 0.99597
                    667:   variance of p one-step probabilities varprob  | prob_nom   ficresprob #One-step probabilities and stand. devi in ()
                    668:    Standard deviation of one-step probabilities | probcor_nom   ficresprobcor #One-step probabilities and correlation matrix
                    669:    Matrix of variance covariance of one-step probabilities |  probcov_nom ficresprobcov #One-step probabilities and covariance matrix
                    670: 
1.126     brouard   671:   forecasting if prevfcast==1 prevforecast call prevalence()
                    672:   health expectancies
                    673:   Variance-covariance of DFLE
                    674:   prevalence()
                    675:    movingaverage()
                    676:   varevsij() 
                    677:   if popbased==1 varevsij(,popbased)
                    678:   total life expectancies
                    679:   Variance of period (stable) prevalence
                    680:  end
                    681: */
                    682: 
1.187     brouard   683: /* #define DEBUG */
                    684: /* #define DEBUGBRENT */
1.203     brouard   685: /* #define DEBUGLINMIN */
                    686: /* #define DEBUGHESS */
                    687: #define DEBUGHESSIJ
                    688: /* #define LINMINORIGINAL  /\* Don't use loop on scale in linmin (accepting nan)*\/ */
1.165     brouard   689: #define POWELL /* Instead of NLOPT */
1.192     brouard   690: #define POWELLF1F3 /* Skip test */
1.186     brouard   691: /* #define POWELLORIGINAL /\* Don't use Directest to decide new direction but original Powell test *\/ */
                    692: /* #define MNBRAKORIGINAL /\* Don't use mnbrak fix *\/ */
1.126     brouard   693: 
                    694: #include <math.h>
                    695: #include <stdio.h>
                    696: #include <stdlib.h>
                    697: #include <string.h>
1.159     brouard   698: 
                    699: #ifdef _WIN32
                    700: #include <io.h>
1.172     brouard   701: #include <windows.h>
                    702: #include <tchar.h>
1.159     brouard   703: #else
1.126     brouard   704: #include <unistd.h>
1.159     brouard   705: #endif
1.126     brouard   706: 
                    707: #include <limits.h>
                    708: #include <sys/types.h>
1.171     brouard   709: 
                    710: #if defined(__GNUC__)
                    711: #include <sys/utsname.h> /* Doesn't work on Windows */
                    712: #endif
                    713: 
1.126     brouard   714: #include <sys/stat.h>
                    715: #include <errno.h>
1.159     brouard   716: /* extern int errno; */
1.126     brouard   717: 
1.157     brouard   718: /* #ifdef LINUX */
                    719: /* #include <time.h> */
                    720: /* #include "timeval.h" */
                    721: /* #else */
                    722: /* #include <sys/time.h> */
                    723: /* #endif */
                    724: 
1.126     brouard   725: #include <time.h>
                    726: 
1.136     brouard   727: #ifdef GSL
                    728: #include <gsl/gsl_errno.h>
                    729: #include <gsl/gsl_multimin.h>
                    730: #endif
                    731: 
1.167     brouard   732: 
1.162     brouard   733: #ifdef NLOPT
                    734: #include <nlopt.h>
                    735: typedef struct {
                    736:   double (* function)(double [] );
                    737: } myfunc_data ;
                    738: #endif
                    739: 
1.126     brouard   740: /* #include <libintl.h> */
                    741: /* #define _(String) gettext (String) */
                    742: 
1.141     brouard   743: #define MAXLINE 1024 /* Was 256. Overflow with 312 with 2 states and 4 covariates. Should be ok */
1.126     brouard   744: 
                    745: #define GNUPLOTPROGRAM "gnuplot"
                    746: /*#define GNUPLOTPROGRAM "..\\gp37mgw\\wgnuplot"*/
                    747: #define FILENAMELENGTH 132
                    748: 
                    749: #define        GLOCK_ERROR_NOPATH              -1      /* empty path */
                    750: #define        GLOCK_ERROR_GETCWD              -2      /* cannot get cwd */
                    751: 
1.144     brouard   752: #define MAXPARM 128 /**< Maximum number of parameters for the optimization */
                    753: #define NPARMAX 64 /**< (nlstate+ndeath-1)*nlstate*ncovmodel */
1.126     brouard   754: 
                    755: #define NINTERVMAX 8
1.144     brouard   756: #define NLSTATEMAX 8 /**< Maximum number of live states (for func) */
                    757: #define NDEATHMAX 8 /**< Maximum number of dead states (for func) */
                    758: #define NCOVMAX 20 /**< Maximum number of covariates, including generated covariates V1*V2 */
1.197     brouard   759: #define codtabm(h,k)  (1 & (h-1) >> (k-1))+1
1.211   ! brouard   760: /*#define decodtabm(h,k,cptcoveff)= (h <= (1<<cptcoveff)?(((h-1) >> (k-1)) & 1) +1 : -1)*/
        !           761: #define decodtabm(h,k,cptcoveff) (((h-1) >> (k-1)) & 1) +1 
1.126     brouard   762: #define MAXN 20000
1.144     brouard   763: #define YEARM 12. /**< Number of months per year */
1.126     brouard   764: #define AGESUP 130
                    765: #define AGEBASE 40
1.194     brouard   766: #define AGEOVERFLOW 1.e20
1.164     brouard   767: #define AGEGOMP 10 /**< Minimal age for Gompertz adjustment */
1.157     brouard   768: #ifdef _WIN32
                    769: #define DIRSEPARATOR '\\'
                    770: #define CHARSEPARATOR "\\"
                    771: #define ODIRSEPARATOR '/'
                    772: #else
1.126     brouard   773: #define DIRSEPARATOR '/'
                    774: #define CHARSEPARATOR "/"
                    775: #define ODIRSEPARATOR '\\'
                    776: #endif
                    777: 
1.211   ! brouard   778: /* $Id: imach.c,v 1.210 2015/11/18 17:41:20 brouard Exp $ */
1.126     brouard   779: /* $State: Exp $ */
1.196     brouard   780: #include "version.h"
                    781: char version[]=__IMACH_VERSION__;
1.204     brouard   782: 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.211   ! brouard   783: char fullversion[]="$Revision: 1.210 $ $Date: 2015/11/18 17:41:20 $"; 
1.126     brouard   784: char strstart[80];
                    785: char optionfilext[10], optionfilefiname[FILENAMELENGTH];
1.130     brouard   786: int erreur=0, nberr=0, nbwarn=0; /* Error number, number of errors number of warnings  */
1.187     brouard   787: int nagesqr=0, nforce=0; /* nagesqr=1 if model is including age*age, number of forces */
1.145     brouard   788: /* Number of covariates model=V2+V1+ V3*age+V2*V4 */
                    789: int cptcovn=0; /**< cptcovn number of covariates added in the model (excepting constant and age and age*product) */
                    790: int cptcovt=0; /**< cptcovt number of covariates added in the model (excepting constant and age) */
                    791: int cptcovs=0; /**< cptcovs number of simple covariates V2+V1 =2 */
                    792: int cptcovage=0; /**< Number of covariates with age: V3*age only =1 */
                    793: int cptcovprodnoage=0; /**< Number of covariate products without age */   
                    794: int cptcoveff=0; /* Total number of covariates to vary for printing results */
                    795: int cptcov=0; /* Working variable */
1.126     brouard   796: int npar=NPARMAX;
                    797: int nlstate=2; /* Number of live states */
                    798: int ndeath=1; /* Number of dead states */
1.130     brouard   799: int ncovmodel=0, ncovcol=0;     /* Total number of covariables including constant a12*1 +b12*x ncovmodel=2 */
1.126     brouard   800: int popbased=0;
                    801: 
                    802: int *wav; /* Number of waves for this individuual 0 is possible */
1.130     brouard   803: int maxwav=0; /* Maxim number of waves */
                    804: int jmin=0, jmax=0; /* min, max spacing between 2 waves */
                    805: int ijmin=0, ijmax=0; /* Individuals having jmin and jmax */ 
                    806: int gipmx=0, gsw=0; /* Global variables on the number of contributions 
1.126     brouard   807:                   to the likelihood and the sum of weights (done by funcone)*/
1.130     brouard   808: int mle=1, weightopt=0;
1.126     brouard   809: int **mw; /* mw[mi][i] is number of the mi wave for this individual */
                    810: int **dh; /* dh[mi][i] is number of steps between mi,mi+1 for this individual */
                    811: int **bh; /* bh[mi][i] is the bias (+ or -) for this individual if the delay between
                    812:           * wave mi and wave mi+1 is not an exact multiple of stepm. */
1.162     brouard   813: int countcallfunc=0;  /* Count the number of calls to func */
1.130     brouard   814: double jmean=1; /* Mean space between 2 waves */
1.145     brouard   815: double **matprod2(); /* test */
1.126     brouard   816: double **oldm, **newm, **savm; /* Working pointers to matrices */
                    817: double **oldms, **newms, **savms; /* Fixed working pointers to matrices */
1.136     brouard   818: /*FILE *fic ; */ /* Used in readdata only */
                    819: FILE *ficpar, *ficparo,*ficres, *ficresp, *ficrespl, *ficrespij, *ficrest,*ficresf,*ficrespop;
1.126     brouard   820: FILE *ficlog, *ficrespow;
1.130     brouard   821: int globpr=0; /* Global variable for printing or not */
1.126     brouard   822: double fretone; /* Only one call to likelihood */
1.130     brouard   823: long ipmx=0; /* Number of contributions */
1.126     brouard   824: double sw; /* Sum of weights */
                    825: char filerespow[FILENAMELENGTH];
                    826: char fileresilk[FILENAMELENGTH]; /* File of individual contributions to the likelihood */
                    827: FILE *ficresilk;
                    828: FILE *ficgp,*ficresprob,*ficpop, *ficresprobcov, *ficresprobcor;
                    829: FILE *ficresprobmorprev;
                    830: FILE *fichtm, *fichtmcov; /* Html File */
                    831: FILE *ficreseij;
                    832: char filerese[FILENAMELENGTH];
                    833: FILE *ficresstdeij;
                    834: char fileresstde[FILENAMELENGTH];
                    835: FILE *ficrescveij;
                    836: char filerescve[FILENAMELENGTH];
                    837: FILE  *ficresvij;
                    838: char fileresv[FILENAMELENGTH];
                    839: FILE  *ficresvpl;
                    840: char fileresvpl[FILENAMELENGTH];
                    841: char title[MAXLINE];
                    842: char optionfile[FILENAMELENGTH], datafile[FILENAMELENGTH],  filerespl[FILENAMELENGTH];
                    843: char plotcmd[FILENAMELENGTH], pplotcmd[FILENAMELENGTH];
                    844: char tmpout[FILENAMELENGTH],  tmpout2[FILENAMELENGTH]; 
                    845: char command[FILENAMELENGTH];
                    846: int  outcmd=0;
                    847: 
                    848: char fileres[FILENAMELENGTH], filerespij[FILENAMELENGTH], filereso[FILENAMELENGTH], rfileres[FILENAMELENGTH];
1.202     brouard   849: char fileresu[FILENAMELENGTH]; /* fileres without r in front */
1.126     brouard   850: char filelog[FILENAMELENGTH]; /* Log file */
                    851: char filerest[FILENAMELENGTH];
                    852: char fileregp[FILENAMELENGTH];
                    853: char popfile[FILENAMELENGTH];
                    854: 
                    855: char optionfilegnuplot[FILENAMELENGTH], optionfilehtm[FILENAMELENGTH], optionfilehtmcov[FILENAMELENGTH] ;
                    856: 
1.157     brouard   857: /* struct timeval start_time, end_time, curr_time, last_time, forecast_time; */
                    858: /* struct timezone tzp; */
                    859: /* extern int gettimeofday(); */
                    860: struct tm tml, *gmtime(), *localtime();
                    861: 
                    862: extern time_t time();
                    863: 
                    864: struct tm start_time, end_time, curr_time, last_time, forecast_time;
                    865: time_t  rstart_time, rend_time, rcurr_time, rlast_time, rforecast_time; /* raw time */
                    866: struct tm tm;
                    867: 
1.126     brouard   868: char strcurr[80], strfor[80];
                    869: 
                    870: char *endptr;
                    871: long lval;
                    872: double dval;
                    873: 
                    874: #define NR_END 1
                    875: #define FREE_ARG char*
                    876: #define FTOL 1.0e-10
                    877: 
                    878: #define NRANSI 
                    879: #define ITMAX 200 
                    880: 
                    881: #define TOL 2.0e-4 
                    882: 
                    883: #define CGOLD 0.3819660 
                    884: #define ZEPS 1.0e-10 
                    885: #define SHFT(a,b,c,d) (a)=(b);(b)=(c);(c)=(d); 
                    886: 
                    887: #define GOLD 1.618034 
                    888: #define GLIMIT 100.0 
                    889: #define TINY 1.0e-20 
                    890: 
                    891: static double maxarg1,maxarg2;
                    892: #define FMAX(a,b) (maxarg1=(a),maxarg2=(b),(maxarg1)>(maxarg2)? (maxarg1):(maxarg2))
                    893: #define FMIN(a,b) (maxarg1=(a),maxarg2=(b),(maxarg1)<(maxarg2)? (maxarg1):(maxarg2))
                    894:   
                    895: #define SIGN(a,b) ((b)>0.0 ? fabs(a) : -fabs(a))
                    896: #define rint(a) floor(a+0.5)
1.166     brouard   897: /* http://www.thphys.uni-heidelberg.de/~robbers/cmbeasy/doc/html/myutils_8h-source.html */
1.183     brouard   898: #define mytinydouble 1.0e-16
1.166     brouard   899: /* #define DEQUAL(a,b) (fabs((a)-(b))<mytinydouble) */
                    900: /* http://www.thphys.uni-heidelberg.de/~robbers/cmbeasy/doc/html/mynrutils_8h-source.html */
                    901: /* static double dsqrarg; */
                    902: /* #define DSQR(a) (DEQUAL((dsqrarg=(a)),0.0) ? 0.0 : dsqrarg*dsqrarg) */
1.126     brouard   903: static double sqrarg;
                    904: #define SQR(a) ((sqrarg=(a)) == 0.0 ? 0.0 :sqrarg*sqrarg)
                    905: #define SWAP(a,b) {temp=(a);(a)=(b);(b)=temp;} 
                    906: int agegomp= AGEGOMP;
                    907: 
                    908: int imx; 
                    909: int stepm=1;
                    910: /* Stepm, step in month: minimum step interpolation*/
                    911: 
                    912: int estepm;
                    913: /* Estepm, step in month to interpolate survival function in order to approximate Life Expectancy*/
                    914: 
                    915: int m,nb;
                    916: long *num;
1.197     brouard   917: int firstpass=0, lastpass=4,*cod, *cens;
1.192     brouard   918: int *ncodemax;  /* ncodemax[j]= Number of modalities of the j th
                    919:                   covariate for which somebody answered excluding 
                    920:                   undefined. Usually 2: 0 and 1. */
                    921: int *ncodemaxwundef;  /* ncodemax[j]= Number of modalities of the j th
                    922:                             covariate for which somebody answered including 
                    923:                             undefined. Usually 3: -1, 0 and 1. */
1.126     brouard   924: double **agev,*moisnais, *annais, *moisdc, *andc,**mint, **anint;
                    925: double **pmmij, ***probs;
                    926: double *ageexmed,*agecens;
                    927: double dateintmean=0;
                    928: 
                    929: double *weight;
                    930: int **s; /* Status */
1.141     brouard   931: double *agedc;
1.145     brouard   932: double  **covar; /**< covar[j,i], value of jth covariate for individual i,
1.141     brouard   933:                  * covar=matrix(0,NCOVMAX,1,n); 
1.187     brouard   934:                  * cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*age; */
1.141     brouard   935: double  idx; 
                    936: int **nbcode, *Tvar; /**< model=V2 => Tvar[1]= 2 */
1.197     brouard   937: int *Tage;
1.145     brouard   938: int *Ndum; /** Freq of modality (tricode */
1.200     brouard   939: /* int **codtab;*/ /**< codtab=imatrix(1,100,1,10); */
1.141     brouard   940: int **Tvard, *Tprod, cptcovprod, *Tvaraff;
1.126     brouard   941: double *lsurv, *lpop, *tpop;
                    942: 
1.143     brouard   943: double ftol=FTOL; /**< Tolerance for computing Max Likelihood */
                    944: double ftolhess; /**< Tolerance for computing hessian */
1.126     brouard   945: 
                    946: /**************** split *************************/
                    947: static int split( char *path, char *dirc, char *name, char *ext, char *finame )
                    948: {
                    949:   /* From a file name with (full) path (either Unix or Windows) we extract the directory (dirc)
                    950:      the name of the file (name), its extension only (ext) and its first part of the name (finame)
                    951:   */ 
                    952:   char *ss;                            /* pointer */
1.186     brouard   953:   int  l1=0, l2=0;                             /* length counters */
1.126     brouard   954: 
                    955:   l1 = strlen(path );                  /* length of path */
                    956:   if ( l1 == 0 ) return( GLOCK_ERROR_NOPATH );
                    957:   ss= strrchr( path, DIRSEPARATOR );           /* find last / */
                    958:   if ( ss == NULL ) {                  /* no directory, so determine current directory */
                    959:     strcpy( name, path );              /* we got the fullname name because no directory */
                    960:     /*if(strrchr(path, ODIRSEPARATOR )==NULL)
                    961:       printf("Warning you should use %s as a separator\n",DIRSEPARATOR);*/
                    962:     /* get current working directory */
                    963:     /*    extern  char* getcwd ( char *buf , int len);*/
1.184     brouard   964: #ifdef WIN32
                    965:     if (_getcwd( dirc, FILENAME_MAX ) == NULL ) {
                    966: #else
                    967:        if (getcwd(dirc, FILENAME_MAX) == NULL) {
                    968: #endif
1.126     brouard   969:       return( GLOCK_ERROR_GETCWD );
                    970:     }
                    971:     /* got dirc from getcwd*/
                    972:     printf(" DIRC = %s \n",dirc);
1.205     brouard   973:   } else {                             /* strip directory from path */
1.126     brouard   974:     ss++;                              /* after this, the filename */
                    975:     l2 = strlen( ss );                 /* length of filename */
                    976:     if ( l2 == 0 ) return( GLOCK_ERROR_NOPATH );
                    977:     strcpy( name, ss );                /* save file name */
                    978:     strncpy( dirc, path, l1 - l2 );    /* now the directory */
1.186     brouard   979:     dirc[l1-l2] = '\0';                        /* add zero */
1.126     brouard   980:     printf(" DIRC2 = %s \n",dirc);
                    981:   }
                    982:   /* We add a separator at the end of dirc if not exists */
                    983:   l1 = strlen( dirc );                 /* length of directory */
                    984:   if( dirc[l1-1] != DIRSEPARATOR ){
                    985:     dirc[l1] =  DIRSEPARATOR;
                    986:     dirc[l1+1] = 0; 
                    987:     printf(" DIRC3 = %s \n",dirc);
                    988:   }
                    989:   ss = strrchr( name, '.' );           /* find last / */
                    990:   if (ss >0){
                    991:     ss++;
                    992:     strcpy(ext,ss);                    /* save extension */
                    993:     l1= strlen( name);
                    994:     l2= strlen(ss)+1;
                    995:     strncpy( finame, name, l1-l2);
                    996:     finame[l1-l2]= 0;
                    997:   }
                    998: 
                    999:   return( 0 );                         /* we're done */
                   1000: }
                   1001: 
                   1002: 
                   1003: /******************************************/
                   1004: 
                   1005: void replace_back_to_slash(char *s, char*t)
                   1006: {
                   1007:   int i;
                   1008:   int lg=0;
                   1009:   i=0;
                   1010:   lg=strlen(t);
                   1011:   for(i=0; i<= lg; i++) {
                   1012:     (s[i] = t[i]);
                   1013:     if (t[i]== '\\') s[i]='/';
                   1014:   }
                   1015: }
                   1016: 
1.132     brouard  1017: char *trimbb(char *out, char *in)
1.137     brouard  1018: { /* Trim multiple blanks in line but keeps first blanks if line starts with blanks */
1.132     brouard  1019:   char *s;
                   1020:   s=out;
                   1021:   while (*in != '\0'){
1.137     brouard  1022:     while( *in == ' ' && *(in+1) == ' '){ /* && *(in+1) != '\0'){*/
1.132     brouard  1023:       in++;
                   1024:     }
                   1025:     *out++ = *in++;
                   1026:   }
                   1027:   *out='\0';
                   1028:   return s;
                   1029: }
                   1030: 
1.187     brouard  1031: /* char *substrchaine(char *out, char *in, char *chain) */
                   1032: /* { */
                   1033: /*   /\* Substract chain 'chain' from 'in', return and output 'out' *\/ */
                   1034: /*   char *s, *t; */
                   1035: /*   t=in;s=out; */
                   1036: /*   while ((*in != *chain) && (*in != '\0')){ */
                   1037: /*     *out++ = *in++; */
                   1038: /*   } */
                   1039: 
                   1040: /*   /\* *in matches *chain *\/ */
                   1041: /*   while ((*in++ == *chain++) && (*in != '\0')){ */
                   1042: /*     printf("*in = %c, *out= %c *chain= %c \n", *in, *out, *chain);  */
                   1043: /*   } */
                   1044: /*   in--; chain--; */
                   1045: /*   while ( (*in != '\0')){ */
                   1046: /*     printf("Bef *in = %c, *out= %c *chain= %c \n", *in, *out, *chain);  */
                   1047: /*     *out++ = *in++; */
                   1048: /*     printf("Aft *in = %c, *out= %c *chain= %c \n", *in, *out, *chain);  */
                   1049: /*   } */
                   1050: /*   *out='\0'; */
                   1051: /*   out=s; */
                   1052: /*   return out; */
                   1053: /* } */
                   1054: char *substrchaine(char *out, char *in, char *chain)
                   1055: {
                   1056:   /* Substract chain 'chain' from 'in', return and output 'out' */
                   1057:   /* in="V1+V1*age+age*age+V2", chain="age*age" */
                   1058: 
                   1059:   char *strloc;
                   1060: 
                   1061:   strcpy (out, in); 
                   1062:   strloc = strstr(out, chain); /* strloc points to out at age*age+V2 */
                   1063:   printf("Bef strloc=%s chain=%s out=%s \n", strloc, chain, out);
                   1064:   if(strloc != NULL){ 
                   1065:     /* will affect out */ /* strloc+strlenc(chain)=+V2 */ /* Will also work in Unicode */
                   1066:     memmove(strloc,strloc+strlen(chain), strlen(strloc+strlen(chain))+1);
                   1067:     /* strcpy (strloc, strloc +strlen(chain));*/
                   1068:   }
                   1069:   printf("Aft strloc=%s chain=%s in=%s out=%s \n", strloc, chain, in, out);
                   1070:   return out;
                   1071: }
                   1072: 
                   1073: 
1.145     brouard  1074: char *cutl(char *blocc, char *alocc, char *in, char occ)
                   1075: {
1.187     brouard  1076:   /* cuts string in into blocc and alocc where blocc ends before FIRST occurence of char 'occ' 
1.145     brouard  1077:      and alocc starts after first occurence of char 'occ' : ex cutv(blocc,alocc,"abcdef2ghi2j",'2')
1.187     brouard  1078:      gives blocc="abcdef" and alocc="ghi2j".
1.145     brouard  1079:      If occ is not found blocc is null and alocc is equal to in. Returns blocc
                   1080:   */
1.160     brouard  1081:   char *s, *t;
1.145     brouard  1082:   t=in;s=in;
                   1083:   while ((*in != occ) && (*in != '\0')){
                   1084:     *alocc++ = *in++;
                   1085:   }
                   1086:   if( *in == occ){
                   1087:     *(alocc)='\0';
                   1088:     s=++in;
                   1089:   }
                   1090:  
                   1091:   if (s == t) {/* occ not found */
                   1092:     *(alocc-(in-s))='\0';
                   1093:     in=s;
                   1094:   }
                   1095:   while ( *in != '\0'){
                   1096:     *blocc++ = *in++;
                   1097:   }
                   1098: 
                   1099:   *blocc='\0';
                   1100:   return t;
                   1101: }
1.137     brouard  1102: char *cutv(char *blocc, char *alocc, char *in, char occ)
                   1103: {
1.187     brouard  1104:   /* cuts string in into blocc and alocc where blocc ends before LAST occurence of char 'occ' 
1.137     brouard  1105:      and alocc starts after last occurence of char 'occ' : ex cutv(blocc,alocc,"abcdef2ghi2j",'2')
                   1106:      gives blocc="abcdef2ghi" and alocc="j".
                   1107:      If occ is not found blocc is null and alocc is equal to in. Returns alocc
                   1108:   */
                   1109:   char *s, *t;
                   1110:   t=in;s=in;
                   1111:   while (*in != '\0'){
                   1112:     while( *in == occ){
                   1113:       *blocc++ = *in++;
                   1114:       s=in;
                   1115:     }
                   1116:     *blocc++ = *in++;
                   1117:   }
                   1118:   if (s == t) /* occ not found */
                   1119:     *(blocc-(in-s))='\0';
                   1120:   else
                   1121:     *(blocc-(in-s)-1)='\0';
                   1122:   in=s;
                   1123:   while ( *in != '\0'){
                   1124:     *alocc++ = *in++;
                   1125:   }
                   1126: 
                   1127:   *alocc='\0';
                   1128:   return s;
                   1129: }
                   1130: 
1.126     brouard  1131: int nbocc(char *s, char occ)
                   1132: {
                   1133:   int i,j=0;
                   1134:   int lg=20;
                   1135:   i=0;
                   1136:   lg=strlen(s);
                   1137:   for(i=0; i<= lg; i++) {
                   1138:   if  (s[i] == occ ) j++;
                   1139:   }
                   1140:   return j;
                   1141: }
                   1142: 
1.137     brouard  1143: /* void cutv(char *u,char *v, char*t, char occ) */
                   1144: /* { */
                   1145: /*   /\* cuts string t into u and v where u ends before last occurence of char 'occ'  */
                   1146: /*      and v starts after last occurence of char 'occ' : ex cutv(u,v,"abcdef2ghi2j",'2') */
                   1147: /*      gives u="abcdef2ghi" and v="j" *\/ */
                   1148: /*   int i,lg,j,p=0; */
                   1149: /*   i=0; */
                   1150: /*   lg=strlen(t); */
                   1151: /*   for(j=0; j<=lg-1; j++) { */
                   1152: /*     if((t[j]!= occ) && (t[j+1]== occ)) p=j+1; */
                   1153: /*   } */
1.126     brouard  1154: 
1.137     brouard  1155: /*   for(j=0; j<p; j++) { */
                   1156: /*     (u[j] = t[j]); */
                   1157: /*   } */
                   1158: /*      u[p]='\0'; */
1.126     brouard  1159: 
1.137     brouard  1160: /*    for(j=0; j<= lg; j++) { */
                   1161: /*     if (j>=(p+1))(v[j-p-1] = t[j]); */
                   1162: /*   } */
                   1163: /* } */
1.126     brouard  1164: 
1.160     brouard  1165: #ifdef _WIN32
                   1166: char * strsep(char **pp, const char *delim)
                   1167: {
                   1168:   char *p, *q;
                   1169:          
                   1170:   if ((p = *pp) == NULL)
                   1171:     return 0;
                   1172:   if ((q = strpbrk (p, delim)) != NULL)
                   1173:   {
                   1174:     *pp = q + 1;
                   1175:     *q = '\0';
                   1176:   }
                   1177:   else
                   1178:     *pp = 0;
                   1179:   return p;
                   1180: }
                   1181: #endif
                   1182: 
1.126     brouard  1183: /********************** nrerror ********************/
                   1184: 
                   1185: void nrerror(char error_text[])
                   1186: {
                   1187:   fprintf(stderr,"ERREUR ...\n");
                   1188:   fprintf(stderr,"%s\n",error_text);
                   1189:   exit(EXIT_FAILURE);
                   1190: }
                   1191: /*********************** vector *******************/
                   1192: double *vector(int nl, int nh)
                   1193: {
                   1194:   double *v;
                   1195:   v=(double *) malloc((size_t)((nh-nl+1+NR_END)*sizeof(double)));
                   1196:   if (!v) nrerror("allocation failure in vector");
                   1197:   return v-nl+NR_END;
                   1198: }
                   1199: 
                   1200: /************************ free vector ******************/
                   1201: void free_vector(double*v, int nl, int nh)
                   1202: {
                   1203:   free((FREE_ARG)(v+nl-NR_END));
                   1204: }
                   1205: 
                   1206: /************************ivector *******************************/
                   1207: int *ivector(long nl,long nh)
                   1208: {
                   1209:   int *v;
                   1210:   v=(int *) malloc((size_t)((nh-nl+1+NR_END)*sizeof(int)));
                   1211:   if (!v) nrerror("allocation failure in ivector");
                   1212:   return v-nl+NR_END;
                   1213: }
                   1214: 
                   1215: /******************free ivector **************************/
                   1216: void free_ivector(int *v, long nl, long nh)
                   1217: {
                   1218:   free((FREE_ARG)(v+nl-NR_END));
                   1219: }
                   1220: 
                   1221: /************************lvector *******************************/
                   1222: long *lvector(long nl,long nh)
                   1223: {
                   1224:   long *v;
                   1225:   v=(long *) malloc((size_t)((nh-nl+1+NR_END)*sizeof(long)));
                   1226:   if (!v) nrerror("allocation failure in ivector");
                   1227:   return v-nl+NR_END;
                   1228: }
                   1229: 
                   1230: /******************free lvector **************************/
                   1231: void free_lvector(long *v, long nl, long nh)
                   1232: {
                   1233:   free((FREE_ARG)(v+nl-NR_END));
                   1234: }
                   1235: 
                   1236: /******************* imatrix *******************************/
                   1237: int **imatrix(long nrl, long nrh, long ncl, long nch) 
                   1238:      /* allocate a int matrix with subscript range m[nrl..nrh][ncl..nch] */ 
                   1239: { 
                   1240:   long i, nrow=nrh-nrl+1,ncol=nch-ncl+1; 
                   1241:   int **m; 
                   1242:   
                   1243:   /* allocate pointers to rows */ 
                   1244:   m=(int **) malloc((size_t)((nrow+NR_END)*sizeof(int*))); 
                   1245:   if (!m) nrerror("allocation failure 1 in matrix()"); 
                   1246:   m += NR_END; 
                   1247:   m -= nrl; 
                   1248:   
                   1249:   
                   1250:   /* allocate rows and set pointers to them */ 
                   1251:   m[nrl]=(int *) malloc((size_t)((nrow*ncol+NR_END)*sizeof(int))); 
                   1252:   if (!m[nrl]) nrerror("allocation failure 2 in matrix()"); 
                   1253:   m[nrl] += NR_END; 
                   1254:   m[nrl] -= ncl; 
                   1255:   
                   1256:   for(i=nrl+1;i<=nrh;i++) m[i]=m[i-1]+ncol; 
                   1257:   
                   1258:   /* return pointer to array of pointers to rows */ 
                   1259:   return m; 
                   1260: } 
                   1261: 
                   1262: /****************** free_imatrix *************************/
                   1263: void free_imatrix(m,nrl,nrh,ncl,nch)
                   1264:       int **m;
                   1265:       long nch,ncl,nrh,nrl; 
                   1266:      /* free an int matrix allocated by imatrix() */ 
                   1267: { 
                   1268:   free((FREE_ARG) (m[nrl]+ncl-NR_END)); 
                   1269:   free((FREE_ARG) (m+nrl-NR_END)); 
                   1270: } 
                   1271: 
                   1272: /******************* matrix *******************************/
                   1273: double **matrix(long nrl, long nrh, long ncl, long nch)
                   1274: {
                   1275:   long i, nrow=nrh-nrl+1, ncol=nch-ncl+1;
                   1276:   double **m;
                   1277: 
                   1278:   m=(double **) malloc((size_t)((nrow+NR_END)*sizeof(double*)));
                   1279:   if (!m) nrerror("allocation failure 1 in matrix()");
                   1280:   m += NR_END;
                   1281:   m -= nrl;
                   1282: 
                   1283:   m[nrl]=(double *) malloc((size_t)((nrow*ncol+NR_END)*sizeof(double)));
                   1284:   if (!m[nrl]) nrerror("allocation failure 2 in matrix()");
                   1285:   m[nrl] += NR_END;
                   1286:   m[nrl] -= ncl;
                   1287: 
                   1288:   for (i=nrl+1; i<=nrh; i++) m[i]=m[i-1]+ncol;
                   1289:   return m;
1.145     brouard  1290:   /* print *(*(m+1)+70) or print m[1][70]; print m+1 or print &(m[1]) or &(m[1][0])
                   1291: m[i] = address of ith row of the table. &(m[i]) is its value which is another adress
                   1292: that of m[i][0]. In order to get the value p m[i][0] but it is unitialized.
1.126     brouard  1293:    */
                   1294: }
                   1295: 
                   1296: /*************************free matrix ************************/
                   1297: void free_matrix(double **m, long nrl, long nrh, long ncl, long nch)
                   1298: {
                   1299:   free((FREE_ARG)(m[nrl]+ncl-NR_END));
                   1300:   free((FREE_ARG)(m+nrl-NR_END));
                   1301: }
                   1302: 
                   1303: /******************* ma3x *******************************/
                   1304: double ***ma3x(long nrl, long nrh, long ncl, long nch, long nll, long nlh)
                   1305: {
                   1306:   long i, j, nrow=nrh-nrl+1, ncol=nch-ncl+1, nlay=nlh-nll+1;
                   1307:   double ***m;
                   1308: 
                   1309:   m=(double ***) malloc((size_t)((nrow+NR_END)*sizeof(double*)));
                   1310:   if (!m) nrerror("allocation failure 1 in matrix()");
                   1311:   m += NR_END;
                   1312:   m -= nrl;
                   1313: 
                   1314:   m[nrl]=(double **) malloc((size_t)((nrow*ncol+NR_END)*sizeof(double)));
                   1315:   if (!m[nrl]) nrerror("allocation failure 2 in matrix()");
                   1316:   m[nrl] += NR_END;
                   1317:   m[nrl] -= ncl;
                   1318: 
                   1319:   for (i=nrl+1; i<=nrh; i++) m[i]=m[i-1]+ncol;
                   1320: 
                   1321:   m[nrl][ncl]=(double *) malloc((size_t)((nrow*ncol*nlay+NR_END)*sizeof(double)));
                   1322:   if (!m[nrl][ncl]) nrerror("allocation failure 3 in matrix()");
                   1323:   m[nrl][ncl] += NR_END;
                   1324:   m[nrl][ncl] -= nll;
                   1325:   for (j=ncl+1; j<=nch; j++) 
                   1326:     m[nrl][j]=m[nrl][j-1]+nlay;
                   1327:   
                   1328:   for (i=nrl+1; i<=nrh; i++) {
                   1329:     m[i][ncl]=m[i-1l][ncl]+ncol*nlay;
                   1330:     for (j=ncl+1; j<=nch; j++) 
                   1331:       m[i][j]=m[i][j-1]+nlay;
                   1332:   }
                   1333:   return m; 
                   1334:   /*  gdb: p *(m+1) <=> p m[1] and p (m+1) <=> p (m+1) <=> p &(m[1])
                   1335:            &(m[i][j][k]) <=> *((*(m+i) + j)+k)
                   1336:   */
                   1337: }
                   1338: 
                   1339: /*************************free ma3x ************************/
                   1340: void free_ma3x(double ***m, long nrl, long nrh, long ncl, long nch,long nll, long nlh)
                   1341: {
                   1342:   free((FREE_ARG)(m[nrl][ncl]+ nll-NR_END));
                   1343:   free((FREE_ARG)(m[nrl]+ncl-NR_END));
                   1344:   free((FREE_ARG)(m+nrl-NR_END));
                   1345: }
                   1346: 
                   1347: /*************** function subdirf ***********/
                   1348: char *subdirf(char fileres[])
                   1349: {
                   1350:   /* Caution optionfilefiname is hidden */
                   1351:   strcpy(tmpout,optionfilefiname);
                   1352:   strcat(tmpout,"/"); /* Add to the right */
                   1353:   strcat(tmpout,fileres);
                   1354:   return tmpout;
                   1355: }
                   1356: 
                   1357: /*************** function subdirf2 ***********/
                   1358: char *subdirf2(char fileres[], char *preop)
                   1359: {
                   1360:   
                   1361:   /* Caution optionfilefiname is hidden */
                   1362:   strcpy(tmpout,optionfilefiname);
                   1363:   strcat(tmpout,"/");
                   1364:   strcat(tmpout,preop);
                   1365:   strcat(tmpout,fileres);
                   1366:   return tmpout;
                   1367: }
                   1368: 
                   1369: /*************** function subdirf3 ***********/
                   1370: char *subdirf3(char fileres[], char *preop, char *preop2)
                   1371: {
                   1372:   
                   1373:   /* Caution optionfilefiname is hidden */
                   1374:   strcpy(tmpout,optionfilefiname);
                   1375:   strcat(tmpout,"/");
                   1376:   strcat(tmpout,preop);
                   1377:   strcat(tmpout,preop2);
                   1378:   strcat(tmpout,fileres);
                   1379:   return tmpout;
                   1380: }
                   1381: 
1.162     brouard  1382: char *asc_diff_time(long time_sec, char ascdiff[])
                   1383: {
                   1384:   long sec_left, days, hours, minutes;
                   1385:   days = (time_sec) / (60*60*24);
                   1386:   sec_left = (time_sec) % (60*60*24);
                   1387:   hours = (sec_left) / (60*60) ;
                   1388:   sec_left = (sec_left) %(60*60);
                   1389:   minutes = (sec_left) /60;
                   1390:   sec_left = (sec_left) % (60);
                   1391:   sprintf(ascdiff,"%ld day(s) %ld hour(s) %ld minute(s) %ld second(s)",days, hours, minutes, sec_left);  
                   1392:   return ascdiff;
                   1393: }
                   1394: 
1.126     brouard  1395: /***************** f1dim *************************/
                   1396: extern int ncom; 
                   1397: extern double *pcom,*xicom;
                   1398: extern double (*nrfunc)(double []); 
                   1399:  
                   1400: double f1dim(double x) 
                   1401: { 
                   1402:   int j; 
                   1403:   double f;
                   1404:   double *xt; 
                   1405:  
                   1406:   xt=vector(1,ncom); 
                   1407:   for (j=1;j<=ncom;j++) xt[j]=pcom[j]+x*xicom[j]; 
                   1408:   f=(*nrfunc)(xt); 
                   1409:   free_vector(xt,1,ncom); 
                   1410:   return f; 
                   1411: } 
                   1412: 
                   1413: /*****************brent *************************/
                   1414: double brent(double ax, double bx, double cx, double (*f)(double), double tol,         double *xmin) 
1.187     brouard  1415: {
                   1416:   /* Given a function f, and given a bracketing triplet of abscissas ax, bx, cx (such that bx is
                   1417:    * between ax and cx, and f(bx) is less than both f(ax) and f(cx) ), this routine isolates
                   1418:    * the minimum to a fractional precision of about tol using Brent’s method. The abscissa of
                   1419:    * the minimum is returned as xmin, and the minimum function value is returned as brent , the
                   1420:    * returned function value. 
                   1421:   */
1.126     brouard  1422:   int iter; 
                   1423:   double a,b,d,etemp;
1.159     brouard  1424:   double fu=0,fv,fw,fx;
1.164     brouard  1425:   double ftemp=0.;
1.126     brouard  1426:   double p,q,r,tol1,tol2,u,v,w,x,xm; 
                   1427:   double e=0.0; 
                   1428:  
                   1429:   a=(ax < cx ? ax : cx); 
                   1430:   b=(ax > cx ? ax : cx); 
                   1431:   x=w=v=bx; 
                   1432:   fw=fv=fx=(*f)(x); 
                   1433:   for (iter=1;iter<=ITMAX;iter++) { 
                   1434:     xm=0.5*(a+b); 
                   1435:     tol2=2.0*(tol1=tol*fabs(x)+ZEPS); 
                   1436:     /*         if (2.0*fabs(fp-(*fret)) <= ftol*(fabs(fp)+fabs(*fret)))*/
                   1437:     printf(".");fflush(stdout);
                   1438:     fprintf(ficlog,".");fflush(ficlog);
1.162     brouard  1439: #ifdef DEBUGBRENT
1.126     brouard  1440:     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);
                   1441:     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);
                   1442:     /*         if ((fabs(x-xm) <= (tol2-0.5*(b-a)))||(2.0*fabs(fu-ftemp) <= ftol*1.e-2*(fabs(fu)+fabs(ftemp)))) { */
                   1443: #endif
                   1444:     if (fabs(x-xm) <= (tol2-0.5*(b-a))){ 
                   1445:       *xmin=x; 
                   1446:       return fx; 
                   1447:     } 
                   1448:     ftemp=fu;
                   1449:     if (fabs(e) > tol1) { 
                   1450:       r=(x-w)*(fx-fv); 
                   1451:       q=(x-v)*(fx-fw); 
                   1452:       p=(x-v)*q-(x-w)*r; 
                   1453:       q=2.0*(q-r); 
                   1454:       if (q > 0.0) p = -p; 
                   1455:       q=fabs(q); 
                   1456:       etemp=e; 
                   1457:       e=d; 
                   1458:       if (fabs(p) >= fabs(0.5*q*etemp) || p <= q*(a-x) || p >= q*(b-x)) 
                   1459:        d=CGOLD*(e=(x >= xm ? a-x : b-x)); 
                   1460:       else { 
                   1461:        d=p/q; 
                   1462:        u=x+d; 
                   1463:        if (u-a < tol2 || b-u < tol2) 
                   1464:          d=SIGN(tol1,xm-x); 
                   1465:       } 
                   1466:     } else { 
                   1467:       d=CGOLD*(e=(x >= xm ? a-x : b-x)); 
                   1468:     } 
                   1469:     u=(fabs(d) >= tol1 ? x+d : x+SIGN(tol1,d)); 
                   1470:     fu=(*f)(u); 
                   1471:     if (fu <= fx) { 
                   1472:       if (u >= x) a=x; else b=x; 
                   1473:       SHFT(v,w,x,u) 
1.183     brouard  1474:       SHFT(fv,fw,fx,fu) 
                   1475:     } else { 
                   1476:       if (u < x) a=u; else b=u; 
                   1477:       if (fu <= fw || w == x) { 
                   1478:        v=w; 
                   1479:        w=u; 
                   1480:        fv=fw; 
                   1481:        fw=fu; 
                   1482:       } else if (fu <= fv || v == x || v == w) { 
                   1483:        v=u; 
                   1484:        fv=fu; 
                   1485:       } 
                   1486:     } 
1.126     brouard  1487:   } 
                   1488:   nrerror("Too many iterations in brent"); 
                   1489:   *xmin=x; 
                   1490:   return fx; 
                   1491: } 
                   1492: 
                   1493: /****************** mnbrak ***********************/
                   1494: 
                   1495: void mnbrak(double *ax, double *bx, double *cx, double *fa, double *fb, double *fc, 
                   1496:            double (*func)(double)) 
1.183     brouard  1497: { /* Given a function func , and given distinct initial points ax and bx , this routine searches in
                   1498: the downhill direction (defined by the function as evaluated at the initial points) and returns
                   1499: new points ax , bx , cx that bracket a minimum of the function. Also returned are the function
                   1500: values at the three points, fa, fb , and fc such that fa > fb and fb < fc.
                   1501:    */
1.126     brouard  1502:   double ulim,u,r,q, dum;
                   1503:   double fu; 
1.187     brouard  1504: 
                   1505:   double scale=10.;
                   1506:   int iterscale=0;
                   1507: 
                   1508:   *fa=(*func)(*ax); /*  xta[j]=pcom[j]+(*ax)*xicom[j]; fa=f(xta[j])*/
                   1509:   *fb=(*func)(*bx); /*  xtb[j]=pcom[j]+(*bx)*xicom[j]; fb=f(xtb[j]) */
                   1510: 
                   1511: 
                   1512:   /* while(*fb != *fb){ /\* *ax should be ok, reducing distance to *ax *\/ */
                   1513:   /*   printf("Warning mnbrak *fb = %lf, *bx=%lf *ax=%lf *fa==%lf iter=%d\n",*fb, *bx, *ax, *fa, iterscale++); */
                   1514:   /*   *bx = *ax - (*ax - *bx)/scale; */
                   1515:   /*   *fb=(*func)(*bx);  /\*  xtb[j]=pcom[j]+(*bx)*xicom[j]; fb=f(xtb[j]) *\/ */
                   1516:   /* } */
                   1517: 
1.126     brouard  1518:   if (*fb > *fa) { 
                   1519:     SHFT(dum,*ax,*bx,dum) 
1.183     brouard  1520:     SHFT(dum,*fb,*fa,dum) 
                   1521:   } 
1.126     brouard  1522:   *cx=(*bx)+GOLD*(*bx-*ax); 
                   1523:   *fc=(*func)(*cx); 
1.183     brouard  1524: #ifdef DEBUG
                   1525:   printf("mnbrak0 *fb=%.12e *fc=%.12e\n",*fb,*fc);
                   1526:   fprintf(ficlog,"mnbrak0 *fb=%.12e *fc=%.12e\n",*fb,*fc);
                   1527: #endif
                   1528:   while (*fb > *fc) { /* Declining a,b,c with fa> fb > fc */
1.126     brouard  1529:     r=(*bx-*ax)*(*fb-*fc); 
                   1530:     q=(*bx-*cx)*(*fb-*fa); 
                   1531:     u=(*bx)-((*bx-*cx)*q-(*bx-*ax)*r)/ 
1.183     brouard  1532:       (2.0*SIGN(FMAX(fabs(q-r),TINY),q-r)); /* Minimum abscissa of a parabolic estimated from (a,fa), (b,fb) and (c,fc). */
                   1533:     ulim=(*bx)+GLIMIT*(*cx-*bx); /* Maximum abscissa where function should be evaluated */
                   1534:     if ((*bx-u)*(u-*cx) > 0.0) { /* if u_p is between b and c */
1.126     brouard  1535:       fu=(*func)(u); 
1.163     brouard  1536: #ifdef DEBUG
                   1537:       /* f(x)=A(x-u)**2+f(u) */
                   1538:       double A, fparabu; 
                   1539:       A= (*fb - *fa)/(*bx-*ax)/(*bx+*ax-2*u);
                   1540:       fparabu= *fa - A*(*ax-u)*(*ax-u);
                   1541:       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);
                   1542:       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  1543:       /* And thus,it can be that fu > *fc even if fparabu < *fc */
                   1544:       /* mnbrak (*ax=7.666299858533, *fa=299039.693133272231), (*bx=8.595447774979, *fb=298976.598289369489),
                   1545:         (*cx=10.098840694817, *fc=298946.631474258087),  (*u=9.852501168332, fu=298948.773013752128, fparabu=298945.434711494134) */
                   1546:       /* In that case, there is no bracket in the output! Routine is wrong with many consequences.*/
1.163     brouard  1547: #endif 
1.184     brouard  1548: #ifdef MNBRAKORIGINAL
1.183     brouard  1549: #else
1.191     brouard  1550: /*       if (fu > *fc) { */
                   1551: /* #ifdef DEBUG */
                   1552: /*       printf("mnbrak4  fu > fc \n"); */
                   1553: /*       fprintf(ficlog, "mnbrak4 fu > fc\n"); */
                   1554: /* #endif */
                   1555: /*     /\* 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 *\\/  *\/ */
                   1556: /*     /\* SHFT(*fa,*fc,fu,*fc) /\\* (b, u, c) is a bracket while test fb > fc will be fu > fc  will exit *\\/ *\/ */
                   1557: /*     dum=u; /\* Shifting c and u *\/ */
                   1558: /*     u = *cx; */
                   1559: /*     *cx = dum; */
                   1560: /*     dum = fu; */
                   1561: /*     fu = *fc; */
                   1562: /*     *fc =dum; */
                   1563: /*       } else { /\* end *\/ */
                   1564: /* #ifdef DEBUG */
                   1565: /*       printf("mnbrak3  fu < fc \n"); */
                   1566: /*       fprintf(ficlog, "mnbrak3 fu < fc\n"); */
                   1567: /* #endif */
                   1568: /*     dum=u; /\* Shifting c and u *\/ */
                   1569: /*     u = *cx; */
                   1570: /*     *cx = dum; */
                   1571: /*     dum = fu; */
                   1572: /*     fu = *fc; */
                   1573: /*     *fc =dum; */
                   1574: /*       } */
1.183     brouard  1575: #ifdef DEBUG
1.191     brouard  1576:       printf("mnbrak34  fu < or >= fc \n");
                   1577:       fprintf(ficlog, "mnbrak34 fu < fc\n");
1.183     brouard  1578: #endif
1.191     brouard  1579:       dum=u; /* Shifting c and u */
                   1580:       u = *cx;
                   1581:       *cx = dum;
                   1582:       dum = fu;
                   1583:       fu = *fc;
                   1584:       *fc =dum;
1.183     brouard  1585: #endif
1.162     brouard  1586:     } else if ((*cx-u)*(u-ulim) > 0.0) { /* u is after c but before ulim */
1.183     brouard  1587: #ifdef DEBUG
                   1588:       printf("mnbrak2  u after c but before ulim\n");
                   1589:       fprintf(ficlog, "mnbrak2 u after c but before ulim\n");
                   1590: #endif
1.126     brouard  1591:       fu=(*func)(u); 
                   1592:       if (fu < *fc) { 
1.183     brouard  1593: #ifdef DEBUG
                   1594:       printf("mnbrak2  u after c but before ulim AND fu < fc\n");
                   1595:       fprintf(ficlog, "mnbrak2 u after c but before ulim AND fu <fc \n");
                   1596: #endif
1.126     brouard  1597:        SHFT(*bx,*cx,u,*cx+GOLD*(*cx-*bx)) 
1.183     brouard  1598:        SHFT(*fb,*fc,fu,(*func)(u)) 
                   1599:       } 
1.162     brouard  1600:     } else if ((u-ulim)*(ulim-*cx) >= 0.0) { /* u outside ulim (verifying that ulim is beyond c) */
1.183     brouard  1601: #ifdef DEBUG
                   1602:       printf("mnbrak2  u outside ulim (verifying that ulim is beyond c)\n");
                   1603:       fprintf(ficlog, "mnbrak2 u outside ulim (verifying that ulim is beyond c)\n");
                   1604: #endif
1.126     brouard  1605:       u=ulim; 
                   1606:       fu=(*func)(u); 
1.183     brouard  1607:     } else { /* u could be left to b (if r > q parabola has a maximum) */
                   1608: #ifdef DEBUG
                   1609:       printf("mnbrak2  u could be left to b (if r > q parabola has a maximum)\n");
                   1610:       fprintf(ficlog, "mnbrak2  u could be left to b (if r > q parabola has a maximum)\n");
                   1611: #endif
1.126     brouard  1612:       u=(*cx)+GOLD*(*cx-*bx); 
                   1613:       fu=(*func)(u); 
1.183     brouard  1614:     } /* end tests */
1.126     brouard  1615:     SHFT(*ax,*bx,*cx,u) 
1.183     brouard  1616:     SHFT(*fa,*fb,*fc,fu) 
                   1617: #ifdef DEBUG
                   1618:       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);
                   1619:       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);
                   1620: #endif
                   1621:   } /* 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  1622: } 
                   1623: 
                   1624: /*************** linmin ************************/
1.162     brouard  1625: /* Given an n -dimensional point p[1..n] and an n -dimensional direction xi[1..n] , moves and
                   1626: resets p to where the function func(p) takes on a minimum along the direction xi from p ,
                   1627: and replaces xi by the actual vector displacement that p was moved. Also returns as fret
                   1628: the value of func at the returned location p . This is actually all accomplished by calling the
                   1629: routines mnbrak and brent .*/
1.126     brouard  1630: int ncom; 
                   1631: double *pcom,*xicom;
                   1632: double (*nrfunc)(double []); 
                   1633:  
                   1634: void linmin(double p[], double xi[], int n, double *fret,double (*func)(double [])) 
                   1635: { 
                   1636:   double brent(double ax, double bx, double cx, 
                   1637:               double (*f)(double), double tol, double *xmin); 
                   1638:   double f1dim(double x); 
                   1639:   void mnbrak(double *ax, double *bx, double *cx, double *fa, double *fb, 
                   1640:              double *fc, double (*func)(double)); 
                   1641:   int j; 
                   1642:   double xx,xmin,bx,ax; 
                   1643:   double fx,fb,fa;
1.187     brouard  1644: 
1.203     brouard  1645: #ifdef LINMINORIGINAL
                   1646: #else
                   1647:   double scale=10., axs, xxs; /* Scale added for infinity */
                   1648: #endif
                   1649:   
1.126     brouard  1650:   ncom=n; 
                   1651:   pcom=vector(1,n); 
                   1652:   xicom=vector(1,n); 
                   1653:   nrfunc=func; 
                   1654:   for (j=1;j<=n;j++) { 
                   1655:     pcom[j]=p[j]; 
1.202     brouard  1656:     xicom[j]=xi[j]; /* Former scale xi[j] of currrent direction i */
1.126     brouard  1657:   } 
1.187     brouard  1658: 
1.203     brouard  1659: #ifdef LINMINORIGINAL
                   1660:   xx=1.;
                   1661: #else
                   1662:   axs=0.0;
                   1663:   xxs=1.;
                   1664:   do{
                   1665:     xx= xxs;
                   1666: #endif
1.187     brouard  1667:     ax=0.;
                   1668:     mnbrak(&ax,&xx,&bx,&fa,&fx,&fb,f1dim);  /* Outputs: xtx[j]=pcom[j]+(*xx)*xicom[j]; fx=f(xtx[j]) */
                   1669:     /* brackets with inputs ax=0 and xx=1, but points, pcom=p, and directions values, xicom=xi, are sent via f1dim(x) */
                   1670:     /* 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))   */
                   1671:     /* Outputs: fa=f(p(j)) and fx=f(p(j) + xxs * xi(j) ) and f(bx)= f(p(j)+ bx* xi(j)) */
                   1672:     /* Given input ax=axs and xx=xxs, xx might be too far from ax to get a finite f(xx) */
                   1673:     /* Searches on line, outputs (ax, xx, bx) such that fx < min(fa and fb) */
                   1674:     /* 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  1675: #ifdef LINMINORIGINAL
                   1676: #else
                   1677:     if (fx != fx){
                   1678:        xxs=xxs/scale; /* Trying a smaller xx, closer to initial ax=0 */
                   1679:        printf("|");
                   1680:        fprintf(ficlog,"|");
                   1681: #ifdef DEBUGLINMIN
                   1682:        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);
                   1683: #endif
                   1684:     }
                   1685:   }while(fx != fx);
                   1686: #endif
                   1687:   
1.191     brouard  1688: #ifdef DEBUGLINMIN
                   1689:   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  1690:   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  1691: #endif
1.187     brouard  1692:   *fret=brent(ax,xx,bx,f1dim,TOL,&xmin); /* Giving a bracketting triplet (ax, xx, bx), find a minimum, xmin, according to f1dim, *fret(xmin),*/
                   1693:   /* fa = f(p[j] + ax * xi[j]), fx = f(p[j] + xx * xi[j]), fb = f(p[j] + bx * xi[j]) */
                   1694:   /* fmin = f(p[j] + xmin * xi[j]) */
                   1695:   /* P+lambda n in that direction (lambdamin), with TOL between abscisses */
                   1696:   /* f1dim(xmin): for (j=1;j<=ncom;j++) xt[j]=pcom[j]+xmin*xicom[j]; */
1.126     brouard  1697: #ifdef DEBUG
                   1698:   printf("retour brent fret=%.12e xmin=%.12e\n",*fret,xmin);
                   1699:   fprintf(ficlog,"retour brent fret=%.12e xmin=%.12e\n",*fret,xmin);
                   1700: #endif
1.191     brouard  1701: #ifdef DEBUGLINMIN
                   1702:   printf("linmin end ");
1.202     brouard  1703:   fprintf(ficlog,"linmin end ");
1.191     brouard  1704: #endif
1.126     brouard  1705:   for (j=1;j<=n;j++) { 
1.203     brouard  1706: #ifdef LINMINORIGINAL
                   1707:     xi[j] *= xmin; 
                   1708: #else
                   1709: #ifdef DEBUGLINMIN
                   1710:     if(xxs <1.0)
                   1711:       printf(" before xi[%d]=%12.8f", j,xi[j]);
                   1712: #endif
                   1713:     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) */
                   1714: #ifdef DEBUGLINMIN
                   1715:     if(xxs <1.0)
                   1716:       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 );
                   1717: #endif
                   1718: #endif
1.187     brouard  1719:     p[j] += xi[j]; /* Parameters values are updated accordingly */
1.126     brouard  1720:   } 
1.191     brouard  1721: #ifdef DEBUGLINMIN
1.203     brouard  1722:   printf("\n");
1.191     brouard  1723:   printf("Comparing last *frec(xmin=%12.8f)=%12.8f from Brent and frec(0.)=%12.8f \n", xmin, *fret, (*func)(p));
1.202     brouard  1724:   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  1725:   for (j=1;j<=n;j++) { 
1.202     brouard  1726:     printf(" xi[%d]= %14.10f p[%d]= %12.7f",j,xi[j],j,p[j]);
                   1727:     fprintf(ficlog," xi[%d]= %14.10f p[%d]= %12.7f",j,xi[j],j,p[j]);
                   1728:     if(j % ncovmodel == 0){
1.191     brouard  1729:       printf("\n");
1.202     brouard  1730:       fprintf(ficlog,"\n");
                   1731:     }
1.191     brouard  1732:   }
1.203     brouard  1733: #else
1.191     brouard  1734: #endif
1.126     brouard  1735:   free_vector(xicom,1,n); 
                   1736:   free_vector(pcom,1,n); 
                   1737: } 
                   1738: 
                   1739: 
                   1740: /*************** powell ************************/
1.162     brouard  1741: /*
                   1742: Minimization of a function func of n variables. Input consists of an initial starting point
                   1743: p[1..n] ; an initial matrix xi[1..n][1..n] , whose columns contain the initial set of di-
                   1744: rections (usually the n unit vectors); and ftol , the fractional tolerance in the function value
                   1745: such that failure to decrease by more than this amount on one iteration signals doneness. On
                   1746: output, p is set to the best point found, xi is the then-current direction set, fret is the returned
                   1747: function value at p , and iter is the number of iterations taken. The routine linmin is used.
                   1748:  */
1.126     brouard  1749: void powell(double p[], double **xi, int n, double ftol, int *iter, double *fret, 
                   1750:            double (*func)(double [])) 
                   1751: { 
                   1752:   void linmin(double p[], double xi[], int n, double *fret, 
                   1753:              double (*func)(double [])); 
                   1754:   int i,ibig,j; 
                   1755:   double del,t,*pt,*ptt,*xit;
1.181     brouard  1756:   double directest;
1.126     brouard  1757:   double fp,fptt;
                   1758:   double *xits;
                   1759:   int niterf, itmp;
                   1760: 
                   1761:   pt=vector(1,n); 
                   1762:   ptt=vector(1,n); 
                   1763:   xit=vector(1,n); 
                   1764:   xits=vector(1,n); 
                   1765:   *fret=(*func)(p); 
                   1766:   for (j=1;j<=n;j++) pt[j]=p[j]; 
1.202     brouard  1767:   rcurr_time = time(NULL);  
1.126     brouard  1768:   for (*iter=1;;++(*iter)) { 
1.187     brouard  1769:     fp=(*fret); /* From former iteration or initial value */
1.126     brouard  1770:     ibig=0; 
                   1771:     del=0.0; 
1.157     brouard  1772:     rlast_time=rcurr_time;
                   1773:     /* (void) gettimeofday(&curr_time,&tzp); */
                   1774:     rcurr_time = time(NULL);  
                   1775:     curr_time = *localtime(&rcurr_time);
                   1776:     printf("\nPowell iter=%d -2*LL=%.12f %ld sec. %ld sec.",*iter,*fret, rcurr_time-rlast_time, rcurr_time-rstart_time);fflush(stdout);
                   1777:     fprintf(ficlog,"\nPowell iter=%d -2*LL=%.12f %ld sec. %ld sec.",*iter,*fret,rcurr_time-rlast_time, rcurr_time-rstart_time); fflush(ficlog);
                   1778: /*     fprintf(ficrespow,"%d %.12f %ld",*iter,*fret,curr_time.tm_sec-start_time.tm_sec); */
1.192     brouard  1779:     for (i=1;i<=n;i++) {
1.126     brouard  1780:       printf(" %d %.12f",i, p[i]);
                   1781:       fprintf(ficlog," %d %.12lf",i, p[i]);
                   1782:       fprintf(ficrespow," %.12lf", p[i]);
                   1783:     }
                   1784:     printf("\n");
                   1785:     fprintf(ficlog,"\n");
                   1786:     fprintf(ficrespow,"\n");fflush(ficrespow);
                   1787:     if(*iter <=3){
1.157     brouard  1788:       tml = *localtime(&rcurr_time);
                   1789:       strcpy(strcurr,asctime(&tml));
                   1790:       rforecast_time=rcurr_time; 
1.126     brouard  1791:       itmp = strlen(strcurr);
                   1792:       if(strcurr[itmp-1]=='\n')  /* Windows outputs with a new line */
                   1793:        strcurr[itmp-1]='\0';
1.162     brouard  1794:       printf("\nConsidering the time needed for the last iteration #%d: %ld seconds,\n",*iter,rcurr_time-rlast_time);
1.157     brouard  1795:       fprintf(ficlog,"\nConsidering the time needed for this last iteration #%d: %ld seconds,\n",*iter,rcurr_time-rlast_time);
1.126     brouard  1796:       for(niterf=10;niterf<=30;niterf+=10){
1.157     brouard  1797:        rforecast_time=rcurr_time+(niterf-*iter)*(rcurr_time-rlast_time);
                   1798:        forecast_time = *localtime(&rforecast_time);
                   1799:        strcpy(strfor,asctime(&forecast_time));
1.126     brouard  1800:        itmp = strlen(strfor);
                   1801:        if(strfor[itmp-1]=='\n')
                   1802:        strfor[itmp-1]='\0';
1.157     brouard  1803:        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);
                   1804:        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  1805:       }
                   1806:     }
1.187     brouard  1807:     for (i=1;i<=n;i++) { /* For each direction i */
                   1808:       for (j=1;j<=n;j++) xit[j]=xi[j][i]; /* Directions stored from previous iteration with previous scales */
1.126     brouard  1809:       fptt=(*fret); 
                   1810: #ifdef DEBUG
1.203     brouard  1811:       printf("fret=%lf, %lf, %lf \n", *fret, *fret, *fret);
                   1812:       fprintf(ficlog, "fret=%lf, %lf, %lf \n", *fret, *fret, *fret);
1.126     brouard  1813: #endif
1.203     brouard  1814:       printf("%d",i);fflush(stdout); /* print direction (parameter) i */
1.126     brouard  1815:       fprintf(ficlog,"%d",i);fflush(ficlog);
1.188     brouard  1816:       linmin(p,xit,n,fret,func); /* Point p[n]. xit[n] has been loaded for direction i as input.*/
                   1817:                                    /* Outputs are fret(new point p) p is updated and xit rescaled */
                   1818:       if (fabs(fptt-(*fret)) > del) { /* We are keeping the max gain on each of the n directions */
                   1819:        /* because that direction will be replaced unless the gain del is small */
                   1820:        /* in comparison with the 'probable' gain, mu^2, with the last average direction. */
                   1821:        /* Unless the n directions are conjugate some gain in the determinant may be obtained */
                   1822:        /* with the new direction. */
1.126     brouard  1823:        del=fabs(fptt-(*fret)); 
                   1824:        ibig=i; 
                   1825:       } 
                   1826: #ifdef DEBUG
                   1827:       printf("%d %.12e",i,(*fret));
                   1828:       fprintf(ficlog,"%d %.12e",i,(*fret));
                   1829:       for (j=1;j<=n;j++) {
                   1830:        xits[j]=FMAX(fabs(p[j]-pt[j]),1.e-5);
                   1831:        printf(" x(%d)=%.12e",j,xit[j]);
                   1832:        fprintf(ficlog," x(%d)=%.12e",j,xit[j]);
                   1833:       }
                   1834:       for(j=1;j<=n;j++) {
1.162     brouard  1835:        printf(" p(%d)=%.12e",j,p[j]);
                   1836:        fprintf(ficlog," p(%d)=%.12e",j,p[j]);
1.126     brouard  1837:       }
                   1838:       printf("\n");
                   1839:       fprintf(ficlog,"\n");
                   1840: #endif
1.187     brouard  1841:     } /* end loop on each direction i */
                   1842:     /* Convergence test will use last linmin estimation (fret) and compare former iteration (fp) */ 
1.188     brouard  1843:     /* But p and xit have been updated at the end of linmin, *fret corresponds to new p, xit  */
1.187     brouard  1844:     /* New value of last point Pn is not computed, P(n-1) */
1.182     brouard  1845:     if (2.0*fabs(fp-(*fret)) <= ftol*(fabs(fp)+fabs(*fret))) { /* Did we reach enough precision? */
1.188     brouard  1846:       /* We could compare with a chi^2. chisquare(0.95,ddl=1)=3.84 */
                   1847:       /* By adding age*age in a model, the new -2LL should be lower and the difference follows a */
                   1848:       /* a chisquare statistics with 1 degree. To be significant at the 95% level, it should have */
                   1849:       /* decreased of more than 3.84  */
                   1850:       /* By adding age*age and V1*age the gain (-2LL) should be more than 5.99 (ddl=2) */
                   1851:       /* By using V1+V2+V3, the gain should be  7.82, compared with basic 1+age. */
                   1852:       /* By adding 10 parameters more the gain should be 18.31 */
                   1853: 
                   1854:       /* Starting the program with initial values given by a former maximization will simply change */
                   1855:       /* the scales of the directions and the directions, because the are reset to canonical directions */
                   1856:       /* Thus the first calls to linmin will give new points and better maximizations until fp-(*fret) is */
                   1857:       /* under the tolerance value. If the tolerance is very small 1.e-9, it could last long.  */
1.126     brouard  1858: #ifdef DEBUG
                   1859:       int k[2],l;
                   1860:       k[0]=1;
                   1861:       k[1]=-1;
                   1862:       printf("Max: %.12e",(*func)(p));
                   1863:       fprintf(ficlog,"Max: %.12e",(*func)(p));
                   1864:       for (j=1;j<=n;j++) {
                   1865:        printf(" %.12e",p[j]);
                   1866:        fprintf(ficlog," %.12e",p[j]);
                   1867:       }
                   1868:       printf("\n");
                   1869:       fprintf(ficlog,"\n");
                   1870:       for(l=0;l<=1;l++) {
                   1871:        for (j=1;j<=n;j++) {
                   1872:          ptt[j]=p[j]+(p[j]-pt[j])*k[l];
                   1873:          printf("l=%d j=%d ptt=%.12e, xits=%.12e, p=%.12e, xit=%.12e", l,j,ptt[j],xits[j],p[j],xit[j]);
                   1874:          fprintf(ficlog,"l=%d j=%d ptt=%.12e, xits=%.12e, p=%.12e, xit=%.12e", l,j,ptt[j],xits[j],p[j],xit[j]);
                   1875:        }
                   1876:        printf("func(ptt)=%.12e, deriv=%.12e\n",(*func)(ptt),(ptt[j]-p[j])/((*func)(ptt)-(*func)(p)));
                   1877:        fprintf(ficlog,"func(ptt)=%.12e, deriv=%.12e\n",(*func)(ptt),(ptt[j]-p[j])/((*func)(ptt)-(*func)(p)));
                   1878:       }
                   1879: #endif
                   1880: 
                   1881: 
                   1882:       free_vector(xit,1,n); 
                   1883:       free_vector(xits,1,n); 
                   1884:       free_vector(ptt,1,n); 
                   1885:       free_vector(pt,1,n); 
                   1886:       return; 
1.192     brouard  1887:     } /* enough precision */ 
1.126     brouard  1888:     if (*iter == ITMAX) nrerror("powell exceeding maximum iterations."); 
1.181     brouard  1889:     for (j=1;j<=n;j++) { /* Computes the extrapolated point P_0 + 2 (P_n-P_0) */
1.126     brouard  1890:       ptt[j]=2.0*p[j]-pt[j]; 
                   1891:       xit[j]=p[j]-pt[j]; 
                   1892:       pt[j]=p[j]; 
                   1893:     } 
1.181     brouard  1894:     fptt=(*func)(ptt); /* f_3 */
1.192     brouard  1895: #ifdef POWELLF1F3
                   1896: #else
1.161     brouard  1897:     if (fptt < fp) { /* If extrapolated point is better, decide if we keep that new direction or not */
1.192     brouard  1898: #endif
1.162     brouard  1899:       /* (x1 f1=fp), (x2 f2=*fret), (x3 f3=fptt), (xm fm) */
1.161     brouard  1900:       /* From x1 (P0) distance of x2 is at h and x3 is 2h */
1.162     brouard  1901:       /* Let f"(x2) be the 2nd derivative equal everywhere.  */
                   1902:       /* Then the parabolic through (x1,f1), (x2,f2) and (x3,f3) */
                   1903:       /* will reach at f3 = fm + h^2/2 f"m  ; f" = (f1 -2f2 +f3 ) / h**2 */
1.181     brouard  1904:       /* Conditional for using this new direction is that mu^2 = (f1-2f2+f3)^2 /2 < del */
1.161     brouard  1905:       /* t=2.0*(fp-2.0*(*fret)+fptt)*SQR(fp-(*fret)-del)-del*SQR(fp-fptt); */
1.183     brouard  1906: #ifdef NRCORIGINAL
                   1907:       t=2.0*(fp-2.0*(*fret)+fptt)*SQR(fp-(*fret)-del)- del*SQR(fp-fptt); /* Original Numerical Recipes in C*/
                   1908: #else
                   1909:       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  1910:       t= t- del*SQR(fp-fptt);
1.183     brouard  1911: #endif
1.202     brouard  1912:       directest = fp-2.0*(*fret)+fptt - 2.0 * del; /* If delta was big enough we change it for a new direction */
1.161     brouard  1913: #ifdef DEBUG
1.181     brouard  1914:       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);
                   1915:       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  1916:       printf("t3= %.12lf, t4= %.12lf, t3*= %.12lf, t4*= %.12lf\n",SQR(fp-(*fret)-del),SQR(fp-fptt),
                   1917:             (fp-(*fret)-del)*(fp-(*fret)-del),(fp-fptt)*(fp-fptt));
                   1918:       fprintf(ficlog,"t3= %.12lf, t4= %.12lf, t3*= %.12lf, t4*= %.12lf\n",SQR(fp-(*fret)-del),SQR(fp-fptt),
                   1919:             (fp-(*fret)-del)*(fp-(*fret)-del),(fp-fptt)*(fp-fptt));
                   1920:       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);
                   1921:       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);
                   1922: #endif
1.183     brouard  1923: #ifdef POWELLORIGINAL
                   1924:       if (t < 0.0) { /* Then we use it for new direction */
                   1925: #else
1.182     brouard  1926:       if (directest*t < 0.0) { /* Contradiction between both tests */
1.202     brouard  1927:        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  1928:         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  1929:         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  1930:         fprintf(ficlog,"f1-2f2+f3= %.12lf, f1-f2-del= %.12lf, f1-f3= %.12lf\n",fp-2.0*(*fret)+fptt, fp -(*fret) -del, fp-fptt);
                   1931:       } 
1.181     brouard  1932:       if (directest < 0.0) { /* Then we use it for new direction */
                   1933: #endif
1.191     brouard  1934: #ifdef DEBUGLINMIN
                   1935:        printf("Before linmin in direction P%d-P0\n",n);
                   1936:        for (j=1;j<=n;j++) { 
1.202     brouard  1937:          printf(" Before xit[%d]= %12.7f p[%d]= %12.7f",j,xit[j],j,p[j]);
                   1938:          fprintf(ficlog," Before xit[%d]= %12.7f p[%d]= %12.7f",j,xit[j],j,p[j]);
                   1939:          if(j % ncovmodel == 0){
1.191     brouard  1940:            printf("\n");
1.202     brouard  1941:            fprintf(ficlog,"\n");
                   1942:          }
1.191     brouard  1943:        }
                   1944: #endif
1.187     brouard  1945:        linmin(p,xit,n,fret,func); /* computes minimum on the extrapolated direction: changes p and rescales xit.*/
1.191     brouard  1946: #ifdef DEBUGLINMIN
                   1947:        for (j=1;j<=n;j++) { 
                   1948:          printf("After xit[%d]= %12.7f p[%d]= %12.7f",j,xit[j],j,p[j]);
1.202     brouard  1949:          fprintf(ficlog,"After xit[%d]= %12.7f p[%d]= %12.7f",j,xit[j],j,p[j]);
                   1950:          if(j % ncovmodel == 0){
1.191     brouard  1951:            printf("\n");
1.202     brouard  1952:            fprintf(ficlog,"\n");
                   1953:          }
1.191     brouard  1954:        }
                   1955: #endif
1.126     brouard  1956:        for (j=1;j<=n;j++) { 
1.181     brouard  1957:          xi[j][ibig]=xi[j][n]; /* Replace direction with biggest decrease by last direction n */
                   1958:          xi[j][n]=xit[j];      /* and this nth direction by the by the average p_0 p_n */
1.126     brouard  1959:        }
1.181     brouard  1960:        printf("Gaining to use new average direction of P0 P%d instead of biggest increase direction %d :\n",n,ibig);
                   1961:        fprintf(ficlog,"Gaining to use new average direction of P0 P%d instead of biggest increase direction %d :\n",n,ibig);
1.161     brouard  1962: 
1.126     brouard  1963: #ifdef DEBUG
1.164     brouard  1964:        printf("Direction changed  last moved %d in place of ibig=%d, new last is the average:\n",n,ibig);
                   1965:        fprintf(ficlog,"Direction changed  last moved %d in place of ibig=%d, new last is the average:\n",n,ibig);
1.126     brouard  1966:        for(j=1;j<=n;j++){
                   1967:          printf(" %.12e",xit[j]);
                   1968:          fprintf(ficlog," %.12e",xit[j]);
                   1969:        }
                   1970:        printf("\n");
                   1971:        fprintf(ficlog,"\n");
                   1972: #endif
1.192     brouard  1973:       } /* end of t or directest negative */
                   1974: #ifdef POWELLF1F3
                   1975: #else
1.162     brouard  1976:     } /* end if (fptt < fp)  */
1.192     brouard  1977: #endif
                   1978:   } /* loop iteration */ 
1.126     brouard  1979: } 
                   1980: 
                   1981: /**** Prevalence limit (stable or period prevalence)  ****************/
                   1982: 
1.203     brouard  1983: double **prevalim(double **prlim, int nlstate, double x[], double age, double **oldm, double **savm, double ftolpl, int *ncvyear, int ij)
1.126     brouard  1984: {
                   1985:   /* Computes the prevalence limit in each live state at age x by left multiplying the unit
1.203     brouard  1986:      matrix by transitions matrix until convergence is reached with precision ftolpl */
1.206     brouard  1987:   /* Wx= Wx-1 Px-1= Wx-2 Px-2 Px-1  = Wx-n Px-n ... Px-2 Px-1 I */
                   1988:   /* Wx is row vector: population in state 1, population in state 2, population dead */
                   1989:   /* or prevalence in state 1, prevalence in state 2, 0 */
                   1990:   /* newm is the matrix after multiplications, its rows are identical at a factor */
                   1991:   /* Initial matrix pimij */
                   1992:   /* {0.85204250825084937, 0.13044499163996345, 0.017512500109187184, */
                   1993:   /* 0.090851990222114765, 0.88271245433047185, 0.026435555447413338, */
                   1994:   /*  0,                   0                  , 1} */
                   1995:   /*
                   1996:    * and after some iteration: */
                   1997:   /* {0.45504275246439968, 0.42731458730878791, 0.11764266022681241, */
                   1998:   /*  0.45201005341706885, 0.42865420071559901, 0.11933574586733192, */
                   1999:   /*  0,                   0                  , 1} */
                   2000:   /* And prevalence by suppressing the deaths are close to identical rows in prlim: */
                   2001:   /* {0.51571254859325999, 0.4842874514067399, */
                   2002:   /*  0.51326036147820708, 0.48673963852179264} */
                   2003:   /* If we start from prlim again, prlim tends to a constant matrix */
                   2004: 
1.126     brouard  2005:   int i, ii,j,k;
1.209     brouard  2006:   double *min, *max, *meandiff, maxmax,sumnew=0.;
1.145     brouard  2007:   /* double **matprod2(); */ /* test */
1.131     brouard  2008:   double **out, cov[NCOVMAX+1], **pmij();
1.126     brouard  2009:   double **newm;
1.209     brouard  2010:   double agefin, delaymax=200. ; /* 100 Max number of years to converge */
1.203     brouard  2011:   int ncvloop=0;
1.169     brouard  2012:   
1.209     brouard  2013:   min=vector(1,nlstate);
                   2014:   max=vector(1,nlstate);
                   2015:   meandiff=vector(1,nlstate);
                   2016: 
1.126     brouard  2017:   for (ii=1;ii<=nlstate+ndeath;ii++)
                   2018:     for (j=1;j<=nlstate+ndeath;j++){
                   2019:       oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   2020:     }
1.169     brouard  2021:   
                   2022:   cov[1]=1.;
                   2023:   
                   2024:   /* Even if hstepm = 1, at least one multiplication by the unit matrix */
1.202     brouard  2025:   /* Start at agefin= age, computes the matrix of passage and loops decreasing agefin until convergence is reached */
1.126     brouard  2026:   for(agefin=age-stepm/YEARM; agefin>=age-delaymax; agefin=agefin-stepm/YEARM){
1.202     brouard  2027:     ncvloop++;
1.126     brouard  2028:     newm=savm;
                   2029:     /* Covariates have to be included here again */
1.138     brouard  2030:     cov[2]=agefin;
1.187     brouard  2031:     if(nagesqr==1)
                   2032:       cov[3]= agefin*agefin;;
1.138     brouard  2033:     for (k=1; k<=cptcovn;k++) {
1.200     brouard  2034:       /* cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(ij,Tvar[k])]; */
                   2035:       cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(ij,k)];
1.198     brouard  2036:       /* 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  2037:     }
1.186     brouard  2038:     /*wrong? for (k=1; k<=cptcovage;k++) cov[2+Tage[k]]=cov[2+Tage[k]]*cov[2]; */
1.200     brouard  2039:     /* for (k=1; k<=cptcovage;k++) cov[2+nagesqr+Tage[k]]=nbcode[Tvar[k]][codtabm(ij,Tvar[k])]*cov[2]; */
                   2040:     for (k=1; k<=cptcovage;k++) cov[2+nagesqr+Tage[k]]=nbcode[Tvar[k]][codtabm(ij,k)]*cov[2];
1.186     brouard  2041:     for (k=1; k<=cptcovprod;k++) /* Useless */
1.200     brouard  2042:       /* cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,Tvard[k][1])] * nbcode[Tvard[k][2]][codtabm(ij,Tvard[k][2])]; */
                   2043:       cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,k)] * nbcode[Tvard[k][2]][codtabm(ij,k)];
1.138     brouard  2044:     
                   2045:     /*printf("ij=%d cptcovprod=%d tvar=%d ", ij, cptcovprod, Tvar[1]);*/
                   2046:     /*printf("ij=%d cov[3]=%lf cov[4]=%lf \n",ij, cov[3],cov[4]);*/
                   2047:     /*printf("ij=%d cov[3]=%lf \n",ij, cov[3]);*/
1.145     brouard  2048:     /* savm=pmij(pmmij,cov,ncovmodel,x,nlstate); */
                   2049:     /* out=matprod2(newm, pmij(pmmij,cov,ncovmodel,x,nlstate),1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, oldm); /\* Bug Valgrind *\/ */
1.142     brouard  2050:     out=matprod2(newm, pmij(pmmij,cov,ncovmodel,x,nlstate),1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, oldm); /* Bug Valgrind */
1.138     brouard  2051:     
1.126     brouard  2052:     savm=oldm;
                   2053:     oldm=newm;
1.209     brouard  2054: 
                   2055:     for(j=1; j<=nlstate; j++){
                   2056:       max[j]=0.;
                   2057:       min[j]=1.;
                   2058:     }
                   2059:     for(i=1;i<=nlstate;i++){
                   2060:       sumnew=0;
                   2061:       for(k=1; k<=ndeath; k++) sumnew+=newm[i][nlstate+k];
                   2062:       for(j=1; j<=nlstate; j++){ 
                   2063:        prlim[i][j]= newm[i][j]/(1-sumnew);
                   2064:        max[j]=FMAX(max[j],prlim[i][j]);
                   2065:        min[j]=FMIN(min[j],prlim[i][j]);
                   2066:       }
                   2067:     }
                   2068: 
1.126     brouard  2069:     maxmax=0.;
1.209     brouard  2070:     for(j=1; j<=nlstate; j++){
                   2071:       meandiff[j]=(max[j]-min[j])/(max[j]+min[j])*2.; /* mean difference for each column */
                   2072:       maxmax=FMAX(maxmax,meandiff[j]);
                   2073:       /* 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  2074:     } /* j loop */
1.203     brouard  2075:     *ncvyear= (int)age- (int)agefin;
1.208     brouard  2076:     /* 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  2077:     if(maxmax < ftolpl){
1.209     brouard  2078:       /* printf("maxmax=%lf ncvloop=%ld, age=%d, agefin=%d ncvyear=%d \n", maxmax, ncvloop, (int)age, (int)agefin, *ncvyear); */
                   2079:       free_vector(min,1,nlstate);
                   2080:       free_vector(max,1,nlstate);
                   2081:       free_vector(meandiff,1,nlstate);
1.126     brouard  2082:       return prlim;
                   2083:     }
1.169     brouard  2084:   } /* age loop */
1.208     brouard  2085:     /* After some age loop it doesn't converge */
1.209     brouard  2086:   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  2087: 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  2088:   /* 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); */
                   2089:   free_vector(min,1,nlstate);
                   2090:   free_vector(max,1,nlstate);
                   2091:   free_vector(meandiff,1,nlstate);
1.208     brouard  2092:   
1.169     brouard  2093:   return prlim; /* should not reach here */
1.126     brouard  2094: }
                   2095: 
                   2096: /*************** transition probabilities ***************/ 
                   2097: 
                   2098: double **pmij(double **ps, double *cov, int ncovmodel, double *x, int nlstate )
                   2099: {
1.138     brouard  2100:   /* According to parameters values stored in x and the covariate's values stored in cov,
                   2101:      computes the probability to be observed in state j being in state i by appying the
                   2102:      model to the ncovmodel covariates (including constant and age).
                   2103:      lnpijopii=ln(pij/pii)= aij+bij*age+cij*v1+dij*v2+... = sum_nc=1^ncovmodel xij(nc)*cov[nc]
                   2104:      and, according on how parameters are entered, the position of the coefficient xij(nc) of the
                   2105:      ncth covariate in the global vector x is given by the formula:
                   2106:      j<i nc+((i-1)*(nlstate+ndeath-1)+j-1)*ncovmodel
                   2107:      j>=i nc + ((i-1)*(nlstate+ndeath-1)+(j-2))*ncovmodel
                   2108:      Computes ln(pij/pii) (lnpijopii), deduces pij/pii by exponentiation,
                   2109:      sums on j different of i to get 1-pii/pii, deduces pii, and then all pij.
                   2110:      Outputs ps[i][j] the probability to be observed in j being in j according to
                   2111:      the values of the covariates cov[nc] and corresponding parameter values x[nc+shiftij]
                   2112:   */
                   2113:   double s1, lnpijopii;
1.126     brouard  2114:   /*double t34;*/
1.164     brouard  2115:   int i,j, nc, ii, jj;
1.126     brouard  2116: 
                   2117:     for(i=1; i<= nlstate; i++){
                   2118:       for(j=1; j<i;j++){
1.138     brouard  2119:        for (nc=1, lnpijopii=0.;nc <=ncovmodel; nc++){
                   2120:          /*lnpijopii += param[i][j][nc]*cov[nc];*/
                   2121:          lnpijopii += x[nc+((i-1)*(nlstate+ndeath-1)+j-1)*ncovmodel]*cov[nc];
                   2122: /*      printf("Int j<i s1=%.17e, lnpijopii=%.17e\n",s1,lnpijopii); */
1.126     brouard  2123:        }
1.138     brouard  2124:        ps[i][j]=lnpijopii; /* In fact ln(pij/pii) */
                   2125: /*     printf("s1=%.17e, lnpijopii=%.17e\n",s1,lnpijopii); */
1.126     brouard  2126:       }
                   2127:       for(j=i+1; j<=nlstate+ndeath;j++){
1.138     brouard  2128:        for (nc=1, lnpijopii=0.;nc <=ncovmodel; nc++){
                   2129:          /*lnpijopii += x[(i-1)*nlstate*ncovmodel+(j-2)*ncovmodel+nc+(i-1)*(ndeath-1)*ncovmodel]*cov[nc];*/
                   2130:          lnpijopii += x[nc + ((i-1)*(nlstate+ndeath-1)+(j-2))*ncovmodel]*cov[nc];
                   2131: /*       printf("Int j>i s1=%.17e, lnpijopii=%.17e %lx %lx\n",s1,lnpijopii,s1,lnpijopii); */
1.126     brouard  2132:        }
1.138     brouard  2133:        ps[i][j]=lnpijopii; /* In fact ln(pij/pii) */
1.126     brouard  2134:       }
                   2135:     }
                   2136:     
                   2137:     for(i=1; i<= nlstate; i++){
                   2138:       s1=0;
1.131     brouard  2139:       for(j=1; j<i; j++){
1.138     brouard  2140:        s1+=exp(ps[i][j]); /* In fact sums pij/pii */
1.131     brouard  2141:        /*printf("debug1 %d %d ps=%lf exp(ps)=%lf s1+=%lf\n",i,j,ps[i][j],exp(ps[i][j]),s1); */
                   2142:       }
                   2143:       for(j=i+1; j<=nlstate+ndeath; j++){
1.138     brouard  2144:        s1+=exp(ps[i][j]); /* In fact sums pij/pii */
1.131     brouard  2145:        /*printf("debug2 %d %d ps=%lf exp(ps)=%lf s1+=%lf\n",i,j,ps[i][j],exp(ps[i][j]),s1); */
                   2146:       }
1.138     brouard  2147:       /* s1= sum_{j<>i} pij/pii=(1-pii)/pii and thus pii is known from s1 */
1.126     brouard  2148:       ps[i][i]=1./(s1+1.);
1.138     brouard  2149:       /* Computing other pijs */
1.126     brouard  2150:       for(j=1; j<i; j++)
                   2151:        ps[i][j]= exp(ps[i][j])*ps[i][i];
                   2152:       for(j=i+1; j<=nlstate+ndeath; j++)
                   2153:        ps[i][j]= exp(ps[i][j])*ps[i][i];
                   2154:       /* ps[i][nlstate+1]=1.-s1- ps[i][i];*/ /* Sum should be 1 */
                   2155:     } /* end i */
                   2156:     
                   2157:     for(ii=nlstate+1; ii<= nlstate+ndeath; ii++){
                   2158:       for(jj=1; jj<= nlstate+ndeath; jj++){
                   2159:        ps[ii][jj]=0;
                   2160:        ps[ii][ii]=1;
                   2161:       }
                   2162:     }
                   2163:     
1.145     brouard  2164:     
                   2165:     /* for(ii=1; ii<= nlstate+ndeath; ii++){ */
                   2166:     /*   for(jj=1; jj<= nlstate+ndeath; jj++){ */
                   2167:     /*         printf(" pmij  ps[%d][%d]=%lf ",ii,jj,ps[ii][jj]); */
                   2168:     /*   } */
                   2169:     /*   printf("\n "); */
                   2170:     /* } */
                   2171:     /* printf("\n ");printf("%lf ",cov[2]);*/
                   2172:     /*
1.126     brouard  2173:       for(i=1; i<= npar; i++) printf("%f ",x[i]);
                   2174:       goto end;*/
                   2175:     return ps;
                   2176: }
                   2177: 
                   2178: /**************** Product of 2 matrices ******************/
                   2179: 
1.145     brouard  2180: double **matprod2(double **out, double **in,int nrl, int nrh, int ncl, int nch, int ncolol, int ncoloh, double **b)
1.126     brouard  2181: {
                   2182:   /* Computes the matrix product of in(1,nrh-nrl+1)(1,nch-ncl+1) times
                   2183:      b(1,nch-ncl+1)(1,ncoloh-ncolol+1) into out(...) */
                   2184:   /* in, b, out are matrice of pointers which should have been initialized 
                   2185:      before: only the contents of out is modified. The function returns
                   2186:      a pointer to pointers identical to out */
1.145     brouard  2187:   int i, j, k;
1.126     brouard  2188:   for(i=nrl; i<= nrh; i++)
1.145     brouard  2189:     for(k=ncolol; k<=ncoloh; k++){
                   2190:       out[i][k]=0.;
                   2191:       for(j=ncl; j<=nch; j++)
                   2192:        out[i][k] +=in[i][j]*b[j][k];
                   2193:     }
1.126     brouard  2194:   return out;
                   2195: }
                   2196: 
                   2197: 
                   2198: /************* Higher Matrix Product ***************/
                   2199: 
                   2200: double ***hpxij(double ***po, int nhstepm, double age, int hstepm, double *x, int nlstate, int stepm, double **oldm, double **savm, int ij )
                   2201: {
                   2202:   /* Computes the transition matrix starting at age 'age' over 
                   2203:      'nhstepm*hstepm*stepm' months (i.e. until
                   2204:      age (in years)  age+nhstepm*hstepm*stepm/12) by multiplying 
                   2205:      nhstepm*hstepm matrices. 
                   2206:      Output is stored in matrix po[i][j][h] for h every 'hstepm' step 
                   2207:      (typically every 2 years instead of every month which is too big 
                   2208:      for the memory).
                   2209:      Model is determined by parameters x and covariates have to be 
                   2210:      included manually here. 
                   2211: 
                   2212:      */
                   2213: 
                   2214:   int i, j, d, h, k;
1.131     brouard  2215:   double **out, cov[NCOVMAX+1];
1.126     brouard  2216:   double **newm;
1.187     brouard  2217:   double agexact;
1.126     brouard  2218: 
                   2219:   /* Hstepm could be zero and should return the unit matrix */
                   2220:   for (i=1;i<=nlstate+ndeath;i++)
                   2221:     for (j=1;j<=nlstate+ndeath;j++){
                   2222:       oldm[i][j]=(i==j ? 1.0 : 0.0);
                   2223:       po[i][j][0]=(i==j ? 1.0 : 0.0);
                   2224:     }
                   2225:   /* Even if hstepm = 1, at least one multiplication by the unit matrix */
                   2226:   for(h=1; h <=nhstepm; h++){
                   2227:     for(d=1; d <=hstepm; d++){
                   2228:       newm=savm;
                   2229:       /* Covariates have to be included here again */
                   2230:       cov[1]=1.;
1.187     brouard  2231:       agexact=age+((h-1)*hstepm + (d-1))*stepm/YEARM;
                   2232:       cov[2]=agexact;
                   2233:       if(nagesqr==1)
                   2234:        cov[3]= agexact*agexact;
1.131     brouard  2235:       for (k=1; k<=cptcovn;k++) 
1.200     brouard  2236:        cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(ij,k)];
                   2237:        /* cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(ij,Tvar[k])]; */
1.186     brouard  2238:       for (k=1; k<=cptcovage;k++) /* Should start at cptcovn+1 */
                   2239:        /* cov[2+Tage[k]]=cov[2+Tage[k]]*cov[2]; */
1.200     brouard  2240:        cov[2+nagesqr+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(ij,k)]*cov[2];
                   2241:        /* cov[2+nagesqr+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(ij,Tvar[Tage[k]])]*cov[2]; */
1.145     brouard  2242:       for (k=1; k<=cptcovprod;k++) /* Useless because included in cptcovn */
1.200     brouard  2243:        cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,k)]*nbcode[Tvard[k][2]][codtabm(ij,k)];
                   2244:        /* 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  2245: 
                   2246: 
                   2247:       /*printf("hxi cptcov=%d cptcode=%d\n",cptcov,cptcode);*/
                   2248:       /*printf("h=%d d=%d age=%f cov=%f\n",h,d,age,cov[2]);*/
                   2249:       out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, 
                   2250:                   pmij(pmmij,cov,ncovmodel,x,nlstate));
                   2251:       savm=oldm;
                   2252:       oldm=newm;
                   2253:     }
                   2254:     for(i=1; i<=nlstate+ndeath; i++)
                   2255:       for(j=1;j<=nlstate+ndeath;j++) {
                   2256:        po[i][j][h]=newm[i][j];
1.128     brouard  2257:        /*if(h==nhstepm) printf("po[%d][%d][%d]=%f ",i,j,h,po[i][j][h]);*/
1.126     brouard  2258:       }
1.128     brouard  2259:     /*printf("h=%d ",h);*/
1.126     brouard  2260:   } /* end h */
1.128     brouard  2261: /*     printf("\n H=%d \n",h); */
1.126     brouard  2262:   return po;
                   2263: }
                   2264: 
1.162     brouard  2265: #ifdef NLOPT
                   2266:   double  myfunc(unsigned n, const double *p1, double *grad, void *pd){
                   2267:   double fret;
                   2268:   double *xt;
                   2269:   int j;
                   2270:   myfunc_data *d2 = (myfunc_data *) pd;
                   2271: /* xt = (p1-1); */
                   2272:   xt=vector(1,n); 
                   2273:   for (j=1;j<=n;j++)   xt[j]=p1[j-1]; /* xt[1]=p1[0] */
                   2274: 
                   2275:   fret=(d2->function)(xt); /*  p xt[1]@8 is fine */
                   2276:   /* fret=(*func)(xt); /\*  p xt[1]@8 is fine *\/ */
                   2277:   printf("Function = %.12lf ",fret);
                   2278:   for (j=1;j<=n;j++) printf(" %d %.8lf", j, xt[j]); 
                   2279:   printf("\n");
                   2280:  free_vector(xt,1,n);
                   2281:   return fret;
                   2282: }
                   2283: #endif
1.126     brouard  2284: 
                   2285: /*************** log-likelihood *************/
                   2286: double func( double *x)
                   2287: {
                   2288:   int i, ii, j, k, mi, d, kk;
1.131     brouard  2289:   double l, ll[NLSTATEMAX+1], cov[NCOVMAX+1];
1.126     brouard  2290:   double **out;
                   2291:   double sw; /* Sum of weights */
                   2292:   double lli; /* Individual log likelihood */
                   2293:   int s1, s2;
                   2294:   double bbh, survp;
                   2295:   long ipmx;
1.187     brouard  2296:   double agexact;
1.126     brouard  2297:   /*extern weight */
                   2298:   /* We are differentiating ll according to initial status */
                   2299:   /*  for (i=1;i<=npar;i++) printf("%f ", x[i]);*/
                   2300:   /*for(i=1;i<imx;i++) 
                   2301:     printf(" %d\n",s[4][i]);
                   2302:   */
1.162     brouard  2303: 
                   2304:   ++countcallfunc;
                   2305: 
1.126     brouard  2306:   cov[1]=1.;
                   2307: 
                   2308:   for(k=1; k<=nlstate; k++) ll[k]=0.;
                   2309: 
                   2310:   if(mle==1){
                   2311:     for (i=1,ipmx=0, sw=0.; i<=imx; i++){
1.138     brouard  2312:       /* Computes the values of the ncovmodel covariates of the model
                   2313:         depending if the covariates are fixed or variying (age dependent) and stores them in cov[]
                   2314:         Then computes with function pmij which return a matrix p[i][j] giving the elementary probability
                   2315:         to be observed in j being in i according to the model.
                   2316:        */
1.145     brouard  2317:       for (k=1; k<=cptcovn;k++){ /* Simple and product covariates without age* products */
1.187     brouard  2318:          cov[2+nagesqr+k]=covar[Tvar[k]][i];
1.145     brouard  2319:       }
1.137     brouard  2320:       /* In model V2+V1*V4+age*V3+V3*V2 Tvar[1] is V2, Tvar[2=V1*V4] 
1.138     brouard  2321:         is 6, Tvar[3=age*V3] should not be computed because of age Tvar[4=V3*V2] 
1.137     brouard  2322:         has been calculated etc */
1.126     brouard  2323:       for(mi=1; mi<= wav[i]-1; mi++){
                   2324:        for (ii=1;ii<=nlstate+ndeath;ii++)
                   2325:          for (j=1;j<=nlstate+ndeath;j++){
                   2326:            oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   2327:            savm[ii][j]=(ii==j ? 1.0 : 0.0);
                   2328:          }
                   2329:        for(d=0; d<dh[mi][i]; d++){
                   2330:          newm=savm;
1.187     brouard  2331:          agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;
                   2332:          cov[2]=agexact;
                   2333:          if(nagesqr==1)
                   2334:            cov[3]= agexact*agexact;
1.126     brouard  2335:          for (kk=1; kk<=cptcovage;kk++) {
1.187     brouard  2336:            cov[Tage[kk]+2+nagesqr]=covar[Tvar[Tage[kk]]][i]*agexact; /* Tage[kk] gives the data-covariate associated with age */
1.126     brouard  2337:          }
                   2338:          out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
                   2339:                       1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
                   2340:          savm=oldm;
                   2341:          oldm=newm;
                   2342:        } /* end mult */
                   2343:       
                   2344:        /*lli=log(out[s[mw[mi][i]][i]][s[mw[mi+1][i]][i]]);*/ /* Original formula */
                   2345:        /* But now since version 0.9 we anticipate for bias at large stepm.
                   2346:         * If stepm is larger than one month (smallest stepm) and if the exact delay 
                   2347:         * (in months) between two waves is not a multiple of stepm, we rounded to 
                   2348:         * the nearest (and in case of equal distance, to the lowest) interval but now
                   2349:         * we keep into memory the bias bh[mi][i] and also the previous matrix product
                   2350:         * (i.e to dh[mi][i]-1) saved in 'savm'. Then we inter(extra)polate the
                   2351:         * probability in order to take into account the bias as a fraction of the way
                   2352:         * from savm to out if bh is negative or even beyond if bh is positive. bh varies
                   2353:         * -stepm/2 to stepm/2 .
                   2354:         * For stepm=1 the results are the same as for previous versions of Imach.
                   2355:         * For stepm > 1 the results are less biased than in previous versions. 
                   2356:         */
                   2357:        s1=s[mw[mi][i]][i];
                   2358:        s2=s[mw[mi+1][i]][i];
                   2359:        bbh=(double)bh[mi][i]/(double)stepm; 
                   2360:        /* bias bh is positive if real duration
                   2361:         * is higher than the multiple of stepm and negative otherwise.
                   2362:         */
                   2363:        /* lli= (savm[s1][s2]>1.e-8 ?(1.+bbh)*log(out[s1][s2])- bbh*log(savm[s1][s2]):log((1.+bbh)*out[s1][s2]));*/
                   2364:        if( s2 > nlstate){ 
                   2365:          /* i.e. if s2 is a death state and if the date of death is known 
                   2366:             then the contribution to the likelihood is the probability to 
                   2367:             die between last step unit time and current  step unit time, 
                   2368:             which is also equal to probability to die before dh 
                   2369:             minus probability to die before dh-stepm . 
                   2370:             In version up to 0.92 likelihood was computed
                   2371:        as if date of death was unknown. Death was treated as any other
                   2372:        health state: the date of the interview describes the actual state
                   2373:        and not the date of a change in health state. The former idea was
                   2374:        to consider that at each interview the state was recorded
                   2375:        (healthy, disable or death) and IMaCh was corrected; but when we
                   2376:        introduced the exact date of death then we should have modified
                   2377:        the contribution of an exact death to the likelihood. This new
                   2378:        contribution is smaller and very dependent of the step unit
                   2379:        stepm. It is no more the probability to die between last interview
                   2380:        and month of death but the probability to survive from last
                   2381:        interview up to one month before death multiplied by the
                   2382:        probability to die within a month. Thanks to Chris
                   2383:        Jackson for correcting this bug.  Former versions increased
                   2384:        mortality artificially. The bad side is that we add another loop
                   2385:        which slows down the processing. The difference can be up to 10%
                   2386:        lower mortality.
                   2387:          */
1.183     brouard  2388:        /* If, at the beginning of the maximization mostly, the
                   2389:           cumulative probability or probability to be dead is
                   2390:           constant (ie = 1) over time d, the difference is equal to
                   2391:           0.  out[s1][3] = savm[s1][3]: probability, being at state
                   2392:           s1 at precedent wave, to be dead a month before current
                   2393:           wave is equal to probability, being at state s1 at
                   2394:           precedent wave, to be dead at mont of the current
                   2395:           wave. Then the observed probability (that this person died)
                   2396:           is null according to current estimated parameter. In fact,
                   2397:           it should be very low but not zero otherwise the log go to
                   2398:           infinity.
                   2399:        */
                   2400: /* #ifdef INFINITYORIGINAL */
                   2401: /*         lli=log(out[s1][s2] - savm[s1][s2]); */
                   2402: /* #else */
                   2403: /*       if ((out[s1][s2] - savm[s1][s2]) < mytinydouble)  */
                   2404: /*         lli=log(mytinydouble); */
                   2405: /*       else */
                   2406: /*         lli=log(out[s1][s2] - savm[s1][s2]); */
                   2407: /* #endif */
                   2408:            lli=log(out[s1][s2] - savm[s1][s2]);
1.126     brouard  2409: 
                   2410:        } else if  (s2==-2) {
                   2411:          for (j=1,survp=0. ; j<=nlstate; j++) 
                   2412:            survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j];
                   2413:          /*survp += out[s1][j]; */
                   2414:          lli= log(survp);
                   2415:        }
                   2416:        
                   2417:        else if  (s2==-4) { 
                   2418:          for (j=3,survp=0. ; j<=nlstate; j++)  
                   2419:            survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j];
                   2420:          lli= log(survp); 
                   2421:        } 
                   2422: 
                   2423:        else if  (s2==-5) { 
                   2424:          for (j=1,survp=0. ; j<=2; j++)  
                   2425:            survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j];
                   2426:          lli= log(survp); 
                   2427:        } 
                   2428:        
                   2429:        else{
                   2430:          lli= log((1.+bbh)*out[s1][s2]- bbh*savm[s1][s2]); /* linear interpolation */
                   2431:          /*  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 */
                   2432:        } 
                   2433:        /*lli=(1.+bbh)*log(out[s1][s2])- bbh*log(savm[s1][s2]);*/
                   2434:        /*if(lli ==000.0)*/
                   2435:        /*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); */
                   2436:        ipmx +=1;
                   2437:        sw += weight[i];
                   2438:        ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
1.183     brouard  2439:        /* if (lli < log(mytinydouble)){ */
                   2440:        /*   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); */
                   2441:        /*   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]); */
                   2442:        /* } */
1.126     brouard  2443:       } /* end of wave */
                   2444:     } /* end of individual */
                   2445:   }  else if(mle==2){
                   2446:     for (i=1,ipmx=0, sw=0.; i<=imx; i++){
1.187     brouard  2447:       for (k=1; k<=cptcovn;k++) cov[2+nagesqr+k]=covar[Tvar[k]][i];
1.126     brouard  2448:       for(mi=1; mi<= wav[i]-1; mi++){
                   2449:        for (ii=1;ii<=nlstate+ndeath;ii++)
                   2450:          for (j=1;j<=nlstate+ndeath;j++){
                   2451:            oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   2452:            savm[ii][j]=(ii==j ? 1.0 : 0.0);
                   2453:          }
                   2454:        for(d=0; d<=dh[mi][i]; d++){
                   2455:          newm=savm;
1.187     brouard  2456:          agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;
                   2457:          cov[2]=agexact;
                   2458:          if(nagesqr==1)
                   2459:            cov[3]= agexact*agexact;
1.126     brouard  2460:          for (kk=1; kk<=cptcovage;kk++) {
1.187     brouard  2461:            cov[Tage[kk]+2+nagesqr]=covar[Tvar[Tage[kk]]][i]*agexact;
1.126     brouard  2462:          }
                   2463:          out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
                   2464:                       1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
                   2465:          savm=oldm;
                   2466:          oldm=newm;
                   2467:        } /* end mult */
                   2468:       
                   2469:        s1=s[mw[mi][i]][i];
                   2470:        s2=s[mw[mi+1][i]][i];
                   2471:        bbh=(double)bh[mi][i]/(double)stepm; 
                   2472:        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 */
                   2473:        ipmx +=1;
                   2474:        sw += weight[i];
                   2475:        ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
                   2476:       } /* end of wave */
                   2477:     } /* end of individual */
                   2478:   }  else if(mle==3){  /* exponential inter-extrapolation */
                   2479:     for (i=1,ipmx=0, sw=0.; i<=imx; i++){
1.187     brouard  2480:       for (k=1; k<=cptcovn;k++) cov[2+nagesqr+k]=covar[Tvar[k]][i];
1.126     brouard  2481:       for(mi=1; mi<= wav[i]-1; mi++){
                   2482:        for (ii=1;ii<=nlstate+ndeath;ii++)
                   2483:          for (j=1;j<=nlstate+ndeath;j++){
                   2484:            oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   2485:            savm[ii][j]=(ii==j ? 1.0 : 0.0);
                   2486:          }
                   2487:        for(d=0; d<dh[mi][i]; d++){
                   2488:          newm=savm;
1.187     brouard  2489:          agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;
                   2490:          cov[2]=agexact;
                   2491:          if(nagesqr==1)
                   2492:            cov[3]= agexact*agexact;
1.126     brouard  2493:          for (kk=1; kk<=cptcovage;kk++) {
1.187     brouard  2494:            cov[Tage[kk]+2+nagesqr]=covar[Tvar[Tage[kk]]][i]*agexact;
1.126     brouard  2495:          }
                   2496:          out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
                   2497:                       1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
                   2498:          savm=oldm;
                   2499:          oldm=newm;
                   2500:        } /* end mult */
                   2501:       
                   2502:        s1=s[mw[mi][i]][i];
                   2503:        s2=s[mw[mi+1][i]][i];
                   2504:        bbh=(double)bh[mi][i]/(double)stepm; 
                   2505:        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 */
                   2506:        ipmx +=1;
                   2507:        sw += weight[i];
                   2508:        ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
                   2509:       } /* end of wave */
                   2510:     } /* end of individual */
                   2511:   }else if (mle==4){  /* ml=4 no inter-extrapolation */
                   2512:     for (i=1,ipmx=0, sw=0.; i<=imx; i++){
1.187     brouard  2513:       for (k=1; k<=cptcovn;k++) cov[2+nagesqr+k]=covar[Tvar[k]][i];
1.126     brouard  2514:       for(mi=1; mi<= wav[i]-1; mi++){
                   2515:        for (ii=1;ii<=nlstate+ndeath;ii++)
                   2516:          for (j=1;j<=nlstate+ndeath;j++){
                   2517:            oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   2518:            savm[ii][j]=(ii==j ? 1.0 : 0.0);
                   2519:          }
                   2520:        for(d=0; d<dh[mi][i]; d++){
                   2521:          newm=savm;
1.187     brouard  2522:          agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;
                   2523:          cov[2]=agexact;
                   2524:          if(nagesqr==1)
                   2525:            cov[3]= agexact*agexact;
1.126     brouard  2526:          for (kk=1; kk<=cptcovage;kk++) {
1.187     brouard  2527:            cov[Tage[kk]+2+nagesqr]=covar[Tvar[Tage[kk]]][i]*agexact;
1.126     brouard  2528:          }
                   2529:        
                   2530:          out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
                   2531:                       1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
                   2532:          savm=oldm;
                   2533:          oldm=newm;
                   2534:        } /* end mult */
                   2535:       
                   2536:        s1=s[mw[mi][i]][i];
                   2537:        s2=s[mw[mi+1][i]][i];
                   2538:        if( s2 > nlstate){ 
                   2539:          lli=log(out[s1][s2] - savm[s1][s2]);
                   2540:        }else{
                   2541:          lli=log(out[s[mw[mi][i]][i]][s[mw[mi+1][i]][i]]); /* Original formula */
                   2542:        }
                   2543:        ipmx +=1;
                   2544:        sw += weight[i];
                   2545:        ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
                   2546: /*     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]); */
                   2547:       } /* end of wave */
                   2548:     } /* end of individual */
                   2549:   }else{  /* ml=5 no inter-extrapolation no jackson =0.8a */
                   2550:     for (i=1,ipmx=0, sw=0.; i<=imx; i++){
1.187     brouard  2551:       for (k=1; k<=cptcovn;k++) cov[2+nagesqr+k]=covar[Tvar[k]][i];
1.126     brouard  2552:       for(mi=1; mi<= wav[i]-1; mi++){
                   2553:        for (ii=1;ii<=nlstate+ndeath;ii++)
                   2554:          for (j=1;j<=nlstate+ndeath;j++){
                   2555:            oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   2556:            savm[ii][j]=(ii==j ? 1.0 : 0.0);
                   2557:          }
                   2558:        for(d=0; d<dh[mi][i]; d++){
                   2559:          newm=savm;
1.187     brouard  2560:          agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;
                   2561:          cov[2]=agexact;
                   2562:          if(nagesqr==1)
                   2563:            cov[3]= agexact*agexact;
1.126     brouard  2564:          for (kk=1; kk<=cptcovage;kk++) {
1.187     brouard  2565:            cov[Tage[kk]+2+nagesqr]=covar[Tvar[Tage[kk]]][i]*agexact;
1.126     brouard  2566:          }
                   2567:        
                   2568:          out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
                   2569:                       1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
                   2570:          savm=oldm;
                   2571:          oldm=newm;
                   2572:        } /* end mult */
                   2573:       
                   2574:        s1=s[mw[mi][i]][i];
                   2575:        s2=s[mw[mi+1][i]][i];
                   2576:        lli=log(out[s[mw[mi][i]][i]][s[mw[mi+1][i]][i]]); /* Original formula */
                   2577:        ipmx +=1;
                   2578:        sw += weight[i];
                   2579:        ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
                   2580:        /*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]);*/
                   2581:       } /* end of wave */
                   2582:     } /* end of individual */
                   2583:   } /* End of if */
                   2584:   for(k=1,l=0.; k<=nlstate; k++) l += ll[k];
                   2585:   /* printf("l1=%f l2=%f ",ll[1],ll[2]); */
                   2586:   l= l*ipmx/sw; /* To get the same order of magnitude as if weight=1 for every body */
                   2587:   return -l;
                   2588: }
                   2589: 
                   2590: /*************** log-likelihood *************/
                   2591: double funcone( double *x)
                   2592: {
                   2593:   /* Same as likeli but slower because of a lot of printf and if */
                   2594:   int i, ii, j, k, mi, d, kk;
1.131     brouard  2595:   double l, ll[NLSTATEMAX+1], cov[NCOVMAX+1];
1.126     brouard  2596:   double **out;
                   2597:   double lli; /* Individual log likelihood */
                   2598:   double llt;
                   2599:   int s1, s2;
                   2600:   double bbh, survp;
1.187     brouard  2601:   double agexact;
1.126     brouard  2602:   /*extern weight */
                   2603:   /* We are differentiating ll according to initial status */
                   2604:   /*  for (i=1;i<=npar;i++) printf("%f ", x[i]);*/
                   2605:   /*for(i=1;i<imx;i++) 
                   2606:     printf(" %d\n",s[4][i]);
                   2607:   */
                   2608:   cov[1]=1.;
                   2609: 
                   2610:   for(k=1; k<=nlstate; k++) ll[k]=0.;
                   2611: 
                   2612:   for (i=1,ipmx=0, sw=0.; i<=imx; i++){
1.187     brouard  2613:     for (k=1; k<=cptcovn;k++) cov[2+nagesqr+k]=covar[Tvar[k]][i];
1.126     brouard  2614:     for(mi=1; mi<= wav[i]-1; mi++){
                   2615:       for (ii=1;ii<=nlstate+ndeath;ii++)
                   2616:        for (j=1;j<=nlstate+ndeath;j++){
                   2617:          oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   2618:          savm[ii][j]=(ii==j ? 1.0 : 0.0);
                   2619:        }
                   2620:       for(d=0; d<dh[mi][i]; d++){
                   2621:        newm=savm;
1.187     brouard  2622:        agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;
                   2623:        cov[2]=agexact;
                   2624:        if(nagesqr==1)
                   2625:          cov[3]= agexact*agexact;
1.126     brouard  2626:        for (kk=1; kk<=cptcovage;kk++) {
1.187     brouard  2627:          cov[Tage[kk]+2+nagesqr]=covar[Tvar[Tage[kk]]][i]*agexact;
1.126     brouard  2628:        }
1.187     brouard  2629: 
1.145     brouard  2630:        /* savm=pmij(pmmij,cov,ncovmodel,x,nlstate); */
1.126     brouard  2631:        out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
                   2632:                     1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
1.145     brouard  2633:        /* out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath, */
                   2634:        /*           1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate)); */
1.126     brouard  2635:        savm=oldm;
                   2636:        oldm=newm;
                   2637:       } /* end mult */
                   2638:       
                   2639:       s1=s[mw[mi][i]][i];
                   2640:       s2=s[mw[mi+1][i]][i];
                   2641:       bbh=(double)bh[mi][i]/(double)stepm; 
                   2642:       /* bias is positive if real duration
                   2643:        * is higher than the multiple of stepm and negative otherwise.
                   2644:        */
                   2645:       if( s2 > nlstate && (mle <5) ){  /* Jackson */
                   2646:        lli=log(out[s1][s2] - savm[s1][s2]);
                   2647:       } else if  (s2==-2) {
                   2648:        for (j=1,survp=0. ; j<=nlstate; j++) 
                   2649:          survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j];
                   2650:        lli= log(survp);
                   2651:       }else if (mle==1){
                   2652:        lli= log((1.+bbh)*out[s1][s2]- bbh*savm[s1][s2]); /* linear interpolation */
                   2653:       } else if(mle==2){
                   2654:        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 */
                   2655:       } else if(mle==3){  /* exponential inter-extrapolation */
                   2656:        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 */
                   2657:       } else if (mle==4){  /* mle=4 no inter-extrapolation */
                   2658:        lli=log(out[s1][s2]); /* Original formula */
1.136     brouard  2659:       } else{  /* mle=0 back to 1 */
                   2660:        lli= log((1.+bbh)*out[s1][s2]- bbh*savm[s1][s2]); /* linear interpolation */
                   2661:        /*lli=log(out[s1][s2]); */ /* Original formula */
1.126     brouard  2662:       } /* End of if */
                   2663:       ipmx +=1;
                   2664:       sw += weight[i];
                   2665:       ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
1.132     brouard  2666:       /*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  2667:       if(globpr){
1.205     brouard  2668:        fprintf(ficresilk,"%9ld %6.1f %6d %2d %2d %2d %2d %3d %11.6f %8.4f %8.3f\
1.126     brouard  2669:  %11.6f %11.6f %11.6f ", \
1.205     brouard  2670:                num[i], agexact, i,s1,s2,mi,mw[mi][i],dh[mi][i],exp(lli),weight[i],weight[i]*gipmx/gsw,
1.126     brouard  2671:                2*weight[i]*lli,out[s1][s2],savm[s1][s2]);
                   2672:        for(k=1,llt=0.,l=0.; k<=nlstate; k++){
                   2673:          llt +=ll[k]*gipmx/gsw;
                   2674:          fprintf(ficresilk," %10.6f",-ll[k]*gipmx/gsw);
                   2675:        }
                   2676:        fprintf(ficresilk," %10.6f\n", -llt);
                   2677:       }
                   2678:     } /* end of wave */
                   2679:   } /* end of individual */
                   2680:   for(k=1,l=0.; k<=nlstate; k++) l += ll[k];
                   2681:   /* printf("l1=%f l2=%f ",ll[1],ll[2]); */
                   2682:   l= l*ipmx/sw; /* To get the same order of magnitude as if weight=1 for every body */
                   2683:   if(globpr==0){ /* First time we count the contributions and weights */
                   2684:     gipmx=ipmx;
                   2685:     gsw=sw;
                   2686:   }
                   2687:   return -l;
                   2688: }
                   2689: 
                   2690: 
                   2691: /*************** function likelione ***********/
                   2692: void likelione(FILE *ficres,double p[], int npar, int nlstate, int *globpri, long *ipmx, double *sw, double *fretone, double (*funcone)(double []))
                   2693: {
                   2694:   /* This routine should help understanding what is done with 
                   2695:      the selection of individuals/waves and
                   2696:      to check the exact contribution to the likelihood.
                   2697:      Plotting could be done.
                   2698:    */
                   2699:   int k;
                   2700: 
                   2701:   if(*globpri !=0){ /* Just counts and sums, no printings */
1.201     brouard  2702:     strcpy(fileresilk,"ILK_"); 
1.202     brouard  2703:     strcat(fileresilk,fileresu);
1.126     brouard  2704:     if((ficresilk=fopen(fileresilk,"w"))==NULL) {
                   2705:       printf("Problem with resultfile: %s\n", fileresilk);
                   2706:       fprintf(ficlog,"Problem with resultfile: %s\n", fileresilk);
                   2707:     }
1.205     brouard  2708:     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  2709:     fprintf(ficresilk, "#num_i age i s1 s2 mi mw dh likeli weight %%weight 2wlli out sav ");
1.126     brouard  2710:     /*         i,s1,s2,mi,mw[mi][i],dh[mi][i],exp(lli),weight[i],2*weight[i]*lli,out[s1][s2],savm[s1][s2]); */
                   2711:     for(k=1; k<=nlstate; k++) 
                   2712:       fprintf(ficresilk," -2*gipw/gsw*weight*ll[%d]++",k);
                   2713:     fprintf(ficresilk," -2*gipw/gsw*weight*ll(total)\n");
                   2714:   }
                   2715: 
                   2716:   *fretone=(*funcone)(p);
                   2717:   if(*globpri !=0){
                   2718:     fclose(ficresilk);
1.205     brouard  2719:     if (mle ==0)
                   2720:       fprintf(fichtm,"\n<br>File of contributions to the likelihood computed with initial parameters and mle = %d.",mle);
                   2721:     else if(mle >=1)
                   2722:       fprintf(fichtm,"\n<br>File of contributions to the likelihood computed with optimized parameters mle = %d.",mle);
                   2723:     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  2724:     
1.208     brouard  2725:       
                   2726:     for (k=1; k<= nlstate ; k++) {
1.211   ! brouard  2727:       fprintf(fichtm,"<br>- Probability p<sub>%dj</sub> by origin %d and destination j. Dot's sizes are related to corresponding weight: <a href=\"%s-p%dj.png\">%s-p%dj.png</a><br> \
1.208     brouard  2728: <img src=\"%s-p%dj.png\">",k,k,subdirf2(optionfilefiname,"ILK_"),k,subdirf2(optionfilefiname,"ILK_"),k,subdirf2(optionfilefiname,"ILK_"),k);
                   2729:     }
1.207     brouard  2730:     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  2731: <img src=\"%s-ori.png\">",subdirf2(optionfilefiname,"ILK_"),subdirf2(optionfilefiname,"ILK_"),subdirf2(optionfilefiname,"ILK_"));
1.207     brouard  2732:     fprintf(fichtm,"<br>- and by state of destination <a href=\"%s-dest.png\">%s-dest.png</a><br> \
1.204     brouard  2733: <img src=\"%s-dest.png\">",subdirf2(optionfilefiname,"ILK_"),subdirf2(optionfilefiname,"ILK_"),subdirf2(optionfilefiname,"ILK_"));
1.207     brouard  2734:     fflush(fichtm);
1.205     brouard  2735:   }
1.126     brouard  2736:   return;
                   2737: }
                   2738: 
                   2739: 
                   2740: /*********** Maximum Likelihood Estimation ***************/
                   2741: 
                   2742: void mlikeli(FILE *ficres,double p[], int npar, int ncovmodel, int nlstate, double ftol, double (*func)(double []))
                   2743: {
1.165     brouard  2744:   int i,j, iter=0;
1.126     brouard  2745:   double **xi;
                   2746:   double fret;
                   2747:   double fretone; /* Only one call to likelihood */
                   2748:   /*  char filerespow[FILENAMELENGTH];*/
1.162     brouard  2749: 
                   2750: #ifdef NLOPT
                   2751:   int creturn;
                   2752:   nlopt_opt opt;
                   2753:   /* double lb[9] = { -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL }; /\* lower bounds *\/ */
                   2754:   double *lb;
                   2755:   double minf; /* the minimum objective value, upon return */
                   2756:   double * p1; /* Shifted parameters from 0 instead of 1 */
                   2757:   myfunc_data dinst, *d = &dinst;
                   2758: #endif
                   2759: 
                   2760: 
1.126     brouard  2761:   xi=matrix(1,npar,1,npar);
                   2762:   for (i=1;i<=npar;i++)
                   2763:     for (j=1;j<=npar;j++)
                   2764:       xi[i][j]=(i==j ? 1.0 : 0.0);
                   2765:   printf("Powell\n");  fprintf(ficlog,"Powell\n");
1.201     brouard  2766:   strcpy(filerespow,"POW_"); 
1.126     brouard  2767:   strcat(filerespow,fileres);
                   2768:   if((ficrespow=fopen(filerespow,"w"))==NULL) {
                   2769:     printf("Problem with resultfile: %s\n", filerespow);
                   2770:     fprintf(ficlog,"Problem with resultfile: %s\n", filerespow);
                   2771:   }
                   2772:   fprintf(ficrespow,"# Powell\n# iter -2*LL");
                   2773:   for (i=1;i<=nlstate;i++)
                   2774:     for(j=1;j<=nlstate+ndeath;j++)
                   2775:       if(j!=i)fprintf(ficrespow," p%1d%1d",i,j);
                   2776:   fprintf(ficrespow,"\n");
1.162     brouard  2777: #ifdef POWELL
1.126     brouard  2778:   powell(p,xi,npar,ftol,&iter,&fret,func);
1.162     brouard  2779: #endif
1.126     brouard  2780: 
1.162     brouard  2781: #ifdef NLOPT
                   2782: #ifdef NEWUOA
                   2783:   opt = nlopt_create(NLOPT_LN_NEWUOA,npar);
                   2784: #else
                   2785:   opt = nlopt_create(NLOPT_LN_BOBYQA,npar);
                   2786: #endif
                   2787:   lb=vector(0,npar-1);
                   2788:   for (i=0;i<npar;i++) lb[i]= -HUGE_VAL;
                   2789:   nlopt_set_lower_bounds(opt, lb);
                   2790:   nlopt_set_initial_step1(opt, 0.1);
                   2791:   
                   2792:   p1= (p+1); /*  p *(p+1)@8 and p *(p1)@8 are equal p1[0]=p[1] */
                   2793:   d->function = func;
                   2794:   printf(" Func %.12lf \n",myfunc(npar,p1,NULL,d));
                   2795:   nlopt_set_min_objective(opt, myfunc, d);
                   2796:   nlopt_set_xtol_rel(opt, ftol);
                   2797:   if ((creturn=nlopt_optimize(opt, p1, &minf)) < 0) {
                   2798:     printf("nlopt failed! %d\n",creturn); 
                   2799:   }
                   2800:   else {
                   2801:     printf("found minimum after %d evaluations (NLOPT=%d)\n", countcallfunc ,NLOPT);
                   2802:     printf("found minimum at f(%g,%g) = %0.10g\n", p[0], p[1], minf);
                   2803:     iter=1; /* not equal */
                   2804:   }
                   2805:   nlopt_destroy(opt);
                   2806: #endif
1.126     brouard  2807:   free_matrix(xi,1,npar,1,npar);
                   2808:   fclose(ficrespow);
1.203     brouard  2809:   printf("\n#Number of iterations & function calls = %d & %d, -2 Log likelihood = %.12f\n",iter, countcallfunc,func(p));
                   2810:   fprintf(ficlog,"\n#Number of iterations & function calls = %d & %d, -2 Log likelihood = %.12f\n",iter, countcallfunc,func(p));
1.180     brouard  2811:   fprintf(ficres,"#Number of iterations & function calls = %d & %d, -2 Log likelihood = %.12f\n",iter, countcallfunc,func(p));
1.126     brouard  2812: 
                   2813: }
                   2814: 
                   2815: /**** Computes Hessian and covariance matrix ***/
1.203     brouard  2816: void hesscov(double **matcov, double **hess, double p[], int npar, double delti[], double ftolhess, double (*func)(double []))
1.126     brouard  2817: {
                   2818:   double  **a,**y,*x,pd;
1.203     brouard  2819:   /* double **hess; */
1.164     brouard  2820:   int i, j;
1.126     brouard  2821:   int *indx;
                   2822: 
                   2823:   double hessii(double p[], double delta, int theta, double delti[],double (*func)(double []),int npar);
1.203     brouard  2824:   double hessij(double p[], double **hess, double delti[], int i, int j,double (*func)(double []),int npar);
1.126     brouard  2825:   void lubksb(double **a, int npar, int *indx, double b[]) ;
                   2826:   void ludcmp(double **a, int npar, int *indx, double *d) ;
                   2827:   double gompertz(double p[]);
1.203     brouard  2828:   /* hess=matrix(1,npar,1,npar); */
1.126     brouard  2829: 
                   2830:   printf("\nCalculation of the hessian matrix. Wait...\n");
                   2831:   fprintf(ficlog,"\nCalculation of the hessian matrix. Wait...\n");
                   2832:   for (i=1;i<=npar;i++){
1.203     brouard  2833:     printf("%d-",i);fflush(stdout);
                   2834:     fprintf(ficlog,"%d-",i);fflush(ficlog);
1.126     brouard  2835:    
                   2836:      hess[i][i]=hessii(p,ftolhess,i,delti,func,npar);
                   2837:     
                   2838:     /*  printf(" %f ",p[i]);
                   2839:        printf(" %lf %lf %lf",hess[i][i],ftolhess,delti[i]);*/
                   2840:   }
                   2841:   
                   2842:   for (i=1;i<=npar;i++) {
                   2843:     for (j=1;j<=npar;j++)  {
                   2844:       if (j>i) { 
1.203     brouard  2845:        printf(".%d-%d",i,j);fflush(stdout);
                   2846:        fprintf(ficlog,".%d-%d",i,j);fflush(ficlog);
                   2847:        hess[i][j]=hessij(p,hess, delti,i,j,func,npar);
1.126     brouard  2848:        
                   2849:        hess[j][i]=hess[i][j];    
                   2850:        /*printf(" %lf ",hess[i][j]);*/
                   2851:       }
                   2852:     }
                   2853:   }
                   2854:   printf("\n");
                   2855:   fprintf(ficlog,"\n");
                   2856: 
                   2857:   printf("\nInverting the hessian to get the covariance matrix. Wait...\n");
                   2858:   fprintf(ficlog,"\nInverting the hessian to get the covariance matrix. Wait...\n");
                   2859:   
                   2860:   a=matrix(1,npar,1,npar);
                   2861:   y=matrix(1,npar,1,npar);
                   2862:   x=vector(1,npar);
                   2863:   indx=ivector(1,npar);
                   2864:   for (i=1;i<=npar;i++)
                   2865:     for (j=1;j<=npar;j++) a[i][j]=hess[i][j];
                   2866:   ludcmp(a,npar,indx,&pd);
                   2867: 
                   2868:   for (j=1;j<=npar;j++) {
                   2869:     for (i=1;i<=npar;i++) x[i]=0;
                   2870:     x[j]=1;
                   2871:     lubksb(a,npar,indx,x);
                   2872:     for (i=1;i<=npar;i++){ 
                   2873:       matcov[i][j]=x[i];
                   2874:     }
                   2875:   }
                   2876: 
                   2877:   printf("\n#Hessian matrix#\n");
                   2878:   fprintf(ficlog,"\n#Hessian matrix#\n");
                   2879:   for (i=1;i<=npar;i++) { 
                   2880:     for (j=1;j<=npar;j++) { 
1.203     brouard  2881:       printf("%.6e ",hess[i][j]);
                   2882:       fprintf(ficlog,"%.6e ",hess[i][j]);
1.126     brouard  2883:     }
                   2884:     printf("\n");
                   2885:     fprintf(ficlog,"\n");
                   2886:   }
                   2887: 
1.203     brouard  2888:   /* printf("\n#Covariance matrix#\n"); */
                   2889:   /* fprintf(ficlog,"\n#Covariance matrix#\n"); */
                   2890:   /* for (i=1;i<=npar;i++) {  */
                   2891:   /*   for (j=1;j<=npar;j++) {  */
                   2892:   /*     printf("%.6e ",matcov[i][j]); */
                   2893:   /*     fprintf(ficlog,"%.6e ",matcov[i][j]); */
                   2894:   /*   } */
                   2895:   /*   printf("\n"); */
                   2896:   /*   fprintf(ficlog,"\n"); */
                   2897:   /* } */
                   2898: 
1.126     brouard  2899:   /* Recompute Inverse */
1.203     brouard  2900:   /* for (i=1;i<=npar;i++) */
                   2901:   /*   for (j=1;j<=npar;j++) a[i][j]=matcov[i][j]; */
                   2902:   /* ludcmp(a,npar,indx,&pd); */
                   2903: 
                   2904:   /*  printf("\n#Hessian matrix recomputed#\n"); */
                   2905: 
                   2906:   /* for (j=1;j<=npar;j++) { */
                   2907:   /*   for (i=1;i<=npar;i++) x[i]=0; */
                   2908:   /*   x[j]=1; */
                   2909:   /*   lubksb(a,npar,indx,x); */
                   2910:   /*   for (i=1;i<=npar;i++){  */
                   2911:   /*     y[i][j]=x[i]; */
                   2912:   /*     printf("%.3e ",y[i][j]); */
                   2913:   /*     fprintf(ficlog,"%.3e ",y[i][j]); */
                   2914:   /*   } */
                   2915:   /*   printf("\n"); */
                   2916:   /*   fprintf(ficlog,"\n"); */
                   2917:   /* } */
                   2918: 
                   2919:   /* Verifying the inverse matrix */
                   2920: #ifdef DEBUGHESS
                   2921:   y=matprod2(y,hess,1,npar,1,npar,1,npar,matcov);
1.126     brouard  2922: 
1.203     brouard  2923:    printf("\n#Verification: multiplying the matrix of covariance by the Hessian matrix, should be unity:#\n");
                   2924:    fprintf(ficlog,"\n#Verification: multiplying the matrix of covariance by the Hessian matrix. Should be unity:#\n");
1.126     brouard  2925: 
                   2926:   for (j=1;j<=npar;j++) {
                   2927:     for (i=1;i<=npar;i++){ 
1.203     brouard  2928:       printf("%.2f ",y[i][j]);
                   2929:       fprintf(ficlog,"%.2f ",y[i][j]);
1.126     brouard  2930:     }
                   2931:     printf("\n");
                   2932:     fprintf(ficlog,"\n");
                   2933:   }
1.203     brouard  2934: #endif
1.126     brouard  2935: 
                   2936:   free_matrix(a,1,npar,1,npar);
                   2937:   free_matrix(y,1,npar,1,npar);
                   2938:   free_vector(x,1,npar);
                   2939:   free_ivector(indx,1,npar);
1.203     brouard  2940:   /* free_matrix(hess,1,npar,1,npar); */
1.126     brouard  2941: 
                   2942: 
                   2943: }
                   2944: 
                   2945: /*************** hessian matrix ****************/
                   2946: double hessii(double x[], double delta, int theta, double delti[], double (*func)(double []), int npar)
1.203     brouard  2947: { /* Around values of x, computes the function func and returns the scales delti and hessian */
1.126     brouard  2948:   int i;
                   2949:   int l=1, lmax=20;
1.203     brouard  2950:   double k1,k2, res, fx;
1.132     brouard  2951:   double p2[MAXPARM+1]; /* identical to x */
1.126     brouard  2952:   double delt=0.0001, delts, nkhi=10.,nkhif=1., khi=1.e-4;
                   2953:   int k=0,kmax=10;
                   2954:   double l1;
                   2955: 
                   2956:   fx=func(x);
                   2957:   for (i=1;i<=npar;i++) p2[i]=x[i];
1.145     brouard  2958:   for(l=0 ; l <=lmax; l++){  /* Enlarging the zone around the Maximum */
1.126     brouard  2959:     l1=pow(10,l);
                   2960:     delts=delt;
                   2961:     for(k=1 ; k <kmax; k=k+1){
                   2962:       delt = delta*(l1*k);
                   2963:       p2[theta]=x[theta] +delt;
1.145     brouard  2964:       k1=func(p2)-fx;   /* Might be negative if too close to the theoretical maximum */
1.126     brouard  2965:       p2[theta]=x[theta]-delt;
                   2966:       k2=func(p2)-fx;
                   2967:       /*res= (k1-2.0*fx+k2)/delt/delt; */
1.203     brouard  2968:       res= (k1+k2)/delt/delt/2.; /* Divided by 2 because L and not 2*L */
1.126     brouard  2969:       
1.203     brouard  2970: #ifdef DEBUGHESSII
1.126     brouard  2971:       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);
                   2972:       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);
                   2973: #endif
                   2974:       /*if(fabs(k1-2.0*fx+k2) <1.e-13){ */
                   2975:       if((k1 <khi/nkhi/2.) || (k2 <khi/nkhi/2.)){
                   2976:        k=kmax;
                   2977:       }
                   2978:       else if((k1 >khi/nkhif) || (k2 >khi/nkhif)){ /* Keeps lastvalue before 3.84/2 KHI2 5% 1d.f. */
1.164     brouard  2979:        k=kmax; l=lmax*10;
1.126     brouard  2980:       }
                   2981:       else if((k1 >khi/nkhi) || (k2 >khi/nkhi)){ 
                   2982:        delts=delt;
                   2983:       }
1.203     brouard  2984:     } /* End loop k */
1.126     brouard  2985:   }
                   2986:   delti[theta]=delts;
                   2987:   return res; 
                   2988:   
                   2989: }
                   2990: 
1.203     brouard  2991: double hessij( double x[], double **hess, double delti[], int thetai,int thetaj,double (*func)(double []),int npar)
1.126     brouard  2992: {
                   2993:   int i;
1.164     brouard  2994:   int l=1, lmax=20;
1.126     brouard  2995:   double k1,k2,k3,k4,res,fx;
1.132     brouard  2996:   double p2[MAXPARM+1];
1.203     brouard  2997:   int k, kmax=1;
                   2998:   double v1, v2, cv12, lc1, lc2;
1.208     brouard  2999: 
                   3000:   int firstime=0;
1.203     brouard  3001:   
1.126     brouard  3002:   fx=func(x);
1.203     brouard  3003:   for (k=1; k<=kmax; k=k+10) {
1.126     brouard  3004:     for (i=1;i<=npar;i++) p2[i]=x[i];
1.203     brouard  3005:     p2[thetai]=x[thetai]+delti[thetai]*k;
                   3006:     p2[thetaj]=x[thetaj]+delti[thetaj]*k;
1.126     brouard  3007:     k1=func(p2)-fx;
                   3008:   
1.203     brouard  3009:     p2[thetai]=x[thetai]+delti[thetai]*k;
                   3010:     p2[thetaj]=x[thetaj]-delti[thetaj]*k;
1.126     brouard  3011:     k2=func(p2)-fx;
                   3012:   
1.203     brouard  3013:     p2[thetai]=x[thetai]-delti[thetai]*k;
                   3014:     p2[thetaj]=x[thetaj]+delti[thetaj]*k;
1.126     brouard  3015:     k3=func(p2)-fx;
                   3016:   
1.203     brouard  3017:     p2[thetai]=x[thetai]-delti[thetai]*k;
                   3018:     p2[thetaj]=x[thetaj]-delti[thetaj]*k;
1.126     brouard  3019:     k4=func(p2)-fx;
1.203     brouard  3020:     res=(k1-k2-k3+k4)/4.0/delti[thetai]/k/delti[thetaj]/k/2.; /* Because of L not 2*L */
                   3021:     if(k1*k2*k3*k4 <0.){
1.208     brouard  3022:       firstime=1;
1.203     brouard  3023:       kmax=kmax+10;
1.208     brouard  3024:     }
                   3025:     if(kmax >=10 || firstime ==1){
1.203     brouard  3026:       printf("Warning: directions %d-%d, you are not estimating the Hessian at the exact maximum likelihood; increase ftol=%.2e\n",thetai,thetaj, ftol);
                   3027:       fprintf(ficlog,"Warning: directions %d-%d, you are not estimating the Hessian at the exact maximum likelihood; increase ftol=%.2e\n",thetai,thetaj, ftol);
                   3028:       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);
                   3029:       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);
                   3030:     }
                   3031: #ifdef DEBUGHESSIJ
                   3032:     v1=hess[thetai][thetai];
                   3033:     v2=hess[thetaj][thetaj];
                   3034:     cv12=res;
                   3035:     /* Computing eigen value of Hessian matrix */
                   3036:     lc1=((v1+v2)+sqrt((v1+v2)*(v1+v2) - 4*(v1*v2-cv12*cv12)))/2.;
                   3037:     lc2=((v1+v2)-sqrt((v1+v2)*(v1+v2) - 4*(v1*v2-cv12*cv12)))/2.;
                   3038:     if ((lc2 <0) || (lc1 <0) ){
                   3039:       printf("Warning: sub Hessian matrix '%d%d' does not have positive eigen values \n",thetai,thetaj);
                   3040:       fprintf(ficlog, "Warning: sub Hessian matrix '%d%d' does not have positive eigen values \n",thetai,thetaj);
                   3041:       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);
                   3042:       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);
                   3043:     }
1.126     brouard  3044: #endif
                   3045:   }
                   3046:   return res;
                   3047: }
                   3048: 
1.203     brouard  3049:     /* Not done yet: Was supposed to fix if not exactly at the maximum */
                   3050: /* double hessij( double x[], double delti[], int thetai,int thetaj,double (*func)(double []),int npar) */
                   3051: /* { */
                   3052: /*   int i; */
                   3053: /*   int l=1, lmax=20; */
                   3054: /*   double k1,k2,k3,k4,res,fx; */
                   3055: /*   double p2[MAXPARM+1]; */
                   3056: /*   double delt=0.0001, delts, nkhi=10.,nkhif=1., khi=1.e-4; */
                   3057: /*   int k=0,kmax=10; */
                   3058: /*   double l1; */
                   3059:   
                   3060: /*   fx=func(x); */
                   3061: /*   for(l=0 ; l <=lmax; l++){  /\* Enlarging the zone around the Maximum *\/ */
                   3062: /*     l1=pow(10,l); */
                   3063: /*     delts=delt; */
                   3064: /*     for(k=1 ; k <kmax; k=k+1){ */
                   3065: /*       delt = delti*(l1*k); */
                   3066: /*       for (i=1;i<=npar;i++) p2[i]=x[i]; */
                   3067: /*       p2[thetai]=x[thetai]+delti[thetai]/k; */
                   3068: /*       p2[thetaj]=x[thetaj]+delti[thetaj]/k; */
                   3069: /*       k1=func(p2)-fx; */
                   3070:       
                   3071: /*       p2[thetai]=x[thetai]+delti[thetai]/k; */
                   3072: /*       p2[thetaj]=x[thetaj]-delti[thetaj]/k; */
                   3073: /*       k2=func(p2)-fx; */
                   3074:       
                   3075: /*       p2[thetai]=x[thetai]-delti[thetai]/k; */
                   3076: /*       p2[thetaj]=x[thetaj]+delti[thetaj]/k; */
                   3077: /*       k3=func(p2)-fx; */
                   3078:       
                   3079: /*       p2[thetai]=x[thetai]-delti[thetai]/k; */
                   3080: /*       p2[thetaj]=x[thetaj]-delti[thetaj]/k; */
                   3081: /*       k4=func(p2)-fx; */
                   3082: /*       res=(k1-k2-k3+k4)/4.0/delti[thetai]*k/delti[thetaj]*k/2.; /\* Because of L not 2*L *\/ */
                   3083: /* #ifdef DEBUGHESSIJ */
                   3084: /*       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); */
                   3085: /*       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); */
                   3086: /* #endif */
                   3087: /*       if((k1 <khi/nkhi/2.) || (k2 <khi/nkhi/2.)|| (k4 <khi/nkhi/2.)|| (k4 <khi/nkhi/2.)){ */
                   3088: /*     k=kmax; */
                   3089: /*       } */
                   3090: /*       else if((k1 >khi/nkhif) || (k2 >khi/nkhif) || (k4 >khi/nkhif) || (k4 >khi/nkhif)){ /\* Keeps lastvalue before 3.84/2 KHI2 5% 1d.f. *\/ */
                   3091: /*     k=kmax; l=lmax*10; */
                   3092: /*       } */
                   3093: /*       else if((k1 >khi/nkhi) || (k2 >khi/nkhi)){  */
                   3094: /*     delts=delt; */
                   3095: /*       } */
                   3096: /*     } /\* End loop k *\/ */
                   3097: /*   } */
                   3098: /*   delti[theta]=delts; */
                   3099: /*   return res;  */
                   3100: /* } */
                   3101: 
                   3102: 
1.126     brouard  3103: /************** Inverse of matrix **************/
                   3104: void ludcmp(double **a, int n, int *indx, double *d) 
                   3105: { 
                   3106:   int i,imax,j,k; 
                   3107:   double big,dum,sum,temp; 
                   3108:   double *vv; 
                   3109:  
                   3110:   vv=vector(1,n); 
                   3111:   *d=1.0; 
                   3112:   for (i=1;i<=n;i++) { 
                   3113:     big=0.0; 
                   3114:     for (j=1;j<=n;j++) 
                   3115:       if ((temp=fabs(a[i][j])) > big) big=temp; 
                   3116:     if (big == 0.0) nrerror("Singular matrix in routine ludcmp"); 
                   3117:     vv[i]=1.0/big; 
                   3118:   } 
                   3119:   for (j=1;j<=n;j++) { 
                   3120:     for (i=1;i<j;i++) { 
                   3121:       sum=a[i][j]; 
                   3122:       for (k=1;k<i;k++) sum -= a[i][k]*a[k][j]; 
                   3123:       a[i][j]=sum; 
                   3124:     } 
                   3125:     big=0.0; 
                   3126:     for (i=j;i<=n;i++) { 
                   3127:       sum=a[i][j]; 
                   3128:       for (k=1;k<j;k++) 
                   3129:        sum -= a[i][k]*a[k][j]; 
                   3130:       a[i][j]=sum; 
                   3131:       if ( (dum=vv[i]*fabs(sum)) >= big) { 
                   3132:        big=dum; 
                   3133:        imax=i; 
                   3134:       } 
                   3135:     } 
                   3136:     if (j != imax) { 
                   3137:       for (k=1;k<=n;k++) { 
                   3138:        dum=a[imax][k]; 
                   3139:        a[imax][k]=a[j][k]; 
                   3140:        a[j][k]=dum; 
                   3141:       } 
                   3142:       *d = -(*d); 
                   3143:       vv[imax]=vv[j]; 
                   3144:     } 
                   3145:     indx[j]=imax; 
                   3146:     if (a[j][j] == 0.0) a[j][j]=TINY; 
                   3147:     if (j != n) { 
                   3148:       dum=1.0/(a[j][j]); 
                   3149:       for (i=j+1;i<=n;i++) a[i][j] *= dum; 
                   3150:     } 
                   3151:   } 
                   3152:   free_vector(vv,1,n);  /* Doesn't work */
                   3153: ;
                   3154: } 
                   3155: 
                   3156: void lubksb(double **a, int n, int *indx, double b[]) 
                   3157: { 
                   3158:   int i,ii=0,ip,j; 
                   3159:   double sum; 
                   3160:  
                   3161:   for (i=1;i<=n;i++) { 
                   3162:     ip=indx[i]; 
                   3163:     sum=b[ip]; 
                   3164:     b[ip]=b[i]; 
                   3165:     if (ii) 
                   3166:       for (j=ii;j<=i-1;j++) sum -= a[i][j]*b[j]; 
                   3167:     else if (sum) ii=i; 
                   3168:     b[i]=sum; 
                   3169:   } 
                   3170:   for (i=n;i>=1;i--) { 
                   3171:     sum=b[i]; 
                   3172:     for (j=i+1;j<=n;j++) sum -= a[i][j]*b[j]; 
                   3173:     b[i]=sum/a[i][i]; 
                   3174:   } 
                   3175: } 
                   3176: 
                   3177: void pstamp(FILE *fichier)
                   3178: {
1.196     brouard  3179:   fprintf(fichier,"# %s.%s\n#IMaCh version %s, %s\n#%s\n# %s", optionfilefiname,optionfilext,version,copyright, fullversion, strstart);
1.126     brouard  3180: }
                   3181: 
                   3182: /************ Frequencies ********************/
                   3183: 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[])
                   3184: {  /* Some frequencies */
                   3185:   
1.164     brouard  3186:   int i, m, jk, j1, bool, z1,j;
1.126     brouard  3187:   int first;
                   3188:   double ***freq; /* Frequencies */
                   3189:   double *pp, **prop;
                   3190:   double pos,posprop, k2, dateintsum=0,k2cpt=0;
                   3191:   char fileresp[FILENAMELENGTH];
                   3192:   
                   3193:   pp=vector(1,nlstate);
                   3194:   prop=matrix(1,nlstate,iagemin,iagemax+3);
1.201     brouard  3195:   strcpy(fileresp,"P_");
                   3196:   strcat(fileresp,fileresu);
1.126     brouard  3197:   if((ficresp=fopen(fileresp,"w"))==NULL) {
                   3198:     printf("Problem with prevalence resultfile: %s\n", fileresp);
                   3199:     fprintf(ficlog,"Problem with prevalence resultfile: %s\n", fileresp);
                   3200:     exit(0);
                   3201:   }
                   3202:   freq= ma3x(-5,nlstate+ndeath,-5,nlstate+ndeath,iagemin,iagemax+3);
                   3203:   j1=0;
                   3204:   
                   3205:   j=cptcoveff;
                   3206:   if (cptcovn<1) {j=1;ncodemax[1]=1;}
                   3207: 
                   3208:   first=1;
                   3209: 
1.169     brouard  3210:   /* for(k1=1; k1<=j ; k1++){ */  /* Loop on covariates */
                   3211:   /*  for(i1=1; i1<=ncodemax[k1];i1++){ */ /* Now it is 2 */
                   3212:   /*    j1++; */
1.145     brouard  3213:   for (j1 = 1; j1 <= (int) pow(2,cptcoveff); j1++){
1.126     brouard  3214:       /*printf("cptcoveff=%d Tvaraff=%d", cptcoveff,Tvaraff[1]);
                   3215:        scanf("%d", i);*/
                   3216:       for (i=-5; i<=nlstate+ndeath; i++)  
                   3217:        for (jk=-5; jk<=nlstate+ndeath; jk++)  
                   3218:          for(m=iagemin; m <= iagemax+3; m++)
                   3219:            freq[i][jk][m]=0;
1.143     brouard  3220:       
                   3221:       for (i=1; i<=nlstate; i++)  
                   3222:        for(m=iagemin; m <= iagemax+3; m++)
                   3223:          prop[i][m]=0;
1.126     brouard  3224:       
                   3225:       dateintsum=0;
                   3226:       k2cpt=0;
                   3227:       for (i=1; i<=imx; i++) {
                   3228:        bool=1;
1.210     brouard  3229:        if (cptcovn>0) { /* Filter is here: Must be looked at for model=V1+V2+V3+V4 */
1.144     brouard  3230:          for (z1=1; z1<=cptcoveff; z1++)       
1.198     brouard  3231:             if (covar[Tvaraff[z1]][i]!= nbcode[Tvaraff[z1]][codtabm(j1,z1)]){
1.145     brouard  3232:                 /* Tests if the value of each of the covariates of i is equal to filter j1 */
1.144     brouard  3233:               bool=0;
1.198     brouard  3234:               /* 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", 
                   3235:                 bool,i,z1, z1, Tvaraff[z1],i,covar[Tvaraff[z1]][i],j1,z1,codtabm(j1,z1),
                   3236:                 j1,z1,nbcode[Tvaraff[z1]][codtabm(j1,z1)],j1);*/
                   3237:               /* For j1=7 in V1+V2+V3+V4 = 0 1 1 0 and codtabm(7,3)=1 and nbcde[3][?]=1*/
1.144     brouard  3238:             } 
1.210     brouard  3239:        } /* cptcovn > 0 */
1.144     brouard  3240:  
1.126     brouard  3241:        if (bool==1){
                   3242:          for(m=firstpass; m<=lastpass; m++){
                   3243:            k2=anint[m][i]+(mint[m][i]/12.);
                   3244:            /*if ((k2>=dateprev1) && (k2<=dateprev2)) {*/
                   3245:              if(agev[m][i]==0) agev[m][i]=iagemax+1;
                   3246:              if(agev[m][i]==1) agev[m][i]=iagemax+2;
                   3247:              if (s[m][i]>0 && s[m][i]<=nlstate) prop[s[m][i]][(int)agev[m][i]] += weight[i];
                   3248:              if (m<lastpass) {
                   3249:                freq[s[m][i]][s[m+1][i]][(int)agev[m][i]] += weight[i];
                   3250:                freq[s[m][i]][s[m+1][i]][iagemax+3] += weight[i];
                   3251:              }
                   3252:              
1.210     brouard  3253:              if ((agev[m][i]>1) && (agev[m][i]< (iagemax+3)) && (anint[m][i]!=9999) && (mint[m][i]!=99)) {
1.126     brouard  3254:                dateintsum=dateintsum+k2;
                   3255:                k2cpt++;
1.210     brouard  3256:                /* printf("i=%ld dateintmean = %lf dateintsum=%lf k2cpt=%lf k2=%lf\n",i, dateintsum/k2cpt, dateintsum,k2cpt, k2); */
1.126     brouard  3257:              }
                   3258:              /*}*/
1.210     brouard  3259:          } /* end m */
                   3260:        } /* end bool */
                   3261:       } /* end i = 1 to imx */
1.126     brouard  3262:        
                   3263:       /*      fprintf(ficresp, "#Count between %.lf/%.lf/%.lf and %.lf/%.lf/%.lf\n",jprev1, mprev1,anprev1,jprev2, mprev2,anprev2);*/
                   3264:       pstamp(ficresp);
                   3265:       if  (cptcovn>0) {
                   3266:        fprintf(ficresp, "\n#********** Variable "); 
1.198     brouard  3267:        for (z1=1; z1<=cptcoveff; z1++) fprintf(ficresp, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
1.126     brouard  3268:        fprintf(ficresp, "**********\n#");
1.143     brouard  3269:        fprintf(ficlog, "\n#********** Variable "); 
1.198     brouard  3270:        for (z1=1; z1<=cptcoveff; z1++) fprintf(ficlog, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
1.143     brouard  3271:        fprintf(ficlog, "**********\n#");
1.126     brouard  3272:       }
                   3273:       for(i=1; i<=nlstate;i++) 
                   3274:        fprintf(ficresp, " Age Prev(%d) N(%d) N",i,i);
                   3275:       fprintf(ficresp, "\n");
                   3276:       
                   3277:       for(i=iagemin; i <= iagemax+3; i++){
                   3278:        if(i==iagemax+3){
                   3279:          fprintf(ficlog,"Total");
                   3280:        }else{
                   3281:          if(first==1){
                   3282:            first=0;
                   3283:            printf("See log file for details...\n");
                   3284:          }
                   3285:          fprintf(ficlog,"Age %d", i);
                   3286:        }
                   3287:        for(jk=1; jk <=nlstate ; jk++){
                   3288:          for(m=-1, pp[jk]=0; m <=nlstate+ndeath ; m++)
                   3289:            pp[jk] += freq[jk][m][i]; 
                   3290:        }
                   3291:        for(jk=1; jk <=nlstate ; jk++){
                   3292:          for(m=-1, pos=0; m <=0 ; m++)
                   3293:            pos += freq[jk][m][i];
                   3294:          if(pp[jk]>=1.e-10){
                   3295:            if(first==1){
1.132     brouard  3296:              printf(" %d.=%.0f loss[%d]=%.1f%%",jk,pp[jk],jk,100*pos/pp[jk]);
1.126     brouard  3297:            }
                   3298:            fprintf(ficlog," %d.=%.0f loss[%d]=%.1f%%",jk,pp[jk],jk,100*pos/pp[jk]);
                   3299:          }else{
                   3300:            if(first==1)
                   3301:              printf(" %d.=%.0f loss[%d]=NaNQ%%",jk,pp[jk],jk);
                   3302:            fprintf(ficlog," %d.=%.0f loss[%d]=NaNQ%%",jk,pp[jk],jk);
                   3303:          }
                   3304:        }
                   3305: 
                   3306:        for(jk=1; jk <=nlstate ; jk++){
                   3307:          for(m=0, pp[jk]=0; m <=nlstate+ndeath; m++)
                   3308:            pp[jk] += freq[jk][m][i];
                   3309:        }       
                   3310:        for(jk=1,pos=0,posprop=0; jk <=nlstate ; jk++){
                   3311:          pos += pp[jk];
                   3312:          posprop += prop[jk][i];
                   3313:        }
                   3314:        for(jk=1; jk <=nlstate ; jk++){
                   3315:          if(pos>=1.e-5){
                   3316:            if(first==1)
                   3317:              printf(" %d.=%.0f prev[%d]=%.1f%%",jk,pp[jk],jk,100*pp[jk]/pos);
                   3318:            fprintf(ficlog," %d.=%.0f prev[%d]=%.1f%%",jk,pp[jk],jk,100*pp[jk]/pos);
                   3319:          }else{
                   3320:            if(first==1)
                   3321:              printf(" %d.=%.0f prev[%d]=NaNQ%%",jk,pp[jk],jk);
                   3322:            fprintf(ficlog," %d.=%.0f prev[%d]=NaNQ%%",jk,pp[jk],jk);
                   3323:          }
                   3324:          if( i <= iagemax){
                   3325:            if(pos>=1.e-5){
                   3326:              fprintf(ficresp," %d %.5f %.0f %.0f",i,prop[jk][i]/posprop, prop[jk][i],posprop);
                   3327:              /*probs[i][jk][j1]= pp[jk]/pos;*/
                   3328:              /*printf("\ni=%d jk=%d j1=%d %.5f %.0f %.0f %f",i,jk,j1,pp[jk]/pos, pp[jk],pos,probs[i][jk][j1]);*/
                   3329:            }
                   3330:            else
                   3331:              fprintf(ficresp," %d NaNq %.0f %.0f",i,prop[jk][i],posprop);
                   3332:          }
                   3333:        }
                   3334:        
                   3335:        for(jk=-1; jk <=nlstate+ndeath; jk++)
                   3336:          for(m=-1; m <=nlstate+ndeath; m++)
                   3337:            if(freq[jk][m][i] !=0 ) {
                   3338:            if(first==1)
                   3339:              printf(" %d%d=%.0f",jk,m,freq[jk][m][i]);
                   3340:              fprintf(ficlog," %d%d=%.0f",jk,m,freq[jk][m][i]);
                   3341:            }
                   3342:        if(i <= iagemax)
                   3343:          fprintf(ficresp,"\n");
                   3344:        if(first==1)
                   3345:          printf("Others in log...\n");
                   3346:        fprintf(ficlog,"\n");
1.210     brouard  3347:       } /* end loop i */
1.145     brouard  3348:       /*}*/
1.210     brouard  3349:   } /* end j1 */
1.126     brouard  3350:   dateintmean=dateintsum/k2cpt; 
                   3351:  
                   3352:   fclose(ficresp);
                   3353:   free_ma3x(freq,-5,nlstate+ndeath,-5,nlstate+ndeath, iagemin, iagemax+3);
                   3354:   free_vector(pp,1,nlstate);
                   3355:   free_matrix(prop,1,nlstate,iagemin, iagemax+3);
                   3356:   /* End of Freq */
                   3357: }
                   3358: 
                   3359: /************ Prevalence ********************/
                   3360: 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)
                   3361: {  
                   3362:   /* Compute observed prevalence between dateprev1 and dateprev2 by counting the number of people
                   3363:      in each health status at the date of interview (if between dateprev1 and dateprev2).
                   3364:      We still use firstpass and lastpass as another selection.
                   3365:   */
                   3366:  
1.164     brouard  3367:   int i, m, jk, j1, bool, z1,j;
                   3368: 
                   3369:   double **prop;
                   3370:   double posprop; 
1.126     brouard  3371:   double  y2; /* in fractional years */
                   3372:   int iagemin, iagemax;
1.145     brouard  3373:   int first; /** to stop verbosity which is redirected to log file */
1.126     brouard  3374: 
                   3375:   iagemin= (int) agemin;
                   3376:   iagemax= (int) agemax;
                   3377:   /*pp=vector(1,nlstate);*/
                   3378:   prop=matrix(1,nlstate,iagemin,iagemax+3); 
                   3379:   /*  freq=ma3x(-1,nlstate+ndeath,-1,nlstate+ndeath,iagemin,iagemax+3);*/
                   3380:   j1=0;
                   3381:   
1.145     brouard  3382:   /*j=cptcoveff;*/
1.126     brouard  3383:   if (cptcovn<1) {j=1;ncodemax[1]=1;}
                   3384:   
1.145     brouard  3385:   first=1;
                   3386:   for(j1=1; j1<= (int) pow(2,cptcoveff);j1++){
                   3387:     /*for(i1=1; i1<=ncodemax[k1];i1++){
                   3388:       j1++;*/
1.126     brouard  3389:       
                   3390:       for (i=1; i<=nlstate; i++)  
                   3391:        for(m=iagemin; m <= iagemax+3; m++)
                   3392:          prop[i][m]=0.0;
                   3393:      
                   3394:       for (i=1; i<=imx; i++) { /* Each individual */
                   3395:        bool=1;
                   3396:        if  (cptcovn>0) {
                   3397:          for (z1=1; z1<=cptcoveff; z1++) 
1.198     brouard  3398:            if (covar[Tvaraff[z1]][i]!= nbcode[Tvaraff[z1]][codtabm(j1,z1)]) 
1.126     brouard  3399:              bool=0;
                   3400:        } 
                   3401:        if (bool==1) { 
                   3402:          for(m=firstpass; m<=lastpass; m++){/* Other selection (we can limit to certain interviews*/
                   3403:            y2=anint[m][i]+(mint[m][i]/12.); /* Fractional date in year */
                   3404:            if ((y2>=dateprev1) && (y2<=dateprev2)) { /* Here is the main selection (fractional years) */
                   3405:              if(agev[m][i]==0) agev[m][i]=iagemax+1;
                   3406:              if(agev[m][i]==1) agev[m][i]=iagemax+2;
                   3407:              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); 
                   3408:              if (s[m][i]>0 && s[m][i]<=nlstate) { 
                   3409:                /*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]]);*/
                   3410:                prop[s[m][i]][(int)agev[m][i]] += weight[i];
                   3411:                prop[s[m][i]][iagemax+3] += weight[i]; 
                   3412:              } 
                   3413:            }
                   3414:          } /* end selection of waves */
                   3415:        }
                   3416:       }
                   3417:       for(i=iagemin; i <= iagemax+3; i++){  
                   3418:        for(jk=1,posprop=0; jk <=nlstate ; jk++) { 
                   3419:          posprop += prop[jk][i]; 
                   3420:        } 
1.145     brouard  3421:        
1.126     brouard  3422:        for(jk=1; jk <=nlstate ; jk++){     
                   3423:          if( i <=  iagemax){ 
                   3424:            if(posprop>=1.e-5){ 
                   3425:              probs[i][jk][j1]= prop[jk][i]/posprop;
1.145     brouard  3426:            } else{
                   3427:              if(first==1){
                   3428:                first=0;
                   3429:                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]);
                   3430:              }
                   3431:            }
1.126     brouard  3432:          } 
                   3433:        }/* end jk */ 
                   3434:       }/* end i */ 
1.145     brouard  3435:     /*} *//* end i1 */
                   3436:   } /* end j1 */
1.126     brouard  3437:   
                   3438:   /*  free_ma3x(freq,-1,nlstate+ndeath,-1,nlstate+ndeath, iagemin, iagemax+3);*/
                   3439:   /*free_vector(pp,1,nlstate);*/
                   3440:   free_matrix(prop,1,nlstate, iagemin,iagemax+3);
                   3441: }  /* End of prevalence */
                   3442: 
                   3443: /************* Waves Concatenation ***************/
                   3444: 
                   3445: 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)
                   3446: {
                   3447:   /* Concatenates waves: wav[i] is the number of effective (useful waves) of individual i.
                   3448:      Death is a valid wave (if date is known).
                   3449:      mw[mi][i] is the mi (mi=1 to wav[i])  effective wave of individual i
                   3450:      dh[m][i] or dh[mw[mi][i]][i] is the delay between two effective waves m=mw[mi][i]
                   3451:      and mw[mi+1][i]. dh depends on stepm.
                   3452:      */
                   3453: 
                   3454:   int i, mi, m;
                   3455:   /* int j, k=0,jk, ju, jl,jmin=1e+5, jmax=-1;
                   3456:      double sum=0., jmean=0.;*/
                   3457:   int first;
                   3458:   int j, k=0,jk, ju, jl;
                   3459:   double sum=0.;
                   3460:   first=0;
1.164     brouard  3461:   jmin=100000;
1.126     brouard  3462:   jmax=-1;
                   3463:   jmean=0.;
                   3464:   for(i=1; i<=imx; i++){
                   3465:     mi=0;
                   3466:     m=firstpass;
                   3467:     while(s[m][i] <= nlstate){
                   3468:       if(s[m][i]>=1 || s[m][i]==-2 || s[m][i]==-4 || s[m][i]==-5)
                   3469:        mw[++mi][i]=m;
                   3470:       if(m >=lastpass)
                   3471:        break;
                   3472:       else
                   3473:        m++;
                   3474:     }/* end while */
                   3475:     if (s[m][i] > nlstate){
                   3476:       mi++;    /* Death is another wave */
                   3477:       /* if(mi==0)  never been interviewed correctly before death */
                   3478:         /* Only death is a correct wave */
                   3479:       mw[mi][i]=m;
                   3480:     }
                   3481: 
                   3482:     wav[i]=mi;
                   3483:     if(mi==0){
                   3484:       nbwarn++;
                   3485:       if(first==0){
                   3486:        printf("Warning! No valid information for individual %ld line=%d (skipped) and may be others, see log file\n",num[i],i);
                   3487:        first=1;
                   3488:       }
                   3489:       if(first==1){
                   3490:        fprintf(ficlog,"Warning! No valid information for individual %ld line=%d (skipped)\n",num[i],i);
                   3491:       }
                   3492:     } /* end mi==0 */
                   3493:   } /* End individuals */
                   3494: 
                   3495:   for(i=1; i<=imx; i++){
                   3496:     for(mi=1; mi<wav[i];mi++){
                   3497:       if (stepm <=0)
                   3498:        dh[mi][i]=1;
                   3499:       else{
                   3500:        if (s[mw[mi+1][i]][i] > nlstate) { /* A death */
                   3501:          if (agedc[i] < 2*AGESUP) {
                   3502:            j= rint(agedc[i]*12-agev[mw[mi][i]][i]*12); 
                   3503:            if(j==0) j=1;  /* Survives at least one month after exam */
                   3504:            else if(j<0){
                   3505:              nberr++;
                   3506:              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]);
                   3507:              j=1; /* Temporary Dangerous patch */
                   3508:              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);
                   3509:              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]);
                   3510:              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);
                   3511:            }
                   3512:            k=k+1;
                   3513:            if (j >= jmax){
                   3514:              jmax=j;
                   3515:              ijmax=i;
                   3516:            }
                   3517:            if (j <= jmin){
                   3518:              jmin=j;
                   3519:              ijmin=i;
                   3520:            }
                   3521:            sum=sum+j;
                   3522:            /*if (j<0) printf("j=%d num=%d \n",j,i);*/
                   3523:            /*    printf("%d %d %d %d\n", s[mw[mi][i]][i] ,s[mw[mi+1][i]][i],j,i);*/
                   3524:          }
                   3525:        }
                   3526:        else{
                   3527:          j= rint( (agev[mw[mi+1][i]][i]*12 - agev[mw[mi][i]][i]*12));
                   3528: /*       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]); */
                   3529: 
                   3530:          k=k+1;
                   3531:          if (j >= jmax) {
                   3532:            jmax=j;
                   3533:            ijmax=i;
                   3534:          }
                   3535:          else if (j <= jmin){
                   3536:            jmin=j;
                   3537:            ijmin=i;
                   3538:          }
                   3539:          /*        if (j<10) printf("j=%d jmin=%d num=%d ",j,jmin,i); */
                   3540:          /*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]);*/
                   3541:          if(j<0){
                   3542:            nberr++;
                   3543:            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]);
                   3544:            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]);
                   3545:          }
                   3546:          sum=sum+j;
                   3547:        }
                   3548:        jk= j/stepm;
                   3549:        jl= j -jk*stepm;
                   3550:        ju= j -(jk+1)*stepm;
                   3551:        if(mle <=1){ /* only if we use a the linear-interpoloation pseudo-likelihood */
                   3552:          if(jl==0){
                   3553:            dh[mi][i]=jk;
                   3554:            bh[mi][i]=0;
                   3555:          }else{ /* We want a negative bias in order to only have interpolation ie
1.136     brouard  3556:                  * to avoid the price of an extra matrix product in likelihood */
1.126     brouard  3557:            dh[mi][i]=jk+1;
                   3558:            bh[mi][i]=ju;
                   3559:          }
                   3560:        }else{
                   3561:          if(jl <= -ju){
                   3562:            dh[mi][i]=jk;
                   3563:            bh[mi][i]=jl;       /* bias is positive if real duration
                   3564:                                 * is higher than the multiple of stepm and negative otherwise.
                   3565:                                 */
                   3566:          }
                   3567:          else{
                   3568:            dh[mi][i]=jk+1;
                   3569:            bh[mi][i]=ju;
                   3570:          }
                   3571:          if(dh[mi][i]==0){
                   3572:            dh[mi][i]=1; /* At least one step */
                   3573:            bh[mi][i]=ju; /* At least one step */
                   3574:            /*  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);*/
                   3575:          }
                   3576:        } /* end if mle */
                   3577:       }
                   3578:     } /* end wave */
                   3579:   }
                   3580:   jmean=sum/k;
                   3581:   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  3582:   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  3583:  }
                   3584: 
                   3585: /*********** Tricode ****************************/
1.145     brouard  3586: void tricode(int *Tvar, int **nbcode, int imx, int *Ndum)
1.126     brouard  3587: {
1.144     brouard  3588:   /**< Uses cptcovn+2*cptcovprod as the number of covariates */
                   3589:   /*     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  3590:    * Boring subroutine which should only output nbcode[Tvar[j]][k]
1.145     brouard  3591:    * Tvar[5] in V2+V1+V3*age+V2*V4 is 2 (V2)
1.169     brouard  3592:    * nbcode[Tvar[j]][1]= 
1.144     brouard  3593:   */
1.130     brouard  3594: 
1.145     brouard  3595:   int ij=1, k=0, j=0, i=0, maxncov=NCOVMAX;
1.136     brouard  3596:   int modmaxcovj=0; /* Modality max of covariates j */
1.145     brouard  3597:   int cptcode=0; /* Modality max of covariates j */
                   3598:   int modmincovj=0; /* Modality min of covariates j */
                   3599: 
                   3600: 
1.126     brouard  3601:   cptcoveff=0; 
                   3602:  
1.144     brouard  3603:   for (k=1; k <= maxncov; k++) ncodemax[k]=0; /* Horrible constant again replaced by NCOVMAX */
1.126     brouard  3604: 
1.145     brouard  3605:   /* Loop on covariates without age and products */
1.186     brouard  3606:   for (j=1; j<=(cptcovs); j++) { /* From model V1 + V2*age+ V3 + V3*V4 keeps V1 + V3 = 2 only */
1.192     brouard  3607:     for (k=-1; k < maxncov; k++) Ndum[k]=0;
1.186     brouard  3608:     for (i=1; i<=imx; i++) { /* Loop on individuals: reads the data file to get the maximum value of the 
1.136     brouard  3609:                               modality of this covariate Vj*/ 
1.145     brouard  3610:       ij=(int)(covar[Tvar[j]][i]); /* ij=0 or 1 or -1. Value of the covariate Tvar[j] for individual i
                   3611:                                    * If product of Vn*Vm, still boolean *:
                   3612:                                    * If it was coded 1, 2, 3, 4 should be splitted into 3 boolean variables
                   3613:                                    * 1 => 0 0 0, 2 => 0 0 1, 3 => 0 1 1, 4=1 0 0   */
                   3614:       /* Finds for covariate j, n=Tvar[j] of Vn . ij is the
1.136     brouard  3615:                                      modality of the nth covariate of individual i. */
1.145     brouard  3616:       if (ij > modmaxcovj)
                   3617:         modmaxcovj=ij; 
                   3618:       else if (ij < modmincovj) 
                   3619:        modmincovj=ij; 
                   3620:       if ((ij < -1) && (ij > NCOVMAX)){
                   3621:        printf( "Error: minimal is less than -1 or maximal is bigger than %d. Exiting. \n", NCOVMAX );
                   3622:        exit(1);
                   3623:       }else
1.136     brouard  3624:       Ndum[ij]++; /*counts and stores the occurence of this modality 0, 1, -1*/
1.145     brouard  3625:       /*  If coded 1, 2, 3 , counts the number of 1 Ndum[1], number of 2, Ndum[2], etc */
1.126     brouard  3626:       /*printf("i=%d ij=%d Ndum[ij]=%d imx=%d",i,ij,Ndum[ij],imx);*/
1.136     brouard  3627:       /* getting the maximum value of the modality of the covariate
                   3628:         (should be 0 or 1 now) Tvar[j]. If V=sex and male is coded 0 and
                   3629:         female is 1, then modmaxcovj=1.*/
1.192     brouard  3630:     } /* end for loop on individuals i */
1.145     brouard  3631:     printf(" Minimal and maximal values of %d th covariate V%d: min=%d max=%d \n", j, Tvar[j], modmincovj, modmaxcovj);
1.192     brouard  3632:     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  3633:     cptcode=modmaxcovj;
1.137     brouard  3634:     /* Ndum[0] = frequency of 0 for model-covariate j, Ndum[1] frequency of 1 etc. */
1.145     brouard  3635:    /*for (i=0; i<=cptcode; i++) {*/
1.192     brouard  3636:     for (k=modmincovj;  k<=modmaxcovj; k++) { /* k=-1 ? 0 and 1*//* For each value k of the modality of model-cov j */
                   3637:       printf("Frequencies of covariates %d ie V%d with value %d: %d\n", j, Tvar[j], k, Ndum[k]);
                   3638:       fprintf(ficlog, "Frequencies of covariates %d ie V%d with value %d: %d\n", j, Tvar[j], k, Ndum[k]);
                   3639:       if( Ndum[k] != 0 ){ /* Counts if nobody answered modality k ie empty modality, we skip it and reorder */
                   3640:        if( k != -1){
                   3641:          ncodemax[j]++;  /* ncodemax[j]= Number of modalities of the j th
                   3642:                             covariate for which somebody answered excluding 
                   3643:                             undefined. Usually 2: 0 and 1. */
                   3644:        }
                   3645:        ncodemaxwundef[j]++; /* ncodemax[j]= Number of modalities of the j th
                   3646:                             covariate for which somebody answered including 
                   3647:                             undefined. Usually 3: -1, 0 and 1. */
1.145     brouard  3648:       }
                   3649:       /* In fact  ncodemax[j]=2 (dichotom. variables only) but it could be more for
                   3650:         historical reasons: 3 if coded 1, 2, 3 and 4 and Ndum[2]=0 */
1.131     brouard  3651:     } /* Ndum[-1] number of undefined modalities */
1.126     brouard  3652: 
1.136     brouard  3653:     /* j is a covariate, n=Tvar[j] of Vn; Fills nbcode */
1.186     brouard  3654:     /* For covariate j, modalities could be 1, 2, 3, 4, 5, 6, 7. 
                   3655:        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  3656:        modmincovj=3; modmaxcovj = 7;
1.186     brouard  3657:        There are only 3 modalities non empty 3, 6, 7 (or 2 if 27 is too few) : ncodemax[j]=3;
                   3658:        which will be coded 0, 1, 2 which in binary on 2=3-1 digits are 0=00 1=01, 2=10;
                   3659:        defining two dummy variables: variables V1_1 and V1_2.
1.145     brouard  3660:        nbcode[Tvar[j]][ij]=k;
                   3661:        nbcode[Tvar[j]][1]=0;
                   3662:        nbcode[Tvar[j]][2]=1;
                   3663:        nbcode[Tvar[j]][3]=2;
1.197     brouard  3664:        To be continued (not working yet).
1.145     brouard  3665:     */
1.197     brouard  3666:     ij=0; /* ij is similar to i but can jump over null modalities */
                   3667:     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*/
                   3668:        if (Ndum[i] == 0) { /* If nobody responded to this modality k */
1.192     brouard  3669:          break;
                   3670:        }
                   3671:        ij++;
1.197     brouard  3672:        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  3673:        cptcode = ij; /* New max modality for covar j */
                   3674:     } /* end of loop on modality i=-1 to 1 or more */
                   3675:       
                   3676:     /*   for (k=0; k<= cptcode; k++) { /\* k=-1 ? k=0 to 1 *\//\* Could be 1 to 4 *\//\* cptcode=modmaxcovj *\/ */
                   3677:     /*         /\*recode from 0 *\/ */
                   3678:     /*                                      k is a modality. If we have model=V1+V1*sex  */
                   3679:     /*                                      then: nbcode[1][1]=0 ; nbcode[1][2]=1; nbcode[2][1]=0 ; nbcode[2][2]=1; */
                   3680:     /*                                   But if some modality were not used, it is recoded from 0 to a newer modmaxcovj=cptcode *\/ */
                   3681:     /*         } */
                   3682:     /*         /\* cptcode = ij; *\/ /\* New max modality for covar j *\/ */
                   3683:     /*         if (ij > ncodemax[j]) { */
                   3684:     /*           printf( " Error ij=%d > ncodemax[%d]=%d\n", ij, j, ncodemax[j]);  */
                   3685:     /*           fprintf(ficlog, " Error ij=%d > ncodemax[%d]=%d\n", ij, j, ncodemax[j]); */
                   3686:     /*           break; */
                   3687:     /*         } */
                   3688:     /*   }  /\* end of loop on modality k *\/ */
1.137     brouard  3689:   } /* end of loop on model-covariate j. nbcode[Tvarj][1]=0 and nbcode[Tvarj][2]=1 sets the value of covariate j*/  
                   3690:   
1.145     brouard  3691:  for (k=-1; k< maxncov; k++) Ndum[k]=0; 
1.137     brouard  3692:   
1.187     brouard  3693:   for (i=1; i<=ncovmodel-2-nagesqr; i++) { /* -2, cste and age and eventually age*age */ 
1.145     brouard  3694:    /* Listing of all covariables in statement model to see if some covariates appear twice. For example, V1 appears twice in V1+V1*V2.*/ 
                   3695:    ij=Tvar[i]; /* Tvar might be -1 if status was unknown */ 
1.187     brouard  3696:    Ndum[ij]++; /* Might be supersed V1 + V1*age */
1.145     brouard  3697:  } 
1.126     brouard  3698: 
1.192     brouard  3699:  ij=0;
1.145     brouard  3700:  for (i=0; i<=  maxncov-1; i++) { /* modmaxcovj is unknown here. Only Ndum[2(V2),3(age*V3), 5(V3*V2) 6(V1*V4) */
                   3701:    /*printf("Ndum[%d]=%d\n",i, Ndum[i]);*/
1.126     brouard  3702:    if((Ndum[i]!=0) && (i<=ncovcol)){
1.192     brouard  3703:      ij++;
1.145     brouard  3704:      /*printf("diff Ndum[%d]=%d\n",i, Ndum[i]);*/
                   3705:      Tvaraff[ij]=i; /*For printing (unclear) */
1.192     brouard  3706:    }else{
                   3707:        /* Tvaraff[ij]=0; */
                   3708:    }
1.126     brouard  3709:  }
1.192     brouard  3710:  /* ij--; */
1.144     brouard  3711:  cptcoveff=ij; /*Number of total covariates*/
1.145     brouard  3712: 
1.126     brouard  3713: }
                   3714: 
1.145     brouard  3715: 
1.126     brouard  3716: /*********** Health Expectancies ****************/
                   3717: 
1.127     brouard  3718: 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  3719: 
                   3720: {
                   3721:   /* Health expectancies, no variances */
1.164     brouard  3722:   int i, j, nhstepm, hstepm, h, nstepm;
1.126     brouard  3723:   int nhstepma, nstepma; /* Decreasing with age */
                   3724:   double age, agelim, hf;
                   3725:   double ***p3mat;
                   3726:   double eip;
                   3727: 
                   3728:   pstamp(ficreseij);
                   3729:   fprintf(ficreseij,"# (a) Life expectancies by health status at initial age and (b) health expectancies by health status at initial age\n");
                   3730:   fprintf(ficreseij,"# Age");
                   3731:   for(i=1; i<=nlstate;i++){
                   3732:     for(j=1; j<=nlstate;j++){
                   3733:       fprintf(ficreseij," e%1d%1d ",i,j);
                   3734:     }
                   3735:     fprintf(ficreseij," e%1d. ",i);
                   3736:   }
                   3737:   fprintf(ficreseij,"\n");
                   3738: 
                   3739:   
                   3740:   if(estepm < stepm){
                   3741:     printf ("Problem %d lower than %d\n",estepm, stepm);
                   3742:   }
                   3743:   else  hstepm=estepm;   
                   3744:   /* We compute the life expectancy from trapezoids spaced every estepm months
                   3745:    * This is mainly to measure the difference between two models: for example
                   3746:    * if stepm=24 months pijx are given only every 2 years and by summing them
                   3747:    * we are calculating an estimate of the Life Expectancy assuming a linear 
                   3748:    * progression in between and thus overestimating or underestimating according
                   3749:    * to the curvature of the survival function. If, for the same date, we 
                   3750:    * estimate the model with stepm=1 month, we can keep estepm to 24 months
                   3751:    * to compare the new estimate of Life expectancy with the same linear 
                   3752:    * hypothesis. A more precise result, taking into account a more precise
                   3753:    * curvature will be obtained if estepm is as small as stepm. */
                   3754: 
                   3755:   /* For example we decided to compute the life expectancy with the smallest unit */
                   3756:   /* hstepm beeing the number of stepms, if hstepm=1 the length of hstepm is stepm. 
                   3757:      nhstepm is the number of hstepm from age to agelim 
                   3758:      nstepm is the number of stepm from age to agelin. 
                   3759:      Look at hpijx to understand the reason of that which relies in memory size
                   3760:      and note for a fixed period like estepm months */
                   3761:   /* We decided (b) to get a life expectancy respecting the most precise curvature of the
                   3762:      survival function given by stepm (the optimization length). Unfortunately it
                   3763:      means that if the survival funtion is printed only each two years of age and if
                   3764:      you sum them up and add 1 year (area under the trapezoids) you won't get the same 
                   3765:      results. So we changed our mind and took the option of the best precision.
                   3766:   */
                   3767:   hstepm=hstepm/stepm; /* Typically in stepm units, if stepm=6 & estepm=24 , = 24/6 months = 4 */ 
                   3768: 
                   3769:   agelim=AGESUP;
                   3770:   /* If stepm=6 months */
                   3771:     /* Computed by stepm unit matrices, product of hstepm matrices, stored
                   3772:        in an array of nhstepm length: nhstepm=10, hstepm=4, stepm=6 months */
                   3773:     
                   3774: /* nhstepm age range expressed in number of stepm */
                   3775:   nstepm=(int) rint((agelim-bage)*YEARM/stepm); /* Biggest nstepm */
                   3776:   /* Typically if 20 years nstepm = 20*12/6=40 stepm */ 
                   3777:   /* if (stepm >= YEARM) hstepm=1;*/
                   3778:   nhstepm = nstepm/hstepm;/* Expressed in hstepm, typically nhstepm=40/4=10 */
                   3779:   p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   3780: 
                   3781:   for (age=bage; age<=fage; age ++){ 
                   3782:     nstepma=(int) rint((agelim-bage)*YEARM/stepm); /* Biggest nstepm */
                   3783:     /* Typically if 20 years nstepm = 20*12/6=40 stepm */ 
                   3784:     /* if (stepm >= YEARM) hstepm=1;*/
                   3785:     nhstepma = nstepma/hstepm;/* Expressed in hstepm, typically nhstepma=40/4=10 */
                   3786: 
                   3787:     /* If stepm=6 months */
                   3788:     /* Computed by stepm unit matrices, product of hstepma matrices, stored
                   3789:        in an array of nhstepma length: nhstepma=10, hstepm=4, stepm=6 months */
                   3790:     
                   3791:     hpxij(p3mat,nhstepma,age,hstepm,x,nlstate,stepm,oldm, savm, cij);  
                   3792:     
                   3793:     hf=hstepm*stepm/YEARM;  /* Duration of hstepm expressed in year unit. */
                   3794:     
                   3795:     printf("%d|",(int)age);fflush(stdout);
                   3796:     fprintf(ficlog,"%d|",(int)age);fflush(ficlog);
                   3797:     
                   3798:     /* Computing expectancies */
                   3799:     for(i=1; i<=nlstate;i++)
                   3800:       for(j=1; j<=nlstate;j++)
                   3801:        for (h=0, eij[i][j][(int)age]=0; h<=nhstepm-1; h++){
                   3802:          eij[i][j][(int)age] += (p3mat[i][j][h]+p3mat[i][j][h+1])/2.0*hf;
                   3803:          
                   3804:          /* 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]);*/
                   3805: 
                   3806:        }
                   3807: 
                   3808:     fprintf(ficreseij,"%3.0f",age );
                   3809:     for(i=1; i<=nlstate;i++){
                   3810:       eip=0;
                   3811:       for(j=1; j<=nlstate;j++){
                   3812:        eip +=eij[i][j][(int)age];
                   3813:        fprintf(ficreseij,"%9.4f", eij[i][j][(int)age] );
                   3814:       }
                   3815:       fprintf(ficreseij,"%9.4f", eip );
                   3816:     }
                   3817:     fprintf(ficreseij,"\n");
                   3818:     
                   3819:   }
                   3820:   free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   3821:   printf("\n");
                   3822:   fprintf(ficlog,"\n");
                   3823:   
                   3824: }
                   3825: 
1.127     brouard  3826: 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  3827: 
                   3828: {
                   3829:   /* Covariances of health expectancies eij and of total life expectancies according
                   3830:    to initial status i, ei. .
                   3831:   */
                   3832:   int i, j, nhstepm, hstepm, h, nstepm, k, cptj, cptj2, i2, j2, ij, ji;
                   3833:   int nhstepma, nstepma; /* Decreasing with age */
                   3834:   double age, agelim, hf;
                   3835:   double ***p3matp, ***p3matm, ***varhe;
                   3836:   double **dnewm,**doldm;
                   3837:   double *xp, *xm;
                   3838:   double **gp, **gm;
                   3839:   double ***gradg, ***trgradg;
                   3840:   int theta;
                   3841: 
                   3842:   double eip, vip;
                   3843: 
                   3844:   varhe=ma3x(1,nlstate*nlstate,1,nlstate*nlstate,(int) bage, (int) fage);
                   3845:   xp=vector(1,npar);
                   3846:   xm=vector(1,npar);
                   3847:   dnewm=matrix(1,nlstate*nlstate,1,npar);
                   3848:   doldm=matrix(1,nlstate*nlstate,1,nlstate*nlstate);
                   3849:   
                   3850:   pstamp(ficresstdeij);
                   3851:   fprintf(ficresstdeij,"# Health expectancies with standard errors\n");
                   3852:   fprintf(ficresstdeij,"# Age");
                   3853:   for(i=1; i<=nlstate;i++){
                   3854:     for(j=1; j<=nlstate;j++)
                   3855:       fprintf(ficresstdeij," e%1d%1d (SE)",i,j);
                   3856:     fprintf(ficresstdeij," e%1d. ",i);
                   3857:   }
                   3858:   fprintf(ficresstdeij,"\n");
                   3859: 
                   3860:   pstamp(ficrescveij);
                   3861:   fprintf(ficrescveij,"# Subdiagonal matrix of covariances of health expectancies by age: cov(eij,ekl)\n");
                   3862:   fprintf(ficrescveij,"# Age");
                   3863:   for(i=1; i<=nlstate;i++)
                   3864:     for(j=1; j<=nlstate;j++){
                   3865:       cptj= (j-1)*nlstate+i;
                   3866:       for(i2=1; i2<=nlstate;i2++)
                   3867:        for(j2=1; j2<=nlstate;j2++){
                   3868:          cptj2= (j2-1)*nlstate+i2;
                   3869:          if(cptj2 <= cptj)
                   3870:            fprintf(ficrescveij,"  %1d%1d,%1d%1d",i,j,i2,j2);
                   3871:        }
                   3872:     }
                   3873:   fprintf(ficrescveij,"\n");
                   3874:   
                   3875:   if(estepm < stepm){
                   3876:     printf ("Problem %d lower than %d\n",estepm, stepm);
                   3877:   }
                   3878:   else  hstepm=estepm;   
                   3879:   /* We compute the life expectancy from trapezoids spaced every estepm months
                   3880:    * This is mainly to measure the difference between two models: for example
                   3881:    * if stepm=24 months pijx are given only every 2 years and by summing them
                   3882:    * we are calculating an estimate of the Life Expectancy assuming a linear 
                   3883:    * progression in between and thus overestimating or underestimating according
                   3884:    * to the curvature of the survival function. If, for the same date, we 
                   3885:    * estimate the model with stepm=1 month, we can keep estepm to 24 months
                   3886:    * to compare the new estimate of Life expectancy with the same linear 
                   3887:    * hypothesis. A more precise result, taking into account a more precise
                   3888:    * curvature will be obtained if estepm is as small as stepm. */
                   3889: 
                   3890:   /* For example we decided to compute the life expectancy with the smallest unit */
                   3891:   /* hstepm beeing the number of stepms, if hstepm=1 the length of hstepm is stepm. 
                   3892:      nhstepm is the number of hstepm from age to agelim 
                   3893:      nstepm is the number of stepm from age to agelin. 
                   3894:      Look at hpijx to understand the reason of that which relies in memory size
                   3895:      and note for a fixed period like estepm months */
                   3896:   /* We decided (b) to get a life expectancy respecting the most precise curvature of the
                   3897:      survival function given by stepm (the optimization length). Unfortunately it
                   3898:      means that if the survival funtion is printed only each two years of age and if
                   3899:      you sum them up and add 1 year (area under the trapezoids) you won't get the same 
                   3900:      results. So we changed our mind and took the option of the best precision.
                   3901:   */
                   3902:   hstepm=hstepm/stepm; /* Typically in stepm units, if stepm=6 & estepm=24 , = 24/6 months = 4 */ 
                   3903: 
                   3904:   /* If stepm=6 months */
                   3905:   /* nhstepm age range expressed in number of stepm */
                   3906:   agelim=AGESUP;
                   3907:   nstepm=(int) rint((agelim-bage)*YEARM/stepm); 
                   3908:   /* Typically if 20 years nstepm = 20*12/6=40 stepm */ 
                   3909:   /* if (stepm >= YEARM) hstepm=1;*/
                   3910:   nhstepm = nstepm/hstepm;/* Expressed in hstepm, typically nhstepm=40/4=10 */
                   3911:   
                   3912:   p3matp=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   3913:   p3matm=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   3914:   gradg=ma3x(0,nhstepm,1,npar,1,nlstate*nlstate);
                   3915:   trgradg =ma3x(0,nhstepm,1,nlstate*nlstate,1,npar);
                   3916:   gp=matrix(0,nhstepm,1,nlstate*nlstate);
                   3917:   gm=matrix(0,nhstepm,1,nlstate*nlstate);
                   3918: 
                   3919:   for (age=bage; age<=fage; age ++){ 
                   3920:     nstepma=(int) rint((agelim-bage)*YEARM/stepm); /* Biggest nstepm */
                   3921:     /* Typically if 20 years nstepm = 20*12/6=40 stepm */ 
                   3922:     /* if (stepm >= YEARM) hstepm=1;*/
                   3923:     nhstepma = nstepma/hstepm;/* Expressed in hstepm, typically nhstepma=40/4=10 */
                   3924: 
                   3925:     /* If stepm=6 months */
                   3926:     /* Computed by stepm unit matrices, product of hstepma matrices, stored
                   3927:        in an array of nhstepma length: nhstepma=10, hstepm=4, stepm=6 months */
                   3928:     
                   3929:     hf=hstepm*stepm/YEARM;  /* Duration of hstepm expressed in year unit. */
                   3930: 
                   3931:     /* Computing  Variances of health expectancies */
                   3932:     /* Gradient is computed with plus gp and minus gm. Code is duplicated in order to
                   3933:        decrease memory allocation */
                   3934:     for(theta=1; theta <=npar; theta++){
                   3935:       for(i=1; i<=npar; i++){ 
                   3936:        xp[i] = x[i] + (i==theta ?delti[theta]:0);
                   3937:        xm[i] = x[i] - (i==theta ?delti[theta]:0);
                   3938:       }
                   3939:       hpxij(p3matp,nhstepm,age,hstepm,xp,nlstate,stepm,oldm,savm, cij);  
                   3940:       hpxij(p3matm,nhstepm,age,hstepm,xm,nlstate,stepm,oldm,savm, cij);  
                   3941:   
                   3942:       for(j=1; j<= nlstate; j++){
                   3943:        for(i=1; i<=nlstate; i++){
                   3944:          for(h=0; h<=nhstepm-1; h++){
                   3945:            gp[h][(j-1)*nlstate + i] = (p3matp[i][j][h]+p3matp[i][j][h+1])/2.;
                   3946:            gm[h][(j-1)*nlstate + i] = (p3matm[i][j][h]+p3matm[i][j][h+1])/2.;
                   3947:          }
                   3948:        }
                   3949:       }
                   3950:      
                   3951:       for(ij=1; ij<= nlstate*nlstate; ij++)
                   3952:        for(h=0; h<=nhstepm-1; h++){
                   3953:          gradg[h][theta][ij]= (gp[h][ij]-gm[h][ij])/2./delti[theta];
                   3954:        }
                   3955:     }/* End theta */
                   3956:     
                   3957:     
                   3958:     for(h=0; h<=nhstepm-1; h++)
                   3959:       for(j=1; j<=nlstate*nlstate;j++)
                   3960:        for(theta=1; theta <=npar; theta++)
                   3961:          trgradg[h][j][theta]=gradg[h][theta][j];
                   3962:     
                   3963: 
                   3964:      for(ij=1;ij<=nlstate*nlstate;ij++)
                   3965:       for(ji=1;ji<=nlstate*nlstate;ji++)
                   3966:        varhe[ij][ji][(int)age] =0.;
                   3967: 
                   3968:      printf("%d|",(int)age);fflush(stdout);
                   3969:      fprintf(ficlog,"%d|",(int)age);fflush(ficlog);
                   3970:      for(h=0;h<=nhstepm-1;h++){
                   3971:       for(k=0;k<=nhstepm-1;k++){
                   3972:        matprod2(dnewm,trgradg[h],1,nlstate*nlstate,1,npar,1,npar,matcov);
                   3973:        matprod2(doldm,dnewm,1,nlstate*nlstate,1,npar,1,nlstate*nlstate,gradg[k]);
                   3974:        for(ij=1;ij<=nlstate*nlstate;ij++)
                   3975:          for(ji=1;ji<=nlstate*nlstate;ji++)
                   3976:            varhe[ij][ji][(int)age] += doldm[ij][ji]*hf*hf;
                   3977:       }
                   3978:     }
                   3979: 
                   3980:     /* Computing expectancies */
                   3981:     hpxij(p3matm,nhstepm,age,hstepm,x,nlstate,stepm,oldm, savm, cij);  
                   3982:     for(i=1; i<=nlstate;i++)
                   3983:       for(j=1; j<=nlstate;j++)
                   3984:        for (h=0, eij[i][j][(int)age]=0; h<=nhstepm-1; h++){
                   3985:          eij[i][j][(int)age] += (p3matm[i][j][h]+p3matm[i][j][h+1])/2.0*hf;
                   3986:          
                   3987:          /* 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]);*/
                   3988: 
                   3989:        }
                   3990: 
                   3991:     fprintf(ficresstdeij,"%3.0f",age );
                   3992:     for(i=1; i<=nlstate;i++){
                   3993:       eip=0.;
                   3994:       vip=0.;
                   3995:       for(j=1; j<=nlstate;j++){
                   3996:        eip += eij[i][j][(int)age];
                   3997:        for(k=1; k<=nlstate;k++) /* Sum on j and k of cov(eij,eik) */
                   3998:          vip += varhe[(j-1)*nlstate+i][(k-1)*nlstate+i][(int)age];
                   3999:        fprintf(ficresstdeij," %9.4f (%.4f)", eij[i][j][(int)age], sqrt(varhe[(j-1)*nlstate+i][(j-1)*nlstate+i][(int)age]) );
                   4000:       }
                   4001:       fprintf(ficresstdeij," %9.4f (%.4f)", eip, sqrt(vip));
                   4002:     }
                   4003:     fprintf(ficresstdeij,"\n");
                   4004: 
                   4005:     fprintf(ficrescveij,"%3.0f",age );
                   4006:     for(i=1; i<=nlstate;i++)
                   4007:       for(j=1; j<=nlstate;j++){
                   4008:        cptj= (j-1)*nlstate+i;
                   4009:        for(i2=1; i2<=nlstate;i2++)
                   4010:          for(j2=1; j2<=nlstate;j2++){
                   4011:            cptj2= (j2-1)*nlstate+i2;
                   4012:            if(cptj2 <= cptj)
                   4013:              fprintf(ficrescveij," %.4f", varhe[cptj][cptj2][(int)age]);
                   4014:          }
                   4015:       }
                   4016:     fprintf(ficrescveij,"\n");
                   4017:    
                   4018:   }
                   4019:   free_matrix(gm,0,nhstepm,1,nlstate*nlstate);
                   4020:   free_matrix(gp,0,nhstepm,1,nlstate*nlstate);
                   4021:   free_ma3x(gradg,0,nhstepm,1,npar,1,nlstate*nlstate);
                   4022:   free_ma3x(trgradg,0,nhstepm,1,nlstate*nlstate,1,npar);
                   4023:   free_ma3x(p3matm,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   4024:   free_ma3x(p3matp,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   4025:   printf("\n");
                   4026:   fprintf(ficlog,"\n");
                   4027: 
                   4028:   free_vector(xm,1,npar);
                   4029:   free_vector(xp,1,npar);
                   4030:   free_matrix(dnewm,1,nlstate*nlstate,1,npar);
                   4031:   free_matrix(doldm,1,nlstate*nlstate,1,nlstate*nlstate);
                   4032:   free_ma3x(varhe,1,nlstate*nlstate,1,nlstate*nlstate,(int) bage, (int)fage);
                   4033: }
                   4034: 
                   4035: /************ Variance ******************/
1.209     brouard  4036:  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  4037: {
                   4038:   /* Variance of health expectancies */
                   4039:   /*  double **prevalim(double **prlim, int nlstate, double *xp, double age, double **oldm, double ** savm,double ftolpl);*/
                   4040:   /* double **newm;*/
1.169     brouard  4041:   /* int movingaverage(double ***probs, double bage,double fage, double ***mobaverage, int mobilav)*/
                   4042:   
                   4043:   int movingaverage();
1.126     brouard  4044:   double **dnewm,**doldm;
                   4045:   double **dnewmp,**doldmp;
                   4046:   int i, j, nhstepm, hstepm, h, nstepm ;
1.164     brouard  4047:   int k;
1.126     brouard  4048:   double *xp;
                   4049:   double **gp, **gm;  /* for var eij */
                   4050:   double ***gradg, ***trgradg; /*for var eij */
                   4051:   double **gradgp, **trgradgp; /* for var p point j */
                   4052:   double *gpp, *gmp; /* for var p point j */
                   4053:   double **varppt; /* for var p point j nlstate to nlstate+ndeath */
                   4054:   double ***p3mat;
                   4055:   double age,agelim, hf;
                   4056:   double ***mobaverage;
                   4057:   int theta;
                   4058:   char digit[4];
                   4059:   char digitp[25];
                   4060: 
                   4061:   char fileresprobmorprev[FILENAMELENGTH];
                   4062: 
                   4063:   if(popbased==1){
                   4064:     if(mobilav!=0)
1.201     brouard  4065:       strcpy(digitp,"-POPULBASED-MOBILAV_");
                   4066:     else strcpy(digitp,"-POPULBASED-NOMOBIL_");
1.126     brouard  4067:   }
                   4068:   else 
1.201     brouard  4069:     strcpy(digitp,"-STABLBASED_");
1.126     brouard  4070: 
                   4071:   if (mobilav!=0) {
                   4072:     mobaverage= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
                   4073:     if (movingaverage(probs, bage, fage, mobaverage,mobilav)!=0){
                   4074:       fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav);
                   4075:       printf(" Error in movingaverage mobilav=%d\n",mobilav);
                   4076:     }
                   4077:   }
                   4078: 
1.201     brouard  4079:   strcpy(fileresprobmorprev,"PRMORPREV-"); 
1.126     brouard  4080:   sprintf(digit,"%-d",ij);
                   4081:   /*printf("DIGIT=%s, ij=%d ijr=%-d|\n",digit, ij,ij);*/
                   4082:   strcat(fileresprobmorprev,digit); /* Tvar to be done */
                   4083:   strcat(fileresprobmorprev,digitp); /* Popbased or not, mobilav or not */
1.202     brouard  4084:   strcat(fileresprobmorprev,fileresu);
1.126     brouard  4085:   if((ficresprobmorprev=fopen(fileresprobmorprev,"w"))==NULL) {
                   4086:     printf("Problem with resultfile: %s\n", fileresprobmorprev);
                   4087:     fprintf(ficlog,"Problem with resultfile: %s\n", fileresprobmorprev);
                   4088:   }
                   4089:   printf("Computing total mortality p.j=w1*p1j+w2*p2j+..: result on file '%s' \n",fileresprobmorprev);
                   4090:   fprintf(ficlog,"Computing total mortality p.j=w1*p1j+w2*p2j+..: result on file '%s' \n",fileresprobmorprev);
                   4091:   pstamp(ficresprobmorprev);
                   4092:   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);
                   4093:   fprintf(ficresprobmorprev,"# Age cov=%-d",ij);
                   4094:   for(j=nlstate+1; j<=(nlstate+ndeath);j++){
                   4095:     fprintf(ficresprobmorprev," p.%-d SE",j);
                   4096:     for(i=1; i<=nlstate;i++)
                   4097:       fprintf(ficresprobmorprev," w%1d p%-d%-d",i,i,j);
                   4098:   }  
                   4099:   fprintf(ficresprobmorprev,"\n");
1.208     brouard  4100:   
1.126     brouard  4101:   fprintf(ficgp,"\n# Routine varevsij");
1.200     brouard  4102:   fprintf(ficgp,"\nunset title \n");
                   4103: /* fprintf(fichtm, "#Local time at start: %s", strstart);*/
1.126     brouard  4104:   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");
                   4105:   fprintf(fichtm,"\n<br>%s  <br>\n",digitp);
                   4106: /*   } */
                   4107:   varppt = matrix(nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);
                   4108:   pstamp(ficresvij);
                   4109:   fprintf(ficresvij,"# Variance and covariance of health expectancies e.j \n#  (weighted average of eij where weights are ");
                   4110:   if(popbased==1)
1.128     brouard  4111:     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  4112:   else
                   4113:     fprintf(ficresvij,"the age specific period (stable) prevalences in each health state \n");
                   4114:   fprintf(ficresvij,"# Age");
                   4115:   for(i=1; i<=nlstate;i++)
                   4116:     for(j=1; j<=nlstate;j++)
                   4117:       fprintf(ficresvij," Cov(e.%1d, e.%1d)",i,j);
                   4118:   fprintf(ficresvij,"\n");
                   4119: 
                   4120:   xp=vector(1,npar);
                   4121:   dnewm=matrix(1,nlstate,1,npar);
                   4122:   doldm=matrix(1,nlstate,1,nlstate);
                   4123:   dnewmp= matrix(nlstate+1,nlstate+ndeath,1,npar);
                   4124:   doldmp= matrix(nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);
                   4125: 
                   4126:   gradgp=matrix(1,npar,nlstate+1,nlstate+ndeath);
                   4127:   gpp=vector(nlstate+1,nlstate+ndeath);
                   4128:   gmp=vector(nlstate+1,nlstate+ndeath);
                   4129:   trgradgp =matrix(nlstate+1,nlstate+ndeath,1,npar); /* mu or p point j*/
                   4130:   
                   4131:   if(estepm < stepm){
                   4132:     printf ("Problem %d lower than %d\n",estepm, stepm);
                   4133:   }
                   4134:   else  hstepm=estepm;   
                   4135:   /* For example we decided to compute the life expectancy with the smallest unit */
                   4136:   /* hstepm beeing the number of stepms, if hstepm=1 the length of hstepm is stepm. 
                   4137:      nhstepm is the number of hstepm from age to agelim 
1.208     brouard  4138:      nstepm is the number of stepm from age to agelim. 
1.209     brouard  4139:      Look at function hpijx to understand why because of memory size limitations, 
1.208     brouard  4140:      we decided (b) to get a life expectancy respecting the most precise curvature of the
1.126     brouard  4141:      survival function given by stepm (the optimization length). Unfortunately it
                   4142:      means that if the survival funtion is printed every two years of age and if
                   4143:      you sum them up and add 1 year (area under the trapezoids) you won't get the same 
                   4144:      results. So we changed our mind and took the option of the best precision.
                   4145:   */
                   4146:   hstepm=hstepm/stepm; /* Typically in stepm units, if stepm=6 & estepm=24 , = 24/6 months = 4 */ 
                   4147:   agelim = AGESUP;
                   4148:   for (age=bage; age<=fage; age ++){ /* If stepm=6 months */
                   4149:     nstepm=(int) rint((agelim-age)*YEARM/stepm); /* Typically 20 years = 20*12/6=40 */ 
                   4150:     nhstepm = nstepm/hstepm;/* Expressed in hstepm, typically nhstepm=40/4=10 */
                   4151:     p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   4152:     gradg=ma3x(0,nhstepm,1,npar,1,nlstate);
                   4153:     gp=matrix(0,nhstepm,1,nlstate);
                   4154:     gm=matrix(0,nhstepm,1,nlstate);
                   4155: 
                   4156: 
                   4157:     for(theta=1; theta <=npar; theta++){
                   4158:       for(i=1; i<=npar; i++){ /* Computes gradient x + delta*/
                   4159:        xp[i] = x[i] + (i==theta ?delti[theta]:0);
                   4160:       }
1.209     brouard  4161: 
                   4162:       prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ncvyearp,ij);
1.126     brouard  4163: 
                   4164:       if (popbased==1) {
                   4165:        if(mobilav ==0){
                   4166:          for(i=1; i<=nlstate;i++)
                   4167:            prlim[i][i]=probs[(int)age][i][ij];
                   4168:        }else{ /* mobilav */ 
                   4169:          for(i=1; i<=nlstate;i++)
                   4170:            prlim[i][i]=mobaverage[(int)age][i][ij];
                   4171:        }
                   4172:       }
                   4173:   
1.209     brouard  4174:       hpxij(p3mat,nhstepm,age,hstepm,xp,nlstate,stepm,oldm,savm, ij);  /* Returns p3mat[i][j][h] for h=1 to nhstepm */
1.126     brouard  4175:       for(j=1; j<= nlstate; j++){
                   4176:        for(h=0; h<=nhstepm; h++){
                   4177:          for(i=1, gp[h][j]=0.;i<=nlstate;i++)
                   4178:            gp[h][j] += prlim[i][i]*p3mat[i][j][h];
                   4179:        }
                   4180:       }
1.209     brouard  4181:       /* Next for computing probability of death (h=1 means
1.126     brouard  4182:          computed over hstepm matrices product = hstepm*stepm months) 
                   4183:          as a weighted average of prlim.
                   4184:       */
                   4185:       for(j=nlstate+1;j<=nlstate+ndeath;j++){
                   4186:        for(i=1,gpp[j]=0.; i<= nlstate; i++)
                   4187:          gpp[j] += prlim[i][i]*p3mat[i][j][1];
                   4188:       }    
                   4189:       /* end probability of death */
                   4190: 
                   4191:       for(i=1; i<=npar; i++) /* Computes gradient x - delta */
                   4192:        xp[i] = x[i] - (i==theta ?delti[theta]:0);
1.209     brouard  4193: 
                   4194:       prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ncvyearp, ij);
1.126     brouard  4195:  
                   4196:       if (popbased==1) {
                   4197:        if(mobilav ==0){
                   4198:          for(i=1; i<=nlstate;i++)
                   4199:            prlim[i][i]=probs[(int)age][i][ij];
                   4200:        }else{ /* mobilav */ 
                   4201:          for(i=1; i<=nlstate;i++)
                   4202:            prlim[i][i]=mobaverage[(int)age][i][ij];
                   4203:        }
                   4204:       }
                   4205: 
1.209     brouard  4206:       hpxij(p3mat,nhstepm,age,hstepm,xp,nlstate,stepm,oldm,savm, ij);  
                   4207: 
1.128     brouard  4208:       for(j=1; j<= nlstate; j++){  /* Sum of wi * eij = e.j */
1.126     brouard  4209:        for(h=0; h<=nhstepm; h++){
                   4210:          for(i=1, gm[h][j]=0.;i<=nlstate;i++)
                   4211:            gm[h][j] += prlim[i][i]*p3mat[i][j][h];
                   4212:        }
                   4213:       }
                   4214:       /* This for computing probability of death (h=1 means
                   4215:          computed over hstepm matrices product = hstepm*stepm months) 
                   4216:          as a weighted average of prlim.
                   4217:       */
                   4218:       for(j=nlstate+1;j<=nlstate+ndeath;j++){
                   4219:        for(i=1,gmp[j]=0.; i<= nlstate; i++)
                   4220:          gmp[j] += prlim[i][i]*p3mat[i][j][1];
                   4221:       }    
                   4222:       /* end probability of death */
                   4223: 
                   4224:       for(j=1; j<= nlstate; j++) /* vareij */
                   4225:        for(h=0; h<=nhstepm; h++){
                   4226:          gradg[h][theta][j]= (gp[h][j]-gm[h][j])/2./delti[theta];
                   4227:        }
                   4228: 
                   4229:       for(j=nlstate+1; j<= nlstate+ndeath; j++){ /* var mu */
                   4230:        gradgp[theta][j]= (gpp[j]-gmp[j])/2./delti[theta];
                   4231:       }
                   4232: 
                   4233:     } /* End theta */
                   4234: 
                   4235:     trgradg =ma3x(0,nhstepm,1,nlstate,1,npar); /* veij */
                   4236: 
                   4237:     for(h=0; h<=nhstepm; h++) /* veij */
                   4238:       for(j=1; j<=nlstate;j++)
                   4239:        for(theta=1; theta <=npar; theta++)
                   4240:          trgradg[h][j][theta]=gradg[h][theta][j];
                   4241: 
                   4242:     for(j=nlstate+1; j<=nlstate+ndeath;j++) /* mu */
                   4243:       for(theta=1; theta <=npar; theta++)
                   4244:        trgradgp[j][theta]=gradgp[theta][j];
                   4245:   
                   4246: 
                   4247:     hf=hstepm*stepm/YEARM;  /* Duration of hstepm expressed in year unit. */
                   4248:     for(i=1;i<=nlstate;i++)
                   4249:       for(j=1;j<=nlstate;j++)
                   4250:        vareij[i][j][(int)age] =0.;
                   4251: 
                   4252:     for(h=0;h<=nhstepm;h++){
                   4253:       for(k=0;k<=nhstepm;k++){
                   4254:        matprod2(dnewm,trgradg[h],1,nlstate,1,npar,1,npar,matcov);
                   4255:        matprod2(doldm,dnewm,1,nlstate,1,npar,1,nlstate,gradg[k]);
                   4256:        for(i=1;i<=nlstate;i++)
                   4257:          for(j=1;j<=nlstate;j++)
                   4258:            vareij[i][j][(int)age] += doldm[i][j]*hf*hf;
                   4259:       }
                   4260:     }
                   4261:   
                   4262:     /* pptj */
                   4263:     matprod2(dnewmp,trgradgp,nlstate+1,nlstate+ndeath,1,npar,1,npar,matcov);
                   4264:     matprod2(doldmp,dnewmp,nlstate+1,nlstate+ndeath,1,npar,nlstate+1,nlstate+ndeath,gradgp);
                   4265:     for(j=nlstate+1;j<=nlstate+ndeath;j++)
                   4266:       for(i=nlstate+1;i<=nlstate+ndeath;i++)
                   4267:        varppt[j][i]=doldmp[j][i];
                   4268:     /* end ppptj */
                   4269:     /*  x centered again */
1.209     brouard  4270: 
                   4271:     prevalim(prlim,nlstate,x,age,oldm,savm,ftolpl,ncvyearp,ij);
1.126     brouard  4272:  
                   4273:     if (popbased==1) {
                   4274:       if(mobilav ==0){
                   4275:        for(i=1; i<=nlstate;i++)
                   4276:          prlim[i][i]=probs[(int)age][i][ij];
                   4277:       }else{ /* mobilav */ 
                   4278:        for(i=1; i<=nlstate;i++)
                   4279:          prlim[i][i]=mobaverage[(int)age][i][ij];
                   4280:       }
                   4281:     }
                   4282:              
                   4283:     /* This for computing probability of death (h=1 means
                   4284:        computed over hstepm (estepm) matrices product = hstepm*stepm months) 
                   4285:        as a weighted average of prlim.
                   4286:     */
1.209     brouard  4287:     hpxij(p3mat,nhstepm,age,hstepm,x,nlstate,stepm,oldm,savm, ij);  
1.126     brouard  4288:     for(j=nlstate+1;j<=nlstate+ndeath;j++){
                   4289:       for(i=1,gmp[j]=0.;i<= nlstate; i++) 
                   4290:        gmp[j] += prlim[i][i]*p3mat[i][j][1]; 
                   4291:     }    
                   4292:     /* end probability of death */
                   4293: 
                   4294:     fprintf(ficresprobmorprev,"%3d %d ",(int) age, ij);
                   4295:     for(j=nlstate+1; j<=(nlstate+ndeath);j++){
                   4296:       fprintf(ficresprobmorprev," %11.3e %11.3e",gmp[j], sqrt(varppt[j][j]));
                   4297:       for(i=1; i<=nlstate;i++){
                   4298:        fprintf(ficresprobmorprev," %11.3e %11.3e ",prlim[i][i],p3mat[i][j][1]);
                   4299:       }
                   4300:     } 
                   4301:     fprintf(ficresprobmorprev,"\n");
                   4302: 
                   4303:     fprintf(ficresvij,"%.0f ",age );
                   4304:     for(i=1; i<=nlstate;i++)
                   4305:       for(j=1; j<=nlstate;j++){
                   4306:        fprintf(ficresvij," %.4f", vareij[i][j][(int)age]);
                   4307:       }
                   4308:     fprintf(ficresvij,"\n");
                   4309:     free_matrix(gp,0,nhstepm,1,nlstate);
                   4310:     free_matrix(gm,0,nhstepm,1,nlstate);
                   4311:     free_ma3x(gradg,0,nhstepm,1,npar,1,nlstate);
                   4312:     free_ma3x(trgradg,0,nhstepm,1,nlstate,1,npar);
                   4313:     free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   4314:   } /* End age */
                   4315:   free_vector(gpp,nlstate+1,nlstate+ndeath);
                   4316:   free_vector(gmp,nlstate+1,nlstate+ndeath);
                   4317:   free_matrix(gradgp,1,npar,nlstate+1,nlstate+ndeath);
                   4318:   free_matrix(trgradgp,nlstate+1,nlstate+ndeath,1,npar); /* mu or p point j*/
1.199     brouard  4319:   /* fprintf(ficgp,"\nunset parametric;unset label; set ter png small size 320, 240"); */
                   4320:   fprintf(ficgp,"\nunset parametric;unset label; set ter svg size 640, 480");
1.126     brouard  4321:   /* for(j=nlstate+1; j<= nlstate+ndeath; j++){ *//* Only the first actually */
1.131     brouard  4322:   fprintf(ficgp,"\n set log y; unset log x;set xlabel \"Age\"; set ylabel \"Force of mortality (year-1)\";");
1.201     brouard  4323:   fprintf(ficgp,"\nset out \"%s%s.svg\";",subdirf3(optionfilefiname,"VARMUPTJGR-",digitp),digit);
1.126     brouard  4324: /*   fprintf(ficgp,"\n plot \"%s\"  u 1:($3*%6.3f) not w l 1 ",fileresprobmorprev,YEARM/estepm); */
                   4325: /*   fprintf(ficgp,"\n replot \"%s\"  u 1:(($3+1.96*$4)*%6.3f) t \"95\%% interval\" w l 2 ",fileresprobmorprev,YEARM/estepm); */
                   4326: /*   fprintf(ficgp,"\n replot \"%s\"  u 1:(($3-1.96*$4)*%6.3f) not w l 2 ",fileresprobmorprev,YEARM/estepm); */
1.145     brouard  4327:   fprintf(ficgp,"\n plot \"%s\"  u 1:($3) not w l lt 1 ",subdirf(fileresprobmorprev));
1.170     brouard  4328:   fprintf(ficgp,"\n replot \"%s\"  u 1:(($3+1.96*$4)) t \"95%% interval\" w l lt 2 ",subdirf(fileresprobmorprev));
1.145     brouard  4329:   fprintf(ficgp,"\n replot \"%s\"  u 1:(($3-1.96*$4)) not w l lt 2 ",subdirf(fileresprobmorprev));
1.126     brouard  4330:   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  4331:   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  4332:   /*  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  4333: */
1.199     brouard  4334: /*   fprintf(ficgp,"\nset out \"varmuptjgr%s%s%s.svg\";replot;",digitp,optionfilefiname,digit); */
1.201     brouard  4335:   fprintf(ficgp,"\nset out;\nset out \"%s%s.svg\";replot;set out;\n",subdirf3(optionfilefiname,"VARMUPTJGR-",digitp),digit);
1.126     brouard  4336: 
                   4337:   free_vector(xp,1,npar);
                   4338:   free_matrix(doldm,1,nlstate,1,nlstate);
                   4339:   free_matrix(dnewm,1,nlstate,1,npar);
                   4340:   free_matrix(doldmp,nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);
                   4341:   free_matrix(dnewmp,nlstate+1,nlstate+ndeath,1,npar);
                   4342:   free_matrix(varppt,nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);
                   4343:   if (mobilav!=0) free_ma3x(mobaverage,1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
                   4344:   fclose(ficresprobmorprev);
                   4345:   fflush(ficgp);
                   4346:   fflush(fichtm); 
                   4347: }  /* end varevsij */
                   4348: 
                   4349: /************ Variance of prevlim ******************/
1.209     brouard  4350:  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  4351: {
1.205     brouard  4352:   /* Variance of prevalence limit  for each state ij using current parameters x[] and estimates of neighbourhood give by delti*/
1.126     brouard  4353:   /*  double **prevalim(double **prlim, int nlstate, double *xp, double age, double **oldm, double **savm,double ftolpl);*/
1.164     brouard  4354: 
1.126     brouard  4355:   double **dnewm,**doldm;
                   4356:   int i, j, nhstepm, hstepm;
                   4357:   double *xp;
                   4358:   double *gp, *gm;
                   4359:   double **gradg, **trgradg;
1.208     brouard  4360:   double **mgm, **mgp;
1.126     brouard  4361:   double age,agelim;
                   4362:   int theta;
                   4363:   
                   4364:   pstamp(ficresvpl);
                   4365:   fprintf(ficresvpl,"# Standard deviation of period (stable) prevalences \n");
                   4366:   fprintf(ficresvpl,"# Age");
                   4367:   for(i=1; i<=nlstate;i++)
                   4368:       fprintf(ficresvpl," %1d-%1d",i,i);
                   4369:   fprintf(ficresvpl,"\n");
                   4370: 
                   4371:   xp=vector(1,npar);
                   4372:   dnewm=matrix(1,nlstate,1,npar);
                   4373:   doldm=matrix(1,nlstate,1,nlstate);
                   4374:   
                   4375:   hstepm=1*YEARM; /* Every year of age */
                   4376:   hstepm=hstepm/stepm; /* Typically in stepm units, if j= 2 years, = 2/6 months = 4 */ 
                   4377:   agelim = AGESUP;
                   4378:   for (age=bage; age<=fage; age ++){ /* If stepm=6 months */
                   4379:     nhstepm=(int) rint((agelim-age)*YEARM/stepm); /* Typically 20 years = 20*12/6=40 */ 
                   4380:     if (stepm >= YEARM) hstepm=1;
                   4381:     nhstepm = nhstepm/hstepm; /* Typically 40/4=10 */
                   4382:     gradg=matrix(1,npar,1,nlstate);
1.208     brouard  4383:     mgp=matrix(1,npar,1,nlstate);
                   4384:     mgm=matrix(1,npar,1,nlstate);
1.126     brouard  4385:     gp=vector(1,nlstate);
                   4386:     gm=vector(1,nlstate);
                   4387: 
                   4388:     for(theta=1; theta <=npar; theta++){
                   4389:       for(i=1; i<=npar; i++){ /* Computes gradient */
                   4390:        xp[i] = x[i] + (i==theta ?delti[theta]:0);
                   4391:       }
1.209     brouard  4392:       if((int)age==79 ||(int)age== 80 ||(int)age== 81 )
                   4393:        prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ncvyearp,ij);
                   4394:       else
                   4395:        prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ncvyearp,ij);
1.208     brouard  4396:       for(i=1;i<=nlstate;i++){
1.126     brouard  4397:        gp[i] = prlim[i][i];
1.208     brouard  4398:        mgp[theta][i] = prlim[i][i];
                   4399:       }
1.126     brouard  4400:       for(i=1; i<=npar; i++) /* Computes gradient */
                   4401:        xp[i] = x[i] - (i==theta ?delti[theta]:0);
1.209     brouard  4402:       if((int)age==79 ||(int)age== 80 ||(int)age== 81 )
                   4403:        prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ncvyearp,ij);
                   4404:       else
                   4405:        prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ncvyearp,ij);
1.208     brouard  4406:       for(i=1;i<=nlstate;i++){
1.126     brouard  4407:        gm[i] = prlim[i][i];
1.208     brouard  4408:        mgm[theta][i] = prlim[i][i];
                   4409:       }
1.126     brouard  4410:       for(i=1;i<=nlstate;i++)
                   4411:        gradg[theta][i]= (gp[i]-gm[i])/2./delti[theta];
1.209     brouard  4412:       /* gradg[theta][2]= -gradg[theta][1]; */ /* For testing if nlstate=2 */
1.126     brouard  4413:     } /* End theta */
                   4414: 
                   4415:     trgradg =matrix(1,nlstate,1,npar);
                   4416: 
                   4417:     for(j=1; j<=nlstate;j++)
                   4418:       for(theta=1; theta <=npar; theta++)
                   4419:        trgradg[j][theta]=gradg[theta][j];
1.209     brouard  4420:     /* if((int)age==79 ||(int)age== 80 ||(int)age== 81 ){ */
                   4421:     /*   printf("\nmgm mgp %d ",(int)age); */
                   4422:     /*   for(j=1; j<=nlstate;j++){ */
                   4423:     /*         printf(" %d ",j); */
                   4424:     /*         for(theta=1; theta <=npar; theta++) */
                   4425:     /*           printf(" %d %lf %lf",theta,mgm[theta][j],mgp[theta][j]); */
                   4426:     /*         printf("\n "); */
                   4427:     /*   } */
                   4428:     /* } */
                   4429:     /* if((int)age==79 ||(int)age== 80 ||(int)age== 81 ){ */
                   4430:     /*   printf("\n gradg %d ",(int)age); */
                   4431:     /*   for(j=1; j<=nlstate;j++){ */
                   4432:     /*         printf("%d ",j); */
                   4433:     /*         for(theta=1; theta <=npar; theta++) */
                   4434:     /*           printf("%d %lf ",theta,gradg[theta][j]); */
                   4435:     /*         printf("\n "); */
                   4436:     /*   } */
                   4437:     /* } */
1.126     brouard  4438: 
                   4439:     for(i=1;i<=nlstate;i++)
                   4440:       varpl[i][(int)age] =0.;
1.209     brouard  4441:     if((int)age==79 ||(int)age== 80  ||(int)age== 81){
1.205     brouard  4442:     matprod2(dnewm,trgradg,1,nlstate,1,npar,1,npar,matcov);
                   4443:     matprod2(doldm,dnewm,1,nlstate,1,npar,1,nlstate,gradg);
                   4444:     }else{
1.126     brouard  4445:     matprod2(dnewm,trgradg,1,nlstate,1,npar,1,npar,matcov);
                   4446:     matprod2(doldm,dnewm,1,nlstate,1,npar,1,nlstate,gradg);
1.205     brouard  4447:     }
1.126     brouard  4448:     for(i=1;i<=nlstate;i++)
                   4449:       varpl[i][(int)age] = doldm[i][i]; /* Covariances are useless */
                   4450: 
                   4451:     fprintf(ficresvpl,"%.0f ",age );
                   4452:     for(i=1; i<=nlstate;i++)
                   4453:       fprintf(ficresvpl," %.5f (%.5f)",prlim[i][i],sqrt(varpl[i][(int)age]));
                   4454:     fprintf(ficresvpl,"\n");
                   4455:     free_vector(gp,1,nlstate);
                   4456:     free_vector(gm,1,nlstate);
1.208     brouard  4457:     free_matrix(mgm,1,npar,1,nlstate);
                   4458:     free_matrix(mgp,1,npar,1,nlstate);
1.126     brouard  4459:     free_matrix(gradg,1,npar,1,nlstate);
                   4460:     free_matrix(trgradg,1,nlstate,1,npar);
                   4461:   } /* End age */
                   4462: 
                   4463:   free_vector(xp,1,npar);
                   4464:   free_matrix(doldm,1,nlstate,1,npar);
                   4465:   free_matrix(dnewm,1,nlstate,1,nlstate);
                   4466: 
                   4467: }
                   4468: 
                   4469: /************ Variance of one-step probabilities  ******************/
                   4470: 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[])
                   4471: {
1.164     brouard  4472:   int i, j=0,  k1, l1, tj;
1.126     brouard  4473:   int k2, l2, j1,  z1;
1.164     brouard  4474:   int k=0, l;
1.145     brouard  4475:   int first=1, first1, first2;
1.126     brouard  4476:   double cv12, mu1, mu2, lc1, lc2, v12, v21, v11, v22,v1,v2, c12, tnalp;
                   4477:   double **dnewm,**doldm;
                   4478:   double *xp;
                   4479:   double *gp, *gm;
                   4480:   double **gradg, **trgradg;
                   4481:   double **mu;
1.164     brouard  4482:   double age, cov[NCOVMAX+1];
1.126     brouard  4483:   double std=2.0; /* Number of standard deviation wide of confidence ellipsoids */
                   4484:   int theta;
                   4485:   char fileresprob[FILENAMELENGTH];
                   4486:   char fileresprobcov[FILENAMELENGTH];
                   4487:   char fileresprobcor[FILENAMELENGTH];
                   4488:   double ***varpij;
                   4489: 
1.201     brouard  4490:   strcpy(fileresprob,"PROB_"); 
1.126     brouard  4491:   strcat(fileresprob,fileres);
                   4492:   if((ficresprob=fopen(fileresprob,"w"))==NULL) {
                   4493:     printf("Problem with resultfile: %s\n", fileresprob);
                   4494:     fprintf(ficlog,"Problem with resultfile: %s\n", fileresprob);
                   4495:   }
1.201     brouard  4496:   strcpy(fileresprobcov,"PROBCOV_"); 
1.202     brouard  4497:   strcat(fileresprobcov,fileresu);
1.126     brouard  4498:   if((ficresprobcov=fopen(fileresprobcov,"w"))==NULL) {
                   4499:     printf("Problem with resultfile: %s\n", fileresprobcov);
                   4500:     fprintf(ficlog,"Problem with resultfile: %s\n", fileresprobcov);
                   4501:   }
1.201     brouard  4502:   strcpy(fileresprobcor,"PROBCOR_"); 
1.202     brouard  4503:   strcat(fileresprobcor,fileresu);
1.126     brouard  4504:   if((ficresprobcor=fopen(fileresprobcor,"w"))==NULL) {
                   4505:     printf("Problem with resultfile: %s\n", fileresprobcor);
                   4506:     fprintf(ficlog,"Problem with resultfile: %s\n", fileresprobcor);
                   4507:   }
                   4508:   printf("Computing standard deviation of one-step probabilities: result on file '%s' \n",fileresprob);
                   4509:   fprintf(ficlog,"Computing standard deviation of one-step probabilities: result on file '%s' \n",fileresprob);
                   4510:   printf("Computing matrix of variance covariance of one-step probabilities: result on file '%s' \n",fileresprobcov);
                   4511:   fprintf(ficlog,"Computing matrix of variance covariance of one-step probabilities: result on file '%s' \n",fileresprobcov);
                   4512:   printf("and correlation matrix of one-step probabilities: result on file '%s' \n",fileresprobcor);
                   4513:   fprintf(ficlog,"and correlation matrix of one-step probabilities: result on file '%s' \n",fileresprobcor);
                   4514:   pstamp(ficresprob);
                   4515:   fprintf(ficresprob,"#One-step probabilities and stand. devi in ()\n");
                   4516:   fprintf(ficresprob,"# Age");
                   4517:   pstamp(ficresprobcov);
                   4518:   fprintf(ficresprobcov,"#One-step probabilities and covariance matrix\n");
                   4519:   fprintf(ficresprobcov,"# Age");
                   4520:   pstamp(ficresprobcor);
                   4521:   fprintf(ficresprobcor,"#One-step probabilities and correlation matrix\n");
                   4522:   fprintf(ficresprobcor,"# Age");
                   4523: 
                   4524: 
                   4525:   for(i=1; i<=nlstate;i++)
                   4526:     for(j=1; j<=(nlstate+ndeath);j++){
                   4527:       fprintf(ficresprob," p%1d-%1d (SE)",i,j);
                   4528:       fprintf(ficresprobcov," p%1d-%1d ",i,j);
                   4529:       fprintf(ficresprobcor," p%1d-%1d ",i,j);
                   4530:     }  
                   4531:  /* fprintf(ficresprob,"\n");
                   4532:   fprintf(ficresprobcov,"\n");
                   4533:   fprintf(ficresprobcor,"\n");
                   4534:  */
1.131     brouard  4535:   xp=vector(1,npar);
1.126     brouard  4536:   dnewm=matrix(1,(nlstate)*(nlstate+ndeath),1,npar);
                   4537:   doldm=matrix(1,(nlstate)*(nlstate+ndeath),1,(nlstate)*(nlstate+ndeath));
                   4538:   mu=matrix(1,(nlstate)*(nlstate+ndeath), (int) bage, (int)fage);
                   4539:   varpij=ma3x(1,nlstate*(nlstate+ndeath),1,nlstate*(nlstate+ndeath),(int) bage, (int) fage);
                   4540:   first=1;
                   4541:   fprintf(ficgp,"\n# Routine varprob");
                   4542:   fprintf(fichtm,"\n<li><h4> Computing and drawing one step probabilities with their confidence intervals</h4></li>\n");
                   4543:   fprintf(fichtm,"\n");
                   4544: 
1.200     brouard  4545:   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  4546:   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);
                   4547:   fprintf(fichtmcov,"\nEllipsoids of confidence centered on point (p<inf>ij</inf>, p<inf>kl</inf>) are estimated \
1.126     brouard  4548: and drawn. It helps understanding how is the covariance between two incidences.\
                   4549:  They are expressed in year<sup>-1</sup> in order to be less dependent of stepm.<br>\n");
                   4550:   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. \
                   4551: It can be understood this way: if pij and pkl where uncorrelated the (2x2) matrix of covariance \
                   4552: would have been (1/(var pij), 0 , 0, 1/(var pkl)), and the confidence interval would be 2 \
                   4553: standard deviations wide on each axis. <br>\
                   4554:  Now, if both incidences are correlated (usual case) we diagonalised the inverse of the covariance matrix\
                   4555:  and made the appropriate rotation to look at the uncorrelated principal directions.<br>\
                   4556: To be simple, these graphs help to understand the significativity of each parameter in relation to a second other one.<br> \n");
                   4557: 
                   4558:   cov[1]=1;
1.145     brouard  4559:   /* tj=cptcoveff; */
                   4560:   tj = (int) pow(2,cptcoveff);
1.126     brouard  4561:   if (cptcovn<1) {tj=1;ncodemax[1]=1;}
                   4562:   j1=0;
1.145     brouard  4563:   for(j1=1; j1<=tj;j1++){
                   4564:     /*for(i1=1; i1<=ncodemax[t];i1++){ */
                   4565:     /*j1++;*/
1.126     brouard  4566:       if  (cptcovn>0) {
                   4567:        fprintf(ficresprob, "\n#********** Variable "); 
1.198     brouard  4568:        for (z1=1; z1<=cptcoveff; z1++) fprintf(ficresprob, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
1.126     brouard  4569:        fprintf(ficresprob, "**********\n#\n");
                   4570:        fprintf(ficresprobcov, "\n#********** Variable "); 
1.198     brouard  4571:        for (z1=1; z1<=cptcoveff; z1++) fprintf(ficresprobcov, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
1.126     brouard  4572:        fprintf(ficresprobcov, "**********\n#\n");
                   4573:        
                   4574:        fprintf(ficgp, "\n#********** Variable "); 
1.198     brouard  4575:        for (z1=1; z1<=cptcoveff; z1++) fprintf(ficgp, " V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
1.126     brouard  4576:        fprintf(ficgp, "**********\n#\n");
                   4577:        
                   4578:        
                   4579:        fprintf(fichtmcov, "\n<hr  size=\"2\" color=\"#EC5E5E\">********** Variable "); 
1.198     brouard  4580:        for (z1=1; z1<=cptcoveff; z1++) fprintf(fichtm, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
1.126     brouard  4581:        fprintf(fichtmcov, "**********\n<hr size=\"2\" color=\"#EC5E5E\">");
                   4582:        
                   4583:        fprintf(ficresprobcor, "\n#********** Variable ");    
1.198     brouard  4584:        for (z1=1; z1<=cptcoveff; z1++) fprintf(ficresprobcor, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
1.126     brouard  4585:        fprintf(ficresprobcor, "**********\n#");    
                   4586:       }
                   4587:       
1.145     brouard  4588:       gradg=matrix(1,npar,1,(nlstate)*(nlstate+ndeath));
                   4589:       trgradg=matrix(1,(nlstate)*(nlstate+ndeath),1,npar);
                   4590:       gp=vector(1,(nlstate)*(nlstate+ndeath));
                   4591:       gm=vector(1,(nlstate)*(nlstate+ndeath));
1.126     brouard  4592:       for (age=bage; age<=fage; age ++){ 
                   4593:        cov[2]=age;
1.187     brouard  4594:        if(nagesqr==1)
                   4595:          cov[3]= age*age;
1.126     brouard  4596:        for (k=1; k<=cptcovn;k++) {
1.200     brouard  4597:          cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(j1,k)];
                   4598:          /*cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(j1,Tvar[k])];*//* j1 1 2 3 4
1.145     brouard  4599:                                                         * 1  1 1 1 1
                   4600:                                                         * 2  2 1 1 1
                   4601:                                                         * 3  1 2 1 1
                   4602:                                                         */
                   4603:          /* nbcode[1][1]=0 nbcode[1][2]=1;*/
1.126     brouard  4604:        }
1.186     brouard  4605:        /* for (k=1; k<=cptcovage;k++) cov[2+Tage[k]]=cov[2+Tage[k]]*cov[2]; */
1.200     brouard  4606:        for (k=1; k<=cptcovage;k++) cov[2+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(ij,k)]*cov[2];
1.126     brouard  4607:        for (k=1; k<=cptcovprod;k++)
1.200     brouard  4608:          cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,k)]*nbcode[Tvard[k][2]][codtabm(ij,k)];
1.126     brouard  4609:        
                   4610:     
                   4611:        for(theta=1; theta <=npar; theta++){
                   4612:          for(i=1; i<=npar; i++)
                   4613:            xp[i] = x[i] + (i==theta ?delti[theta]:(double)0);
                   4614:          
                   4615:          pmij(pmmij,cov,ncovmodel,xp,nlstate);
                   4616:          
                   4617:          k=0;
                   4618:          for(i=1; i<= (nlstate); i++){
                   4619:            for(j=1; j<=(nlstate+ndeath);j++){
                   4620:              k=k+1;
                   4621:              gp[k]=pmmij[i][j];
                   4622:            }
                   4623:          }
                   4624:          
                   4625:          for(i=1; i<=npar; i++)
                   4626:            xp[i] = x[i] - (i==theta ?delti[theta]:(double)0);
                   4627:     
                   4628:          pmij(pmmij,cov,ncovmodel,xp,nlstate);
                   4629:          k=0;
                   4630:          for(i=1; i<=(nlstate); i++){
                   4631:            for(j=1; j<=(nlstate+ndeath);j++){
                   4632:              k=k+1;
                   4633:              gm[k]=pmmij[i][j];
                   4634:            }
                   4635:          }
                   4636:      
                   4637:          for(i=1; i<= (nlstate)*(nlstate+ndeath); i++) 
                   4638:            gradg[theta][i]=(gp[i]-gm[i])/(double)2./delti[theta];  
                   4639:        }
                   4640: 
                   4641:        for(j=1; j<=(nlstate)*(nlstate+ndeath);j++)
                   4642:          for(theta=1; theta <=npar; theta++)
                   4643:            trgradg[j][theta]=gradg[theta][j];
                   4644:        
                   4645:        matprod2(dnewm,trgradg,1,(nlstate)*(nlstate+ndeath),1,npar,1,npar,matcov); 
                   4646:        matprod2(doldm,dnewm,1,(nlstate)*(nlstate+ndeath),1,npar,1,(nlstate)*(nlstate+ndeath),gradg);
                   4647: 
                   4648:        pmij(pmmij,cov,ncovmodel,x,nlstate);
                   4649:        
                   4650:        k=0;
                   4651:        for(i=1; i<=(nlstate); i++){
                   4652:          for(j=1; j<=(nlstate+ndeath);j++){
                   4653:            k=k+1;
                   4654:            mu[k][(int) age]=pmmij[i][j];
                   4655:          }
                   4656:        }
                   4657:        for(i=1;i<=(nlstate)*(nlstate+ndeath);i++)
                   4658:          for(j=1;j<=(nlstate)*(nlstate+ndeath);j++)
                   4659:            varpij[i][j][(int)age] = doldm[i][j];
                   4660: 
                   4661:        /*printf("\n%d ",(int)age);
                   4662:          for (i=1; i<=(nlstate)*(nlstate+ndeath);i++){
                   4663:          printf("%e [%e ;%e] ",gm[i],gm[i]-2*sqrt(doldm[i][i]),gm[i]+2*sqrt(doldm[i][i]));
                   4664:          fprintf(ficlog,"%e [%e ;%e] ",gm[i],gm[i]-2*sqrt(doldm[i][i]),gm[i]+2*sqrt(doldm[i][i]));
                   4665:          }*/
                   4666: 
                   4667:        fprintf(ficresprob,"\n%d ",(int)age);
                   4668:        fprintf(ficresprobcov,"\n%d ",(int)age);
                   4669:        fprintf(ficresprobcor,"\n%d ",(int)age);
                   4670: 
                   4671:        for (i=1; i<=(nlstate)*(nlstate+ndeath);i++)
                   4672:          fprintf(ficresprob,"%11.3e (%11.3e) ",mu[i][(int) age],sqrt(varpij[i][i][(int)age]));
                   4673:        for (i=1; i<=(nlstate)*(nlstate+ndeath);i++){
                   4674:          fprintf(ficresprobcov,"%11.3e ",mu[i][(int) age]);
                   4675:          fprintf(ficresprobcor,"%11.3e ",mu[i][(int) age]);
                   4676:        }
                   4677:        i=0;
                   4678:        for (k=1; k<=(nlstate);k++){
                   4679:          for (l=1; l<=(nlstate+ndeath);l++){ 
1.145     brouard  4680:            i++;
1.126     brouard  4681:            fprintf(ficresprobcov,"\n%d %d-%d",(int)age,k,l);
                   4682:            fprintf(ficresprobcor,"\n%d %d-%d",(int)age,k,l);
                   4683:            for (j=1; j<=i;j++){
1.145     brouard  4684:              /* printf(" k=%d l=%d i=%d j=%d\n",k,l,i,j);fflush(stdout); */
1.126     brouard  4685:              fprintf(ficresprobcov," %11.3e",varpij[i][j][(int)age]);
                   4686:              fprintf(ficresprobcor," %11.3e",varpij[i][j][(int) age]/sqrt(varpij[i][i][(int) age])/sqrt(varpij[j][j][(int)age]));
                   4687:            }
                   4688:          }
                   4689:        }/* end of loop for state */
                   4690:       } /* end of loop for age */
1.145     brouard  4691:       free_vector(gp,1,(nlstate+ndeath)*(nlstate+ndeath));
                   4692:       free_vector(gm,1,(nlstate+ndeath)*(nlstate+ndeath));
                   4693:       free_matrix(trgradg,1,(nlstate+ndeath)*(nlstate+ndeath),1,npar);
                   4694:       free_matrix(gradg,1,(nlstate+ndeath)*(nlstate+ndeath),1,npar);
                   4695:       
1.126     brouard  4696:       /* Confidence intervalle of pij  */
                   4697:       /*
1.131     brouard  4698:        fprintf(ficgp,"\nunset parametric;unset label");
1.126     brouard  4699:        fprintf(ficgp,"\nset log y;unset log x; set xlabel \"Age\";set ylabel \"probability (year-1)\"");
                   4700:        fprintf(ficgp,"\nset ter png small\nset size 0.65,0.65");
                   4701:        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);
                   4702:        fprintf(fichtm,"\n<br><img src=\"pijgr%s.png\"> ",optionfilefiname);
                   4703:        fprintf(ficgp,"\nset out \"pijgr%s.png\"",optionfilefiname);
                   4704:        fprintf(ficgp,"\nplot \"%s\" every :::%d::%d u 1:2 \"\%%lf",k1,k2,xfilevarprob);
                   4705:       */
                   4706: 
                   4707:       /* Drawing ellipsoids of confidence of two variables p(k1-l1,k2-l2)*/
1.145     brouard  4708:       first1=1;first2=2;
1.126     brouard  4709:       for (k2=1; k2<=(nlstate);k2++){
                   4710:        for (l2=1; l2<=(nlstate+ndeath);l2++){ 
                   4711:          if(l2==k2) continue;
                   4712:          j=(k2-1)*(nlstate+ndeath)+l2;
                   4713:          for (k1=1; k1<=(nlstate);k1++){
                   4714:            for (l1=1; l1<=(nlstate+ndeath);l1++){ 
                   4715:              if(l1==k1) continue;
                   4716:              i=(k1-1)*(nlstate+ndeath)+l1;
                   4717:              if(i<=j) continue;
                   4718:              for (age=bage; age<=fage; age ++){ 
                   4719:                if ((int)age %5==0){
                   4720:                  v1=varpij[i][i][(int)age]/stepm*YEARM/stepm*YEARM;
                   4721:                  v2=varpij[j][j][(int)age]/stepm*YEARM/stepm*YEARM;
                   4722:                  cv12=varpij[i][j][(int)age]/stepm*YEARM/stepm*YEARM;
                   4723:                  mu1=mu[i][(int) age]/stepm*YEARM ;
                   4724:                  mu2=mu[j][(int) age]/stepm*YEARM;
                   4725:                  c12=cv12/sqrt(v1*v2);
                   4726:                  /* Computing eigen value of matrix of covariance */
                   4727:                  lc1=((v1+v2)+sqrt((v1+v2)*(v1+v2) - 4*(v1*v2-cv12*cv12)))/2.;
                   4728:                  lc2=((v1+v2)-sqrt((v1+v2)*(v1+v2) - 4*(v1*v2-cv12*cv12)))/2.;
1.135     brouard  4729:                  if ((lc2 <0) || (lc1 <0) ){
1.145     brouard  4730:                    if(first2==1){
                   4731:                      first1=0;
                   4732:                    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);
                   4733:                    }
                   4734:                    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);
                   4735:                    /* lc1=fabs(lc1); */ /* If we want to have them positive */
                   4736:                    /* lc2=fabs(lc2); */
1.135     brouard  4737:                  }
                   4738: 
1.126     brouard  4739:                  /* Eigen vectors */
                   4740:                  v11=(1./sqrt(1+(v1-lc1)*(v1-lc1)/cv12/cv12));
                   4741:                  /*v21=sqrt(1.-v11*v11); *//* error */
                   4742:                  v21=(lc1-v1)/cv12*v11;
                   4743:                  v12=-v21;
                   4744:                  v22=v11;
                   4745:                  tnalp=v21/v11;
                   4746:                  if(first1==1){
                   4747:                    first1=0;
                   4748:                    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);
                   4749:                  }
                   4750:                  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);
                   4751:                  /*printf(fignu*/
                   4752:                  /* mu1+ v11*lc1*cost + v12*lc2*sin(t) */
                   4753:                  /* mu2+ v21*lc1*cost + v22*lc2*sin(t) */
                   4754:                  if(first==1){
                   4755:                    first=0;
1.200     brouard  4756:                    fprintf(ficgp,"\n# Ellipsoids of confidence\n#\n");
1.126     brouard  4757:                    fprintf(ficgp,"\nset parametric;unset label");
                   4758:                    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  4759:                    fprintf(ficgp,"\nset ter svg size 640, 480");
1.126     brouard  4760:                    fprintf(fichtmcov,"\n<br>Ellipsoids of confidence cov(p%1d%1d,p%1d%1d) expressed in year<sup>-1</sup>\
1.201     brouard  4761:  :<a href=\"%s_%d%1d%1d-%1d%1d.svg\">\
                   4762: %s_%d%1d%1d-%1d%1d.svg</A>, ",k1,l1,k2,l2,\
                   4763:                            subdirf2(optionfilefiname,"VARPIJGR_"), j1,k1,l1,k2,l2,\
                   4764:                            subdirf2(optionfilefiname,"VARPIJGR_"), j1,k1,l1,k2,l2);
                   4765:                    fprintf(fichtmcov,"\n<br><img src=\"%s_%d%1d%1d-%1d%1d.svg\"> ",subdirf2(optionfilefiname,"VARPIJGR_"), j1,k1,l1,k2,l2);
1.126     brouard  4766:                    fprintf(fichtmcov,"\n<br> Correlation at age %d (%.3f),",(int) age, c12);
1.201     brouard  4767:                    fprintf(ficgp,"\nset out \"%s_%d%1d%1d-%1d%1d.svg\"",subdirf2(optionfilefiname,"VARPIJGR_"), j1,k1,l1,k2,l2);
1.126     brouard  4768:                    fprintf(ficgp,"\nset label \"%d\" at %11.3e,%11.3e center",(int) age, mu1,mu2);
                   4769:                    fprintf(ficgp,"\n# Age %d, p%1d%1d - p%1d%1d",(int) age, k1,l1,k2,l2);
                   4770:                    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",\
                   4771:                            mu1,std,v11,sqrt(lc1),v12,sqrt(lc2),\
                   4772:                            mu2,std,v21,sqrt(lc1),v22,sqrt(lc2));
                   4773:                  }else{
                   4774:                    first=0;
                   4775:                    fprintf(fichtmcov," %d (%.3f),",(int) age, c12);
                   4776:                    fprintf(ficgp,"\n# Age %d, p%1d%1d - p%1d%1d",(int) age, k1,l1,k2,l2);
                   4777:                    fprintf(ficgp,"\nset label \"%d\" at %11.3e,%11.3e center",(int) age, mu1,mu2);
                   4778:                    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",\
                   4779:                            mu1,std,v11,sqrt(lc1),v12,sqrt(lc2),\
                   4780:                            mu2,std,v21,sqrt(lc1),v22,sqrt(lc2));
                   4781:                  }/* if first */
                   4782:                } /* age mod 5 */
                   4783:              } /* end loop age */
1.201     brouard  4784:              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  4785:              first=1;
                   4786:            } /*l12 */
                   4787:          } /* k12 */
                   4788:        } /*l1 */
                   4789:       }/* k1 */
1.169     brouard  4790:       /* } */ /* loop covariates */
1.126     brouard  4791:   }
                   4792:   free_ma3x(varpij,1,nlstate,1,nlstate+ndeath,(int) bage, (int)fage);
                   4793:   free_matrix(mu,1,(nlstate+ndeath)*(nlstate+ndeath),(int) bage, (int)fage);
                   4794:   free_matrix(doldm,1,(nlstate)*(nlstate+ndeath),1,(nlstate)*(nlstate+ndeath));
                   4795:   free_matrix(dnewm,1,(nlstate)*(nlstate+ndeath),1,npar);
                   4796:   free_vector(xp,1,npar);
                   4797:   fclose(ficresprob);
                   4798:   fclose(ficresprobcov);
                   4799:   fclose(ficresprobcor);
                   4800:   fflush(ficgp);
                   4801:   fflush(fichtmcov);
                   4802: }
                   4803: 
                   4804: 
                   4805: /******************* Printing html file ***********/
1.201     brouard  4806: void printinghtml(char fileresu[], char title[], char datafile[], int firstpass, \
1.126     brouard  4807:                  int lastpass, int stepm, int weightopt, char model[],\
                   4808:                  int imx,int jmin, int jmax, double jmeanint,char rfileres[],\
1.211   ! brouard  4809:                  int popforecast, int prevfcast, int estepm ,          \
1.126     brouard  4810:                  double jprev1, double mprev1,double anprev1, \
                   4811:                  double jprev2, double mprev2,double anprev2){
                   4812:   int jj1, k1, i1, cpt;
                   4813: 
                   4814:    fprintf(fichtm,"<ul><li><a href='#firstorder'>Result files (first order: no variance)</a>\n \
                   4815:    <li><a href='#secondorder'>Result files (second order (variance)</a>\n \
                   4816: </ul>");
                   4817:    fprintf(fichtm,"<ul><li><h4><a name='firstorder'>Result files (first order: no variance)</a></h4>\n \
                   4818:  - 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  4819:           jprev1, mprev1,anprev1,jprev2, mprev2,anprev2,subdirf2(fileresu,"P_"),subdirf2(fileresu,"P_"));
1.126     brouard  4820:    fprintf(fichtm,"\
                   4821:  - Estimated transition probabilities over %d (stepm) months: <a href=\"%s\">%s</a><br>\n ",
1.201     brouard  4822:           stepm,subdirf2(fileresu,"PIJ_"),subdirf2(fileresu,"PIJ_"));
1.126     brouard  4823:    fprintf(fichtm,"\
                   4824:  - Period (stable) prevalence in each health state: <a href=\"%s\">%s</a> <br>\n",
1.201     brouard  4825:           subdirf2(fileresu,"PL_"),subdirf2(fileresu,"PL_"));
1.126     brouard  4826:    fprintf(fichtm,"\
1.211   ! brouard  4827:  - (a) Life expectancies by health status at initial age, e<sub>i.</sub> (b) health expectancies by health status at initial age, e<sub>ij</sub> . 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  4828:    <a href=\"%s\">%s</a> <br>\n",
1.201     brouard  4829:           estepm,subdirf2(fileresu,"E_"),subdirf2(fileresu,"E_"));
1.211   ! brouard  4830:    if(prevfcast==1){
        !          4831:      fprintf(fichtm,"\
        !          4832:  - Prevalence projections by age and states:                           \
1.201     brouard  4833:    <a href=\"%s\">%s</a> <br>\n</li>", subdirf2(fileresu,"F_"),subdirf2(fileresu,"F_"));
1.211   ! brouard  4834:    }
1.126     brouard  4835: 
                   4836: fprintf(fichtm," \n<ul><li><b>Graphs</b></li><p>");
                   4837: 
1.145     brouard  4838:  m=pow(2,cptcoveff);
1.126     brouard  4839:  if (cptcovn < 1) {m=1;ncodemax[1]=1;}
                   4840: 
                   4841:  jj1=0;
                   4842:  for(k1=1; k1<=m;k1++){
1.192     brouard  4843:    /* for(i1=1; i1<=ncodemax[k1];i1++){ */
1.126     brouard  4844:      jj1++;
                   4845:      if (cptcovn > 0) {
                   4846:        fprintf(fichtm,"<hr  size=\"2\" color=\"#EC5E5E\">************ Results for covariates");
1.192     brouard  4847:        for (cpt=1; cpt<=cptcoveff;cpt++){ 
1.198     brouard  4848:         fprintf(fichtm," V%d=%d ",Tvaraff[cpt],nbcode[Tvaraff[cpt]][codtabm(jj1,cpt)]);
                   4849:         printf(" V%d=%d ",Tvaraff[cpt],nbcode[Tvaraff[cpt]][codtabm(jj1,cpt)]);fflush(stdout);
1.192     brouard  4850:        }
1.126     brouard  4851:        fprintf(fichtm," ************\n<hr size=\"2\" color=\"#EC5E5E\">");
                   4852:      }
1.201     brouard  4853:      /* aij, bij */
1.211   ! brouard  4854:      fprintf(fichtm,"<br>- Logit model (yours is: 1+age+%s), 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> \
        !          4855: <img src=\"%s_%d-1.svg\">",model,subdirf2(optionfilefiname,"PE_"),jj1,subdirf2(optionfilefiname,"PE_"),jj1,subdirf2(optionfilefiname,"PE_"),jj1);
1.126     brouard  4856:      /* Pij */
1.211   ! brouard  4857:      fprintf(fichtm,"<br>\n- P<sub>ij</sub> 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  4858: <img src=\"%s_%d-2.svg\">",stepm,subdirf2(optionfilefiname,"PE_"),jj1,subdirf2(optionfilefiname,"PE_"),jj1,subdirf2(optionfilefiname,"PE_"),jj1);     
1.126     brouard  4859:      /* Quasi-incidences */
1.211   ! brouard  4860:      fprintf(fichtm,"<br>\n- I<sub>ij</sub> or Conditional probabilities to be observed in state j being in state i %d (stepm) months\
1.201     brouard  4861:  before but expressed in per year i.e. quasi incidences if stepm is small and probabilities too,\
1.211   ! brouard  4862:  incidence (rates) are the limit when h tends to zero of the ratio of the probability  <sub>h</sub>P<sub>ij</sub> \
        !          4863: divided by h: <sub>h</sub>P<sub>ij</sub>/h : <a href=\"%s_%d-3.svg\">%s_%d-3.svg</a><br> \
1.201     brouard  4864: <img src=\"%s_%d-3.svg\">",stepm,subdirf2(optionfilefiname,"PE_"),jj1,subdirf2(optionfilefiname,"PE_"),jj1,subdirf2(optionfilefiname,"PE_"),jj1); 
                   4865:      /* Survival functions (period) in state j */
                   4866:      for(cpt=1; cpt<=nlstate;cpt++){
                   4867:        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> \
                   4868: <img src=\"%s_%d-%d.svg\">", cpt, cpt, nlstate, subdirf2(optionfilefiname,"LIJ_"),cpt,jj1,subdirf2(optionfilefiname,"LIJ_"),cpt,jj1,subdirf2(optionfilefiname,"LIJ_"),cpt,jj1);
                   4869:      }
                   4870:      /* State specific survival functions (period) */
                   4871:      for(cpt=1; cpt<=nlstate;cpt++){
1.208     brouard  4872:        fprintf(fichtm,"<br>\n- Survival functions from state %d in each live state and total.\
1.201     brouard  4873:  Or probability to survive in various states (1 to %d) being in state %d at different ages.\
                   4874:  <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);
                   4875:      }
                   4876:      /* Period (stable) prevalence in each health state */
                   4877:      for(cpt=1; cpt<=nlstate;cpt++){
                   4878:        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> \
                   4879: <img src=\"%s_%d-%d.svg\">", cpt, cpt, nlstate, subdirf2(optionfilefiname,"P_"),cpt,jj1,subdirf2(optionfilefiname,"P_"),cpt,jj1,subdirf2(optionfilefiname,"P_"),cpt,jj1);
                   4880:      }
1.211   ! brouard  4881:     if(prevfcast==1){
        !          4882:       /* Projection of prevalence up to period (stable) prevalence in each health state */
        !          4883:       for(cpt=1; cpt<=nlstate;cpt++){
        !          4884:        fprintf(fichtm,"<br>\n- Projection of prevalece up 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> \
        !          4885: <img src=\"%s_%d-%d.svg\">", cpt, cpt, nlstate, subdirf2(optionfilefiname,"PROJ_"),cpt,jj1,subdirf2(optionfilefiname,"PROJ_"),cpt,jj1,subdirf2(optionfilefiname,"PROJ_"),cpt,jj1);
        !          4886:       }
        !          4887:     }
        !          4888: 
1.126     brouard  4889:      for(cpt=1; cpt<=nlstate;cpt++) {
1.205     brouard  4890:        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  4891: <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  4892:      }
1.192     brouard  4893:    /* } /\* end i1 *\/ */
1.126     brouard  4894:  }/* End k1 */
                   4895:  fprintf(fichtm,"</ul>");
                   4896: 
                   4897:  fprintf(fichtm,"\
                   4898: \n<br><li><h4> <a name='secondorder'>Result files (second order: variances)</a></h4>\n\
1.193     brouard  4899:  - Parameter file with estimated parameters and covariance matrix: <a href=\"%s\">%s</a> <br> \
1.203     brouard  4900:  - 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  4901: But because parameters are usually highly correlated (a higher incidence of disability \
                   4902: and a higher incidence of recovery can give very close observed transition) it might \
                   4903: be very useful to look not only at linear confidence intervals estimated from the \
                   4904: variances but at the covariance matrix. And instead of looking at the estimated coefficients \
                   4905: (parameters) of the logistic regression, it might be more meaningful to visualize the \
                   4906: covariance matrix of the one-step probabilities. \
                   4907: See page 'Matrix of variance-covariance of one-step probabilities' below. \n", rfileres,rfileres);
1.126     brouard  4908: 
1.193     brouard  4909:  fprintf(fichtm," - Standard deviation of one-step probabilities: <a href=\"%s\">%s</a> <br>\n",
1.201     brouard  4910:         subdirf2(fileresu,"PROB_"),subdirf2(fileresu,"PROB_"));
1.126     brouard  4911:  fprintf(fichtm,"\
                   4912:  - Variance-covariance of one-step probabilities: <a href=\"%s\">%s</a> <br>\n",
1.201     brouard  4913:         subdirf2(fileresu,"PROBCOV_"),subdirf2(fileresu,"PROBCOV_"));
1.126     brouard  4914: 
                   4915:  fprintf(fichtm,"\
                   4916:  - Correlation matrix of one-step probabilities: <a href=\"%s\">%s</a> <br>\n",
1.201     brouard  4917:         subdirf2(fileresu,"PROBCOR_"),subdirf2(fileresu,"PROBCOR_"));
1.126     brouard  4918:  fprintf(fichtm,"\
                   4919:  - 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): \
                   4920:    <a href=\"%s\">%s</a> <br>\n</li>",
1.201     brouard  4921:           estepm,subdirf2(fileresu,"CVE_"),subdirf2(fileresu,"CVE_"));
1.126     brouard  4922:  fprintf(fichtm,"\
                   4923:  - (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): \
                   4924:    <a href=\"%s\">%s</a> <br>\n</li>",
1.201     brouard  4925:           estepm,subdirf2(fileresu,"STDE_"),subdirf2(fileresu,"STDE_"));
1.126     brouard  4926:  fprintf(fichtm,"\
1.128     brouard  4927:  - 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  4928:         estepm, subdirf2(fileresu,"V_"),subdirf2(fileresu,"V_"));
1.126     brouard  4929:  fprintf(fichtm,"\
1.128     brouard  4930:  - 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  4931:         estepm, subdirf2(fileresu,"T_"),subdirf2(fileresu,"T_"));
1.126     brouard  4932:  fprintf(fichtm,"\
                   4933:  - Standard deviation of period (stable) prevalences: <a href=\"%s\">%s</a> <br>\n",\
1.201     brouard  4934:         subdirf2(fileresu,"VPL_"),subdirf2(fileresu,"VPL_"));
1.126     brouard  4935: 
                   4936: /*  if(popforecast==1) fprintf(fichtm,"\n */
                   4937: /*  - Prevalences forecasting: <a href=\"f%s\">f%s</a> <br>\n */
                   4938: /*  - Population forecasting (if popforecast=1): <a href=\"pop%s\">pop%s</a> <br>\n */
                   4939: /*     <br>",fileres,fileres,fileres,fileres); */
                   4940: /*  else  */
                   4941: /*    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); */
                   4942:  fflush(fichtm);
                   4943:  fprintf(fichtm," <ul><li><b>Graphs</b></li><p>");
                   4944: 
1.145     brouard  4945:  m=pow(2,cptcoveff);
1.126     brouard  4946:  if (cptcovn < 1) {m=1;ncodemax[1]=1;}
                   4947: 
                   4948:  jj1=0;
                   4949:  for(k1=1; k1<=m;k1++){
1.192     brouard  4950:    /* for(i1=1; i1<=ncodemax[k1];i1++){ */
1.126     brouard  4951:      jj1++;
                   4952:      if (cptcovn > 0) {
                   4953:        fprintf(fichtm,"<hr  size=\"2\" color=\"#EC5E5E\">************ Results for covariates");
                   4954:        for (cpt=1; cpt<=cptcoveff;cpt++) 
1.198     brouard  4955:         fprintf(fichtm," V%d=%d ",Tvaraff[cpt],nbcode[Tvaraff[cpt]][codtabm(jj1,cpt)]);
1.126     brouard  4956:        fprintf(fichtm," ************\n<hr size=\"2\" color=\"#EC5E5E\">");
                   4957:      }
                   4958:      for(cpt=1; cpt<=nlstate;cpt++) {
                   4959:        fprintf(fichtm,"<br>- Observed (cross-sectional) and period (incidence based) \
1.205     brouard  4960: prevalence (with 95%% confidence interval) in state (%d): <a href=\"%s_%d%d.svg\"> %s_%d-%d.svg <br>\
                   4961: <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  4962:      }
                   4963:      fprintf(fichtm,"\n<br>- Total life expectancy by age and \
1.128     brouard  4964: health expectancies in states (1) and (2). If popbased=1 the smooth (due to the model) \
                   4965: true period expectancies (those weighted with period prevalences are also\
                   4966:  drawn in addition to the population based expectancies computed using\
1.205     brouard  4967:  observed and cahotic prevalences:  <a href=\"%s_%d.svg\">%s_%d.svg<br>\
                   4968: <img src=\"%s_%d.svg\">",subdirf2(optionfilefiname,"E_"),jj1,subdirf2(optionfilefiname,"E_"),jj1,subdirf2(optionfilefiname,"E_"),jj1);
1.192     brouard  4969:    /* } /\* end i1 *\/ */
1.126     brouard  4970:  }/* End k1 */
                   4971:  fprintf(fichtm,"</ul>");
                   4972:  fflush(fichtm);
                   4973: }
                   4974: 
                   4975: /******************* Gnuplot file **************/
1.211   ! brouard  4976:     void printinggnuplot(char fileresu[], char optionfilefiname[], double ageminpar, double agemaxpar, double fage , int prevfcast, char pathc[], double p[]){
1.126     brouard  4977: 
                   4978:   char dirfileres[132],optfileres[132];
1.164     brouard  4979:   int cpt=0,k1=0,i=0,k=0,j=0,jk=0,k2=0,k3=0,ij=0,l=0;
1.211   ! brouard  4980:   int lv=0, vlv=0, kl=0;
1.130     brouard  4981:   int ng=0;
1.201     brouard  4982:   int vpopbased;
1.126     brouard  4983: /*   if((ficgp=fopen(optionfilegnuplot,"a"))==NULL) { */
                   4984: /*     printf("Problem with file %s",optionfilegnuplot); */
                   4985: /*     fprintf(ficlog,"Problem with file %s",optionfilegnuplot); */
                   4986: /*   } */
                   4987: 
                   4988:   /*#ifdef windows */
                   4989:   fprintf(ficgp,"cd \"%s\" \n",pathc);
                   4990:     /*#endif */
                   4991:   m=pow(2,cptcoveff);
                   4992: 
1.202     brouard  4993:   /* Contribution to likelihood */
                   4994:   /* Plot the probability implied in the likelihood */
                   4995:     fprintf(ficgp,"\n# Contributions to the Likelihood, mle >=1. For mle=4 no interpolation, pure matrix products.\n#\n");
                   4996:     fprintf(ficgp,"\n set log y; unset log x;set xlabel \"Age\"; set ylabel \"Likelihood (-2Log(L))\";");
                   4997:     /* fprintf(ficgp,"\nset ter svg size 640, 480"); */ /* Too big for svg */
1.205     brouard  4998:     fprintf(ficgp,"\nset ter pngcairo size 640, 480");
1.204     brouard  4999: /* nice for mle=4 plot by number of matrix products.
1.202     brouard  5000:    replot  "rrtest1/toto.txt" u 2:($4 == 1 && $5==2 ? $9 : 1/0):5 t "p12" with point lc 1 */
                   5001: /* replot exp(p1+p2*x)/(1+exp(p1+p2*x)+exp(p3+p4*x)+exp(p5+p6*x)) t "p12(x)"  */
                   5002:     /* fprintf(ficgp,"\nset out \"%s.svg\";",subdirf2(optionfilefiname,"ILK_")); */
1.204     brouard  5003:     fprintf(ficgp,"\nset out \"%s-dest.png\";",subdirf2(optionfilefiname,"ILK_"));
1.205     brouard  5004:     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  5005:     fprintf(ficgp,"\nset out \"%s-ori.png\";",subdirf2(optionfilefiname,"ILK_"));
1.205     brouard  5006:     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  5007:     for (i=1; i<= nlstate ; i ++) {
                   5008:       fprintf(ficgp,"\nset out \"%s-p%dj.png\";set ylabel \"Probability for each individual/wave\";",subdirf2(optionfilefiname,"ILK_"),i);
1.205     brouard  5009:       fprintf(ficgp,"unset log;\n# plot weighted, mean weight should have point size of 0.5\n plot  \"%s\"",subdirf(fileresilk));
                   5010:       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  5011:       for (j=2; j<= nlstate+ndeath ; j ++) {
1.205     brouard  5012:        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  5013:       }
                   5014:       fprintf(ficgp,";\nset out; unset ylabel;\n"); 
                   5015:     }
                   5016:     /* 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 */             
                   5017:     /* fprintf(ficgp,"\nset log y;plot  \"%s\" u 2:(-$11):3 t \"All sample, all transitions\" with dots lc variable",subdirf(fileresilk)); */
                   5018:     /* 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  5019:     fprintf(ficgp,"\nset out;unset log\n");
1.202     brouard  5020:     /* fprintf(ficgp,"\nset out \"%s.svg\"; replot; set out; # bug gnuplot",subdirf2(optionfilefiname,"ILK_")); */
                   5021: 
1.126     brouard  5022:   strcpy(dirfileres,optionfilefiname);
                   5023:   strcpy(optfileres,"vpl");
                   5024:  /* 1eme*/
1.211   ! brouard  5025:   for (cpt=1; cpt<= nlstate ; cpt ++) { /* For each live state */
        !          5026:     for (k1=1; k1<= m ; k1 ++) { /* For each combination of covariate */
        !          5027:       /* plot [100000000000000000000:-100000000000000000000] "mysbiaspar/vplrmysbiaspar.txt to check */
        !          5028:       fprintf(ficgp,"\n# 1st: Period (stable) prevalence with CI: 'VPL_' files ");
        !          5029:       for (k=1; k<=cptcoveff; k++){    /* For each covariate and each value */
        !          5030:        lv= decodtabm(k1,k,cptcoveff); /* Should be the covariate number corresponding to k1 combination */
        !          5031:        /* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
        !          5032:        /* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
        !          5033:        /* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
        !          5034:        vlv= nbcode[Tvaraff[lv]][lv];
        !          5035:        fprintf(ficgp," V%d=%d ",k,vlv);
        !          5036:       }
        !          5037:       fprintf(ficgp,"\n#\n");
        !          5038: 
1.201     brouard  5039:      fprintf(ficgp,"\nset out \"%s_%d-%d.svg\" \n",subdirf2(optionfilefiname,"V_"),cpt,k1);
                   5040:      fprintf(ficgp,"\n#set out \"V_%s_%d-%d.svg\" \n",optionfilefiname,cpt,k1);
1.126     brouard  5041:      fprintf(ficgp,"set xlabel \"Age\" \n\
                   5042: set ylabel \"Probability\" \n\
1.199     brouard  5043: set ter svg size 640, 480\n\
1.201     brouard  5044: plot [%.f:%.f] \"%s\" every :::%d::%d u 1:2 \"%%lf",ageminpar,fage,subdirf2(fileresu,"VPL_"),k1-1,k1-1);
1.126     brouard  5045: 
                   5046:      for (i=1; i<= nlstate ; i ++) {
1.170     brouard  5047:        if (i==cpt) fprintf(ficgp," %%lf (%%lf)");
                   5048:        else        fprintf(ficgp," %%*lf (%%*lf)");
1.126     brouard  5049:      }
1.201     brouard  5050:      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  5051:      for (i=1; i<= nlstate ; i ++) {
1.170     brouard  5052:        if (i==cpt) fprintf(ficgp," %%lf (%%lf)");
                   5053:        else fprintf(ficgp," %%*lf (%%*lf)");
1.126     brouard  5054:      } 
1.201     brouard  5055:      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  5056:      for (i=1; i<= nlstate ; i ++) {
1.170     brouard  5057:        if (i==cpt) fprintf(ficgp," %%lf (%%lf)");
                   5058:        else fprintf(ficgp," %%*lf (%%*lf)");
1.126     brouard  5059:      }  
1.201     brouard  5060:      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));
                   5061:      fprintf(ficgp,"\nset out \n");
                   5062:     } /* k1 */
                   5063:   } /* cpt */
1.126     brouard  5064:   /*2 eme*/
                   5065:   for (k1=1; k1<= m ; k1 ++) { 
1.211   ! brouard  5066:       fprintf(ficgp,"\n# 2nd: Total life expectancy with CI: 't' files ");
        !          5067:       for (k=1; k<=cptcoveff; k++){    /* For each covariate and each value */
        !          5068:        lv= decodtabm(k1,k,cptcoveff); /* Should be the covariate number corresponding to k1 combination */
        !          5069:        /* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
        !          5070:        /* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
        !          5071:        /* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
        !          5072:        vlv= nbcode[Tvaraff[lv]][lv];
        !          5073:        fprintf(ficgp," V%d=%d ",k,vlv);
        !          5074:       }
        !          5075:       fprintf(ficgp,"\n#\n");
        !          5076: 
1.201     brouard  5077:     fprintf(ficgp,"\nset out \"%s_%d.svg\" \n",subdirf2(optionfilefiname,"E_"),k1);
                   5078:     for(vpopbased=0; vpopbased <= popbased; vpopbased++){ /* Done for vpopbased=0 and vpopbased=1 if popbased==1*/
                   5079:       if(vpopbased==0)
                   5080:        fprintf(ficgp,"set ylabel \"Years\" \nset ter svg size 640, 480\nplot [%.f:%.f] ",ageminpar,fage);
                   5081:       else
                   5082:        fprintf(ficgp,"\nreplot ");
                   5083:       for (i=1; i<= nlstate+1 ; i ++) {
                   5084:        k=2*i;
                   5085:        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);
                   5086:        for (j=1; j<= nlstate+1 ; j ++) {
                   5087:          if (j==i) fprintf(ficgp," %%lf (%%lf)");
                   5088:          else fprintf(ficgp," %%*lf (%%*lf)");
                   5089:        }   
                   5090:        if (i== 1) fprintf(ficgp,"\" t\"TLE\" w l lt %d, \\\n",i);
                   5091:        else fprintf(ficgp,"\" t\"LE in state (%d)\" w l lt %d, \\\n",i-1,i+1);
                   5092:        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);
                   5093:        for (j=1; j<= nlstate+1 ; j ++) {
                   5094:          if (j==i) fprintf(ficgp," %%lf (%%lf)");
                   5095:          else fprintf(ficgp," %%*lf (%%*lf)");
                   5096:        }   
                   5097:        fprintf(ficgp,"\" t\"\" w l lt 0,");
                   5098:        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);
                   5099:        for (j=1; j<= nlstate+1 ; j ++) {
                   5100:          if (j==i) fprintf(ficgp," %%lf (%%lf)");
                   5101:          else fprintf(ficgp," %%*lf (%%*lf)");
                   5102:        }   
                   5103:        if (i== (nlstate+1)) fprintf(ficgp,"\" t\"\" w l lt 0");
                   5104:        else fprintf(ficgp,"\" t\"\" w l lt 0,\\\n");
                   5105:       } /* state */
                   5106:     } /* vpopbased */
                   5107:     fprintf(ficgp,"\nset out;set out \"%s_%d.svg\"; replot; set out; \n",subdirf2(optionfilefiname,"E_"),k1); /* Buggy gnuplot */
                   5108:   } /* k1 */
1.211   ! brouard  5109: 
        !          5110: 
1.126     brouard  5111:   /*3eme*/
                   5112:   for (k1=1; k1<= m ; k1 ++) { 
                   5113:     for (cpt=1; cpt<= nlstate ; cpt ++) {
1.211   ! brouard  5114:       fprintf(ficgp,"\n# 3d: Life expectancy with EXP_ files:  cov=%d state=%d",k1, cpt);
        !          5115:       for (k=1; k<=cptcoveff; k++){    /* For each covariate and each value */
        !          5116:        lv= decodtabm(k1,k,cptcoveff); /* Should be the covariate number corresponding to k1 combination */
        !          5117:        /* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
        !          5118:        /* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
        !          5119:        /* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
        !          5120:        vlv= nbcode[Tvaraff[lv]][lv];
        !          5121:        fprintf(ficgp," V%d=%d ",k,vlv);
        !          5122:       }
        !          5123:       fprintf(ficgp,"\n#\n");
        !          5124: 
1.126     brouard  5125:       /*       k=2+nlstate*(2*cpt-2); */
                   5126:       k=2+(nlstate+1)*(cpt-1);
1.201     brouard  5127:       fprintf(ficgp,"\nset out \"%s_%d%d.svg\" \n",subdirf2(optionfilefiname,"EXP_"),cpt,k1);
1.199     brouard  5128:       fprintf(ficgp,"set ter svg size 640, 480\n\
1.201     brouard  5129: 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  5130:       /*fprintf(ficgp,",\"e%s\" every :::%d::%d u 1:($%d-2*$%d) \"\%%lf ",fileres,k1-1,k1-1,k,k+1);
                   5131:        for (i=1; i<= nlstate*2 ; i ++) fprintf(ficgp,"\%%lf (\%%lf) ");
                   5132:        fprintf(ficgp,"\" t \"e%d1\" w l",cpt);
                   5133:        fprintf(ficgp,",\"e%s\" every :::%d::%d u 1:($%d+2*$%d) \"\%%lf ",fileres,k1-1,k1-1,k,k+1);
                   5134:        for (i=1; i<= nlstate*2 ; i ++) fprintf(ficgp,"\%%lf (\%%lf) ");
                   5135:        fprintf(ficgp,"\" t \"e%d1\" w l",cpt);
                   5136:        
                   5137:       */
                   5138:       for (i=1; i< nlstate ; i ++) {
1.201     brouard  5139:        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  5140:        /*      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);*/
                   5141:        
                   5142:       } 
1.201     brouard  5143:       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  5144:     }
                   5145:   }
                   5146:   
1.201     brouard  5147:   /* Survival functions (period) from state i in state j by initial state i */
                   5148:   for (k1=1; k1<= m ; k1 ++) { /* For each multivariate if any */
                   5149:     for (cpt=1; cpt<=nlstate ; cpt ++) { /* For each life state */
1.211   ! brouard  5150:       fprintf(ficgp,"\n#\n#\n# Survival functions in state j : 'LIJ_' files, cov=%d state=%d",k1, cpt);
        !          5151:       for (k=1; k<=cptcoveff; k++){    /* For each covariate and each value */
        !          5152:        lv= decodtabm(k1,k,cptcoveff); /* Should be the covariate number corresponding to k1 combination */
        !          5153:        /* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
        !          5154:        /* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
        !          5155:        /* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
        !          5156:        vlv= nbcode[Tvaraff[lv]][lv];
        !          5157:        fprintf(ficgp," V%d=%d ",k,vlv);
        !          5158:       }
        !          5159:       fprintf(ficgp,"\n#\n");
        !          5160: 
1.201     brouard  5161:       fprintf(ficgp,"\nset out \"%s_%d-%d.svg\" \n",subdirf2(optionfilefiname,"LIJ_"),cpt,k1);
                   5162:       fprintf(ficgp,"set xlabel \"Age\" \nset ylabel \"Probability to be alive\" \n\
                   5163: set ter svg size 640, 480\n\
                   5164: unset log y\n\
                   5165: plot [%.f:%.f]  ", ageminpar, agemaxpar);
1.211   ! brouard  5166:       k=3;
1.201     brouard  5167:       for (i=1; i<= nlstate ; i ++){
                   5168:        if(i==1)
                   5169:          fprintf(ficgp,"\"%s\"",subdirf2(fileresu,"PIJ_"));
                   5170:        else
                   5171:          fprintf(ficgp,", '' ");
                   5172:        l=(nlstate+ndeath)*(i-1)+1;
                   5173:        fprintf(ficgp," u ($1==%d ? ($3):1/0):($%d/($%d",k1,k+l+(cpt-1),k+l);
                   5174:        for (j=2; j<= nlstate+ndeath ; j ++)
                   5175:          fprintf(ficgp,"+$%d",k+l+j-1);
                   5176:        fprintf(ficgp,")) t \"l(%d,%d)\" w l",i,cpt);
                   5177:       } /* nlstate */
                   5178:       fprintf(ficgp,"\nset out\n");
                   5179:     } /* end cpt state*/ 
                   5180:   } /* end covariate */  
                   5181: 
                   5182:   /* Survival functions (period) from state i in state j by final state j */
1.202     brouard  5183:   for (k1=1; k1<= m ; k1 ++) { /* For each covariate if any */
1.201     brouard  5184:     for (cpt=1; cpt<=nlstate ; cpt ++) { /* For each inital state  */
                   5185:       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);
1.211   ! brouard  5186:       for (k=1; k<=cptcoveff; k++){    /* For each covariate and each value */
        !          5187:        lv= decodtabm(k1,k,cptcoveff); /* Should be the covariate number corresponding to k1 combination */
        !          5188:        /* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
        !          5189:        /* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
        !          5190:        /* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
        !          5191:        vlv= nbcode[Tvaraff[lv]][lv];
        !          5192:        fprintf(ficgp," V%d=%d ",k,vlv);
        !          5193:       }
        !          5194:       fprintf(ficgp,"\n#\n");
        !          5195: 
1.201     brouard  5196:       fprintf(ficgp,"\nset out \"%s_%d-%d.svg\" \n",subdirf2(optionfilefiname,"LIJT_"),cpt,k1);
                   5197:       fprintf(ficgp,"set xlabel \"Age\" \nset ylabel \"Probability to be alive\" \n\
                   5198: set ter svg size 640, 480\n\
                   5199: unset log y\n\
                   5200: plot [%.f:%.f]  ", ageminpar, agemaxpar);
1.211   ! brouard  5201:       k=3;
1.201     brouard  5202:       for (j=1; j<= nlstate ; j ++){ /* Lived in state j */
                   5203:        if(j==1)
                   5204:          fprintf(ficgp,"\"%s\"",subdirf2(fileresu,"PIJ_"));
                   5205:        else
                   5206:          fprintf(ficgp,", '' ");
                   5207:        l=(nlstate+ndeath)*(cpt-1) +j;
                   5208:        fprintf(ficgp," u (($1==%d && (floor($2)%%5 == 0)) ? ($3):1/0):($%d",k1,k+l);
                   5209:        /* for (i=2; i<= nlstate+ndeath ; i ++) */
                   5210:        /*   fprintf(ficgp,"+$%d",k+l+i-1); */
                   5211:        fprintf(ficgp,") t \"l(%d,%d)\" w l",cpt,j);
                   5212:       } /* nlstate */
                   5213:       fprintf(ficgp,", '' ");
                   5214:       fprintf(ficgp," u (($1==%d && (floor($2)%%5 == 0)) ? ($3):1/0):(",k1);
                   5215:       for (j=1; j<= nlstate ; j ++){ /* Lived in state j */
                   5216:        l=(nlstate+ndeath)*(cpt-1) +j;
                   5217:        if(j < nlstate)
                   5218:          fprintf(ficgp,"$%d +",k+l);
                   5219:        else
                   5220:          fprintf(ficgp,"$%d) t\"l(%d,.)\" w l",k+l,cpt);
                   5221:       }
                   5222:       fprintf(ficgp,"\nset out\n");
                   5223:     } /* end cpt state*/ 
                   5224:   } /* end covariate */  
                   5225: 
1.202     brouard  5226:   /* CV preval stable (period) for each covariate */
1.211   ! brouard  5227:   for (k1=1; k1<= m ; k1 ++) { /* For each covariate combination (1 to m=2**k), if any covariate is present */
1.153     brouard  5228:     for (cpt=1; cpt<=nlstate ; cpt ++) { /* For each life state */
1.211   ! brouard  5229:       fprintf(ficgp,"\n#\n#\n#CV preval stable (period): 'pij' files, covariatecombination#=%d state=%d",k1, cpt);
        !          5230:       for (k=1; k<=cptcoveff; k++){    /* For each covariate and each value */
        !          5231:        lv= decodtabm(k1,k,cptcoveff); /* Should be the covariate number corresponding to k1 combination */
        !          5232:        /* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
        !          5233:        /* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
        !          5234:        /* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
        !          5235:        vlv= nbcode[Tvaraff[lv]][lv];
        !          5236:        fprintf(ficgp," V%d=%d ",k,vlv);
        !          5237:       }
        !          5238:       fprintf(ficgp,"\n#\n");
        !          5239: 
1.201     brouard  5240:       fprintf(ficgp,"\nset out \"%s_%d-%d.svg\" \n",subdirf2(optionfilefiname,"P_"),cpt,k1);
1.126     brouard  5241:       fprintf(ficgp,"set xlabel \"Age\" \nset ylabel \"Probability\" \n\
1.199     brouard  5242: set ter svg size 640, 480\n\
1.126     brouard  5243: unset log y\n\
1.153     brouard  5244: plot [%.f:%.f]  ", ageminpar, agemaxpar);
1.211   ! brouard  5245:       k=3; /* Offset */
1.153     brouard  5246:       for (i=1; i<= nlstate ; i ++){
                   5247:        if(i==1)
1.201     brouard  5248:          fprintf(ficgp,"\"%s\"",subdirf2(fileresu,"PIJ_"));
1.153     brouard  5249:        else
                   5250:          fprintf(ficgp,", '' ");
1.154     brouard  5251:        l=(nlstate+ndeath)*(i-1)+1;
                   5252:        fprintf(ficgp," u ($1==%d ? ($3):1/0):($%d/($%d",k1,k+l+(cpt-1),k+l);
1.201     brouard  5253:        for (j=2; j<= nlstate ; j ++)
                   5254:          fprintf(ficgp,"+$%d",k+l+j-1);
1.153     brouard  5255:        fprintf(ficgp,")) t \"prev(%d,%d)\" w l",i,cpt);
                   5256:       } /* nlstate */
1.201     brouard  5257:       fprintf(ficgp,"\nset out\n");
1.153     brouard  5258:     } /* end cpt state*/ 
                   5259:   } /* end covariate */  
1.201     brouard  5260: 
1.211   ! brouard  5261:   if(prevfcast==1){
        !          5262:   /* Projection from cross-sectional to stable (period) for each covariate */
        !          5263: 
        !          5264:     for (k1=1; k1<= m ; k1 ++) { /* For each covariate combination (1 to m=2**k), if any covariate is present */
        !          5265:       for (cpt=1; cpt<=nlstate ; cpt ++) { /* For each life state */
        !          5266:        fprintf(ficgp,"\n#\n#\n#Projection of prevalence to stable (period): 'PROJ_' files, covariatecombination#=%d state=%d",k1, cpt);
        !          5267:        for (k=1; k<=cptcoveff; k++){    /* For each correspondig covariate value  */
        !          5268:          lv= decodtabm(k1,k,cptcoveff); /* Should be the covariate value corresponding to k1 combination and kth covariate */
        !          5269:          /* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
        !          5270:          /* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
        !          5271:          /* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
        !          5272:          vlv= nbcode[Tvaraff[lv]][lv];
        !          5273:          fprintf(ficgp," V%d=%d ",k,vlv);
        !          5274:        }
        !          5275:        fprintf(ficgp,"\n#\n");
        !          5276:        
        !          5277:        fprintf(ficgp,"# hpijx=probability over h years, hp.jx is weighted by observed prev\n ");
        !          5278:        fprintf(ficgp,"\nset out \"%s_%d-%d.svg\" \n",subdirf2(optionfilefiname,"PROJ_"),cpt,k1);
        !          5279:        fprintf(ficgp,"set xlabel \"Age\" \nset ylabel \"Prevalence\" \n\
        !          5280: set ter svg size 640, 480\n\
        !          5281: unset log y\n\
        !          5282: plot [%.f:%.f]  ", ageminpar, agemaxpar);
        !          5283:        for (i=1; i<= nlstate+1 ; i ++){  /* nlstate +1 p11 p21 p.1 */
        !          5284:          /*#  V1  = 1  V2 =  0 yearproj age p11 p21 p.1 p12 p22 p.2 p13 p23 p.3*/
        !          5285:          /*#   1    2   3    4    5      6  7   8   9   10   11 12  13   14  15 */   
        !          5286:          /*# yearproj age p11 p21 p.1 p12 p22 p.2 p13 p23 p.3*/
        !          5287:          /*#   1       2   3    4    5      6  7   8   9   10   11 12  13   14  15 */   
        !          5288:          if(i==1){
        !          5289:            fprintf(ficgp,"\"%s\"",subdirf2(fileresu,"F_"));
        !          5290:          }else{
        !          5291:            fprintf(ficgp,",\\\n '' ");
        !          5292:          }
        !          5293:          if(cptcoveff ==0){ /* No covariate */
        !          5294:            fprintf(ficgp," u 2:("); /* Age is in 2 */
        !          5295:            /*# yearproj age p11 p21 p31 p.1 p12 p22 p32 p.2 p13 p23 p33 p.3 p14 p24 p34 p.4*/
        !          5296:            /*#   1       2   3   4   5  6    7  8   9   10  11  12  13  14  15  16  17  18 */
        !          5297:            if(i==nlstate+1)
        !          5298:              fprintf(ficgp," $%d/(1.-$%d)) t 'p.%d' with line ", \
        !          5299:                        2+(cpt-1)*(nlstate+1)+1+(i-1),  2+1+(i-1)+(nlstate+1)*nlstate,cpt );
        !          5300:            else
        !          5301:              fprintf(ficgp," $%d/(1.-$%d)) t 'p%d%d' with line ", \
        !          5302:                      2+(cpt-1)*(nlstate+1)+1+(i-1),  2+1+(i-1)+(nlstate+1)*nlstate,i,cpt );
        !          5303:          }else{
        !          5304:            fprintf(ficgp,"u 6:(("); /* Age is in 6 */
        !          5305:            /*#  V1  = 1  V2 =  0 yearproj age p11 p21 p.1 p12 p22 p.2 p13 p23 p.3*/
        !          5306:            /*#   1    2   3    4    5      6  7   8   9   10   11 12  13   14  15 */   
        !          5307:            kl=0;
        !          5308:            for (k=1; k<=cptcoveff; k++){    /* For each covariate  */
        !          5309:              lv= decodtabm(k1,k,cptcoveff); /* Should be the covariate value corresponding to k1 combination and kth covariate */
        !          5310:              /* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
        !          5311:              /* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
        !          5312:              /* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
        !          5313:              vlv= nbcode[Tvaraff[lv]][lv];
        !          5314:              kl++;
        !          5315:              /* kl=6+(cpt-1)*(nlstate+1)+1+(i-1); /\* 6+(1-1)*(2+1)+1+(1-1)=7, 6+(2-1)(2+1)+1+(1-1)=10 *\/ */
        !          5316:              /*6+(cpt-1)*(nlstate+1)+1+(i-1)+(nlstate+1)*nlstate; 6+(1-1)*(2+1)+1+(1-1) +(2+1)*2=13 */ 
        !          5317:              /*6+1+(i-1)+(nlstate+1)*nlstate; 6+1+(1-1) +(2+1)*2=13 */ 
        !          5318:              /* ''  u 6:(($1==1 && $2==0 && $3==2 && $4==0)? $9/(1.-$15) : 1/0):($5==2000? 3:2) t 'p.1' with line lc variable*/
        !          5319:              if(k==cptcoveff)
        !          5320:                if(i==nlstate+1)
        !          5321:                  fprintf(ficgp,"$%d==%d && $%d==%d)? $%d/(1.-$%d) : 1/0) t 'p.%d' with line ",kl, k,kl+1,nbcode[Tvaraff[lv]][lv], \
        !          5322:                          6+(cpt-1)*(nlstate+1)+1+(i-1),  6+1+(i-1)+(nlstate+1)*nlstate,cpt );
        !          5323:                else
        !          5324:                  fprintf(ficgp,"$%d==%d && $%d==%d)? $%d/(1.-$%d) : 1/0) t 'p%d%d' with line ",kl, k,kl+1,nbcode[Tvaraff[lv]][lv], \
        !          5325:                          6+(cpt-1)*(nlstate+1)+1+(i-1),  6+1+(i-1)+(nlstate+1)*nlstate,i,cpt );
        !          5326:              else{
        !          5327:                fprintf(ficgp,"$%d==%d && $%d==%d && ",kl, k,kl+1,nbcode[Tvaraff[lv]][lv]);
        !          5328:                kl++;
        !          5329:              }
        !          5330:            } /* end covariate */
        !          5331:          } /* end if covariate */
        !          5332:        } /* nlstate */
        !          5333:        fprintf(ficgp,"\nset out\n");
        !          5334:       } /* end cpt state*/
        !          5335:     } /* end covariate */
        !          5336:   } /* End if prevfcast */
        !          5337: 
        !          5338: 
1.126     brouard  5339:   /* proba elementaires */
1.187     brouard  5340:   fprintf(ficgp,"\n##############\n#MLE estimated parameters\n#############\n");
1.126     brouard  5341:   for(i=1,jk=1; i <=nlstate; i++){
1.187     brouard  5342:     fprintf(ficgp,"# initial state %d\n",i);
1.126     brouard  5343:     for(k=1; k <=(nlstate+ndeath); k++){
                   5344:       if (k != i) {
1.187     brouard  5345:        fprintf(ficgp,"#   current state %d\n",k);
1.126     brouard  5346:        for(j=1; j <=ncovmodel; j++){
1.187     brouard  5347:          fprintf(ficgp,"p%d=%f; ",jk,p[jk]);
1.126     brouard  5348:          jk++; 
                   5349:        }
1.187     brouard  5350:        fprintf(ficgp,"\n");
1.126     brouard  5351:       }
                   5352:     }
                   5353:    }
1.187     brouard  5354:   fprintf(ficgp,"##############\n#\n");
                   5355: 
1.145     brouard  5356:   /*goto avoid;*/
1.200     brouard  5357:   fprintf(ficgp,"\n##############\n#Graphics of probabilities or incidences\n#############\n");
1.187     brouard  5358:   fprintf(ficgp,"# logi(p12/p11)=a12+b12*age+c12age*age+d12*V1+e12*V1*age\n");
                   5359:   fprintf(ficgp,"# logi(p12/p11)=p1 +p2*age +p3*age*age+ p4*V1+ p5*V1*age\n");
                   5360:   fprintf(ficgp,"# logi(p13/p11)=a13+b13*age+c13age*age+d13*V1+e13*V1*age\n");
                   5361:   fprintf(ficgp,"# logi(p13/p11)=p6 +p7*age +p8*age*age+ p9*V1+ p10*V1*age\n");
                   5362:   fprintf(ficgp,"# p12+p13+p14+p11=1=p11(1+exp(a12+b12*age+c12age*age+d12*V1+e12*V1*age)\n");
                   5363:   fprintf(ficgp,"#                      +exp(a13+b13*age+c13age*age+d13*V1+e13*V1*age)+...)\n");
                   5364:   fprintf(ficgp,"# p11=1/(1+exp(a12+b12*age+c12age*age+d12*V1+e12*V1*age)\n");
                   5365:   fprintf(ficgp,"#                      +exp(a13+b13*age+c13age*age+d13*V1+e13*V1*age)+...)\n");
                   5366:   fprintf(ficgp,"# p12=exp(a12+b12*age+c12age*age+d12*V1+e12*V1*age)/\n");
                   5367:   fprintf(ficgp,"#     (1+exp(a12+b12*age+c12age*age+d12*V1+e12*V1*age)\n");
                   5368:   fprintf(ficgp,"#       +exp(a13+b13*age+c13age*age+d13*V1+e13*V1*age))\n");
                   5369:   fprintf(ficgp,"#       +exp(a14+b14*age+c14age*age+d14*V1+e14*V1*age)+...)\n");
                   5370:   fprintf(ficgp,"#\n");
1.201     brouard  5371:    for(ng=1; ng<=3;ng++){ /* Number of graphics: first is logit, 2nd is probabilities, third is incidences per year*/
1.187     brouard  5372:      fprintf(ficgp,"# ng=%d\n",ng);
                   5373:      fprintf(ficgp,"#   jk=1 to 2^%d=%d\n",cptcoveff,m);
1.126     brouard  5374:      for(jk=1; jk <=m; jk++) {
1.187     brouard  5375:        fprintf(ficgp,"#    jk=%d\n",jk);
1.201     brouard  5376:        fprintf(ficgp,"\nset out \"%s_%d-%d.svg\" ",subdirf2(optionfilefiname,"PE_"),jk,ng);
                   5377:        fprintf(ficgp,"\nset ter svg size 640, 480 ");
                   5378:        if (ng==1){
                   5379:         fprintf(ficgp,"\nset ylabel \"Value of the logit of the model\"\n"); /* exp(a12+b12*x) could be nice */
                   5380:         fprintf(ficgp,"\nunset log y");
                   5381:        }else if (ng==2){
                   5382:         fprintf(ficgp,"\nset ylabel \"Probability\"\n");
                   5383:         fprintf(ficgp,"\nset log y");
                   5384:        }else if (ng==3){
1.126     brouard  5385:         fprintf(ficgp,"\nset ylabel \"Quasi-incidence per year\"\n");
1.201     brouard  5386:         fprintf(ficgp,"\nset log y");
                   5387:        }else
                   5388:         fprintf(ficgp,"\nunset title ");
                   5389:        fprintf(ficgp,"\nplot  [%.f:%.f] ",ageminpar,agemaxpar);
1.126     brouard  5390:        i=1;
                   5391:        for(k2=1; k2<=nlstate; k2++) {
                   5392:         k3=i;
                   5393:         for(k=1; k<=(nlstate+ndeath); k++) {
                   5394:           if (k != k2){
1.201     brouard  5395:             switch( ng) {
                   5396:             case 1:
1.187     brouard  5397:               if(nagesqr==0)
1.201     brouard  5398:                 fprintf(ficgp," p%d+p%d*x",i,i+1);
1.187     brouard  5399:               else /* nagesqr =1 */
1.201     brouard  5400:                 fprintf(ficgp," p%d+p%d*x+p%d*x*x",i,i+1,i+1+nagesqr);
                   5401:               break;
                   5402:             case 2: /* ng=2 */
1.187     brouard  5403:               if(nagesqr==0)
                   5404:                 fprintf(ficgp," exp(p%d+p%d*x",i,i+1);
                   5405:               else /* nagesqr =1 */
1.201     brouard  5406:                   fprintf(ficgp," exp(p%d+p%d*x+p%d*x*x",i,i+1,i+1+nagesqr);
                   5407:               break;
                   5408:             case 3:
                   5409:               if(nagesqr==0)
                   5410:                 fprintf(ficgp," %f*exp(p%d+p%d*x",YEARM/stepm,i,i+1);
                   5411:               else /* nagesqr =1 */
                   5412:                 fprintf(ficgp," %f*exp(p%d+p%d*x+p%d*x*x",YEARM/stepm,i,i+1,i+1+nagesqr);
                   5413:               break;
                   5414:             }
1.141     brouard  5415:             ij=1;/* To be checked else nbcode[0][0] wrong */
1.187     brouard  5416:             for(j=3; j <=ncovmodel-nagesqr; j++) {
1.197     brouard  5417:               /* printf("Tage[%d]=%d, j=%d\n", ij, Tage[ij], j); */
                   5418:               if(ij <=cptcovage) { /* Bug valgrind */
                   5419:                 if((j-2)==Tage[ij]) { /* Bug valgrind */
1.200     brouard  5420:                   fprintf(ficgp,"+p%d*%d*x",i+j+nagesqr-1,nbcode[Tvar[j-2]][codtabm(jk,j-2)]);
                   5421:                   /* fprintf(ficgp,"+p%d*%d*x",i+j+nagesqr-1,nbcode[Tvar[j-2]][codtabm(jk,Tvar[j-2])]); */
1.197     brouard  5422:                   ij++;
                   5423:                 }
1.186     brouard  5424:               }
                   5425:               else
1.198     brouard  5426:                 fprintf(ficgp,"+p%d*%d",i+j+nagesqr-1,nbcode[Tvar[j-2]][codtabm(jk,j-2)]);
1.126     brouard  5427:             }
1.201     brouard  5428:             if(ng != 1){
                   5429:               fprintf(ficgp,")/(1");
1.126     brouard  5430:             
1.201     brouard  5431:               for(k1=1; k1 <=nlstate; k1++){ 
                   5432:                 if(nagesqr==0)
                   5433:                   fprintf(ficgp,"+exp(p%d+p%d*x",k3+(k1-1)*ncovmodel,k3+(k1-1)*ncovmodel+1);
                   5434:                 else /* nagesqr =1 */
                   5435:                   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);
                   5436:                 
                   5437:                 ij=1;
                   5438:                 for(j=3; j <=ncovmodel-nagesqr; j++){
                   5439:                   if(ij <=cptcovage) { /* Bug valgrind */
                   5440:                     if((j-2)==Tage[ij]) { /* Bug valgrind */
                   5441:                       fprintf(ficgp,"+p%d*%d*x",k3+(k1-1)*ncovmodel+1+j-2+nagesqr,nbcode[Tvar[j-2]][codtabm(jk,j-2)]);
                   5442:                       /* fprintf(ficgp,"+p%d*%d*x",k3+(k1-1)*ncovmodel+1+j-2+nagesqr,nbcode[Tvar[j-2]][codtabm(jk,Tvar[j-2])]); */
                   5443:                       ij++;
                   5444:                     }
1.197     brouard  5445:                   }
1.201     brouard  5446:                   else
                   5447:                     fprintf(ficgp,"+p%d*%d",k3+(k1-1)*ncovmodel+1+j-2+nagesqr,nbcode[Tvar[j-2]][codtabm(jk,j-2)]);
1.186     brouard  5448:                 }
1.201     brouard  5449:                 fprintf(ficgp,")");
1.126     brouard  5450:               }
                   5451:               fprintf(ficgp,")");
1.201     brouard  5452:               if(ng ==2)
                   5453:                 fprintf(ficgp," t \"p%d%d\" ", k2,k);
                   5454:               else /* ng= 3 */
                   5455:                 fprintf(ficgp," t \"i%d%d\" ", k2,k);
                   5456:             }else{ /* end ng <> 1 */
                   5457:               fprintf(ficgp," t \"logit(p%d%d)\" ", k2,k);
1.126     brouard  5458:             }
                   5459:             if ((k+k2)!= (nlstate*2+ndeath)) fprintf(ficgp,",");
                   5460:             i=i+ncovmodel;
                   5461:           }
                   5462:         } /* end k */
                   5463:        } /* end k2 */
1.201     brouard  5464:        fprintf(ficgp,"\n set out\n");
1.126     brouard  5465:      } /* end jk */
                   5466:    } /* end ng */
1.164     brouard  5467:  /* avoid: */
1.126     brouard  5468:    fflush(ficgp); 
                   5469: }  /* end gnuplot */
                   5470: 
                   5471: 
                   5472: /*************** Moving average **************/
                   5473: int movingaverage(double ***probs, double bage,double fage, double ***mobaverage, int mobilav){
                   5474: 
                   5475:   int i, cpt, cptcod;
                   5476:   int modcovmax =1;
                   5477:   int mobilavrange, mob;
                   5478:   double age;
                   5479: 
                   5480:   modcovmax=2*cptcoveff;/* Max number of modalities. We suppose 
                   5481:                           a covariate has 2 modalities */
                   5482:   if (cptcovn<1) modcovmax=1; /* At least 1 pass */
                   5483: 
                   5484:   if(mobilav==1||mobilav ==3 ||mobilav==5 ||mobilav== 7){
                   5485:     if(mobilav==1) mobilavrange=5; /* default */
                   5486:     else mobilavrange=mobilav;
                   5487:     for (age=bage; age<=fage; age++)
                   5488:       for (i=1; i<=nlstate;i++)
                   5489:        for (cptcod=1;cptcod<=modcovmax;cptcod++)
                   5490:          mobaverage[(int)age][i][cptcod]=probs[(int)age][i][cptcod];
                   5491:     /* We keep the original values on the extreme ages bage, fage and for 
                   5492:        fage+1 and bage-1 we use a 3 terms moving average; for fage+2 bage+2
                   5493:        we use a 5 terms etc. until the borders are no more concerned. 
                   5494:     */ 
                   5495:     for (mob=3;mob <=mobilavrange;mob=mob+2){
                   5496:       for (age=bage+(mob-1)/2; age<=fage-(mob-1)/2; age++){
                   5497:        for (i=1; i<=nlstate;i++){
                   5498:          for (cptcod=1;cptcod<=modcovmax;cptcod++){
                   5499:            mobaverage[(int)age][i][cptcod] =probs[(int)age][i][cptcod];
                   5500:              for (cpt=1;cpt<=(mob-1)/2;cpt++){
                   5501:                mobaverage[(int)age][i][cptcod] +=probs[(int)age-cpt][i][cptcod];
                   5502:                mobaverage[(int)age][i][cptcod] +=probs[(int)age+cpt][i][cptcod];
                   5503:              }
                   5504:            mobaverage[(int)age][i][cptcod]=mobaverage[(int)age][i][cptcod]/mob;
                   5505:          }
                   5506:        }
                   5507:       }/* end age */
                   5508:     }/* end mob */
                   5509:   }else return -1;
                   5510:   return 0;
                   5511: }/* End movingaverage */
                   5512: 
                   5513: 
                   5514: /************** Forecasting ******************/
1.169     brouard  5515: 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  5516:   /* proj1, year, month, day of starting projection 
                   5517:      agemin, agemax range of age
                   5518:      dateprev1 dateprev2 range of dates during which prevalence is computed
                   5519:      anproj2 year of en of projection (same day and month as proj1).
                   5520:   */
1.164     brouard  5521:   int yearp, stepsize, hstepm, nhstepm, j, k, cptcod, i, h, i1;
1.126     brouard  5522:   double agec; /* generic age */
                   5523:   double agelim, ppij, yp,yp1,yp2,jprojmean,mprojmean,anprojmean;
                   5524:   double *popeffectif,*popcount;
                   5525:   double ***p3mat;
                   5526:   double ***mobaverage;
                   5527:   char fileresf[FILENAMELENGTH];
                   5528: 
                   5529:   agelim=AGESUP;
1.211   ! brouard  5530:   /* Compute observed prevalence between dateprev1 and dateprev2 by counting the number of people
        !          5531:      in each health status at the date of interview (if between dateprev1 and dateprev2).
        !          5532:      We still use firstpass and lastpass as another selection.
        !          5533:   */
1.126     brouard  5534:   prevalence(probs, ageminpar, agemax, s, agev, nlstate, imx, Tvar, nbcode, ncodemax, mint, anint, dateprev1, dateprev2, firstpass, lastpass);
                   5535:  
1.201     brouard  5536:   strcpy(fileresf,"F_"); 
                   5537:   strcat(fileresf,fileresu);
1.126     brouard  5538:   if((ficresf=fopen(fileresf,"w"))==NULL) {
                   5539:     printf("Problem with forecast resultfile: %s\n", fileresf);
                   5540:     fprintf(ficlog,"Problem with forecast resultfile: %s\n", fileresf);
                   5541:   }
                   5542:   printf("Computing forecasting: result on file '%s' \n", fileresf);
                   5543:   fprintf(ficlog,"Computing forecasting: result on file '%s' \n", fileresf);
                   5544: 
                   5545:   if (cptcoveff==0) ncodemax[cptcoveff]=1;
                   5546: 
                   5547:   if (mobilav!=0) {
                   5548:     mobaverage= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
                   5549:     if (movingaverage(probs, ageminpar, fage, mobaverage,mobilav)!=0){
                   5550:       fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav);
                   5551:       printf(" Error in movingaverage mobilav=%d\n",mobilav);
                   5552:     }
                   5553:   }
                   5554: 
                   5555:   stepsize=(int) (stepm+YEARM-1)/YEARM;
                   5556:   if (stepm<=12) stepsize=1;
                   5557:   if(estepm < stepm){
                   5558:     printf ("Problem %d lower than %d\n",estepm, stepm);
                   5559:   }
                   5560:   else  hstepm=estepm;   
                   5561: 
                   5562:   hstepm=hstepm/stepm; 
                   5563:   yp1=modf(dateintmean,&yp);/* extracts integral of datemean in yp  and
                   5564:                                fractional in yp1 */
                   5565:   anprojmean=yp;
                   5566:   yp2=modf((yp1*12),&yp);
                   5567:   mprojmean=yp;
                   5568:   yp1=modf((yp2*30.5),&yp);
                   5569:   jprojmean=yp;
                   5570:   if(jprojmean==0) jprojmean=1;
                   5571:   if(mprojmean==0) jprojmean=1;
                   5572: 
                   5573:   i1=cptcoveff;
                   5574:   if (cptcovn < 1){i1=1;}
                   5575:   
                   5576:   fprintf(ficresf,"# Mean day of interviews %.lf/%.lf/%.lf (%.2f) between %.2f and %.2f \n",jprojmean,mprojmean,anprojmean,dateintmean,dateprev1,dateprev2); 
                   5577:   
                   5578:   fprintf(ficresf,"#****** Routine prevforecast **\n");
                   5579: 
                   5580: /*           if (h==(int)(YEARM*yearp)){ */
                   5581:   for(cptcov=1, k=0;cptcov<=i1;cptcov++){
                   5582:     for(cptcod=1;cptcod<=ncodemax[cptcoveff];cptcod++){
                   5583:       k=k+1;
1.211   ! brouard  5584:       fprintf(ficresf,"\n#****** hpijx=probability over h years, hp.jx is weighted by observed prev \n#");
1.126     brouard  5585:       for(j=1;j<=cptcoveff;j++) {
1.211   ! brouard  5586:        fprintf(ficresf," V%d (=) %d",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
1.126     brouard  5587:       }
1.211   ! brouard  5588:       fprintf(ficresf," yearproj age");
1.126     brouard  5589:       for(j=1; j<=nlstate+ndeath;j++){ 
                   5590:        for(i=1; i<=nlstate;i++)              
                   5591:           fprintf(ficresf," p%d%d",i,j);
                   5592:        fprintf(ficresf," p.%d",j);
                   5593:       }
                   5594:       for (yearp=0; yearp<=(anproj2-anproj1);yearp +=stepsize) { 
                   5595:        fprintf(ficresf,"\n");
                   5596:        fprintf(ficresf,"\n# Forecasting at date %.lf/%.lf/%.lf ",jproj1,mproj1,anproj1+yearp);   
                   5597: 
                   5598:        for (agec=fage; agec>=(ageminpar-1); agec--){ 
                   5599:          nhstepm=(int) rint((agelim-agec)*YEARM/stepm); 
                   5600:          nhstepm = nhstepm/hstepm; 
                   5601:          p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   5602:          oldm=oldms;savm=savms;
                   5603:          hpxij(p3mat,nhstepm,agec,hstepm,p,nlstate,stepm,oldm,savm, k);  
                   5604:        
                   5605:          for (h=0; h<=nhstepm; h++){
                   5606:            if (h*hstepm/YEARM*stepm ==yearp) {
                   5607:               fprintf(ficresf,"\n");
                   5608:               for(j=1;j<=cptcoveff;j++) 
1.198     brouard  5609:                 fprintf(ficresf,"%d %d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
1.126     brouard  5610:              fprintf(ficresf,"%.f %.f ",anproj1+yearp,agec+h*hstepm/YEARM*stepm);
                   5611:            } 
                   5612:            for(j=1; j<=nlstate+ndeath;j++) {
                   5613:              ppij=0.;
                   5614:              for(i=1; i<=nlstate;i++) {
                   5615:                if (mobilav==1) 
                   5616:                  ppij=ppij+p3mat[i][j][h]*mobaverage[(int)agec][i][cptcod];
                   5617:                else {
                   5618:                  ppij=ppij+p3mat[i][j][h]*probs[(int)(agec)][i][cptcod];
                   5619:                }
                   5620:                if (h*hstepm/YEARM*stepm== yearp) {
                   5621:                  fprintf(ficresf," %.3f", p3mat[i][j][h]);
                   5622:                }
                   5623:              } /* end i */
                   5624:              if (h*hstepm/YEARM*stepm==yearp) {
                   5625:                fprintf(ficresf," %.3f", ppij);
                   5626:              }
                   5627:            }/* end j */
                   5628:          } /* end h */
                   5629:          free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   5630:        } /* end agec */
                   5631:       } /* end yearp */
                   5632:     } /* end cptcod */
                   5633:   } /* end  cptcov */
                   5634:        
                   5635:   if (mobilav!=0) free_ma3x(mobaverage,1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
                   5636: 
                   5637:   fclose(ficresf);
                   5638: }
                   5639: 
                   5640: /************** Forecasting *****not tested NB*************/
1.169     brouard  5641: 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  5642:   
                   5643:   int cpt, stepsize, hstepm, nhstepm, j,k,c, cptcod, i,h;
                   5644:   int *popage;
                   5645:   double calagedatem, agelim, kk1, kk2;
                   5646:   double *popeffectif,*popcount;
                   5647:   double ***p3mat,***tabpop,***tabpopprev;
                   5648:   double ***mobaverage;
                   5649:   char filerespop[FILENAMELENGTH];
                   5650: 
                   5651:   tabpop= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
                   5652:   tabpopprev= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
                   5653:   agelim=AGESUP;
                   5654:   calagedatem=(anpyram+mpyram/12.+jpyram/365.-dateintmean)*YEARM;
                   5655:   
                   5656:   prevalence(probs, ageminpar, agemax, s, agev, nlstate, imx, Tvar, nbcode, ncodemax, mint, anint, dateprev1, dateprev2, firstpass, lastpass);
                   5657:   
                   5658:   
1.201     brouard  5659:   strcpy(filerespop,"POP_"); 
                   5660:   strcat(filerespop,fileresu);
1.126     brouard  5661:   if((ficrespop=fopen(filerespop,"w"))==NULL) {
                   5662:     printf("Problem with forecast resultfile: %s\n", filerespop);
                   5663:     fprintf(ficlog,"Problem with forecast resultfile: %s\n", filerespop);
                   5664:   }
                   5665:   printf("Computing forecasting: result on file '%s' \n", filerespop);
                   5666:   fprintf(ficlog,"Computing forecasting: result on file '%s' \n", filerespop);
                   5667: 
                   5668:   if (cptcoveff==0) ncodemax[cptcoveff]=1;
                   5669: 
                   5670:   if (mobilav!=0) {
                   5671:     mobaverage= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
                   5672:     if (movingaverage(probs, ageminpar, fage, mobaverage,mobilav)!=0){
                   5673:       fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav);
                   5674:       printf(" Error in movingaverage mobilav=%d\n",mobilav);
                   5675:     }
                   5676:   }
                   5677: 
                   5678:   stepsize=(int) (stepm+YEARM-1)/YEARM;
                   5679:   if (stepm<=12) stepsize=1;
                   5680:   
                   5681:   agelim=AGESUP;
                   5682:   
                   5683:   hstepm=1;
                   5684:   hstepm=hstepm/stepm; 
                   5685:   
                   5686:   if (popforecast==1) {
                   5687:     if((ficpop=fopen(popfile,"r"))==NULL) {
                   5688:       printf("Problem with population file : %s\n",popfile);exit(0);
                   5689:       fprintf(ficlog,"Problem with population file : %s\n",popfile);exit(0);
                   5690:     } 
                   5691:     popage=ivector(0,AGESUP);
                   5692:     popeffectif=vector(0,AGESUP);
                   5693:     popcount=vector(0,AGESUP);
                   5694:     
                   5695:     i=1;   
                   5696:     while ((c=fscanf(ficpop,"%d %lf\n",&popage[i],&popcount[i])) != EOF) i=i+1;
                   5697:    
                   5698:     imx=i;
                   5699:     for (i=1; i<imx;i++) popeffectif[popage[i]]=popcount[i];
                   5700:   }
                   5701: 
                   5702:   for(cptcov=1,k=0;cptcov<=i2;cptcov++){
                   5703:    for(cptcod=1;cptcod<=ncodemax[cptcoveff];cptcod++){
                   5704:       k=k+1;
                   5705:       fprintf(ficrespop,"\n#******");
                   5706:       for(j=1;j<=cptcoveff;j++) {
1.198     brouard  5707:        fprintf(ficrespop," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
1.126     brouard  5708:       }
                   5709:       fprintf(ficrespop,"******\n");
                   5710:       fprintf(ficrespop,"# Age");
                   5711:       for(j=1; j<=nlstate+ndeath;j++) fprintf(ficrespop," P.%d",j);
                   5712:       if (popforecast==1)  fprintf(ficrespop," [Population]");
                   5713:       
                   5714:       for (cpt=0; cpt<=0;cpt++) { 
                   5715:        fprintf(ficrespop,"\n\n# Forecasting at date %.lf/%.lf/%.lf ",jpyram,mpyram,anpyram+cpt);   
                   5716:        
                   5717:        for (agedeb=(fage-((int)calagedatem %12/12.)); agedeb>=(ageminpar-((int)calagedatem %12)/12.); agedeb--){ 
                   5718:          nhstepm=(int) rint((agelim-agedeb)*YEARM/stepm); 
                   5719:          nhstepm = nhstepm/hstepm; 
                   5720:          
                   5721:          p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   5722:          oldm=oldms;savm=savms;
                   5723:          hpxij(p3mat,nhstepm,agedeb,hstepm,p,nlstate,stepm,oldm,savm, k);  
                   5724:        
                   5725:          for (h=0; h<=nhstepm; h++){
                   5726:            if (h==(int) (calagedatem+YEARM*cpt)) {
                   5727:              fprintf(ficrespop,"\n %3.f ",agedeb+h*hstepm/YEARM*stepm);
                   5728:            } 
                   5729:            for(j=1; j<=nlstate+ndeath;j++) {
                   5730:              kk1=0.;kk2=0;
                   5731:              for(i=1; i<=nlstate;i++) {              
                   5732:                if (mobilav==1) 
                   5733:                  kk1=kk1+p3mat[i][j][h]*mobaverage[(int)agedeb+1][i][cptcod];
                   5734:                else {
                   5735:                  kk1=kk1+p3mat[i][j][h]*probs[(int)(agedeb+1)][i][cptcod];
                   5736:                }
                   5737:              }
                   5738:              if (h==(int)(calagedatem+12*cpt)){
                   5739:                tabpop[(int)(agedeb)][j][cptcod]=kk1;
                   5740:                  /*fprintf(ficrespop," %.3f", kk1);
                   5741:                    if (popforecast==1) fprintf(ficrespop," [%.f]", kk1*popeffectif[(int)agedeb+1]);*/
                   5742:              }
                   5743:            }
                   5744:            for(i=1; i<=nlstate;i++){
                   5745:              kk1=0.;
                   5746:                for(j=1; j<=nlstate;j++){
                   5747:                  kk1= kk1+tabpop[(int)(agedeb)][j][cptcod]; 
                   5748:                }
                   5749:                  tabpopprev[(int)(agedeb)][i][cptcod]=tabpop[(int)(agedeb)][i][cptcod]/kk1*popeffectif[(int)(agedeb+(calagedatem+12*cpt)*hstepm/YEARM*stepm-1)];
                   5750:            }
                   5751: 
                   5752:            if (h==(int)(calagedatem+12*cpt)) for(j=1; j<=nlstate;j++) 
                   5753:              fprintf(ficrespop," %15.2f",tabpopprev[(int)(agedeb+1)][j][cptcod]);
                   5754:          }
                   5755:          free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   5756:        }
                   5757:       }
                   5758:  
                   5759:   /******/
                   5760: 
                   5761:       for (cpt=1; cpt<=(anpyram1-anpyram);cpt++) { 
                   5762:        fprintf(ficrespop,"\n\n# Forecasting at date %.lf/%.lf/%.lf ",jpyram,mpyram,anpyram+cpt);   
                   5763:        for (agedeb=(fage-((int)calagedatem %12/12.)); agedeb>=(ageminpar-((int)calagedatem %12)/12.); agedeb--){ 
                   5764:          nhstepm=(int) rint((agelim-agedeb)*YEARM/stepm); 
                   5765:          nhstepm = nhstepm/hstepm; 
                   5766:          
                   5767:          p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   5768:          oldm=oldms;savm=savms;
                   5769:          hpxij(p3mat,nhstepm,agedeb,hstepm,p,nlstate,stepm,oldm,savm, k);  
                   5770:          for (h=0; h<=nhstepm; h++){
                   5771:            if (h==(int) (calagedatem+YEARM*cpt)) {
                   5772:              fprintf(ficresf,"\n %3.f ",agedeb+h*hstepm/YEARM*stepm);
                   5773:            } 
                   5774:            for(j=1; j<=nlstate+ndeath;j++) {
                   5775:              kk1=0.;kk2=0;
                   5776:              for(i=1; i<=nlstate;i++) {              
                   5777:                kk1=kk1+p3mat[i][j][h]*tabpopprev[(int)agedeb+1][i][cptcod];    
                   5778:              }
                   5779:              if (h==(int)(calagedatem+12*cpt)) fprintf(ficresf," %15.2f", kk1);        
                   5780:            }
                   5781:          }
                   5782:          free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   5783:        }
                   5784:       }
                   5785:    } 
                   5786:   }
                   5787:  
                   5788:   if (mobilav!=0) free_ma3x(mobaverage,1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
                   5789: 
                   5790:   if (popforecast==1) {
                   5791:     free_ivector(popage,0,AGESUP);
                   5792:     free_vector(popeffectif,0,AGESUP);
                   5793:     free_vector(popcount,0,AGESUP);
                   5794:   }
                   5795:   free_ma3x(tabpop,1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
                   5796:   free_ma3x(tabpopprev,1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
                   5797:   fclose(ficrespop);
                   5798: } /* End of popforecast */
                   5799: 
                   5800: int fileappend(FILE *fichier, char *optionfich)
                   5801: {
                   5802:   if((fichier=fopen(optionfich,"a"))==NULL) {
                   5803:     printf("Problem with file: %s\n", optionfich);
                   5804:     fprintf(ficlog,"Problem with file: %s\n", optionfich);
                   5805:     return (0);
                   5806:   }
                   5807:   fflush(fichier);
                   5808:   return (1);
                   5809: }
                   5810: 
                   5811: 
                   5812: /**************** function prwizard **********************/
                   5813: void prwizard(int ncovmodel, int nlstate, int ndeath,  char model[], FILE *ficparo)
                   5814: {
                   5815: 
                   5816:   /* Wizard to print covariance matrix template */
                   5817: 
1.164     brouard  5818:   char ca[32], cb[32];
                   5819:   int i,j, k, li, lj, lk, ll, jj, npar, itimes;
1.126     brouard  5820:   int numlinepar;
                   5821: 
                   5822:   printf("# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
                   5823:   fprintf(ficparo,"# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
                   5824:   for(i=1; i <=nlstate; i++){
                   5825:     jj=0;
                   5826:     for(j=1; j <=nlstate+ndeath; j++){
                   5827:       if(j==i) continue;
                   5828:       jj++;
                   5829:       /*ca[0]= k+'a'-1;ca[1]='\0';*/
                   5830:       printf("%1d%1d",i,j);
                   5831:       fprintf(ficparo,"%1d%1d",i,j);
                   5832:       for(k=1; k<=ncovmodel;k++){
                   5833:        /*        printf(" %lf",param[i][j][k]); */
                   5834:        /*        fprintf(ficparo," %lf",param[i][j][k]); */
                   5835:        printf(" 0.");
                   5836:        fprintf(ficparo," 0.");
                   5837:       }
                   5838:       printf("\n");
                   5839:       fprintf(ficparo,"\n");
                   5840:     }
                   5841:   }
                   5842:   printf("# Scales (for hessian or gradient estimation)\n");
                   5843:   fprintf(ficparo,"# Scales (for hessian or gradient estimation)\n");
                   5844:   npar= (nlstate+ndeath-1)*nlstate*ncovmodel; /* Number of parameters*/ 
                   5845:   for(i=1; i <=nlstate; i++){
                   5846:     jj=0;
                   5847:     for(j=1; j <=nlstate+ndeath; j++){
                   5848:       if(j==i) continue;
                   5849:       jj++;
                   5850:       fprintf(ficparo,"%1d%1d",i,j);
                   5851:       printf("%1d%1d",i,j);
                   5852:       fflush(stdout);
                   5853:       for(k=1; k<=ncovmodel;k++){
                   5854:        /*      printf(" %le",delti3[i][j][k]); */
                   5855:        /*      fprintf(ficparo," %le",delti3[i][j][k]); */
                   5856:        printf(" 0.");
                   5857:        fprintf(ficparo," 0.");
                   5858:       }
                   5859:       numlinepar++;
                   5860:       printf("\n");
                   5861:       fprintf(ficparo,"\n");
                   5862:     }
                   5863:   }
                   5864:   printf("# Covariance matrix\n");
                   5865: /* # 121 Var(a12)\n\ */
                   5866: /* # 122 Cov(b12,a12) Var(b12)\n\ */
                   5867: /* # 131 Cov(a13,a12) Cov(a13,b12, Var(a13)\n\ */
                   5868: /* # 132 Cov(b13,a12) Cov(b13,b12, Cov(b13,a13) Var(b13)\n\ */
                   5869: /* # 212 Cov(a21,a12) Cov(a21,b12, Cov(a21,a13) Cov(a21,b13) Var(a21)\n\ */
                   5870: /* # 212 Cov(b21,a12) Cov(b21,b12, Cov(b21,a13) Cov(b21,b13) Cov(b21,a21) Var(b21)\n\ */
                   5871: /* # 232 Cov(a23,a12) Cov(a23,b12, Cov(a23,a13) Cov(a23,b13) Cov(a23,a21) Cov(a23,b21) Var(a23)\n\ */
                   5872: /* # 232 Cov(b23,a12) Cov(b23,b12) ... Var (b23)\n" */
                   5873:   fflush(stdout);
                   5874:   fprintf(ficparo,"# Covariance matrix\n");
                   5875:   /* # 121 Var(a12)\n\ */
                   5876:   /* # 122 Cov(b12,a12) Var(b12)\n\ */
                   5877:   /* #   ...\n\ */
                   5878:   /* # 232 Cov(b23,a12)  Cov(b23,b12) ... Var (b23)\n" */
                   5879:   
                   5880:   for(itimes=1;itimes<=2;itimes++){
                   5881:     jj=0;
                   5882:     for(i=1; i <=nlstate; i++){
                   5883:       for(j=1; j <=nlstate+ndeath; j++){
                   5884:        if(j==i) continue;
                   5885:        for(k=1; k<=ncovmodel;k++){
                   5886:          jj++;
                   5887:          ca[0]= k+'a'-1;ca[1]='\0';
                   5888:          if(itimes==1){
                   5889:            printf("#%1d%1d%d",i,j,k);
                   5890:            fprintf(ficparo,"#%1d%1d%d",i,j,k);
                   5891:          }else{
                   5892:            printf("%1d%1d%d",i,j,k);
                   5893:            fprintf(ficparo,"%1d%1d%d",i,j,k);
                   5894:            /*  printf(" %.5le",matcov[i][j]); */
                   5895:          }
                   5896:          ll=0;
                   5897:          for(li=1;li <=nlstate; li++){
                   5898:            for(lj=1;lj <=nlstate+ndeath; lj++){
                   5899:              if(lj==li) continue;
                   5900:              for(lk=1;lk<=ncovmodel;lk++){
                   5901:                ll++;
                   5902:                if(ll<=jj){
                   5903:                  cb[0]= lk +'a'-1;cb[1]='\0';
                   5904:                  if(ll<jj){
                   5905:                    if(itimes==1){
                   5906:                      printf(" Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
                   5907:                      fprintf(ficparo," Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
                   5908:                    }else{
                   5909:                      printf(" 0.");
                   5910:                      fprintf(ficparo," 0.");
                   5911:                    }
                   5912:                  }else{
                   5913:                    if(itimes==1){
                   5914:                      printf(" Var(%s%1d%1d)",ca,i,j);
                   5915:                      fprintf(ficparo," Var(%s%1d%1d)",ca,i,j);
                   5916:                    }else{
                   5917:                      printf(" 0.");
                   5918:                      fprintf(ficparo," 0.");
                   5919:                    }
                   5920:                  }
                   5921:                }
                   5922:              } /* end lk */
                   5923:            } /* end lj */
                   5924:          } /* end li */
                   5925:          printf("\n");
                   5926:          fprintf(ficparo,"\n");
                   5927:          numlinepar++;
                   5928:        } /* end k*/
                   5929:       } /*end j */
                   5930:     } /* end i */
                   5931:   } /* end itimes */
                   5932: 
                   5933: } /* end of prwizard */
                   5934: /******************* Gompertz Likelihood ******************************/
                   5935: double gompertz(double x[])
                   5936: { 
                   5937:   double A,B,L=0.0,sump=0.,num=0.;
                   5938:   int i,n=0; /* n is the size of the sample */
                   5939: 
                   5940:   for (i=0;i<=imx-1 ; i++) {
                   5941:     sump=sump+weight[i];
                   5942:     /*    sump=sump+1;*/
                   5943:     num=num+1;
                   5944:   }
                   5945:  
                   5946:  
                   5947:   /* for (i=0; i<=imx; i++) 
                   5948:      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]);*/
                   5949: 
                   5950:   for (i=1;i<=imx ; i++)
                   5951:     {
                   5952:       if (cens[i] == 1 && wav[i]>1)
                   5953:        A=-x[1]/(x[2])*(exp(x[2]*(agecens[i]-agegomp))-exp(x[2]*(ageexmed[i]-agegomp)));
                   5954:       
                   5955:       if (cens[i] == 0 && wav[i]>1)
                   5956:        A=-x[1]/(x[2])*(exp(x[2]*(agedc[i]-agegomp))-exp(x[2]*(ageexmed[i]-agegomp)))
                   5957:             +log(x[1]/YEARM)+x[2]*(agedc[i]-agegomp)+log(YEARM);  
                   5958:       
                   5959:       /*if (wav[i] > 1 && agecens[i] > 15) {*/ /* ??? */
                   5960:       if (wav[i] > 1 ) { /* ??? */
                   5961:        L=L+A*weight[i];
                   5962:        /*      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]);*/
                   5963:       }
                   5964:     }
                   5965: 
                   5966:  /*printf("x1=%2.9f x2=%2.9f x3=%2.9f L=%f\n",x[1],x[2],x[3],L);*/
                   5967:  
                   5968:   return -2*L*num/sump;
                   5969: }
                   5970: 
1.136     brouard  5971: #ifdef GSL
                   5972: /******************* Gompertz_f Likelihood ******************************/
                   5973: double gompertz_f(const gsl_vector *v, void *params)
                   5974: { 
                   5975:   double A,B,LL=0.0,sump=0.,num=0.;
                   5976:   double *x= (double *) v->data;
                   5977:   int i,n=0; /* n is the size of the sample */
                   5978: 
                   5979:   for (i=0;i<=imx-1 ; i++) {
                   5980:     sump=sump+weight[i];
                   5981:     /*    sump=sump+1;*/
                   5982:     num=num+1;
                   5983:   }
                   5984:  
                   5985:  
                   5986:   /* for (i=0; i<=imx; i++) 
                   5987:      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]);*/
                   5988:   printf("x[0]=%lf x[1]=%lf\n",x[0],x[1]);
                   5989:   for (i=1;i<=imx ; i++)
                   5990:     {
                   5991:       if (cens[i] == 1 && wav[i]>1)
                   5992:        A=-x[0]/(x[1])*(exp(x[1]*(agecens[i]-agegomp))-exp(x[1]*(ageexmed[i]-agegomp)));
                   5993:       
                   5994:       if (cens[i] == 0 && wav[i]>1)
                   5995:        A=-x[0]/(x[1])*(exp(x[1]*(agedc[i]-agegomp))-exp(x[1]*(ageexmed[i]-agegomp)))
                   5996:             +log(x[0]/YEARM)+x[1]*(agedc[i]-agegomp)+log(YEARM);  
                   5997:       
                   5998:       /*if (wav[i] > 1 && agecens[i] > 15) {*/ /* ??? */
                   5999:       if (wav[i] > 1 ) { /* ??? */
                   6000:        LL=LL+A*weight[i];
                   6001:        /*      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]);*/
                   6002:       }
                   6003:     }
                   6004: 
                   6005:  /*printf("x1=%2.9f x2=%2.9f x3=%2.9f L=%f\n",x[1],x[2],x[3],L);*/
                   6006:   printf("x[0]=%lf x[1]=%lf -2*LL*num/sump=%lf\n",x[0],x[1],-2*LL*num/sump);
                   6007:  
                   6008:   return -2*LL*num/sump;
                   6009: }
                   6010: #endif
                   6011: 
1.126     brouard  6012: /******************* Printing html file ***********/
1.201     brouard  6013: void printinghtmlmort(char fileresu[], char title[], char datafile[], int firstpass, \
1.126     brouard  6014:                  int lastpass, int stepm, int weightopt, char model[],\
                   6015:                  int imx,  double p[],double **matcov,double agemortsup){
                   6016:   int i,k;
                   6017: 
                   6018:   fprintf(fichtm,"<ul><li><h4>Result files </h4>\n Force of mortality. Parameters of the Gompertz fit (with confidence interval in brackets):<br>");
                   6019:   fprintf(fichtm,"  mu(age) =%lf*exp(%lf*(age-%d)) per year<br><br>",p[1],p[2],agegomp);
                   6020:   for (i=1;i<=2;i++) 
                   6021:     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  6022:   fprintf(fichtm,"<br><br><img src=\"graphmort.svg\">");
1.126     brouard  6023:   fprintf(fichtm,"</ul>");
                   6024: 
                   6025: fprintf(fichtm,"<ul><li><h4>Life table</h4>\n <br>");
                   6026: 
                   6027:  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>");
                   6028: 
                   6029:  for (k=agegomp;k<(agemortsup-2);k++) 
                   6030:    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]);
                   6031: 
                   6032:  
                   6033:   fflush(fichtm);
                   6034: }
                   6035: 
                   6036: /******************* Gnuplot file **************/
1.201     brouard  6037: void printinggnuplotmort(char fileresu[], char optionfilefiname[], double ageminpar, double agemaxpar, double fage , char pathc[], double p[]){
1.126     brouard  6038: 
                   6039:   char dirfileres[132],optfileres[132];
1.164     brouard  6040: 
1.126     brouard  6041:   int ng;
                   6042: 
                   6043: 
                   6044:   /*#ifdef windows */
                   6045:   fprintf(ficgp,"cd \"%s\" \n",pathc);
                   6046:     /*#endif */
                   6047: 
                   6048: 
                   6049:   strcpy(dirfileres,optionfilefiname);
                   6050:   strcpy(optfileres,"vpl");
1.199     brouard  6051:   fprintf(ficgp,"set out \"graphmort.svg\"\n "); 
1.126     brouard  6052:   fprintf(ficgp,"set xlabel \"Age\"\n set ylabel \"Force of mortality (per year)\" \n "); 
1.199     brouard  6053:   fprintf(ficgp, "set ter svg size 640, 480\n set log y\n"); 
1.145     brouard  6054:   /* fprintf(ficgp, "set size 0.65,0.65\n"); */
1.126     brouard  6055:   fprintf(ficgp,"plot [%d:100] %lf*exp(%lf*(x-%d))",agegomp,p[1],p[2],agegomp);
                   6056: 
                   6057: } 
                   6058: 
1.136     brouard  6059: int readdata(char datafile[], int firstobs, int lastobs, int *imax)
                   6060: {
1.126     brouard  6061: 
1.136     brouard  6062:   /*-------- data file ----------*/
                   6063:   FILE *fic;
                   6064:   char dummy[]="                         ";
1.164     brouard  6065:   int i=0, j=0, n=0;
1.136     brouard  6066:   int linei, month, year,iout;
                   6067:   char line[MAXLINE], linetmp[MAXLINE];
1.164     brouard  6068:   char stra[MAXLINE], strb[MAXLINE];
1.136     brouard  6069:   char *stratrunc;
                   6070:   int lstra;
1.126     brouard  6071: 
                   6072: 
1.136     brouard  6073:   if((fic=fopen(datafile,"r"))==NULL)    {
1.195     brouard  6074:     printf("Problem while opening datafile: %s\n", datafile);fflush(stdout);
                   6075:     fprintf(ficlog,"Problem while opening datafile: %s\n", datafile);fflush(ficlog);return 1;
1.136     brouard  6076:   }
1.126     brouard  6077: 
1.136     brouard  6078:   i=1;
                   6079:   linei=0;
                   6080:   while ((fgets(line, MAXLINE, fic) != NULL) &&((i >= firstobs) && (i <=lastobs))) {
                   6081:     linei=linei+1;
                   6082:     for(j=strlen(line); j>=0;j--){  /* Untabifies line */
                   6083:       if(line[j] == '\t')
                   6084:        line[j] = ' ';
                   6085:     }
                   6086:     for(j=strlen(line)-1; (line[j]==' ')||(line[j]==10)||(line[j]==13);j--){
                   6087:       ;
                   6088:     };
                   6089:     line[j+1]=0;  /* Trims blanks at end of line */
                   6090:     if(line[0]=='#'){
                   6091:       fprintf(ficlog,"Comment line\n%s\n",line);
                   6092:       printf("Comment line\n%s\n",line);
                   6093:       continue;
                   6094:     }
                   6095:     trimbb(linetmp,line); /* Trims multiple blanks in line */
1.164     brouard  6096:     strcpy(line, linetmp);
1.136     brouard  6097:   
1.126     brouard  6098: 
1.136     brouard  6099:     for (j=maxwav;j>=1;j--){
1.137     brouard  6100:       cutv(stra, strb, line, ' '); 
1.136     brouard  6101:       if(strb[0]=='.') { /* Missing status */
                   6102:        lval=-1;
                   6103:       }else{
                   6104:        errno=0;
                   6105:        lval=strtol(strb,&endptr,10); 
                   6106:       /*       if (errno == ERANGE && (lval == LONG_MAX || lval == LONG_MIN))*/
                   6107:        if( strb[0]=='\0' || (*endptr != '\0')){
1.141     brouard  6108:          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);
                   6109:          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  6110:          return 1;
                   6111:        }
                   6112:       }
                   6113:       s[j][i]=lval;
                   6114:       
                   6115:       strcpy(line,stra);
                   6116:       cutv(stra, strb,line,' ');
1.169     brouard  6117:       if( (iout=sscanf(strb,"%d/%d",&month, &year)) != 0){
1.136     brouard  6118:       }
1.169     brouard  6119:       else  if( (iout=sscanf(strb,"%s.",dummy)) != 0){
1.136     brouard  6120:        month=99;
                   6121:        year=9999;
                   6122:       }else{
1.141     brouard  6123:        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);
                   6124:        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  6125:        return 1;
                   6126:       }
                   6127:       anint[j][i]= (double) year; 
                   6128:       mint[j][i]= (double)month; 
                   6129:       strcpy(line,stra);
                   6130:     } /* ENd Waves */
                   6131:     
                   6132:     cutv(stra, strb,line,' '); 
1.169     brouard  6133:     if( (iout=sscanf(strb,"%d/%d",&month, &year)) != 0){
1.136     brouard  6134:     }
1.169     brouard  6135:     else  if( (iout=sscanf(strb,"%s.",dummy)) != 0){
1.136     brouard  6136:       month=99;
                   6137:       year=9999;
                   6138:     }else{
1.141     brouard  6139:       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);
                   6140:        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  6141:        return 1;
                   6142:     }
                   6143:     andc[i]=(double) year; 
                   6144:     moisdc[i]=(double) month; 
                   6145:     strcpy(line,stra);
                   6146:     
                   6147:     cutv(stra, strb,line,' '); 
1.169     brouard  6148:     if( (iout=sscanf(strb,"%d/%d",&month, &year)) != 0){
1.136     brouard  6149:     }
1.169     brouard  6150:     else  if( (iout=sscanf(strb,"%s.", dummy)) != 0){
1.136     brouard  6151:       month=99;
                   6152:       year=9999;
                   6153:     }else{
1.141     brouard  6154:       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);
                   6155:       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  6156:        return 1;
                   6157:     }
                   6158:     if (year==9999) {
1.141     brouard  6159:       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);
                   6160:       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  6161:        return 1;
1.126     brouard  6162: 
1.136     brouard  6163:     }
                   6164:     annais[i]=(double)(year);
                   6165:     moisnais[i]=(double)(month); 
                   6166:     strcpy(line,stra);
                   6167:     
                   6168:     cutv(stra, strb,line,' '); 
                   6169:     errno=0;
                   6170:     dval=strtod(strb,&endptr); 
                   6171:     if( strb[0]=='\0' || (*endptr != '\0')){
1.141     brouard  6172:       printf("Error reading data around '%f' at line number %d, \"%s\" for individual %d\nShould be a weight.  Exiting.\n",dval, i,line,linei);
                   6173:       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  6174:       fflush(ficlog);
                   6175:       return 1;
                   6176:     }
                   6177:     weight[i]=dval; 
                   6178:     strcpy(line,stra);
                   6179:     
                   6180:     for (j=ncovcol;j>=1;j--){
                   6181:       cutv(stra, strb,line,' '); 
                   6182:       if(strb[0]=='.') { /* Missing status */
                   6183:        lval=-1;
                   6184:       }else{
                   6185:        errno=0;
                   6186:        lval=strtol(strb,&endptr,10); 
                   6187:        if( strb[0]=='\0' || (*endptr != '\0')){
1.141     brouard  6188:          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);
                   6189:          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  6190:          return 1;
                   6191:        }
                   6192:       }
                   6193:       if(lval <-1 || lval >1){
1.141     brouard  6194:        printf("Error reading data around '%ld' at line number %d for individual %d, '%s'\n \
1.136     brouard  6195:  Should be a value of %d(nth) covariate (0 should be the value for the reference and 1\n \
                   6196:  for the alternative. IMaCh does not build design variables automatically, do it yourself.\n \
                   6197:  For example, for multinomial values like 1, 2 and 3,\n \
                   6198:  build V1=0 V2=0 for the reference value (1),\n \
                   6199:         V1=1 V2=0 for (2) \n \
                   6200:  and V1=0 V2=1 for (3). V1=1 V2=1 should not exist and the corresponding\n \
                   6201:  output of IMaCh is often meaningless.\n \
                   6202:  Exiting.\n",lval,linei, i,line,j);
1.141     brouard  6203:        fprintf(ficlog,"Error reading data around '%ld' at line number %d for individual %d, '%s'\n \
1.136     brouard  6204:  Should be a value of %d(nth) covariate (0 should be the value for the reference and 1\n \
                   6205:  for the alternative. IMaCh does not build design variables automatically, do it yourself.\n \
                   6206:  For example, for multinomial values like 1, 2 and 3,\n \
                   6207:  build V1=0 V2=0 for the reference value (1),\n \
                   6208:         V1=1 V2=0 for (2) \n \
                   6209:  and V1=0 V2=1 for (3). V1=1 V2=1 should not exist and the corresponding\n \
                   6210:  output of IMaCh is often meaningless.\n \
                   6211:  Exiting.\n",lval,linei, i,line,j);fflush(ficlog);
                   6212:        return 1;
                   6213:       }
                   6214:       covar[j][i]=(double)(lval);
                   6215:       strcpy(line,stra);
                   6216:     }  
                   6217:     lstra=strlen(stra);
                   6218:      
                   6219:     if(lstra > 9){ /* More than 2**32 or max of what printf can write with %ld */
                   6220:       stratrunc = &(stra[lstra-9]);
                   6221:       num[i]=atol(stratrunc);
                   6222:     }
                   6223:     else
                   6224:       num[i]=atol(stra);
                   6225:     /*if((s[2][i]==2) && (s[3][i]==-1)&&(s[4][i]==9)){
                   6226:       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;}*/
                   6227:     
                   6228:     i=i+1;
                   6229:   } /* End loop reading  data */
1.126     brouard  6230: 
1.136     brouard  6231:   *imax=i-1; /* Number of individuals */
                   6232:   fclose(fic);
                   6233:  
                   6234:   return (0);
1.164     brouard  6235:   /* endread: */
1.136     brouard  6236:     printf("Exiting readdata: ");
                   6237:     fclose(fic);
                   6238:     return (1);
1.126     brouard  6239: 
                   6240: 
                   6241: 
1.136     brouard  6242: }
1.145     brouard  6243: void removespace(char *str) {
                   6244:   char *p1 = str, *p2 = str;
                   6245:   do
                   6246:     while (*p2 == ' ')
                   6247:       p2++;
1.169     brouard  6248:   while (*p1++ == *p2++);
1.145     brouard  6249: }
                   6250: 
                   6251: int decodemodel ( char model[], int lastobs) /**< This routine decode the model and returns:
1.187     brouard  6252:    * Model  V1+V2+V3+V8+V7*V8+V5*V6+V8*age+V3*age+age*age
                   6253:    * - nagesqr = 1 if age*age in the model, otherwise 0.
                   6254:    * - cptcovt total number of covariates of the model nbocc(+)+1 = 8 excepting constant and age and age*age
                   6255:    * - cptcovn or number of covariates k of the models excluding age*products =6 and age*age
1.145     brouard  6256:    * - cptcovage number of covariates with age*products =2
                   6257:    * - cptcovs number of simple covariates
                   6258:    * - 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
                   6259:    *     which is a new column after the 9 (ncovcol) variables. 
                   6260:    * - if k is a product Vn*Vm covar[k][i] is filled with correct values for each individual
                   6261:    * - Tprod[l] gives the kth covariates of the product Vn*Vm l=1 to cptcovprod-cptcovage
                   6262:    *    Tprod[1]@2 {5, 6}: position of first product V7*V8 is 5, and second V5*V6 is 6.
                   6263:    * - Tvard[k]  p Tvard[1][1]@4 {7, 8, 5, 6} for V7*V8 and V5*V6 .
                   6264:  */
1.136     brouard  6265: {
1.145     brouard  6266:   int i, j, k, ks;
1.164     brouard  6267:   int  j1, k1, k2;
1.136     brouard  6268:   char modelsav[80];
1.145     brouard  6269:   char stra[80], strb[80], strc[80], strd[80],stre[80];
1.187     brouard  6270:   char *strpt;
1.136     brouard  6271: 
1.145     brouard  6272:   /*removespace(model);*/
1.136     brouard  6273:   if (strlen(model) >1){ /* If there is at least 1 covariate */
1.145     brouard  6274:     j=0, j1=0, k1=0, k2=-1, ks=0, cptcovn=0;
1.137     brouard  6275:     if (strstr(model,"AGE") !=0){
1.192     brouard  6276:       printf("Error. AGE must be in lower case 'age' model=1+age+%s. ",model);
                   6277:       fprintf(ficlog,"Error. AGE must be in lower case model=1+age+%s. ",model);fflush(ficlog);
1.136     brouard  6278:       return 1;
                   6279:     }
1.141     brouard  6280:     if (strstr(model,"v") !=0){
                   6281:       printf("Error. 'v' must be in upper case 'V' model=%s ",model);
                   6282:       fprintf(ficlog,"Error. 'v' must be in upper case model=%s ",model);fflush(ficlog);
                   6283:       return 1;
                   6284:     }
1.187     brouard  6285:     strcpy(modelsav,model); 
                   6286:     if ((strpt=strstr(model,"age*age")) !=0){
                   6287:       printf(" strpt=%s, model=%s\n",strpt, model);
                   6288:       if(strpt != model){
                   6289:       printf("Error in model: 'model=%s'; 'age*age' should in first place before other covariates\n \
1.192     brouard  6290:  'model=1+age+age*age+V1.' or 'model=1+age+age*age+V1+V1*age.', please swap as well as \n \
1.187     brouard  6291:  corresponding column of parameters.\n",model);
                   6292:       fprintf(ficlog,"Error in model: 'model=%s'; 'age*age' should in first place before other covariates\n \
1.192     brouard  6293:  'model=1+age+age*age+V1.' or 'model=1+age+age*age+V1+V1*age.', please swap as well as \n \
1.187     brouard  6294:  corresponding column of parameters.\n",model); fflush(ficlog);
                   6295:       return 1;
                   6296:     }
                   6297: 
                   6298:       nagesqr=1;
                   6299:       if (strstr(model,"+age*age") !=0)
                   6300:        substrchaine(modelsav, model, "+age*age");
                   6301:       else if (strstr(model,"age*age+") !=0)
                   6302:        substrchaine(modelsav, model, "age*age+");
                   6303:       else 
                   6304:        substrchaine(modelsav, model, "age*age");
                   6305:     }else
                   6306:       nagesqr=0;
                   6307:     if (strlen(modelsav) >1){
                   6308:       j=nbocc(modelsav,'+'); /**< j=Number of '+' */
                   6309:       j1=nbocc(modelsav,'*'); /**< j1=Number of '*' */
                   6310:       cptcovs=j+1-j1; /**<  Number of simple covariates V1+V1*age+V3 +V3*V4+age*age=> V1 + V3 =2  */
                   6311:       cptcovt= j+1; /* Number of total covariates in the model, not including
                   6312:                   * cst, age and age*age 
                   6313:                   * V1+V1*age+ V3 + V3*V4+age*age=> 4*/
                   6314:                   /* including age products which are counted in cptcovage.
                   6315:                  * but the covariates which are products must be treated 
                   6316:                  * separately: ncovn=4- 2=2 (V1+V3). */
                   6317:       cptcovprod=j1; /**< Number of products  V1*V2 +v3*age = 2 */
                   6318:       cptcovprodnoage=0; /**< Number of covariate products without age: V3*V4 =1  */
                   6319: 
                   6320:     
                   6321:       /*   Design
                   6322:        *  V1   V2   V3   V4  V5  V6  V7  V8  V9 Weight
                   6323:        *  <          ncovcol=8                >
                   6324:        * Model V2 + V1 + V3*age + V3 + V5*V6 + V7*V8 + V8*age + V8
                   6325:        *   k=  1    2      3       4     5       6      7        8
                   6326:        *  cptcovn number of covariates (not including constant and age ) = # of + plus 1 = 7+1=8
                   6327:        *  covar[k,i], value of kth covariate if not including age for individual i:
                   6328:        *       covar[1][i]= (V2), covar[4][i]=(V3), covar[8][i]=(V8)
                   6329:        *  Tvar[k] # of the kth covariate:  Tvar[1]=2  Tvar[4]=3 Tvar[8]=8
                   6330:        *       if multiplied by age: V3*age Tvar[3=V3*age]=3 (V3) Tvar[7]=8 and 
                   6331:        *  Tage[++cptcovage]=k
                   6332:        *       if products, new covar are created after ncovcol with k1
                   6333:        *  Tvar[k]=ncovcol+k1; # of the kth covariate product:  Tvar[5]=ncovcol+1=10  Tvar[6]=ncovcol+1=11
                   6334:        *  Tprod[k1]=k; Tprod[1]=5 Tprod[2]= 6; gives the position of the k1th product
                   6335:        *  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
                   6336:        *  Tvar[cptcovn+k2]=Tvard[k1][1];Tvar[cptcovn+k2+1]=Tvard[k1][2];
                   6337:        *  Tvar[8+1]=5;Tvar[8+2]=6;Tvar[8+3]=7;Tvar[8+4]=8 inverted
                   6338:        *  V1   V2   V3   V4  V5  V6  V7  V8  V9  V10  V11
                   6339:        *  <          ncovcol=8                >
                   6340:        *       Model V2 + V1 + V3*age + V3 + V5*V6 + V7*V8 + V8*age + V8    d1   d1   d2  d2
                   6341:        *          k=  1    2      3       4     5       6      7        8    9   10   11  12
                   6342:        *     Tvar[k]= 2    1      3       3    10      11      8        8    5    6    7   8
                   6343:        * p Tvar[1]@12={2,   1,     3,      3,   11,     10,     8,       8,   7,   8,   5,  6}
                   6344:        * p Tprod[1]@2={                         6, 5}
                   6345:        *p Tvard[1][1]@4= {7, 8, 5, 6}
                   6346:        * covar[k][i]= V2   V1      ?      V3    V5*V6?   V7*V8?  ?       V8   
                   6347:        *  cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*cov[2];
                   6348:        *How to reorganize?
                   6349:        * Model V1 + V2 + V3 + V8 + V5*V6 + V7*V8 + V3*age + V8*age
                   6350:        * Tvars {2,   1,     3,      3,   11,     10,     8,       8,   7,   8,   5,  6}
                   6351:        *       {2,   1,     4,      8,    5,      6,     3,       7}
                   6352:        * Struct []
                   6353:        */
1.145     brouard  6354: 
1.187     brouard  6355:       /* This loop fills the array Tvar from the string 'model'.*/
                   6356:       /* j is the number of + signs in the model V1+V2+V3 j=2 i=3 to 1 */
                   6357:       /*   modelsav=V2+V1+V4+age*V3 strb=age*V3 stra=V2+V1+V4  */
                   6358:       /*       k=4 (age*V3) Tvar[k=4]= 3 (from V3) Tage[cptcovage=1]=4 */
                   6359:       /*       k=3 V4 Tvar[k=3]= 4 (from V4) */
                   6360:       /*       k=2 V1 Tvar[k=2]= 1 (from V1) */
                   6361:       /*       k=1 Tvar[1]=2 (from V2) */
                   6362:       /*       k=5 Tvar[5] */
                   6363:       /* for (k=1; k<=cptcovn;k++) { */
1.198     brouard  6364:       /*       cov[2+k]=nbcode[Tvar[k]][codtabm(ij,Tvar[k])]; */
1.187     brouard  6365:       /*       } */
1.198     brouard  6366:       /* for (k=1; k<=cptcovage;k++) cov[2+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(ij,Tvar[Tage[k])]]*cov[2]; */
1.187     brouard  6367:       /*
                   6368:        * Treating invertedly V2+V1+V3*age+V2*V4 is as if written V2*V4 +V3*age + V1 + V2 */
                   6369:       for(k=cptcovt; k>=1;k--) /**< Number of covariates */
1.145     brouard  6370:         Tvar[k]=0;
1.187     brouard  6371:       cptcovage=0;
                   6372:       for(k=1; k<=cptcovt;k++){ /* Loop on total covariates of the model */
                   6373:        cutl(stra,strb,modelsav,'+'); /* keeps in strb after the first '+' 
                   6374:                                         modelsav==V2+V1+V4+V3*age strb=V3*age stra=V2+V1+V4 */ 
                   6375:        if (nbocc(modelsav,'+')==0) strcpy(strb,modelsav); /* and analyzes it */
                   6376:        /*      printf("i=%d a=%s b=%s sav=%s\n",i, stra,strb,modelsav);*/
                   6377:        /*scanf("%d",i);*/
                   6378:        if (strchr(strb,'*')) {  /**< Model includes a product V2+V1+V4+V3*age strb=V3*age */
                   6379:          cutl(strc,strd,strb,'*'); /**< strd*strc  Vm*Vn: strb=V3*age(input) strc=age strd=V3 ; V3*V2 strc=V2, strd=V3 */
                   6380:          if (strcmp(strc,"age")==0) { /**< Model includes age: Vn*age */
                   6381:            /* covar is not filled and then is empty */
                   6382:            cptcovprod--;
                   6383:            cutl(stre,strb,strd,'V'); /* strd=V3(input): stre="3" */
                   6384:            Tvar[k]=atoi(stre);  /* V2+V1+V4+V3*age Tvar[4]=3 ; V1+V2*age Tvar[2]=2; V1+V1*age Tvar[2]=1 */
                   6385:            cptcovage++; /* Sums the number of covariates which include age as a product */
                   6386:            Tage[cptcovage]=k;  /* Tvar[4]=3, Tage[1] = 4 or V1+V1*age Tvar[2]=1, Tage[1]=2 */
                   6387:            /*printf("stre=%s ", stre);*/
                   6388:          } else if (strcmp(strd,"age")==0) { /* or age*Vn */
                   6389:            cptcovprod--;
                   6390:            cutl(stre,strb,strc,'V');
                   6391:            Tvar[k]=atoi(stre);
                   6392:            cptcovage++;
                   6393:            Tage[cptcovage]=k;
                   6394:          } else {  /* Age is not in the model product V2+V1+V1*V4+V3*age+V3*V2  strb=V3*V2*/
                   6395:            /* loops on k1=1 (V3*V2) and k1=2 V4*V3 */
                   6396:            cptcovn++;
                   6397:            cptcovprodnoage++;k1++;
                   6398:            cutl(stre,strb,strc,'V'); /* strc= Vn, stre is n; strb=V3*V2 stre=3 strc=*/
                   6399:            Tvar[k]=ncovcol+k1; /* For model-covariate k tells which data-covariate to use but
                   6400:                                   because this model-covariate is a construction we invent a new column
                   6401:                                   ncovcol + k1
                   6402:                                   If already ncovcol=4 and model=V2+V1+V1*V4+age*V3+V3*V2
                   6403:                                   Tvar[3=V1*V4]=4+1 Tvar[5=V3*V2]=4 + 2= 6, etc */
                   6404:            cutl(strc,strb,strd,'V'); /* strd was Vm, strc is m */
                   6405:            Tprod[k1]=k;  /* Tprod[1]=3(=V1*V4) for V2+V1+V1*V4+age*V3+V3*V2  */
                   6406:            Tvard[k1][1] =atoi(strc); /* m 1 for V1*/
                   6407:            Tvard[k1][2] =atoi(stre); /* n 4 for V4*/
                   6408:            k2=k2+2;
                   6409:            Tvar[cptcovt+k2]=Tvard[k1][1]; /* Tvar[(cptcovt=4+k2=1)=5]= 1 (V1) */
                   6410:            Tvar[cptcovt+k2+1]=Tvard[k1][2];  /* Tvar[(cptcovt=4+(k2=1)+1)=6]= 4 (V4) */
                   6411:            for (i=1; i<=lastobs;i++){
                   6412:              /* Computes the new covariate which is a product of
                   6413:                 covar[n][i]* covar[m][i] and stores it at ncovol+k1 May not be defined */
                   6414:              covar[ncovcol+k1][i]=covar[atoi(stre)][i]*covar[atoi(strc)][i];
                   6415:            }
                   6416:          } /* End age is not in the model */
                   6417:        } /* End if model includes a product */
                   6418:        else { /* no more sum */
                   6419:          /*printf("d=%s c=%s b=%s\n", strd,strc,strb);*/
                   6420:          /*  scanf("%d",i);*/
                   6421:          cutl(strd,strc,strb,'V');
                   6422:          ks++; /**< Number of simple covariates */
1.145     brouard  6423:          cptcovn++;
1.187     brouard  6424:          Tvar[k]=atoi(strd);
                   6425:        }
                   6426:        strcpy(modelsav,stra);  /* modelsav=V2+V1+V4 stra=V2+V1+V4 */ 
                   6427:        /*printf("a=%s b=%s sav=%s\n", stra,strb,modelsav);
                   6428:          scanf("%d",i);*/
                   6429:       } /* end of loop + on total covariates */
                   6430:     } /* end if strlen(modelsave == 0) age*age might exist */
                   6431:   } /* end if strlen(model == 0) */
1.136     brouard  6432:   
                   6433:   /*The number n of Vn is stored in Tvar. cptcovage =number of age covariate. Tage gives the position of age. cptcovprod= number of products.
                   6434:     If model=V1+V1*age then Tvar[1]=1 Tvar[2]=1 cptcovage=1 Tage[1]=2 cptcovprod=0*/
                   6435: 
                   6436:   /* printf("tvar1=%d tvar2=%d tvar3=%d cptcovage=%d Tage=%d",Tvar[1],Tvar[2],Tvar[3],cptcovage,Tage[1]);
                   6437:   printf("cptcovprod=%d ", cptcovprod);
                   6438:   fprintf(ficlog,"cptcovprod=%d ", cptcovprod);
                   6439: 
                   6440:   scanf("%d ",i);*/
                   6441: 
                   6442: 
1.137     brouard  6443:   return (0); /* with covar[new additional covariate if product] and Tage if age */ 
1.164     brouard  6444:   /*endread:*/
1.136     brouard  6445:     printf("Exiting decodemodel: ");
                   6446:     return (1);
                   6447: }
                   6448: 
1.169     brouard  6449: int calandcheckages(int imx, int maxwav, double *agemin, double *agemax, int *nberr, int *nbwarn )
1.136     brouard  6450: {
                   6451:   int i, m;
                   6452: 
                   6453:   for (i=1; i<=imx; i++) {
                   6454:     for(m=2; (m<= maxwav); m++) {
                   6455:       if (((int)mint[m][i]== 99) && (s[m][i] <= nlstate)){
                   6456:        anint[m][i]=9999;
                   6457:        s[m][i]=-1;
                   6458:       }
                   6459:       if((int)moisdc[i]==99 && (int)andc[i]==9999 && s[m][i]>nlstate){
1.169     brouard  6460:        *nberr = *nberr + 1;
                   6461:        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);
                   6462:        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  6463:        s[m][i]=-1;
                   6464:       }
                   6465:       if((int)moisdc[i]==99 && (int)andc[i]!=9999 && s[m][i]>nlstate){
1.169     brouard  6466:        (*nberr)++;
1.136     brouard  6467:        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]); 
                   6468:        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]); 
                   6469:        s[m][i]=-1; /* We prefer to skip it (and to skip it in version 0.8a1 too */
                   6470:       }
                   6471:     }
                   6472:   }
                   6473: 
                   6474:   for (i=1; i<=imx; i++)  {
                   6475:     agedc[i]=(moisdc[i]/12.+andc[i])-(moisnais[i]/12.+annais[i]);
                   6476:     for(m=firstpass; (m<= lastpass); m++){
                   6477:       if(s[m][i] >0 || s[m][i]==-2 || s[m][i]==-4 || s[m][i]==-5){
                   6478:        if (s[m][i] >= nlstate+1) {
1.169     brouard  6479:          if(agedc[i]>0){
                   6480:            if((int)moisdc[i]!=99 && (int)andc[i]!=9999){
1.136     brouard  6481:              agev[m][i]=agedc[i];
                   6482:          /*if(moisdc[i]==99 && andc[i]==9999) s[m][i]=-1;*/
1.169     brouard  6483:            }else {
1.136     brouard  6484:              if ((int)andc[i]!=9999){
                   6485:                nbwarn++;
                   6486:                printf("Warning negative age at death: %ld line:%d\n",num[i],i);
                   6487:                fprintf(ficlog,"Warning negative age at death: %ld line:%d\n",num[i],i);
                   6488:                agev[m][i]=-1;
                   6489:              }
                   6490:            }
1.169     brouard  6491:          } /* agedc > 0 */
1.136     brouard  6492:        }
                   6493:        else if(s[m][i] !=9){ /* Standard case, age in fractional
                   6494:                                 years but with the precision of a month */
                   6495:          agev[m][i]=(mint[m][i]/12.+1./24.+anint[m][i])-(moisnais[i]/12.+1./24.+annais[i]);
                   6496:          if((int)mint[m][i]==99 || (int)anint[m][i]==9999)
                   6497:            agev[m][i]=1;
                   6498:          else if(agev[m][i] < *agemin){ 
                   6499:            *agemin=agev[m][i];
                   6500:            printf(" Min anint[%d][%d]=%.2f annais[%d]=%.2f, agemin=%.2f\n",m,i,anint[m][i], i,annais[i], *agemin);
                   6501:          }
                   6502:          else if(agev[m][i] >*agemax){
                   6503:            *agemax=agev[m][i];
1.156     brouard  6504:            /* printf(" Max anint[%d][%d]=%.0f annais[%d]=%.0f, agemax=%.2f\n",m,i,anint[m][i], i,annais[i], *agemax);*/
1.136     brouard  6505:          }
                   6506:          /*agev[m][i]=anint[m][i]-annais[i];*/
                   6507:          /*     agev[m][i] = age[i]+2*m;*/
                   6508:        }
                   6509:        else { /* =9 */
                   6510:          agev[m][i]=1;
                   6511:          s[m][i]=-1;
                   6512:        }
                   6513:       }
                   6514:       else /*= 0 Unknown */
                   6515:        agev[m][i]=1;
                   6516:     }
                   6517:     
                   6518:   }
                   6519:   for (i=1; i<=imx; i++)  {
                   6520:     for(m=firstpass; (m<=lastpass); m++){
                   6521:       if (s[m][i] > (nlstate+ndeath)) {
1.169     brouard  6522:        (*nberr)++;
1.136     brouard  6523:        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);     
                   6524:        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);     
                   6525:        return 1;
                   6526:       }
                   6527:     }
                   6528:   }
                   6529: 
                   6530:   /*for (i=1; i<=imx; i++){
                   6531:   for (m=firstpass; (m<lastpass); m++){
                   6532:      printf("%ld %d %.lf %d %d\n", num[i],(covar[1][i]),agev[m][i],s[m][i],s[m+1][i]);
                   6533: }
                   6534: 
                   6535: }*/
                   6536: 
                   6537: 
1.139     brouard  6538:   printf("Total number of individuals= %d, Agemin = %.2f, Agemax= %.2f\n\n", imx, *agemin, *agemax);
                   6539:   fprintf(ficlog,"Total number of individuals= %d, Agemin = %.2f, Agemax= %.2f\n\n", imx, *agemin, *agemax); 
1.136     brouard  6540: 
                   6541:   return (0);
1.164     brouard  6542:  /* endread:*/
1.136     brouard  6543:     printf("Exiting calandcheckages: ");
                   6544:     return (1);
                   6545: }
                   6546: 
1.172     brouard  6547: #if defined(_MSC_VER)
                   6548: /*printf("Visual C++ compiler: %s \n;", _MSC_FULL_VER);*/
                   6549: /*fprintf(ficlog, "Visual C++ compiler: %s \n;", _MSC_FULL_VER);*/
                   6550: //#include "stdafx.h"
                   6551: //#include <stdio.h>
                   6552: //#include <tchar.h>
                   6553: //#include <windows.h>
                   6554: //#include <iostream>
                   6555: typedef BOOL(WINAPI *LPFN_ISWOW64PROCESS) (HANDLE, PBOOL);
                   6556: 
                   6557: LPFN_ISWOW64PROCESS fnIsWow64Process;
                   6558: 
                   6559: BOOL IsWow64()
                   6560: {
                   6561:        BOOL bIsWow64 = FALSE;
                   6562: 
                   6563:        //typedef BOOL (APIENTRY *LPFN_ISWOW64PROCESS)
                   6564:        //  (HANDLE, PBOOL);
                   6565: 
                   6566:        //LPFN_ISWOW64PROCESS fnIsWow64Process;
                   6567: 
                   6568:        HMODULE module = GetModuleHandle(_T("kernel32"));
                   6569:        const char funcName[] = "IsWow64Process";
                   6570:        fnIsWow64Process = (LPFN_ISWOW64PROCESS)
                   6571:                GetProcAddress(module, funcName);
                   6572: 
                   6573:        if (NULL != fnIsWow64Process)
                   6574:        {
                   6575:                if (!fnIsWow64Process(GetCurrentProcess(),
                   6576:                        &bIsWow64))
                   6577:                        //throw std::exception("Unknown error");
                   6578:                        printf("Unknown error\n");
                   6579:        }
                   6580:        return bIsWow64 != FALSE;
                   6581: }
                   6582: #endif
1.177     brouard  6583: 
1.191     brouard  6584: void syscompilerinfo(int logged)
1.167     brouard  6585:  {
                   6586:    /* #include "syscompilerinfo.h"*/
1.185     brouard  6587:    /* command line Intel compiler 32bit windows, XP compatible:*/
                   6588:    /* /GS /W3 /Gy
                   6589:       /Zc:wchar_t /Zi /O2 /Fd"Release\vc120.pdb" /D "WIN32" /D "NDEBUG" /D
                   6590:       "_CONSOLE" /D "_LIB" /D "_USING_V110_SDK71_" /D "_UNICODE" /D
                   6591:       "UNICODE" /Qipo /Zc:forScope /Gd /Oi /MT /Fa"Release\" /EHsc /nologo
1.186     brouard  6592:       /Fo"Release\" /Qprof-dir "Release\" /Fp"Release\IMaCh.pch"
                   6593:    */ 
                   6594:    /* 64 bits */
1.185     brouard  6595:    /*
                   6596:      /GS /W3 /Gy
                   6597:      /Zc:wchar_t /Zi /O2 /Fd"x64\Release\vc120.pdb" /D "WIN32" /D "NDEBUG"
                   6598:      /D "_CONSOLE" /D "_LIB" /D "_UNICODE" /D "UNICODE" /Qipo /Zc:forScope
                   6599:      /Oi /MD /Fa"x64\Release\" /EHsc /nologo /Fo"x64\Release\" /Qprof-dir
                   6600:      "x64\Release\" /Fp"x64\Release\IMaCh.pch" */
                   6601:    /* Optimization are useless and O3 is slower than O2 */
                   6602:    /*
                   6603:      /GS /W3 /Gy /Zc:wchar_t /Zi /O3 /Fd"x64\Release\vc120.pdb" /D "WIN32" 
                   6604:      /D "NDEBUG" /D "_CONSOLE" /D "_LIB" /D "_UNICODE" /D "UNICODE" /Qipo 
                   6605:      /Zc:forScope /Oi /MD /Fa"x64\Release\" /EHsc /nologo /Qparallel 
                   6606:      /Fo"x64\Release\" /Qprof-dir "x64\Release\" /Fp"x64\Release\IMaCh.pch" 
                   6607:    */
1.186     brouard  6608:    /* Link is */ /* /OUT:"visual studio
1.185     brouard  6609:       2013\Projects\IMaCh\Release\IMaCh.exe" /MANIFEST /NXCOMPAT
                   6610:       /PDB:"visual studio
                   6611:       2013\Projects\IMaCh\Release\IMaCh.pdb" /DYNAMICBASE
                   6612:       "kernel32.lib" "user32.lib" "gdi32.lib" "winspool.lib"
                   6613:       "comdlg32.lib" "advapi32.lib" "shell32.lib" "ole32.lib"
                   6614:       "oleaut32.lib" "uuid.lib" "odbc32.lib" "odbccp32.lib"
                   6615:       /MACHINE:X86 /OPT:REF /SAFESEH /INCREMENTAL:NO
                   6616:       /SUBSYSTEM:CONSOLE",5.01" /MANIFESTUAC:"level='asInvoker'
                   6617:       uiAccess='false'"
                   6618:       /ManifestFile:"Release\IMaCh.exe.intermediate.manifest" /OPT:ICF
                   6619:       /NOLOGO /TLBID:1
                   6620:    */
1.177     brouard  6621: #if defined __INTEL_COMPILER
1.178     brouard  6622: #if defined(__GNUC__)
                   6623:        struct utsname sysInfo;  /* For Intel on Linux and OS/X */
                   6624: #endif
1.177     brouard  6625: #elif defined(__GNUC__) 
1.179     brouard  6626: #ifndef  __APPLE__
1.174     brouard  6627: #include <gnu/libc-version.h>  /* Only on gnu */
1.179     brouard  6628: #endif
1.177     brouard  6629:    struct utsname sysInfo;
1.178     brouard  6630:    int cross = CROSS;
                   6631:    if (cross){
                   6632:           printf("Cross-");
1.191     brouard  6633:           if(logged) fprintf(ficlog, "Cross-");
1.178     brouard  6634:    }
1.174     brouard  6635: #endif
                   6636: 
1.171     brouard  6637: #include <stdint.h>
1.178     brouard  6638: 
1.191     brouard  6639:    printf("Compiled with:");if(logged)fprintf(ficlog,"Compiled with:");
1.169     brouard  6640: #if defined(__clang__)
1.191     brouard  6641:    printf(" Clang/LLVM");if(logged)fprintf(ficlog," Clang/LLVM");      /* Clang/LLVM. ---------------------------------------------- */
1.169     brouard  6642: #endif
                   6643: #if defined(__ICC) || defined(__INTEL_COMPILER)
1.191     brouard  6644:    printf(" Intel ICC/ICPC");if(logged)fprintf(ficlog," Intel ICC/ICPC");/* Intel ICC/ICPC. ------------------------------------------ */
1.169     brouard  6645: #endif
                   6646: #if defined(__GNUC__) || defined(__GNUG__)
1.191     brouard  6647:    printf(" GNU GCC/G++");if(logged)fprintf(ficlog," GNU GCC/G++");/* GNU GCC/G++. --------------------------------------------- */
1.169     brouard  6648: #endif
                   6649: #if defined(__HP_cc) || defined(__HP_aCC)
1.191     brouard  6650:    printf(" Hewlett-Packard C/aC++");if(logged)fprintf(fcilog," Hewlett-Packard C/aC++"); /* Hewlett-Packard C/aC++. ---------------------------------- */
1.169     brouard  6651: #endif
                   6652: #if defined(__IBMC__) || defined(__IBMCPP__)
1.191     brouard  6653:    printf(" IBM XL C/C++"); if(logged) fprintf(ficlog," IBM XL C/C++");/* IBM XL C/C++. -------------------------------------------- */
1.169     brouard  6654: #endif
                   6655: #if defined(_MSC_VER)
1.191     brouard  6656:    printf(" Microsoft Visual Studio");if(logged)fprintf(ficlog," Microsoft Visual Studio");/* Microsoft Visual Studio. --------------------------------- */
1.169     brouard  6657: #endif
                   6658: #if defined(__PGI)
1.191     brouard  6659:    printf(" Portland Group PGCC/PGCPP");if(logged) fprintf(ficlog," Portland Group PGCC/PGCPP");/* Portland Group PGCC/PGCPP. ------------------------------- */
1.169     brouard  6660: #endif
                   6661: #if defined(__SUNPRO_C) || defined(__SUNPRO_CC)
1.191     brouard  6662:    printf(" Oracle Solaris Studio");if(logged)fprintf(ficlog," Oracle Solaris Studio\n");/* Oracle Solaris Studio. ----------------------------------- */
1.167     brouard  6663: #endif
1.191     brouard  6664:    printf(" for "); if (logged) fprintf(ficlog, " for ");
1.169     brouard  6665:    
1.167     brouard  6666: // http://stackoverflow.com/questions/4605842/how-to-identify-platform-compiler-from-preprocessor-macros
                   6667: #ifdef _WIN32 // note the underscore: without it, it's not msdn official!
                   6668:     // Windows (x64 and x86)
1.191     brouard  6669:    printf("Windows (x64 and x86) ");if(logged) fprintf(ficlog,"Windows (x64 and x86) ");
1.167     brouard  6670: #elif __unix__ // all unices, not all compilers
                   6671:     // Unix
1.191     brouard  6672:    printf("Unix ");if(logged) fprintf(ficlog,"Unix ");
1.167     brouard  6673: #elif __linux__
                   6674:     // linux
1.191     brouard  6675:    printf("linux ");if(logged) fprintf(ficlog,"linux ");
1.167     brouard  6676: #elif __APPLE__
1.174     brouard  6677:     // Mac OS, not sure if this is covered by __posix__ and/or __unix__ though..
1.191     brouard  6678:    printf("Mac OS ");if(logged) fprintf(ficlog,"Mac OS ");
1.167     brouard  6679: #endif
                   6680: 
                   6681: /*  __MINGW32__          */
                   6682: /*  __CYGWIN__  */
                   6683: /* __MINGW64__  */
                   6684: // http://msdn.microsoft.com/en-us/library/b0084kay.aspx
                   6685: /* _MSC_VER  //the Visual C++ compiler is 17.00.51106.1, the _MSC_VER macro evaluates to 1700. Type cl /?  */
                   6686: /* _MSC_FULL_VER //the Visual C++ compiler is 15.00.20706.01, the _MSC_FULL_VER macro evaluates to 150020706 */
                   6687: /* _WIN64  // Defined for applications for Win64. */
                   6688: /* _M_X64 // Defined for compilations that target x64 processors. */
                   6689: /* _DEBUG // Defined when you compile with /LDd, /MDd, and /MTd. */
1.171     brouard  6690: 
1.167     brouard  6691: #if UINTPTR_MAX == 0xffffffff
1.191     brouard  6692:    printf(" 32-bit"); if(logged) fprintf(ficlog," 32-bit");/* 32-bit */
1.167     brouard  6693: #elif UINTPTR_MAX == 0xffffffffffffffff
1.191     brouard  6694:    printf(" 64-bit"); if(logged) fprintf(ficlog," 64-bit");/* 64-bit */
1.167     brouard  6695: #else
1.191     brouard  6696:    printf(" wtf-bit"); if(logged) fprintf(ficlog," wtf-bit");/* wtf */
1.167     brouard  6697: #endif
                   6698: 
1.169     brouard  6699: #if defined(__GNUC__)
                   6700: # if defined(__GNUC_PATCHLEVEL__)
                   6701: #  define __GNUC_VERSION__ (__GNUC__ * 10000 \
                   6702:                             + __GNUC_MINOR__ * 100 \
                   6703:                             + __GNUC_PATCHLEVEL__)
                   6704: # else
                   6705: #  define __GNUC_VERSION__ (__GNUC__ * 10000 \
                   6706:                             + __GNUC_MINOR__ * 100)
                   6707: # endif
1.174     brouard  6708:    printf(" using GNU C version %d.\n", __GNUC_VERSION__);
1.191     brouard  6709:    if(logged) fprintf(ficlog, " using GNU C version %d.\n", __GNUC_VERSION__);
1.176     brouard  6710: 
                   6711:    if (uname(&sysInfo) != -1) {
                   6712:      printf("Running on: %s %s %s %s %s\n",sysInfo.sysname, sysInfo.nodename, sysInfo.release, sysInfo.version, sysInfo.machine);
1.191     brouard  6713:         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  6714:    }
                   6715:    else
                   6716:       perror("uname() error");
1.179     brouard  6717:    //#ifndef __INTEL_COMPILER 
                   6718: #if !defined (__INTEL_COMPILER) && !defined(__APPLE__)
1.174     brouard  6719:    printf("GNU libc version: %s\n", gnu_get_libc_version()); 
1.191     brouard  6720:    if(logged) fprintf(ficlog,"GNU libc version: %s\n", gnu_get_libc_version());
1.177     brouard  6721: #endif
1.169     brouard  6722: #endif
1.172     brouard  6723: 
                   6724:    //   void main()
                   6725:    //   {
1.169     brouard  6726: #if defined(_MSC_VER)
1.174     brouard  6727:    if (IsWow64()){
1.191     brouard  6728:           printf("\nThe program (probably compiled for 32bit) is running under WOW64 (64bit) emulation.\n");
                   6729:           if (logged) fprintf(ficlog, "\nThe program (probably compiled for 32bit) is running under WOW64 (64bit) emulation.\n");
1.174     brouard  6730:    }
                   6731:    else{
1.191     brouard  6732:           printf("\nThe program is not running under WOW64 (i.e probably on a 64bit Windows).\n");
                   6733:           if (logged) fprintf(ficlog, "\nThe programm is not running under WOW64 (i.e probably on a 64bit Windows).\n");
1.174     brouard  6734:    }
1.172     brouard  6735:    //     printf("\nPress Enter to continue...");
                   6736:    //     getchar();
                   6737:    //   }
                   6738: 
1.169     brouard  6739: #endif
                   6740:    
1.167     brouard  6741: 
                   6742:  }
1.136     brouard  6743: 
1.209     brouard  6744:  int prevalence_limit(double *p, double **prlim, double ageminpar, double agemaxpar, double ftolpl, int *ncvyearp){
1.180     brouard  6745:   /*--------------- Prevalence limit  (period or stable prevalence) --------------*/
                   6746:   int i, j, k, i1 ;
1.202     brouard  6747:   /* double ftolpl = 1.e-10; */
1.180     brouard  6748:   double age, agebase, agelim;
1.203     brouard  6749:   double tot;
1.180     brouard  6750: 
1.202     brouard  6751:   strcpy(filerespl,"PL_");
                   6752:   strcat(filerespl,fileresu);
                   6753:   if((ficrespl=fopen(filerespl,"w"))==NULL) {
                   6754:     printf("Problem with period (stable) prevalence resultfile: %s\n", filerespl);return 1;
                   6755:     fprintf(ficlog,"Problem with period (stable) prevalence resultfile: %s\n", filerespl);return 1;
                   6756:   }
                   6757:   printf("Computing period (stable) prevalence: result on file '%s' \n", filerespl);
                   6758:   fprintf(ficlog,"Computing period (stable) prevalence: result on file '%s' \n", filerespl);
                   6759:   pstamp(ficrespl);
1.203     brouard  6760:   fprintf(ficrespl,"# Period (stable) prevalence. Precision given by ftolpl=%g \n", ftolpl);
1.202     brouard  6761:   fprintf(ficrespl,"#Age ");
                   6762:   for(i=1; i<=nlstate;i++) fprintf(ficrespl,"%d-%d ",i,i);
                   6763:   fprintf(ficrespl,"\n");
1.180     brouard  6764:   
                   6765:     /* prlim=matrix(1,nlstate,1,nlstate);*/ /* back in main */
                   6766: 
                   6767:     agebase=ageminpar;
                   6768:     agelim=agemaxpar;
                   6769: 
                   6770:     i1=pow(2,cptcoveff);
                   6771:     if (cptcovn < 1){i1=1;}
                   6772: 
                   6773:     for(cptcov=1,k=0;cptcov<=i1;cptcov++){
                   6774:     /* for(cptcov=1,k=0;cptcov<=1;cptcov++){ */
                   6775:       //for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){
                   6776:        k=k+1;
                   6777:        /* to clean */
1.198     brouard  6778:        //printf("cptcov=%d cptcod=%d codtab=%d\n",cptcov, cptcod,codtabm(cptcod,cptcov));
1.200     brouard  6779:        fprintf(ficrespl,"#******");
                   6780:        printf("#******");
                   6781:        fprintf(ficlog,"#******");
1.180     brouard  6782:        for(j=1;j<=cptcoveff;j++) {
1.198     brouard  6783:          fprintf(ficrespl," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
                   6784:          printf(" V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
                   6785:          fprintf(ficlog," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
1.180     brouard  6786:        }
                   6787:        fprintf(ficrespl,"******\n");
                   6788:        printf("******\n");
                   6789:        fprintf(ficlog,"******\n");
                   6790: 
                   6791:        fprintf(ficrespl,"#Age ");
                   6792:        for(j=1;j<=cptcoveff;j++) {
1.200     brouard  6793:          fprintf(ficrespl,"V%d %d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
1.180     brouard  6794:        }
1.203     brouard  6795:        for(i=1; i<=nlstate;i++) fprintf(ficrespl,"  %d-%d   ",i,i);
                   6796:        fprintf(ficrespl,"Total Years_to_converge\n");
1.180     brouard  6797:        
                   6798:        for (age=agebase; age<=agelim; age++){
                   6799:        /* for (age=agebase; age<=agebase; age++){ */
1.209     brouard  6800:          prevalim(prlim, nlstate, p, age, oldm, savm, ftolpl, ncvyearp, k);
1.180     brouard  6801:          fprintf(ficrespl,"%.0f ",age );
                   6802:          for(j=1;j<=cptcoveff;j++)
1.198     brouard  6803:            fprintf(ficrespl,"%d %d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
1.203     brouard  6804:          tot=0.;
                   6805:          for(i=1; i<=nlstate;i++){
                   6806:            tot +=  prlim[i][i];
1.180     brouard  6807:            fprintf(ficrespl," %.5f", prlim[i][i]);
1.203     brouard  6808:          }
1.209     brouard  6809:          fprintf(ficrespl," %.3f %d\n", tot, *ncvyearp);
1.180     brouard  6810:        } /* Age */
                   6811:        /* was end of cptcod */
                   6812:     } /* cptcov */
1.184     brouard  6813:        return 0;
1.180     brouard  6814: }
                   6815: 
                   6816: int hPijx(double *p, int bage, int fage){
                   6817:     /*------------- h Pij x at various ages ------------*/
                   6818: 
                   6819:   int stepsize;
                   6820:   int agelim;
                   6821:   int hstepm;
                   6822:   int nhstepm;
                   6823:   int h, i, i1, j, k;
                   6824: 
                   6825:   double agedeb;
                   6826:   double ***p3mat;
                   6827: 
1.201     brouard  6828:     strcpy(filerespij,"PIJ_");  strcat(filerespij,fileresu);
1.180     brouard  6829:     if((ficrespij=fopen(filerespij,"w"))==NULL) {
                   6830:       printf("Problem with Pij resultfile: %s\n", filerespij); return 1;
                   6831:       fprintf(ficlog,"Problem with Pij resultfile: %s\n", filerespij); return 1;
                   6832:     }
                   6833:     printf("Computing pij: result on file '%s' \n", filerespij);
                   6834:     fprintf(ficlog,"Computing pij: result on file '%s' \n", filerespij);
                   6835:   
                   6836:     stepsize=(int) (stepm+YEARM-1)/YEARM;
                   6837:     /*if (stepm<=24) stepsize=2;*/
                   6838: 
                   6839:     agelim=AGESUP;
                   6840:     hstepm=stepsize*YEARM; /* Every year of age */
                   6841:     hstepm=hstepm/stepm; /* Typically 2 years, = 2/6 months = 4 */ 
                   6842: 
                   6843:     /* hstepm=1;   aff par mois*/
                   6844:     pstamp(ficrespij);
                   6845:     fprintf(ficrespij,"#****** h Pij x Probability to be in state j at age x+h being in i at x ");
                   6846:     i1= pow(2,cptcoveff);
1.183     brouard  6847:    /* for(cptcov=1,k=0;cptcov<=i1;cptcov++){ */
                   6848:    /*    /\*for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){*\/ */
                   6849:    /*          k=k+1;  */
                   6850:     for (k=1; k <= (int) pow(2,cptcoveff); k++){
                   6851:       fprintf(ficrespij,"\n#****** ");
                   6852:       for(j=1;j<=cptcoveff;j++) 
1.198     brouard  6853:        fprintf(ficrespij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
1.183     brouard  6854:       fprintf(ficrespij,"******\n");
                   6855:       
                   6856:       for (agedeb=fage; agedeb>=bage; agedeb--){ /* If stepm=6 months */
                   6857:        nhstepm=(int) rint((agelim-agedeb)*YEARM/stepm); /* Typically 20 years = 20*12/6=40 */ 
                   6858:        nhstepm = nhstepm/hstepm; /* Typically 40/4=10 */
                   6859:        
                   6860:        /*        nhstepm=nhstepm*YEARM; aff par mois*/
1.180     brouard  6861:        
1.183     brouard  6862:        p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   6863:        oldm=oldms;savm=savms;
                   6864:        hpxij(p3mat,nhstepm,agedeb,hstepm,p,nlstate,stepm,oldm,savm, k);  
                   6865:        fprintf(ficrespij,"# Cov Agex agex+h hpijx with i,j=");
                   6866:        for(i=1; i<=nlstate;i++)
                   6867:          for(j=1; j<=nlstate+ndeath;j++)
                   6868:            fprintf(ficrespij," %1d-%1d",i,j);
                   6869:        fprintf(ficrespij,"\n");
                   6870:        for (h=0; h<=nhstepm; h++){
                   6871:          /*agedebphstep = agedeb + h*hstepm/YEARM*stepm;*/
                   6872:          fprintf(ficrespij,"%d %3.f %3.f",k, agedeb, agedeb + h*hstepm/YEARM*stepm );
1.180     brouard  6873:          for(i=1; i<=nlstate;i++)
                   6874:            for(j=1; j<=nlstate+ndeath;j++)
1.183     brouard  6875:              fprintf(ficrespij," %.5f", p3mat[i][j][h]);
1.180     brouard  6876:          fprintf(ficrespij,"\n");
                   6877:        }
1.183     brouard  6878:        free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   6879:        fprintf(ficrespij,"\n");
                   6880:       }
1.180     brouard  6881:       /*}*/
                   6882:     }
1.184     brouard  6883:        return 0;
1.180     brouard  6884: }
                   6885: 
                   6886: 
1.136     brouard  6887: /***********************************************/
                   6888: /**************** Main Program *****************/
                   6889: /***********************************************/
                   6890: 
                   6891: int main(int argc, char *argv[])
                   6892: {
                   6893: #ifdef GSL
                   6894:   const gsl_multimin_fminimizer_type *T;
                   6895:   size_t iteri = 0, it;
                   6896:   int rval = GSL_CONTINUE;
                   6897:   int status = GSL_SUCCESS;
                   6898:   double ssval;
                   6899: #endif
                   6900:   int movingaverage(double ***probs, double bage,double fage, double ***mobaverage, int mobilav);
1.164     brouard  6901:   int i,j, k, n=MAXN,iter=0,m,size=100, cptcod;
1.209     brouard  6902:   int ncvyear=0; /* Number of years needed for the period prevalence to converge */
1.164     brouard  6903:   int jj, ll, li, lj, lk;
1.136     brouard  6904:   int numlinepar=0; /* Current linenumber of parameter file */
1.197     brouard  6905:   int num_filled;
1.136     brouard  6906:   int itimes;
                   6907:   int NDIM=2;
                   6908:   int vpopbased=0;
                   6909: 
1.164     brouard  6910:   char ca[32], cb[32];
1.136     brouard  6911:   /*  FILE *fichtm; *//* Html File */
                   6912:   /* FILE *ficgp;*/ /*Gnuplot File */
                   6913:   struct stat info;
1.191     brouard  6914:   double agedeb=0.;
1.194     brouard  6915: 
                   6916:   double ageminpar=AGEOVERFLOW,agemin=AGEOVERFLOW, agemaxpar=-AGEOVERFLOW, agemax=-AGEOVERFLOW;
1.136     brouard  6917: 
1.165     brouard  6918:   double fret;
1.191     brouard  6919:   double dum=0.; /* Dummy variable */
1.136     brouard  6920:   double ***p3mat;
                   6921:   double ***mobaverage;
1.164     brouard  6922: 
                   6923:   char line[MAXLINE];
1.197     brouard  6924:   char path[MAXLINE],pathc[MAXLINE],pathcd[MAXLINE],pathtot[MAXLINE];
                   6925: 
                   6926:   char model[MAXLINE], modeltemp[MAXLINE];
1.136     brouard  6927:   char pathr[MAXLINE], pathimach[MAXLINE]; 
1.164     brouard  6928:   char *tok, *val; /* pathtot */
1.136     brouard  6929:   int firstobs=1, lastobs=10;
1.195     brouard  6930:   int c,  h , cpt, c2;
1.191     brouard  6931:   int jl=0;
                   6932:   int i1, j1, jk, stepsize=0;
1.194     brouard  6933:   int count=0;
                   6934: 
1.164     brouard  6935:   int *tab; 
1.136     brouard  6936:   int mobilavproj=0 , prevfcast=0 ; /* moving average of prev, If prevfcast=1 prevalence projection */
                   6937:   int mobilav=0,popforecast=0;
1.191     brouard  6938:   int hstepm=0, nhstepm=0;
1.136     brouard  6939:   int agemortsup;
                   6940:   float  sumlpop=0.;
                   6941:   double jprev1=1, mprev1=1,anprev1=2000,jprev2=1, mprev2=1,anprev2=2000;
                   6942:   double jpyram=1, mpyram=1,anpyram=2000,jpyram1=1, mpyram1=1,anpyram1=2000;
                   6943: 
1.191     brouard  6944:   double bage=0, fage=110., age, agelim=0., agebase=0.;
1.136     brouard  6945:   double ftolpl=FTOL;
                   6946:   double **prlim;
                   6947:   double ***param; /* Matrix of parameters */
                   6948:   double  *p;
                   6949:   double **matcov; /* Matrix of covariance */
1.203     brouard  6950:   double **hess; /* Hessian matrix */
1.136     brouard  6951:   double ***delti3; /* Scale */
                   6952:   double *delti; /* Scale */
                   6953:   double ***eij, ***vareij;
                   6954:   double **varpl; /* Variances of prevalence limits by age */
                   6955:   double *epj, vepp;
1.164     brouard  6956: 
1.136     brouard  6957:   double dateprev1, dateprev2,jproj1=1,mproj1=1,anproj1=2000,jproj2=1,mproj2=1,anproj2=2000;
                   6958:   double **ximort;
1.145     brouard  6959:   char *alph[]={"a","a","b","c","d","e"}, str[4]="1234";
1.136     brouard  6960:   int *dcwave;
                   6961: 
1.164     brouard  6962:   char z[1]="c";
1.136     brouard  6963: 
                   6964:   /*char  *strt;*/
                   6965:   char strtend[80];
1.126     brouard  6966: 
1.164     brouard  6967: 
1.126     brouard  6968: /*   setlocale (LC_ALL, ""); */
                   6969: /*   bindtextdomain (PACKAGE, LOCALEDIR); */
                   6970: /*   textdomain (PACKAGE); */
                   6971: /*   setlocale (LC_CTYPE, ""); */
                   6972: /*   setlocale (LC_MESSAGES, ""); */
                   6973: 
                   6974:   /*   gettimeofday(&start_time, (struct timezone*)0); */ /* at first time */
1.157     brouard  6975:   rstart_time = time(NULL);  
                   6976:   /*  (void) gettimeofday(&start_time,&tzp);*/
                   6977:   start_time = *localtime(&rstart_time);
1.126     brouard  6978:   curr_time=start_time;
1.157     brouard  6979:   /*tml = *localtime(&start_time.tm_sec);*/
                   6980:   /* strcpy(strstart,asctime(&tml)); */
                   6981:   strcpy(strstart,asctime(&start_time));
1.126     brouard  6982: 
                   6983: /*  printf("Localtime (at start)=%s",strstart); */
1.157     brouard  6984: /*  tp.tm_sec = tp.tm_sec +86400; */
                   6985: /*  tm = *localtime(&start_time.tm_sec); */
1.126     brouard  6986: /*   tmg.tm_year=tmg.tm_year +dsign*dyear; */
                   6987: /*   tmg.tm_mon=tmg.tm_mon +dsign*dmonth; */
                   6988: /*   tmg.tm_hour=tmg.tm_hour + 1; */
1.157     brouard  6989: /*   tp.tm_sec = mktime(&tmg); */
1.126     brouard  6990: /*   strt=asctime(&tmg); */
                   6991: /*   printf("Time(after) =%s",strstart);  */
                   6992: /*  (void) time (&time_value);
                   6993: *  printf("time=%d,t-=%d\n",time_value,time_value-86400);
                   6994: *  tm = *localtime(&time_value);
                   6995: *  strstart=asctime(&tm);
                   6996: *  printf("tim_value=%d,asctime=%s\n",time_value,strstart); 
                   6997: */
                   6998: 
                   6999:   nberr=0; /* Number of errors and warnings */
                   7000:   nbwarn=0;
1.184     brouard  7001: #ifdef WIN32
                   7002:   _getcwd(pathcd, size);
                   7003: #else
1.126     brouard  7004:   getcwd(pathcd, size);
1.184     brouard  7005: #endif
1.191     brouard  7006:   syscompilerinfo(0);
1.196     brouard  7007:   printf("\nIMaCh version %s, %s\n%s",version, copyright, fullversion);
1.126     brouard  7008:   if(argc <=1){
                   7009:     printf("\nEnter the parameter file name: ");
1.205     brouard  7010:     if(!fgets(pathr,FILENAMELENGTH,stdin)){
                   7011:       printf("ERROR Empty parameter file name\n");
                   7012:       goto end;
                   7013:     }
1.126     brouard  7014:     i=strlen(pathr);
                   7015:     if(pathr[i-1]=='\n')
                   7016:       pathr[i-1]='\0';
1.156     brouard  7017:     i=strlen(pathr);
1.205     brouard  7018:     if(i >= 1 && pathr[i-1]==' ') {/* This may happen when dragging on oS/X! */
1.156     brouard  7019:       pathr[i-1]='\0';
1.205     brouard  7020:     }
                   7021:     i=strlen(pathr);
                   7022:     if( i==0 ){
                   7023:       printf("ERROR Empty parameter file name\n");
                   7024:       goto end;
                   7025:     }
                   7026:     for (tok = pathr; tok != NULL; ){
1.126     brouard  7027:       printf("Pathr |%s|\n",pathr);
                   7028:       while ((val = strsep(&tok, "\"" )) != NULL && *val == '\0');
                   7029:       printf("val= |%s| pathr=%s\n",val,pathr);
                   7030:       strcpy (pathtot, val);
                   7031:       if(pathr[0] == '\0') break; /* Dirty */
                   7032:     }
                   7033:   }
                   7034:   else{
                   7035:     strcpy(pathtot,argv[1]);
                   7036:   }
                   7037:   /*if(getcwd(pathcd, MAXLINE)!= NULL)printf ("Error pathcd\n");*/
                   7038:   /*cygwin_split_path(pathtot,path,optionfile);
                   7039:     printf("pathtot=%s, path=%s, optionfile=%s\n",pathtot,path,optionfile);*/
                   7040:   /* cutv(path,optionfile,pathtot,'\\');*/
                   7041: 
                   7042:   /* Split argv[0], imach program to get pathimach */
                   7043:   printf("\nargv[0]=%s argv[1]=%s, \n",argv[0],argv[1]);
                   7044:   split(argv[0],pathimach,optionfile,optionfilext,optionfilefiname);
                   7045:   printf("\nargv[0]=%s pathimach=%s, \noptionfile=%s \noptionfilext=%s \noptionfilefiname=%s\n",argv[0],pathimach,optionfile,optionfilext,optionfilefiname);
                   7046:  /*   strcpy(pathimach,argv[0]); */
                   7047:   /* Split argv[1]=pathtot, parameter file name to get path, optionfile, extension and name */
                   7048:   split(pathtot,path,optionfile,optionfilext,optionfilefiname);
                   7049:   printf("\npathtot=%s,\npath=%s,\noptionfile=%s \noptionfilext=%s \noptionfilefiname=%s\n",pathtot,path,optionfile,optionfilext,optionfilefiname);
1.184     brouard  7050: #ifdef WIN32
                   7051:   _chdir(path); /* Can be a relative path */
                   7052:   if(_getcwd(pathcd,MAXLINE) > 0) /* So pathcd is the full path */
                   7053: #else
1.126     brouard  7054:   chdir(path); /* Can be a relative path */
1.184     brouard  7055:   if (getcwd(pathcd, MAXLINE) > 0) /* So pathcd is the full path */
                   7056: #endif
                   7057:   printf("Current directory %s!\n",pathcd);
1.126     brouard  7058:   strcpy(command,"mkdir ");
                   7059:   strcat(command,optionfilefiname);
                   7060:   if((outcmd=system(command)) != 0){
1.169     brouard  7061:     printf("Directory already exists (or can't create it) %s%s, err=%d\n",path,optionfilefiname,outcmd);
1.126     brouard  7062:     /* fprintf(ficlog,"Problem creating directory %s%s\n",path,optionfilefiname); */
                   7063:     /* fclose(ficlog); */
                   7064: /*     exit(1); */
                   7065:   }
                   7066: /*   if((imk=mkdir(optionfilefiname))<0){ */
                   7067: /*     perror("mkdir"); */
                   7068: /*   } */
                   7069: 
                   7070:   /*-------- arguments in the command line --------*/
                   7071: 
1.186     brouard  7072:   /* Main Log file */
1.126     brouard  7073:   strcat(filelog, optionfilefiname);
                   7074:   strcat(filelog,".log");    /* */
                   7075:   if((ficlog=fopen(filelog,"w"))==NULL)    {
                   7076:     printf("Problem with logfile %s\n",filelog);
                   7077:     goto end;
                   7078:   }
                   7079:   fprintf(ficlog,"Log filename:%s\n",filelog);
1.197     brouard  7080:   fprintf(ficlog,"Version %s %s",version,fullversion);
1.126     brouard  7081:   fprintf(ficlog,"\nEnter the parameter file name: \n");
                   7082:   fprintf(ficlog,"pathimach=%s\npathtot=%s\n\
                   7083:  path=%s \n\
                   7084:  optionfile=%s\n\
                   7085:  optionfilext=%s\n\
1.156     brouard  7086:  optionfilefiname='%s'\n",pathimach,pathtot,path,optionfile,optionfilext,optionfilefiname);
1.126     brouard  7087: 
1.197     brouard  7088:   syscompilerinfo(1);
1.167     brouard  7089: 
1.126     brouard  7090:   printf("Local time (at start):%s",strstart);
                   7091:   fprintf(ficlog,"Local time (at start): %s",strstart);
                   7092:   fflush(ficlog);
                   7093: /*   (void) gettimeofday(&curr_time,&tzp); */
1.157     brouard  7094: /*   printf("Elapsed time %d\n", asc_diff_time(curr_time.tm_sec-start_time.tm_sec,tmpout)); */
1.126     brouard  7095: 
                   7096:   /* */
                   7097:   strcpy(fileres,"r");
                   7098:   strcat(fileres, optionfilefiname);
1.201     brouard  7099:   strcat(fileresu, optionfilefiname); /* Without r in front */
1.126     brouard  7100:   strcat(fileres,".txt");    /* Other files have txt extension */
1.201     brouard  7101:   strcat(fileresu,".txt");    /* Other files have txt extension */
1.126     brouard  7102: 
1.186     brouard  7103:   /* Main ---------arguments file --------*/
1.126     brouard  7104: 
                   7105:   if((ficpar=fopen(optionfile,"r"))==NULL)    {
1.155     brouard  7106:     printf("Problem with optionfile '%s' with errno='%s'\n",optionfile,strerror(errno));
                   7107:     fprintf(ficlog,"Problem with optionfile '%s' with errno='%s'\n",optionfile,strerror(errno));
1.126     brouard  7108:     fflush(ficlog);
1.149     brouard  7109:     /* goto end; */
                   7110:     exit(70); 
1.126     brouard  7111:   }
                   7112: 
                   7113: 
                   7114: 
                   7115:   strcpy(filereso,"o");
1.201     brouard  7116:   strcat(filereso,fileresu);
1.126     brouard  7117:   if((ficparo=fopen(filereso,"w"))==NULL) { /* opened on subdirectory */
                   7118:     printf("Problem with Output resultfile: %s\n", filereso);
                   7119:     fprintf(ficlog,"Problem with Output resultfile: %s\n", filereso);
                   7120:     fflush(ficlog);
                   7121:     goto end;
                   7122:   }
                   7123: 
                   7124:   /* Reads comments: lines beginning with '#' */
                   7125:   numlinepar=0;
1.197     brouard  7126: 
                   7127:     /* First parameter line */
                   7128:   while(fgets(line, MAXLINE, ficpar)) {
                   7129:     /* If line starts with a # it is a comment */
                   7130:     if (line[0] == '#') {
                   7131:       numlinepar++;
                   7132:       fputs(line,stdout);
                   7133:       fputs(line,ficparo);
                   7134:       fputs(line,ficlog);
                   7135:       continue;
                   7136:     }else
                   7137:       break;
                   7138:   }
                   7139:   if((num_filled=sscanf(line,"title=%s datafile=%s lastobs=%d firstpass=%d lastpass=%d\n", \
                   7140:                        title, datafile, &lastobs, &firstpass,&lastpass)) !=EOF){
                   7141:     if (num_filled != 5) {
                   7142:       printf("Should be 5 parameters\n");
                   7143:     }
1.126     brouard  7144:     numlinepar++;
1.197     brouard  7145:     printf("title=%s datafile=%s lastobs=%d firstpass=%d lastpass=%d\n", title, datafile, lastobs, firstpass,lastpass);
                   7146:   }
                   7147:   /* Second parameter line */
                   7148:   while(fgets(line, MAXLINE, ficpar)) {
                   7149:     /* If line starts with a # it is a comment */
                   7150:     if (line[0] == '#') {
                   7151:       numlinepar++;
                   7152:       fputs(line,stdout);
                   7153:       fputs(line,ficparo);
                   7154:       fputs(line,ficlog);
                   7155:       continue;
                   7156:     }else
                   7157:       break;
                   7158:   }
                   7159:   if((num_filled=sscanf(line,"ftol=%lf stepm=%d ncovcol=%d nlstate=%d ndeath=%d maxwav=%d mle=%d weight=%d\n", \
                   7160:                        &ftol, &stepm, &ncovcol, &nlstate, &ndeath, &maxwav, &mle, &weightopt)) !=EOF){
                   7161:     if (num_filled != 8) {
1.209     brouard  7162:       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");
                   7163:       printf("but line=%s\n",line);
1.197     brouard  7164:     }
                   7165:     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  7166:   }
1.203     brouard  7167:   /* ftolpl=6*ftol*1.e5; /\* 6.e-3 make convergences in less than 80 loops for the prevalence limit *\/ */
1.209     brouard  7168:   /*ftolpl=6.e-4; *//* 6.e-3 make convergences in less than 80 loops for the prevalence limit */
1.197     brouard  7169:   /* Third parameter line */
                   7170:   while(fgets(line, MAXLINE, ficpar)) {
                   7171:     /* If line starts with a # it is a comment */
                   7172:     if (line[0] == '#') {
                   7173:       numlinepar++;
                   7174:       fputs(line,stdout);
                   7175:       fputs(line,ficparo);
                   7176:       fputs(line,ficlog);
                   7177:       continue;
                   7178:     }else
                   7179:       break;
                   7180:   }
1.201     brouard  7181:   if((num_filled=sscanf(line,"model=1+age%[^.\n]", model)) !=EOF){
                   7182:     if (num_filled == 0)
                   7183:             model[0]='\0';
                   7184:     else if (num_filled != 1){
1.197     brouard  7185:       printf("ERROR %d: Model should be at minimum 'model=1+age.' %s\n",num_filled, line);
                   7186:       fprintf(ficlog,"ERROR %d: Model should be at minimum 'model=1+age.' %s\n",num_filled, line);
                   7187:       model[0]='\0';
                   7188:       goto end;
                   7189:     }
                   7190:     else{
                   7191:       if (model[0]=='+'){
                   7192:        for(i=1; i<=strlen(model);i++)
                   7193:          modeltemp[i-1]=model[i];
1.201     brouard  7194:        strcpy(model,modeltemp); 
1.197     brouard  7195:       }
                   7196:     }
1.199     brouard  7197:     /* printf(" model=1+age%s modeltemp= %s, model=%s\n",model, modeltemp, model);fflush(stdout); */
1.203     brouard  7198:     printf("model=1+age+%s\n",model);fflush(stdout);
1.197     brouard  7199:   }
                   7200:   /* 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); */
                   7201:   /* numlinepar=numlinepar+3; /\* In general *\/ */
                   7202:   /* 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  7203:   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);
                   7204:   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  7205:   fflush(ficlog);
1.190     brouard  7206:   /* if(model[0]=='#'|| model[0]== '\0'){ */
                   7207:   if(model[0]=='#'){
1.187     brouard  7208:     printf("Error in 'model' line: model should start with 'model=1+age+' and end with '.' \n \
                   7209:  'model=1+age+.' or 'model=1+age+V1.' or 'model=1+age+age*age+V1+V1*age.' or \n \
                   7210:  'model=1+age+V1+V2.' or 'model=1+age+V1+V2+V1*V2.' etc. \n");         \
                   7211:     if(mle != -1){
                   7212:       printf("Fix the model line and run imach with mle=-1 to get a correct template of the parameter file.\n");
                   7213:       exit(1);
                   7214:     }
                   7215:   }
1.126     brouard  7216:   while((c=getc(ficpar))=='#' && c!= EOF){
                   7217:     ungetc(c,ficpar);
                   7218:     fgets(line, MAXLINE, ficpar);
                   7219:     numlinepar++;
1.195     brouard  7220:     if(line[1]=='q'){ /* This #q will quit imach (the answer is q) */
                   7221:       z[0]=line[1];
                   7222:     }
                   7223:     /* printf("****line [1] = %c \n",line[1]); */
1.141     brouard  7224:     fputs(line, stdout);
                   7225:     //puts(line);
1.126     brouard  7226:     fputs(line,ficparo);
                   7227:     fputs(line,ficlog);
                   7228:   }
                   7229:   ungetc(c,ficpar);
                   7230: 
                   7231:    
1.145     brouard  7232:   covar=matrix(0,NCOVMAX,1,n);  /**< used in readdata */
1.136     brouard  7233:   cptcovn=0; /*Number of covariates, i.e. number of '+' in model statement plus one, indepently of n in Vn*/
                   7234:   /* v1+v2+v3+v2*v4+v5*age makes cptcovn = 5
                   7235:      v1+v2*age+v2*v3 makes cptcovn = 3
                   7236:   */
                   7237:   if (strlen(model)>1) 
1.187     brouard  7238:     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  7239:   else
1.187     brouard  7240:     ncovmodel=2; /* Constant and age */
1.133     brouard  7241:   nforce= (nlstate+ndeath-1)*nlstate; /* Number of forces ij from state i to j */
                   7242:   npar= nforce*ncovmodel; /* Number of parameters like aij*/
1.131     brouard  7243:   if(npar >MAXPARM || nlstate >NLSTATEMAX || ndeath >NDEATHMAX || ncovmodel>NCOVMAX){
                   7244:     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);
                   7245:     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);
                   7246:     fflush(stdout);
                   7247:     fclose (ficlog);
                   7248:     goto end;
                   7249:   }
1.126     brouard  7250:   delti3= ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel);
                   7251:   delti=delti3[1][1];
                   7252:   /*delti=vector(1,npar); *//* Scale of each paramater (output from hesscov)*/
                   7253:   if(mle==-1){ /* Print a wizard for help writing covariance matrix */
                   7254:     prwizard(ncovmodel, nlstate, ndeath, model, ficparo);
1.191     brouard  7255:     printf(" You chose mle=-1, look at file %s for a template of covariance matrix \n",filereso);
                   7256:     fprintf(ficlog," You chose mle=-1, look at file %s for a template of covariance matrix \n",filereso);
1.126     brouard  7257:     free_ma3x(delti3,1,nlstate,1, nlstate+ndeath-1,1,ncovmodel); 
                   7258:     fclose (ficparo);
                   7259:     fclose (ficlog);
                   7260:     goto end;
                   7261:     exit(0);
                   7262:   }
1.186     brouard  7263:   else if(mle==-3) { /* Main Wizard */
1.126     brouard  7264:     prwizard(ncovmodel, nlstate, ndeath, model, ficparo);
1.192     brouard  7265:     printf(" You chose mle=-3, look at file %s for a template of covariance matrix \n",filereso);
                   7266:     fprintf(ficlog," You chose mle=-3, look at file %s for a template of covariance matrix \n",filereso);
1.126     brouard  7267:     param= ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel);
                   7268:     matcov=matrix(1,npar,1,npar);
1.203     brouard  7269:     hess=matrix(1,npar,1,npar);
1.126     brouard  7270:   }
                   7271:   else{
1.145     brouard  7272:     /* Read guessed parameters */
1.126     brouard  7273:     /* Reads comments: lines beginning with '#' */
                   7274:     while((c=getc(ficpar))=='#' && c!= EOF){
                   7275:       ungetc(c,ficpar);
                   7276:       fgets(line, MAXLINE, ficpar);
                   7277:       numlinepar++;
1.141     brouard  7278:       fputs(line,stdout);
1.126     brouard  7279:       fputs(line,ficparo);
                   7280:       fputs(line,ficlog);
                   7281:     }
                   7282:     ungetc(c,ficpar);
                   7283:     
                   7284:     param= ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel);
                   7285:     for(i=1; i <=nlstate; i++){
                   7286:       j=0;
                   7287:       for(jj=1; jj <=nlstate+ndeath; jj++){
                   7288:        if(jj==i) continue;
                   7289:        j++;
                   7290:        fscanf(ficpar,"%1d%1d",&i1,&j1);
1.193     brouard  7291:        if ((i1 != i) || (j1 != jj)){
1.126     brouard  7292:          printf("Error in line parameters number %d, %1d%1d instead of %1d%1d \n \
                   7293: It might be a problem of design; if ncovcol and the model are correct\n \
                   7294: run imach with mle=-1 to get a correct template of the parameter file.\n",numlinepar, i,j, i1, j1);
                   7295:          exit(1);
                   7296:        }
                   7297:        fprintf(ficparo,"%1d%1d",i1,j1);
                   7298:        if(mle==1)
1.193     brouard  7299:          printf("%1d%1d",i,jj);
                   7300:        fprintf(ficlog,"%1d%1d",i,jj);
1.126     brouard  7301:        for(k=1; k<=ncovmodel;k++){
                   7302:          fscanf(ficpar," %lf",&param[i][j][k]);
                   7303:          if(mle==1){
                   7304:            printf(" %lf",param[i][j][k]);
                   7305:            fprintf(ficlog," %lf",param[i][j][k]);
                   7306:          }
                   7307:          else
                   7308:            fprintf(ficlog," %lf",param[i][j][k]);
                   7309:          fprintf(ficparo," %lf",param[i][j][k]);
                   7310:        }
                   7311:        fscanf(ficpar,"\n");
                   7312:        numlinepar++;
                   7313:        if(mle==1)
                   7314:          printf("\n");
                   7315:        fprintf(ficlog,"\n");
                   7316:        fprintf(ficparo,"\n");
                   7317:       }
                   7318:     }  
                   7319:     fflush(ficlog);
                   7320: 
1.145     brouard  7321:     /* Reads scales values */
1.126     brouard  7322:     p=param[1][1];
                   7323:     
                   7324:     /* Reads comments: lines beginning with '#' */
                   7325:     while((c=getc(ficpar))=='#' && c!= EOF){
                   7326:       ungetc(c,ficpar);
                   7327:       fgets(line, MAXLINE, ficpar);
                   7328:       numlinepar++;
1.141     brouard  7329:       fputs(line,stdout);
1.126     brouard  7330:       fputs(line,ficparo);
                   7331:       fputs(line,ficlog);
                   7332:     }
                   7333:     ungetc(c,ficpar);
                   7334: 
                   7335:     for(i=1; i <=nlstate; i++){
                   7336:       for(j=1; j <=nlstate+ndeath-1; j++){
                   7337:        fscanf(ficpar,"%1d%1d",&i1,&j1);
1.164     brouard  7338:        if ( (i1-i) * (j1-j) != 0){
1.126     brouard  7339:          printf("Error in line parameters number %d, %1d%1d instead of %1d%1d \n",numlinepar, i,j, i1, j1);
                   7340:          exit(1);
                   7341:        }
                   7342:        printf("%1d%1d",i,j);
                   7343:        fprintf(ficparo,"%1d%1d",i1,j1);
                   7344:        fprintf(ficlog,"%1d%1d",i1,j1);
                   7345:        for(k=1; k<=ncovmodel;k++){
                   7346:          fscanf(ficpar,"%le",&delti3[i][j][k]);
                   7347:          printf(" %le",delti3[i][j][k]);
                   7348:          fprintf(ficparo," %le",delti3[i][j][k]);
                   7349:          fprintf(ficlog," %le",delti3[i][j][k]);
                   7350:        }
                   7351:        fscanf(ficpar,"\n");
                   7352:        numlinepar++;
                   7353:        printf("\n");
                   7354:        fprintf(ficparo,"\n");
                   7355:        fprintf(ficlog,"\n");
                   7356:       }
                   7357:     }
                   7358:     fflush(ficlog);
                   7359: 
1.145     brouard  7360:     /* Reads covariance matrix */
1.126     brouard  7361:     delti=delti3[1][1];
                   7362: 
                   7363: 
                   7364:     /* free_ma3x(delti3,1,nlstate,1,nlstate+ndeath-1,1,ncovmodel); */ /* Hasn't to to freed here otherwise delti is no more allocated */
                   7365:   
                   7366:     /* Reads comments: lines beginning with '#' */
                   7367:     while((c=getc(ficpar))=='#' && c!= EOF){
                   7368:       ungetc(c,ficpar);
                   7369:       fgets(line, MAXLINE, ficpar);
                   7370:       numlinepar++;
1.141     brouard  7371:       fputs(line,stdout);
1.126     brouard  7372:       fputs(line,ficparo);
                   7373:       fputs(line,ficlog);
                   7374:     }
                   7375:     ungetc(c,ficpar);
                   7376:   
                   7377:     matcov=matrix(1,npar,1,npar);
1.203     brouard  7378:     hess=matrix(1,npar,1,npar);
1.131     brouard  7379:     for(i=1; i <=npar; i++)
                   7380:       for(j=1; j <=npar; j++) matcov[i][j]=0.;
                   7381:       
1.194     brouard  7382:     /* Scans npar lines */
1.126     brouard  7383:     for(i=1; i <=npar; i++){
1.194     brouard  7384:       count=fscanf(ficpar,"%1d%1d%1d",&i1,&j1,&jk);
                   7385:       if(count != 3){
                   7386:        printf("Error! Error in parameter file %s at line %d after line starting with %1d%1d%1d\n\
                   7387: This is probably because your covariance matrix doesn't \n  contain exactly %d lines corresponding to your model line '1+age+%s'.\n\
                   7388: Please run with mle=-1 to get a correct covariance matrix.\n",optionfile,numlinepar, i1,j1,jk, npar, model);
                   7389:        fprintf(ficlog,"Error! Error in parameter file %s at line %d after line starting with %1d%1d%1d\n\
                   7390: This is probably because your covariance matrix doesn't \n  contain exactly %d lines corresponding to your model line '1+age+%s'.\n\
                   7391: Please run with mle=-1 to get a correct covariance matrix.\n",optionfile,numlinepar, i1,j1,jk, npar, model);
                   7392:        exit(1);
                   7393:       }else
1.126     brouard  7394:       if(mle==1)
1.194     brouard  7395:        printf("%1d%1d%1d",i1,j1,jk);
                   7396:       fprintf(ficlog,"%1d%1d%1d",i1,j1,jk);
                   7397:       fprintf(ficparo,"%1d%1d%1d",i1,j1,jk);
1.126     brouard  7398:       for(j=1; j <=i; j++){
                   7399:        fscanf(ficpar," %le",&matcov[i][j]);
                   7400:        if(mle==1){
                   7401:          printf(" %.5le",matcov[i][j]);
                   7402:        }
                   7403:        fprintf(ficlog," %.5le",matcov[i][j]);
                   7404:        fprintf(ficparo," %.5le",matcov[i][j]);
                   7405:       }
                   7406:       fscanf(ficpar,"\n");
                   7407:       numlinepar++;
                   7408:       if(mle==1)
                   7409:        printf("\n");
                   7410:       fprintf(ficlog,"\n");
                   7411:       fprintf(ficparo,"\n");
                   7412:     }
1.194     brouard  7413:     /* End of read covariance matrix npar lines */
1.126     brouard  7414:     for(i=1; i <=npar; i++)
                   7415:       for(j=i+1;j<=npar;j++)
                   7416:        matcov[i][j]=matcov[j][i];
                   7417:     
                   7418:     if(mle==1)
                   7419:       printf("\n");
                   7420:     fprintf(ficlog,"\n");
                   7421:     
                   7422:     fflush(ficlog);
                   7423:     
                   7424:     /*-------- Rewriting parameter file ----------*/
                   7425:     strcpy(rfileres,"r");    /* "Rparameterfile */
                   7426:     strcat(rfileres,optionfilefiname);    /* Parameter file first name*/
                   7427:     strcat(rfileres,".");    /* */
                   7428:     strcat(rfileres,optionfilext);    /* Other files have txt extension */
                   7429:     if((ficres =fopen(rfileres,"w"))==NULL) {
1.201     brouard  7430:       printf("Problem writing new parameter file: %s\n", rfileres);goto end;
                   7431:       fprintf(ficlog,"Problem writing new parameter file: %s\n", rfileres);goto end;
1.126     brouard  7432:     }
                   7433:     fprintf(ficres,"#%s\n",version);
                   7434:   }    /* End of mle != -3 */
                   7435: 
1.186     brouard  7436:   /*  Main data
                   7437:    */
1.126     brouard  7438:   n= lastobs;
                   7439:   num=lvector(1,n);
                   7440:   moisnais=vector(1,n);
                   7441:   annais=vector(1,n);
                   7442:   moisdc=vector(1,n);
                   7443:   andc=vector(1,n);
                   7444:   agedc=vector(1,n);
                   7445:   cod=ivector(1,n);
                   7446:   weight=vector(1,n);
                   7447:   for(i=1;i<=n;i++) weight[i]=1.0; /* Equal weights, 1 by default */
                   7448:   mint=matrix(1,maxwav,1,n);
                   7449:   anint=matrix(1,maxwav,1,n);
1.131     brouard  7450:   s=imatrix(1,maxwav+1,1,n); /* s[i][j] health state for wave i and individual j */ 
1.126     brouard  7451:   tab=ivector(1,NCOVMAX);
1.144     brouard  7452:   ncodemax=ivector(1,NCOVMAX); /* Number of code per covariate; if O and 1 only, 2**ncov; V1+V2+V3+V4=>16 */
1.192     brouard  7453:   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  7454: 
1.136     brouard  7455:   /* Reads data from file datafile */
                   7456:   if (readdata(datafile, firstobs, lastobs, &imx)==1)
                   7457:     goto end;
                   7458: 
                   7459:   /* Calculation of the number of parameters from char model */
1.137     brouard  7460:     /*    modelsav=V2+V1+V4+age*V3 strb=age*V3 stra=V2+V1+V4 
                   7461:        k=4 (age*V3) Tvar[k=4]= 3 (from V3) Tag[cptcovage=1]=4
                   7462:        k=3 V4 Tvar[k=3]= 4 (from V4)
                   7463:        k=2 V1 Tvar[k=2]= 1 (from V1)
                   7464:        k=1 Tvar[1]=2 (from V2)
                   7465:     */
                   7466:   Tvar=ivector(1,NCOVMAX); /* Was 15 changed to NCOVMAX. */
                   7467:   /*  V2+V1+V4+age*V3 is a model with 4 covariates (3 plus signs). 
                   7468:       For each model-covariate stores the data-covariate id. Tvar[1]=2, Tvar[2]=1, Tvar[3]=4, 
                   7469:       Tvar[4=age*V3] is 3 and 'age' is recorded in Tage.
                   7470:   */
                   7471:   /* For model-covariate k tells which data-covariate to use but
                   7472:     because this model-covariate is a construction we invent a new column
                   7473:     ncovcol + k1
                   7474:     If already ncovcol=4 and model=V2+V1+V1*V4+age*V3
                   7475:     Tvar[3=V1*V4]=4+1 etc */
1.145     brouard  7476:   Tprod=ivector(1,NCOVMAX); /* Gives the position of a product */
1.137     brouard  7477:   /* Tprod[k1=1]=3(=V1*V4) for V2+V1+V1*V4+age*V3
                   7478:      if  V2+V1+V1*V4+age*V3+V3*V2   TProd[k1=2]=5 (V3*V2)
                   7479:   */
1.145     brouard  7480:   Tvaraff=ivector(1,NCOVMAX); /* Unclear */
                   7481:   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  7482:                            * For V3*V2 (in V2+V1+V1*V4+age*V3+V3*V2), V3*V2 position is 2nd. 
                   7483:                            * Tvard[k1=2][1]=3 (V3) Tvard[k1=2][2]=2(V2) */
1.145     brouard  7484:   Tage=ivector(1,NCOVMAX); /* Gives the covariate id of covariates associated with age: V2 + V1 + age*V4 + V3*age
1.137     brouard  7485:                         4 covariates (3 plus signs)
                   7486:                         Tage[1=V3*age]= 4; Tage[2=age*V4] = 3
                   7487:                      */  
1.136     brouard  7488: 
1.186     brouard  7489: /* Main decodemodel */
                   7490: 
1.187     brouard  7491: 
1.136     brouard  7492:   if(decodemodel(model, lastobs) == 1)
                   7493:     goto end;
                   7494: 
1.137     brouard  7495:   if((double)(lastobs-imx)/(double)imx > 1.10){
                   7496:     nbwarn++;
                   7497:     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); 
                   7498:     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); 
                   7499:   }
1.136     brouard  7500:     /*  if(mle==1){*/
1.137     brouard  7501:   if (weightopt != 1) { /* Maximisation without weights. We can have weights different from 1 but want no weight*/
                   7502:     for(i=1;i<=imx;i++) weight[i]=1.0; /* changed to imx */
1.136     brouard  7503:   }
                   7504: 
                   7505:     /*-calculation of age at interview from date of interview and age at death -*/
                   7506:   agev=matrix(1,maxwav,1,imx);
                   7507: 
                   7508:   if(calandcheckages(imx, maxwav, &agemin, &agemax, &nberr, &nbwarn) == 1)
                   7509:     goto end;
                   7510: 
1.126     brouard  7511: 
1.136     brouard  7512:   agegomp=(int)agemin;
                   7513:   free_vector(moisnais,1,n);
                   7514:   free_vector(annais,1,n);
1.126     brouard  7515:   /* free_matrix(mint,1,maxwav,1,n);
                   7516:      free_matrix(anint,1,maxwav,1,n);*/
                   7517:   free_vector(moisdc,1,n);
                   7518:   free_vector(andc,1,n);
1.145     brouard  7519:   /* */
                   7520:   
1.126     brouard  7521:   wav=ivector(1,imx);
                   7522:   dh=imatrix(1,lastpass-firstpass+1,1,imx);
                   7523:   bh=imatrix(1,lastpass-firstpass+1,1,imx);
                   7524:   mw=imatrix(1,lastpass-firstpass+1,1,imx);
                   7525:    
                   7526:   /* Concatenates waves */
                   7527:   concatwav(wav, dh, bh, mw, s, agedc, agev,  firstpass, lastpass, imx, nlstate, stepm);
1.145     brouard  7528:   /* */
                   7529:  
1.126     brouard  7530:   /* Routine tricode is to calculate cptcoveff (real number of unique covariates) and to associate covariable number and modality */
                   7531: 
                   7532:   nbcode=imatrix(0,NCOVMAX,0,NCOVMAX); 
                   7533:   ncodemax[1]=1;
1.145     brouard  7534:   Ndum =ivector(-1,NCOVMAX);  
1.187     brouard  7535:   if (ncovmodel-nagesqr > 2 ) /* That is if covariate other than cst, age and age*age */
1.145     brouard  7536:     tricode(Tvar,nbcode,imx, Ndum); /**< Fills nbcode[Tvar[j]][l]; */
1.211   ! brouard  7537:   /* Nbcode gives the value of the lth modality (currently 1 to 2) of jth covariate, in
1.186     brouard  7538:      V2+V1*age, there are 3 covariates Tvar[2]=1 (V1).*/
1.211   ! brouard  7539:   /* 1 to ncodemax[j] which is the maximum value of this jth covariate */
1.145     brouard  7540: 
1.200     brouard  7541:   /*  codtab=imatrix(1,100,1,10);*/ /* codtab[h,k]=( (h-1) - mod(k-1,2**(k-1) )/2**(k-1) */
1.198     brouard  7542:   /*printf(" codtab[1,1],codtab[100,10]=%d,%d\n", codtab[1][1],codtabm(100,10));*/
1.186     brouard  7543:   /* codtab gives the value 1 or 2 of the hth combination of k covariates (1 or 2).*/
1.211   ! brouard  7544:   /* nbcode[Tvaraff[j]][codtabm(h,j)]) : if there are only 2 modalities for a covariate j, 
        !          7545:    * codtabm(h,j) gives its value classified at position h and nbcode gives how it is coded 
        !          7546:    * (currently 0 or 1) in the data.
        !          7547:    * In a loop on h=1 to 2**k, and a loop on j (=1 to k), we get the value of 
        !          7548:    * corresponding modality (h,j).
        !          7549:    */
        !          7550: 
1.145     brouard  7551:   h=0;
                   7552: 
                   7553: 
                   7554:   /*if (cptcovn > 0) */
1.126     brouard  7555:       
1.145     brouard  7556:  
1.126     brouard  7557:   m=pow(2,cptcoveff);
                   7558:  
1.144     brouard  7559:          /**< codtab(h,k)  k   = codtab[h,k]=( (h-1) - mod(k-1,2**(k-1) )/2**(k-1) + 1
1.211   ! brouard  7560:           * For k=4 covariates, h goes from 1 to m=2**k
        !          7561:           * codtabm(h,k)=  (1 & (h-1) >> (k-1)) + 1;
        !          7562:            * #define codtabm(h,k)  (1 & (h-1) >> (k-1))+1
1.186     brouard  7563:           *     h\k   1     2     3     4
1.143     brouard  7564:           *______________________________  
                   7565:           *     1 i=1 1 i=1 1 i=1 1 i=1 1
                   7566:           *     2     2     1     1     1
                   7567:           *     3 i=2 1     2     1     1
                   7568:           *     4     2     2     1     1
                   7569:           *     5 i=3 1 i=2 1     2     1
                   7570:           *     6     2     1     2     1
                   7571:           *     7 i=4 1     2     2     1
                   7572:           *     8     2     2     2     1
1.197     brouard  7573:           *     9 i=5 1 i=3 1 i=2 1     2
                   7574:           *    10     2     1     1     2
                   7575:           *    11 i=6 1     2     1     2
                   7576:           *    12     2     2     1     2
                   7577:           *    13 i=7 1 i=4 1     2     2    
                   7578:           *    14     2     1     2     2
                   7579:           *    15 i=8 1     2     2     2
                   7580:           *    16     2     2     2     2
1.143     brouard  7581:           */
1.211   ! brouard  7582:   /* How to do the opposite? From combination h (=1 to 2**k) how to get the value on the covariates?
        !          7583:      /* from h=5 and m, we get then number of covariates k=log(m)/log(2)=4
        !          7584:      * and the value of each covariate?
        !          7585:      * V1=1, V2=1, V3=2, V4=1 ?
        !          7586:      * h-1=4 and 4 is 0100 or reverse 0010, and +1 is 1121 ok.
        !          7587:      * h=6, 6-1=5, 5 is 0101, 1010, 2121, V1=2nd, V2=1st, V3=2nd, V4=1st.
        !          7588:      * In order to get the real value in the data, we use nbcode
        !          7589:      * nbcode[Tvar[3][2nd]]=1 and nbcode[Tvar[4][1]]=0
        !          7590:      * We are keeping this crazy system in order to be able (in the future?) 
        !          7591:      * to have more than 2 values (0 or 1) for a covariate.
        !          7592:      * #define codtabm(h,k)  (1 & (h-1) >> (k-1))+1
        !          7593:      * h=6, k=2? h-1=5=0101, reverse 1010, +1=2121, k=2nd position: value is 1: codtabm(6,2)=1
        !          7594:      *              bbbbbbbb
        !          7595:      *              76543210     
        !          7596:      *   h-1        00000101 (6-1=5)
        !          7597:      *(h-1)>>(k-1)= 00000001 >> (2-1) = 1 right shift
        !          7598:      *           &
        !          7599:      *     1        00000001 (1)
        !          7600:      *              00000001        = 1 & ((h-1) >> (k-1))
        !          7601:      *          +1= 00000010 =2 
        !          7602:      *
        !          7603:      * h=14, k=3 => h'=h-1=13, k'=k-1=2
        !          7604:      *          h'      1101 =2^3+2^2+0x2^1+2^0
        !          7605:      *    >>k'            11
        !          7606:      *          &   00000001
        !          7607:      *            = 00000001
        !          7608:      *      +1    = 00000010=2    =  codtabm(14,3)   
        !          7609:      * Reverse h=6 and m=16?
        !          7610:      * cptcoveff=log(16)/log(2)=4 covariate: 6-1=5=0101 reversed=1010 +1=2121 =>V1=2, V2=1, V3=2, V4=1.
        !          7611:      * for (j=1 to cptcoveff) Vj=decodtabm(j,h,cptcoveff)
        !          7612:      * decodtabm(h,j,cptcoveff)= (((h-1) >> (j-1)) & 1) +1 
        !          7613:      * decodtabm(h,j,cptcoveff)= (h <= (1<<cptcoveff)?(((h-1) >> (j-1)) & 1) +1 : -1)
        !          7614:      * V3=decodtabm(14,3,2**4)=2
        !          7615:      *          h'=13   1101 =2^3+2^2+0x2^1+2^0
        !          7616:      *(h-1) >> (j-1)    0011 =13 >> 2
        !          7617:      *          &1 000000001
        !          7618:      *           = 000000001
        !          7619:      *         +1= 000000010 =2
        !          7620:      *                  2211
        !          7621:      *                  V1=1+1, V2=0+1, V3=1+1, V4=1+1
        !          7622:      *                  V3=2
        !          7623:      */
        !          7624: 
1.202     brouard  7625:   /* /\* for(h=1; h <=100 ;h++){  *\/ */
                   7626:   /*   /\* printf("h=%2d ", h); *\/ */
                   7627:   /*    /\* for(k=1; k <=10; k++){ *\/ */
                   7628:   /*      /\* printf("k=%d %d ",k,codtabm(h,k)); *\/ */
                   7629:   /*    /\*   codtab[h][k]=codtabm(h,k); *\/ */
                   7630:   /*    /\* } *\/ */
                   7631:   /*    /\* printf("\n"); *\/ */
                   7632:   /* } */
1.197     brouard  7633:   /* for(k=1;k<=cptcoveff; k++){ /\* scans any effective covariate *\/ */
                   7634:   /*   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 *\/  */
                   7635:   /*     for(j=1; j <= ncodemax[k]; j++){ /\* For each modality of this covariate ncodemax=2*\/ */
                   7636:   /*   for(cpt=1; cpt <=pow(2,k-1); cpt++){  /\* cpt=1 to 8/2**(3+1-1 or 3+1-3) =1 or 4 *\/  */
                   7637:   /*     h++; */
                   7638:   /*     if (h>m)  */
                   7639:   /*       h=1; */
                   7640:   /*     codtab[h][k]=j; */
                   7641:   /*     /\* codtab[12][3]=1; *\/ */
                   7642:   /*     /\*codtab[h][Tvar[k]]=j;*\/ */
                   7643:   /*     /\* 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]]); *\/ */
                   7644:   /*   }  */
                   7645:   /*     } */
                   7646:   /*   } */
                   7647:   /* }  */
1.126     brouard  7648:   /* printf("codtab[1][2]=%d codtab[2][2]=%d",codtab[1][2],codtab[2][2]); 
                   7649:      codtab[1][2]=1;codtab[2][2]=2; */
1.197     brouard  7650:   /* for(i=1; i <=m ;i++){  */
                   7651:   /*    for(k=1; k <=cptcovn; k++){ */
                   7652:   /*      printf("i=%d k=%d %d %d ",i,k,codtab[i][k], cptcoveff); */
                   7653:   /*    } */
                   7654:   /*    printf("\n"); */
                   7655:   /* } */
                   7656:   /*   scanf("%d",i);*/
1.145     brouard  7657: 
                   7658:  free_ivector(Ndum,-1,NCOVMAX);
                   7659: 
                   7660: 
1.126     brouard  7661:     
1.186     brouard  7662:   /* Initialisation of ----------- gnuplot -------------*/
1.126     brouard  7663:   strcpy(optionfilegnuplot,optionfilefiname);
                   7664:   if(mle==-3)
1.201     brouard  7665:     strcat(optionfilegnuplot,"-MORT_");
1.126     brouard  7666:   strcat(optionfilegnuplot,".gp");
                   7667: 
                   7668:   if((ficgp=fopen(optionfilegnuplot,"w"))==NULL) {
                   7669:     printf("Problem with file %s",optionfilegnuplot);
                   7670:   }
                   7671:   else{
1.204     brouard  7672:     fprintf(ficgp,"\n# IMaCh-%s\n", version); 
1.126     brouard  7673:     fprintf(ficgp,"# %s\n", optionfilegnuplot); 
1.141     brouard  7674:     //fprintf(ficgp,"set missing 'NaNq'\n");
                   7675:     fprintf(ficgp,"set datafile missing 'NaNq'\n");
1.126     brouard  7676:   }
                   7677:   /*  fclose(ficgp);*/
1.186     brouard  7678: 
                   7679: 
                   7680:   /* Initialisation of --------- index.htm --------*/
1.126     brouard  7681: 
                   7682:   strcpy(optionfilehtm,optionfilefiname); /* Main html file */
                   7683:   if(mle==-3)
1.201     brouard  7684:     strcat(optionfilehtm,"-MORT_");
1.126     brouard  7685:   strcat(optionfilehtm,".htm");
                   7686:   if((fichtm=fopen(optionfilehtm,"w"))==NULL)    {
1.131     brouard  7687:     printf("Problem with %s \n",optionfilehtm);
                   7688:     exit(0);
1.126     brouard  7689:   }
                   7690: 
                   7691:   strcpy(optionfilehtmcov,optionfilefiname); /* Only for matrix of covariance */
                   7692:   strcat(optionfilehtmcov,"-cov.htm");
                   7693:   if((fichtmcov=fopen(optionfilehtmcov,"w"))==NULL)    {
                   7694:     printf("Problem with %s \n",optionfilehtmcov), exit(0);
                   7695:   }
                   7696:   else{
                   7697:   fprintf(fichtmcov,"<html><head>\n<title>IMaCh Cov %s</title></head>\n <body><font size=\"2\">%s <br> %s</font> \
                   7698: <hr size=\"2\" color=\"#EC5E5E\"> \n\
1.204     brouard  7699: Title=%s <br>Datafile=%s Firstpass=%d Lastpass=%d Stepm=%d Weight=%d Model=1+age+%s<br>\n",\
1.126     brouard  7700:          optionfilehtmcov,version,fullversion,title,datafile,firstpass,lastpass,stepm, weightopt, model);
                   7701:   }
                   7702: 
1.204     brouard  7703:   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>  \
                   7704: <hr size=\"2\" color=\"#EC5E5E\"> \n\
                   7705: <font size=\"2\">IMaCh-%s <br> %s</font> \
1.126     brouard  7706: <hr size=\"2\" color=\"#EC5E5E\"> \n\
1.204     brouard  7707: Title=%s <br>Datafile=%s Firstpass=%d Lastpass=%d Stepm=%d Weight=%d Model=1+age+%s<br>\n\
1.126     brouard  7708: \n\
                   7709: <hr  size=\"2\" color=\"#EC5E5E\">\
                   7710:  <ul><li><h4>Parameter files</h4>\n\
                   7711:  - Parameter file: <a href=\"%s.%s\">%s.%s</a><br>\n\
                   7712:  - Copy of the parameter file: <a href=\"o%s\">o%s</a><br>\n\
                   7713:  - Log file of the run: <a href=\"%s\">%s</a><br>\n\
                   7714:  - Gnuplot file name: <a href=\"%s\">%s</a><br>\n\
                   7715:  - Date and time at start: %s</ul>\n",\
                   7716:          optionfilehtm,version,fullversion,title,datafile,firstpass,lastpass,stepm, weightopt, model,\
                   7717:          optionfilefiname,optionfilext,optionfilefiname,optionfilext,\
                   7718:          fileres,fileres,\
                   7719:          filelog,filelog,optionfilegnuplot,optionfilegnuplot,strstart);
                   7720:   fflush(fichtm);
                   7721: 
                   7722:   strcpy(pathr,path);
                   7723:   strcat(pathr,optionfilefiname);
1.184     brouard  7724: #ifdef WIN32
                   7725:   _chdir(optionfilefiname); /* Move to directory named optionfile */
                   7726: #else
1.126     brouard  7727:   chdir(optionfilefiname); /* Move to directory named optionfile */
1.184     brouard  7728: #endif
                   7729:          
1.126     brouard  7730:   
                   7731:   /* Calculates basic frequencies. Computes observed prevalence at single age
                   7732:      and prints on file fileres'p'. */
                   7733:   freqsummary(fileres, agemin, agemax, s, agev, nlstate, imx,Tvaraff,nbcode, ncodemax,mint,anint,strstart);
                   7734: 
                   7735:   fprintf(fichtm,"\n");
                   7736:   fprintf(fichtm,"<br>Total number of observations=%d <br>\n\
                   7737: Youngest age at first (selected) pass %.2f, oldest age %.2f<br>\n\
                   7738: Interval (in months) between two waves: Min=%d Max=%d Mean=%.2lf<br>\n",\
                   7739:          imx,agemin,agemax,jmin,jmax,jmean);
                   7740:   pmmij= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
                   7741:     oldms= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
                   7742:     newms= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
                   7743:     savms= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
                   7744:     oldm=oldms; newm=newms; savm=savms; /* Keeps fixed addresses to free */
                   7745:     
                   7746:    
                   7747:   /* For Powell, parameters are in a vector p[] starting at p[1]
                   7748:      so we point p on param[1][1] so that p[1] maps on param[1][1][1] */
                   7749:   p=param[1][1]; /* *(*(*(param +1)+1)+0) */
                   7750: 
                   7751:   globpr=0; /* To get the number ipmx of contributions and the sum of weights*/
1.186     brouard  7752:   /* For mortality only */
1.126     brouard  7753:   if (mle==-3){
1.136     brouard  7754:     ximort=matrix(1,NDIM,1,NDIM); 
1.186     brouard  7755:     /*     ximort=gsl_matrix_alloc(1,NDIM,1,NDIM); */
1.126     brouard  7756:     cens=ivector(1,n);
                   7757:     ageexmed=vector(1,n);
                   7758:     agecens=vector(1,n);
                   7759:     dcwave=ivector(1,n);
                   7760:  
                   7761:     for (i=1; i<=imx; i++){
                   7762:       dcwave[i]=-1;
                   7763:       for (m=firstpass; m<=lastpass; m++)
                   7764:        if (s[m][i]>nlstate) {
                   7765:          dcwave[i]=m;
                   7766:          /*    printf("i=%d j=%d s=%d dcwave=%d\n",i,j, s[j][i],dcwave[i]);*/
                   7767:          break;
                   7768:        }
                   7769:     }
                   7770: 
                   7771:     for (i=1; i<=imx; i++) {
                   7772:       if (wav[i]>0){
                   7773:        ageexmed[i]=agev[mw[1][i]][i];
                   7774:        j=wav[i];
                   7775:        agecens[i]=1.; 
                   7776: 
                   7777:        if (ageexmed[i]> 1 && wav[i] > 0){
                   7778:          agecens[i]=agev[mw[j][i]][i];
                   7779:          cens[i]= 1;
                   7780:        }else if (ageexmed[i]< 1) 
                   7781:          cens[i]= -1;
                   7782:        if (agedc[i]< AGESUP && agedc[i]>1 && dcwave[i]>firstpass && dcwave[i]<=lastpass)
                   7783:          cens[i]=0 ;
                   7784:       }
                   7785:       else cens[i]=-1;
                   7786:     }
                   7787:     
                   7788:     for (i=1;i<=NDIM;i++) {
                   7789:       for (j=1;j<=NDIM;j++)
                   7790:        ximort[i][j]=(i == j ? 1.0 : 0.0);
                   7791:     }
                   7792:     
1.145     brouard  7793:     /*p[1]=0.0268; p[NDIM]=0.083;*/
1.126     brouard  7794:     /*printf("%lf %lf", p[1], p[2]);*/
                   7795:     
                   7796:     
1.136     brouard  7797: #ifdef GSL
                   7798:     printf("GSL optimization\n");  fprintf(ficlog,"Powell\n");
1.162     brouard  7799: #else
1.126     brouard  7800:     printf("Powell\n");  fprintf(ficlog,"Powell\n");
1.136     brouard  7801: #endif
1.201     brouard  7802:     strcpy(filerespow,"POW-MORT_"); 
                   7803:     strcat(filerespow,fileresu);
1.126     brouard  7804:     if((ficrespow=fopen(filerespow,"w"))==NULL) {
                   7805:       printf("Problem with resultfile: %s\n", filerespow);
                   7806:       fprintf(ficlog,"Problem with resultfile: %s\n", filerespow);
                   7807:     }
1.136     brouard  7808: #ifdef GSL
                   7809:     fprintf(ficrespow,"# GSL optimization\n# iter -2*LL");
1.162     brouard  7810: #else
1.126     brouard  7811:     fprintf(ficrespow,"# Powell\n# iter -2*LL");
1.136     brouard  7812: #endif
1.126     brouard  7813:     /*  for (i=1;i<=nlstate;i++)
                   7814:        for(j=1;j<=nlstate+ndeath;j++)
                   7815:        if(j!=i)fprintf(ficrespow," p%1d%1d",i,j);
                   7816:     */
                   7817:     fprintf(ficrespow,"\n");
1.136     brouard  7818: #ifdef GSL
                   7819:     /* gsl starts here */ 
                   7820:     T = gsl_multimin_fminimizer_nmsimplex;
                   7821:     gsl_multimin_fminimizer *sfm = NULL;
                   7822:     gsl_vector *ss, *x;
                   7823:     gsl_multimin_function minex_func;
                   7824: 
                   7825:     /* Initial vertex size vector */
                   7826:     ss = gsl_vector_alloc (NDIM);
                   7827:     
                   7828:     if (ss == NULL){
                   7829:       GSL_ERROR_VAL ("failed to allocate space for ss", GSL_ENOMEM, 0);
                   7830:     }
                   7831:     /* Set all step sizes to 1 */
                   7832:     gsl_vector_set_all (ss, 0.001);
                   7833: 
                   7834:     /* Starting point */
1.126     brouard  7835:     
1.136     brouard  7836:     x = gsl_vector_alloc (NDIM);
                   7837:     
                   7838:     if (x == NULL){
                   7839:       gsl_vector_free(ss);
                   7840:       GSL_ERROR_VAL ("failed to allocate space for x", GSL_ENOMEM, 0);
                   7841:     }
                   7842:   
                   7843:     /* Initialize method and iterate */
                   7844:     /*     p[1]=0.0268; p[NDIM]=0.083; */
1.186     brouard  7845:     /*     gsl_vector_set(x, 0, 0.0268); */
                   7846:     /*     gsl_vector_set(x, 1, 0.083); */
1.136     brouard  7847:     gsl_vector_set(x, 0, p[1]);
                   7848:     gsl_vector_set(x, 1, p[2]);
                   7849: 
                   7850:     minex_func.f = &gompertz_f;
                   7851:     minex_func.n = NDIM;
                   7852:     minex_func.params = (void *)&p; /* ??? */
                   7853:     
                   7854:     sfm = gsl_multimin_fminimizer_alloc (T, NDIM);
                   7855:     gsl_multimin_fminimizer_set (sfm, &minex_func, x, ss);
                   7856:     
                   7857:     printf("Iterations beginning .....\n\n");
                   7858:     printf("Iter. #    Intercept       Slope     -Log Likelihood     Simplex size\n");
                   7859: 
                   7860:     iteri=0;
                   7861:     while (rval == GSL_CONTINUE){
                   7862:       iteri++;
                   7863:       status = gsl_multimin_fminimizer_iterate(sfm);
                   7864:       
                   7865:       if (status) printf("error: %s\n", gsl_strerror (status));
                   7866:       fflush(0);
                   7867:       
                   7868:       if (status) 
                   7869:         break;
                   7870:       
                   7871:       rval = gsl_multimin_test_size (gsl_multimin_fminimizer_size (sfm), 1e-6);
                   7872:       ssval = gsl_multimin_fminimizer_size (sfm);
                   7873:       
                   7874:       if (rval == GSL_SUCCESS)
                   7875:         printf ("converged to a local maximum at\n");
                   7876:       
                   7877:       printf("%5d ", iteri);
                   7878:       for (it = 0; it < NDIM; it++){
                   7879:        printf ("%10.5f ", gsl_vector_get (sfm->x, it));
                   7880:       }
                   7881:       printf("f() = %-10.5f ssize = %.7f\n", sfm->fval, ssval);
                   7882:     }
                   7883:     
                   7884:     printf("\n\n Please note: Program should be run many times with varying starting points to detemine global maximum\n\n");
                   7885:     
                   7886:     gsl_vector_free(x); /* initial values */
                   7887:     gsl_vector_free(ss); /* inital step size */
                   7888:     for (it=0; it<NDIM; it++){
                   7889:       p[it+1]=gsl_vector_get(sfm->x,it);
                   7890:       fprintf(ficrespow," %.12lf", p[it]);
                   7891:     }
                   7892:     gsl_multimin_fminimizer_free (sfm); /* p *(sfm.x.data) et p *(sfm.x.data+1)  */
                   7893: #endif
                   7894: #ifdef POWELL
                   7895:      powell(p,ximort,NDIM,ftol,&iter,&fret,gompertz);
                   7896: #endif  
1.126     brouard  7897:     fclose(ficrespow);
                   7898:     
1.203     brouard  7899:     hesscov(matcov, hess, p, NDIM, delti, 1e-4, gompertz); 
1.126     brouard  7900: 
                   7901:     for(i=1; i <=NDIM; i++)
                   7902:       for(j=i+1;j<=NDIM;j++)
                   7903:        matcov[i][j]=matcov[j][i];
                   7904:     
                   7905:     printf("\nCovariance matrix\n ");
1.203     brouard  7906:     fprintf(ficlog,"\nCovariance matrix\n ");
1.126     brouard  7907:     for(i=1; i <=NDIM; i++) {
                   7908:       for(j=1;j<=NDIM;j++){ 
                   7909:        printf("%f ",matcov[i][j]);
1.203     brouard  7910:        fprintf(ficlog,"%f ",matcov[i][j]);
1.126     brouard  7911:       }
1.203     brouard  7912:       printf("\n ");  fprintf(ficlog,"\n ");
1.126     brouard  7913:     }
                   7914:     
                   7915:     printf("iter=%d MLE=%f Eq=%lf*exp(%lf*(age-%d))\n",iter,-gompertz(p),p[1],p[2],agegomp);
1.193     brouard  7916:     for (i=1;i<=NDIM;i++) {
1.126     brouard  7917:       printf("%f [%f ; %f]\n",p[i],p[i]-2*sqrt(matcov[i][i]),p[i]+2*sqrt(matcov[i][i]));
1.193     brouard  7918:       fprintf(ficlog,"%f [%f ; %f]\n",p[i],p[i]-2*sqrt(matcov[i][i]),p[i]+2*sqrt(matcov[i][i]));
                   7919:     }
1.126     brouard  7920:     lsurv=vector(1,AGESUP);
                   7921:     lpop=vector(1,AGESUP);
                   7922:     tpop=vector(1,AGESUP);
                   7923:     lsurv[agegomp]=100000;
                   7924:     
                   7925:     for (k=agegomp;k<=AGESUP;k++) {
                   7926:       agemortsup=k;
                   7927:       if (p[1]*exp(p[2]*(k-agegomp))>1) break;
                   7928:     }
                   7929:     
                   7930:     for (k=agegomp;k<agemortsup;k++)
                   7931:       lsurv[k+1]=lsurv[k]-lsurv[k]*(p[1]*exp(p[2]*(k-agegomp)));
                   7932:     
                   7933:     for (k=agegomp;k<agemortsup;k++){
                   7934:       lpop[k]=(lsurv[k]+lsurv[k+1])/2.;
                   7935:       sumlpop=sumlpop+lpop[k];
                   7936:     }
                   7937:     
                   7938:     tpop[agegomp]=sumlpop;
                   7939:     for (k=agegomp;k<(agemortsup-3);k++){
                   7940:       /*  tpop[k+1]=2;*/
                   7941:       tpop[k+1]=tpop[k]-lpop[k];
                   7942:     }
                   7943:     
                   7944:     
                   7945:     printf("\nAge   lx     qx    dx    Lx     Tx     e(x)\n");
                   7946:     for (k=agegomp;k<(agemortsup-2);k++) 
                   7947:       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]);
                   7948:     
                   7949:     
                   7950:     replace_back_to_slash(pathc,pathcd); /* Even gnuplot wants a / */
1.194     brouard  7951:     if(ageminpar == AGEOVERFLOW ||agemaxpar == AGEOVERFLOW){
                   7952:        printf("Warning! Error in gnuplot file with ageminpar %f or agemaxpar %f overflow\n\
                   7953: This is probably because your parameter file doesn't \n  contain the exact number of lines (or columns) corresponding to your model line.\n\
                   7954: Please run with mle=-1 to get a correct covariance matrix.\n",ageminpar,agemaxpar);
                   7955:        fprintf(ficlog,"Warning! Error in gnuplot file with ageminpar %f or agemaxpar %f overflow\n\
                   7956: This is probably because your parameter file doesn't \n  contain the exact number of lines (or columns) corresponding to your model line.\n\
                   7957: Please run with mle=-1 to get a correct covariance matrix.\n",ageminpar,agemaxpar);
                   7958:     }else
1.201     brouard  7959:       printinggnuplotmort(fileresu, optionfilefiname,ageminpar,agemaxpar,fage, pathc,p);
                   7960:     printinghtmlmort(fileresu,title,datafile, firstpass, lastpass, \
1.126     brouard  7961:                     stepm, weightopt,\
                   7962:                     model,imx,p,matcov,agemortsup);
                   7963:     
                   7964:     free_vector(lsurv,1,AGESUP);
                   7965:     free_vector(lpop,1,AGESUP);
                   7966:     free_vector(tpop,1,AGESUP);
1.136     brouard  7967: #ifdef GSL
                   7968:     free_ivector(cens,1,n);
                   7969:     free_vector(agecens,1,n);
                   7970:     free_ivector(dcwave,1,n);
                   7971:     free_matrix(ximort,1,NDIM,1,NDIM);
                   7972: #endif
1.186     brouard  7973:   } /* Endof if mle==-3 mortality only */
1.205     brouard  7974:   /* Standard  */
                   7975:   else{ /* For mle !=- 3, could be 0 or 1 or 4 etc. */
                   7976:     globpr=0;/* Computes sum of likelihood for globpr=1 and funcone */
                   7977:     /* Computes likelihood for initial parameters, uses funcone to compute gpimx and gsw */
1.132     brouard  7978:     likelione(ficres, p, npar, nlstate, &globpr, &ipmx, &sw, &fretone, funcone); /* Prints the contributions to the likelihood */
1.126     brouard  7979:     printf("First Likeli=%12.6f ipmx=%ld sw=%12.6f",fretone,ipmx,sw);
                   7980:     for (k=1; k<=npar;k++)
                   7981:       printf(" %d %8.5f",k,p[k]);
                   7982:     printf("\n");
1.205     brouard  7983:     if(mle>=1){ /* Could be 1 or 2, Real Maximization */
                   7984:       /* mlikeli uses func not funcone */
                   7985:       mlikeli(ficres,p, npar, ncovmodel, nlstate, ftol, func);
                   7986:     }
                   7987:     if(mle==0) {/* No optimization, will print the likelihoods for the datafile */
                   7988:       globpr=0;/* Computes sum of likelihood for globpr=1 and funcone */
                   7989:       /* Computes likelihood for initial parameters, uses funcone to compute gpimx and gsw */
                   7990:       likelione(ficres, p, npar, nlstate, &globpr, &ipmx, &sw, &fretone, funcone); /* Prints the contributions to the likelihood */
                   7991:     }
                   7992:     globpr=1; /* again, to print the individual contributions using computed gpimx and gsw */
1.126     brouard  7993:     likelione(ficres, p, npar, nlstate, &globpr, &ipmx, &sw, &fretone, funcone); /* Prints the contributions to the likelihood */
                   7994:     printf("Second Likeli=%12.6f ipmx=%ld sw=%12.6f",fretone,ipmx,sw);
                   7995:     for (k=1; k<=npar;k++)
                   7996:       printf(" %d %8.5f",k,p[k]);
                   7997:     printf("\n");
                   7998:     
                   7999:     /*--------- results files --------------*/
1.192     brouard  8000:     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  8001:     
                   8002:     
                   8003:     fprintf(ficres,"# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
                   8004:     printf("# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
                   8005:     fprintf(ficlog,"# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
                   8006:     for(i=1,jk=1; i <=nlstate; i++){
                   8007:       for(k=1; k <=(nlstate+ndeath); k++){
                   8008:        if (k != i) {
                   8009:          printf("%d%d ",i,k);
                   8010:          fprintf(ficlog,"%d%d ",i,k);
                   8011:          fprintf(ficres,"%1d%1d ",i,k);
                   8012:          for(j=1; j <=ncovmodel; j++){
1.190     brouard  8013:            printf("%12.7f ",p[jk]);
                   8014:            fprintf(ficlog,"%12.7f ",p[jk]);
                   8015:            fprintf(ficres,"%12.7f ",p[jk]);
1.126     brouard  8016:            jk++; 
                   8017:          }
                   8018:          printf("\n");
                   8019:          fprintf(ficlog,"\n");
                   8020:          fprintf(ficres,"\n");
                   8021:        }
                   8022:       }
                   8023:     }
1.203     brouard  8024:     if(mle != 0){
                   8025:       /* Computing hessian and covariance matrix only at a peak of the Likelihood, that is after optimization */
1.126     brouard  8026:       ftolhess=ftol; /* Usually correct */
1.203     brouard  8027:       hesscov(matcov, hess, p, npar, delti, ftolhess, func);
                   8028:       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");
                   8029:       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");
                   8030:       for(i=1,jk=1; i <=nlstate; i++){
                   8031:        for(k=1; k <=(nlstate+ndeath); k++){
                   8032:          if (k != i) {
                   8033:            printf("%d%d ",i,k);
                   8034:            fprintf(ficlog,"%d%d ",i,k);
                   8035:            for(j=1; j <=ncovmodel; j++){
                   8036:              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]));
                   8037:              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]));
                   8038:              jk++; 
                   8039:            }
                   8040:            printf("\n");
                   8041:            fprintf(ficlog,"\n");
1.193     brouard  8042:          }
                   8043:        }
                   8044:       }
1.203     brouard  8045:     } /* end of hesscov and Wald tests */
1.193     brouard  8046: 
1.203     brouard  8047:     /*  */
1.126     brouard  8048:     fprintf(ficres,"# Scales (for hessian or gradient estimation)\n");
                   8049:     printf("# Scales (for hessian or gradient estimation)\n");
                   8050:     fprintf(ficlog,"# Scales (for hessian or gradient estimation)\n");
                   8051:     for(i=1,jk=1; i <=nlstate; i++){
                   8052:       for(j=1; j <=nlstate+ndeath; j++){
                   8053:        if (j!=i) {
                   8054:          fprintf(ficres,"%1d%1d",i,j);
                   8055:          printf("%1d%1d",i,j);
                   8056:          fprintf(ficlog,"%1d%1d",i,j);
                   8057:          for(k=1; k<=ncovmodel;k++){
                   8058:            printf(" %.5e",delti[jk]);
                   8059:            fprintf(ficlog," %.5e",delti[jk]);
                   8060:            fprintf(ficres," %.5e",delti[jk]);
                   8061:            jk++;
                   8062:          }
                   8063:          printf("\n");
                   8064:          fprintf(ficlog,"\n");
                   8065:          fprintf(ficres,"\n");
                   8066:        }
                   8067:       }
                   8068:     }
                   8069:     
                   8070:     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  8071:     if(mle >= 1) /* To big for the screen */
1.126     brouard  8072:       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");
                   8073:     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");
                   8074:     /* # 121 Var(a12)\n\ */
                   8075:     /* # 122 Cov(b12,a12) Var(b12)\n\ */
                   8076:     /* # 131 Cov(a13,a12) Cov(a13,b12, Var(a13)\n\ */
                   8077:     /* # 132 Cov(b13,a12) Cov(b13,b12, Cov(b13,a13) Var(b13)\n\ */
                   8078:     /* # 212 Cov(a21,a12) Cov(a21,b12, Cov(a21,a13) Cov(a21,b13) Var(a21)\n\ */
                   8079:     /* # 212 Cov(b21,a12) Cov(b21,b12, Cov(b21,a13) Cov(b21,b13) Cov(b21,a21) Var(b21)\n\ */
                   8080:     /* # 232 Cov(a23,a12) Cov(a23,b12, Cov(a23,a13) Cov(a23,b13) Cov(a23,a21) Cov(a23,b21) Var(a23)\n\ */
                   8081:     /* # 232 Cov(b23,a12) Cov(b23,b12) ... Var (b23)\n" */
                   8082:     
                   8083:     
                   8084:     /* Just to have a covariance matrix which will be more understandable
                   8085:        even is we still don't want to manage dictionary of variables
                   8086:     */
                   8087:     for(itimes=1;itimes<=2;itimes++){
                   8088:       jj=0;
                   8089:       for(i=1; i <=nlstate; i++){
                   8090:        for(j=1; j <=nlstate+ndeath; j++){
                   8091:          if(j==i) continue;
                   8092:          for(k=1; k<=ncovmodel;k++){
                   8093:            jj++;
                   8094:            ca[0]= k+'a'-1;ca[1]='\0';
                   8095:            if(itimes==1){
                   8096:              if(mle>=1)
                   8097:                printf("#%1d%1d%d",i,j,k);
                   8098:              fprintf(ficlog,"#%1d%1d%d",i,j,k);
                   8099:              fprintf(ficres,"#%1d%1d%d",i,j,k);
                   8100:            }else{
                   8101:              if(mle>=1)
                   8102:                printf("%1d%1d%d",i,j,k);
                   8103:              fprintf(ficlog,"%1d%1d%d",i,j,k);
                   8104:              fprintf(ficres,"%1d%1d%d",i,j,k);
                   8105:            }
                   8106:            ll=0;
                   8107:            for(li=1;li <=nlstate; li++){
                   8108:              for(lj=1;lj <=nlstate+ndeath; lj++){
                   8109:                if(lj==li) continue;
                   8110:                for(lk=1;lk<=ncovmodel;lk++){
                   8111:                  ll++;
                   8112:                  if(ll<=jj){
                   8113:                    cb[0]= lk +'a'-1;cb[1]='\0';
                   8114:                    if(ll<jj){
                   8115:                      if(itimes==1){
                   8116:                        if(mle>=1)
                   8117:                          printf(" Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
                   8118:                        fprintf(ficlog," Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
                   8119:                        fprintf(ficres," Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
                   8120:                      }else{
                   8121:                        if(mle>=1)
                   8122:                          printf(" %.5e",matcov[jj][ll]); 
                   8123:                        fprintf(ficlog," %.5e",matcov[jj][ll]); 
                   8124:                        fprintf(ficres," %.5e",matcov[jj][ll]); 
                   8125:                      }
                   8126:                    }else{
                   8127:                      if(itimes==1){
                   8128:                        if(mle>=1)
                   8129:                          printf(" Var(%s%1d%1d)",ca,i,j);
                   8130:                        fprintf(ficlog," Var(%s%1d%1d)",ca,i,j);
                   8131:                        fprintf(ficres," Var(%s%1d%1d)",ca,i,j);
                   8132:                      }else{
                   8133:                        if(mle>=1)
1.203     brouard  8134:                          printf(" %.7e",matcov[jj][ll]); 
                   8135:                        fprintf(ficlog," %.7e",matcov[jj][ll]); 
                   8136:                        fprintf(ficres," %.7e",matcov[jj][ll]); 
1.126     brouard  8137:                      }
                   8138:                    }
                   8139:                  }
                   8140:                } /* end lk */
                   8141:              } /* end lj */
                   8142:            } /* end li */
                   8143:            if(mle>=1)
                   8144:              printf("\n");
                   8145:            fprintf(ficlog,"\n");
                   8146:            fprintf(ficres,"\n");
                   8147:            numlinepar++;
                   8148:          } /* end k*/
                   8149:        } /*end j */
                   8150:       } /* end i */
                   8151:     } /* end itimes */
                   8152:     
                   8153:     fflush(ficlog);
                   8154:     fflush(ficres);
1.209     brouard  8155:       while(fgets(line, MAXLINE, ficpar)) {
                   8156:     /* If line starts with a # it is a comment */
                   8157:     if (line[0] == '#') {
                   8158:       numlinepar++;
1.141     brouard  8159:       fputs(line,stdout);
1.126     brouard  8160:       fputs(line,ficparo);
1.209     brouard  8161:       fputs(line,ficlog);
                   8162:       continue;
                   8163:     }else
                   8164:       break;
                   8165:   }
                   8166: 
                   8167:     /* while((c=getc(ficpar))=='#' && c!= EOF){ */
                   8168:     /*   ungetc(c,ficpar); */
                   8169:     /*   fgets(line, MAXLINE, ficpar); */
                   8170:     /*   fputs(line,stdout); */
                   8171:     /*   fputs(line,ficparo); */
                   8172:     /* } */
                   8173:     /* ungetc(c,ficpar); */
1.126     brouard  8174:     
                   8175:     estepm=0;
1.209     brouard  8176:     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){
                   8177: 
                   8178:     if (num_filled != 6) {
                   8179:       printf("Not 6 parameters in line, for example:agemin=60 agemax=95 bage=55 fage=95 estepm=24 ftolpl=6e-4\n");
                   8180:       printf("but line=%s\n",line);
                   8181:       goto end;
                   8182:     }
                   8183:     printf("agemin=%lf agemax=%lf bage=%lf fage=%lf estepm=%d ftolpl=%lf\n",ageminpar,agemaxpar, bage, fage, estepm, ftolpl);
                   8184:   }
                   8185:   /* ftolpl=6*ftol*1.e5; /\* 6.e-3 make convergences in less than 80 loops for the prevalence limit *\/ */
                   8186:   /*ftolpl=6.e-4;*/ /* 6.e-3 make convergences in less than 80 loops for the prevalence limit */
                   8187: 
                   8188:     /* fscanf(ficpar,"agemin=%lf agemax=%lf bage=%lf fage=%lf estepm=%d ftolpl=%\n",&ageminpar,&agemaxpar, &bage, &fage, &estepm); */
1.126     brouard  8189:     if (estepm==0 || estepm < stepm) estepm=stepm;
                   8190:     if (fage <= 2) {
                   8191:       bage = ageminpar;
                   8192:       fage = agemaxpar;
                   8193:     }
                   8194:     
                   8195:     fprintf(ficres,"# agemin agemax for life expectancy, bage fage (if mle==0 ie no data nor Max likelihood).\n");
1.211   ! brouard  8196:     fprintf(ficres,"agemin=%.0f agemax=%.0f bage=%.0f fage=%.0f estepm=%d ftolpl=%e\n",ageminpar,agemaxpar,bage,fage, estepm, ftolpl);
        !          8197:     fprintf(ficparo,"agemin=%.0f agemax=%.0f bage=%.0f fage=%.0f estepm=%d, ftolpl=%e\n",ageminpar,agemaxpar,bage,fage, estepm, ftolpl);
1.186     brouard  8198: 
                   8199:     /* Other stuffs, more or less useful */    
1.126     brouard  8200:     while((c=getc(ficpar))=='#' && c!= EOF){
                   8201:       ungetc(c,ficpar);
                   8202:       fgets(line, MAXLINE, ficpar);
1.141     brouard  8203:       fputs(line,stdout);
1.126     brouard  8204:       fputs(line,ficparo);
                   8205:     }
                   8206:     ungetc(c,ficpar);
                   8207:     
                   8208:     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);
                   8209:     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);
                   8210:     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);
                   8211:     printf("begin-prev-date=%.lf/%.lf/%.lf end-prev-date=%.lf/%.lf/%.lf mov_average=%d\n",jprev1, mprev1,anprev1,jprev2, mprev2,anprev2,mobilav);
                   8212:     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);
                   8213:     
                   8214:     while((c=getc(ficpar))=='#' && c!= EOF){
                   8215:       ungetc(c,ficpar);
                   8216:       fgets(line, MAXLINE, ficpar);
1.141     brouard  8217:       fputs(line,stdout);
1.126     brouard  8218:       fputs(line,ficparo);
                   8219:     }
                   8220:     ungetc(c,ficpar);
                   8221:     
                   8222:     
                   8223:     dateprev1=anprev1+(mprev1-1)/12.+(jprev1-1)/365.;
                   8224:     dateprev2=anprev2+(mprev2-1)/12.+(jprev2-1)/365.;
                   8225:     
                   8226:     fscanf(ficpar,"pop_based=%d\n",&popbased);
1.193     brouard  8227:     fprintf(ficlog,"pop_based=%d\n",popbased);
1.126     brouard  8228:     fprintf(ficparo,"pop_based=%d\n",popbased);   
                   8229:     fprintf(ficres,"pop_based=%d\n",popbased);   
                   8230:     
                   8231:     while((c=getc(ficpar))=='#' && c!= EOF){
                   8232:       ungetc(c,ficpar);
                   8233:       fgets(line, MAXLINE, ficpar);
1.141     brouard  8234:       fputs(line,stdout);
1.126     brouard  8235:       fputs(line,ficparo);
                   8236:     }
                   8237:     ungetc(c,ficpar);
                   8238:     
                   8239:     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);
                   8240:     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);
                   8241:     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);
                   8242:     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);
                   8243:     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);
                   8244:     /* day and month of proj2 are not used but only year anproj2.*/
                   8245:     
                   8246:     
                   8247:     
1.145     brouard  8248:      /* freqsummary(fileres, agemin, agemax, s, agev, nlstate, imx,Tvaraff,nbcode, ncodemax,mint,anint); */
                   8249:     /* ,dateprev1,dateprev2,jprev1, mprev1,anprev1,jprev2, mprev2,anprev2); */
1.126     brouard  8250:     
                   8251:     replace_back_to_slash(pathc,pathcd); /* Even gnuplot wants a / */
1.194     brouard  8252:     if(ageminpar == AGEOVERFLOW ||agemaxpar == -AGEOVERFLOW){
                   8253:        printf("Warning! Error in gnuplot file with ageminpar %f or agemaxpar %f overflow\n\
                   8254: This is probably because your parameter file doesn't \n  contain the exact number of lines (or columns) corresponding to your model line.\n\
                   8255: Please run with mle=-1 to get a correct covariance matrix.\n",ageminpar,agemaxpar);
                   8256:        fprintf(ficlog,"Warning! Error in gnuplot file with ageminpar %f or agemaxpar %f overflow\n\
                   8257: This is probably because your parameter file doesn't \n  contain the exact number of lines (or columns) corresponding to your model line.\n\
                   8258: Please run with mle=-1 to get a correct covariance matrix.\n",ageminpar,agemaxpar);
                   8259:     }else
1.211   ! brouard  8260:       printinggnuplot(fileresu, optionfilefiname,ageminpar,agemaxpar,fage, prevfcast, pathc,p);
1.126     brouard  8261:     
1.201     brouard  8262:     printinghtml(fileresu,title,datafile, firstpass, lastpass, stepm, weightopt,\
1.211   ! brouard  8263:                 model,imx,jmin,jmax,jmean,rfileres,popforecast,prevfcast,estepm, \
1.126     brouard  8264:                 jprev1,mprev1,anprev1,jprev2,mprev2,anprev2);
                   8265:       
                   8266:    /*------------ free_vector  -------------*/
                   8267:    /*  chdir(path); */
                   8268:  
                   8269:     free_ivector(wav,1,imx);
                   8270:     free_imatrix(dh,1,lastpass-firstpass+1,1,imx);
                   8271:     free_imatrix(bh,1,lastpass-firstpass+1,1,imx);
                   8272:     free_imatrix(mw,1,lastpass-firstpass+1,1,imx);   
                   8273:     free_lvector(num,1,n);
                   8274:     free_vector(agedc,1,n);
                   8275:     /*free_matrix(covar,0,NCOVMAX,1,n);*/
                   8276:     /*free_matrix(covar,1,NCOVMAX,1,n);*/
                   8277:     fclose(ficparo);
                   8278:     fclose(ficres);
                   8279: 
                   8280: 
1.186     brouard  8281:     /* Other results (useful)*/
                   8282: 
                   8283: 
1.126     brouard  8284:     /*--------------- Prevalence limit  (period or stable prevalence) --------------*/
1.180     brouard  8285:     /*#include "prevlim.h"*/  /* Use ficrespl, ficlog */
                   8286:     prlim=matrix(1,nlstate,1,nlstate);
1.209     brouard  8287:     prevalence_limit(p, prlim,  ageminpar, agemaxpar, ftolpl, &ncvyear);
1.126     brouard  8288:     fclose(ficrespl);
                   8289: 
1.145     brouard  8290: #ifdef FREEEXIT2
                   8291: #include "freeexit2.h"
                   8292: #endif
                   8293: 
1.126     brouard  8294:     /*------------- h Pij x at various ages ------------*/
1.180     brouard  8295:     /*#include "hpijx.h"*/
                   8296:     hPijx(p, bage, fage);
1.145     brouard  8297:     fclose(ficrespij);
1.126     brouard  8298: 
1.145     brouard  8299:   /*-------------- Variance of one-step probabilities---*/
                   8300:     k=1;
1.126     brouard  8301:     varprob(optionfilefiname, matcov, p, delti, nlstate, bage, fage,k,Tvar,nbcode, ncodemax,strstart);
                   8302: 
                   8303: 
                   8304:     probs= ma3x(1,AGESUP,1,NCOVMAX, 1,NCOVMAX);
                   8305:     for(i=1;i<=AGESUP;i++)
                   8306:       for(j=1;j<=NCOVMAX;j++)
                   8307:        for(k=1;k<=NCOVMAX;k++)
                   8308:          probs[i][j][k]=0.;
                   8309: 
                   8310:     /*---------- Forecasting ------------------*/
                   8311:     /*if((stepm == 1) && (strcmp(model,".")==0)){*/
                   8312:     if(prevfcast==1){
                   8313:       /*    if(stepm ==1){*/
1.201     brouard  8314:       prevforecast(fileresu, anproj1, mproj1, jproj1, agemin, agemax, dateprev1, dateprev2, mobilavproj, bage, fage, firstpass, lastpass, anproj2, p, cptcoveff);
1.126     brouard  8315:       /* (popforecast==1) populforecast(fileres, anpyram,mpyram,jpyram, agemin,agemax, dateprev1, dateprev2,mobilav, agedeb, fage, popforecast, popfile, anpyram1,p, i1);*/
                   8316:       /*      }  */
                   8317:       /*      else{ */
                   8318:       /*        erreur=108; */
                   8319:       /*        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); */
                   8320:       /*        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); */
                   8321:       /*      } */
                   8322:     }
1.186     brouard  8323:  
                   8324:     /* ------ Other prevalence ratios------------ */
1.126     brouard  8325: 
1.127     brouard  8326:     /* Computes prevalence between agemin (i.e minimal age computed) and no more ageminpar */
                   8327: 
                   8328:     prevalence(probs, agemin, agemax, s, agev, nlstate, imx, Tvar, nbcode, ncodemax, mint, anint, dateprev1, dateprev2, firstpass, lastpass);
                   8329:     /*  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",\
                   8330:        ageminpar, agemax, s[lastpass][imx], agev[lastpass][imx], nlstate, imx, mint[lastpass][imx],anint[lastpass][imx], dateprev1, dateprev2, firstpass, lastpass);
                   8331:     */
1.126     brouard  8332: 
1.127     brouard  8333:     if (mobilav!=0) {
                   8334:       mobaverage= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
                   8335:       if (movingaverage(probs, bage, fage, mobaverage,mobilav)!=0){
                   8336:        fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav);
                   8337:        printf(" Error in movingaverage mobilav=%d\n",mobilav);
                   8338:       }
1.126     brouard  8339:     }
                   8340: 
                   8341: 
1.127     brouard  8342:     /*---------- Health expectancies, no variances ------------*/
                   8343: 
1.201     brouard  8344:     strcpy(filerese,"E_");
                   8345:     strcat(filerese,fileresu);
1.126     brouard  8346:     if((ficreseij=fopen(filerese,"w"))==NULL) {
                   8347:       printf("Problem with Health Exp. resultfile: %s\n", filerese); exit(0);
                   8348:       fprintf(ficlog,"Problem with Health Exp. resultfile: %s\n", filerese); exit(0);
                   8349:     }
1.208     brouard  8350:     printf("Computing Health Expectancies: result on file '%s' ...", filerese);fflush(stdout);
                   8351:     fprintf(ficlog,"Computing Health Expectancies: result on file '%s' ...", filerese);fflush(ficlog);
1.145     brouard  8352:     /*for(cptcov=1,k=0;cptcov<=i1;cptcov++){
                   8353:       for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){*/
                   8354:           
                   8355:     for (k=1; k <= (int) pow(2,cptcoveff); k++){
1.127     brouard  8356:        fprintf(ficreseij,"\n#****** ");
                   8357:        for(j=1;j<=cptcoveff;j++) {
1.200     brouard  8358:          fprintf(ficreseij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
1.127     brouard  8359:        }
                   8360:        fprintf(ficreseij,"******\n");
                   8361: 
                   8362:        eij=ma3x(1,nlstate,1,nlstate,(int) bage, (int) fage);
                   8363:        oldm=oldms;savm=savms;
                   8364:        evsij(eij, p, nlstate, stepm, (int) bage, (int)fage, oldm, savm, k, estepm, strstart);  
                   8365:       
                   8366:        free_ma3x(eij,1,nlstate,1,nlstate,(int) bage, (int)fage);
1.145     brouard  8367:       /*}*/
1.127     brouard  8368:     }
                   8369:     fclose(ficreseij);
1.208     brouard  8370:     printf("done evsij\n");fflush(stdout);
                   8371:     fprintf(ficlog,"done evsij\n");fflush(ficlog);
1.127     brouard  8372: 
                   8373:     /*---------- Health expectancies and variances ------------*/
                   8374: 
                   8375: 
1.201     brouard  8376:     strcpy(filerest,"T_");
                   8377:     strcat(filerest,fileresu);
1.127     brouard  8378:     if((ficrest=fopen(filerest,"w"))==NULL) {
                   8379:       printf("Problem with total LE resultfile: %s\n", filerest);goto end;
                   8380:       fprintf(ficlog,"Problem with total LE resultfile: %s\n", filerest);goto end;
                   8381:     }
1.208     brouard  8382:     printf("Computing Total Life expectancies with their standard errors: file '%s' ...\n", filerest); fflush(stdout);
                   8383:     fprintf(ficlog,"Computing Total Life expectancies with their standard errors: file '%s' ...\n", filerest); fflush(ficlog);
1.127     brouard  8384: 
1.126     brouard  8385: 
1.201     brouard  8386:     strcpy(fileresstde,"STDE_");
                   8387:     strcat(fileresstde,fileresu);
1.126     brouard  8388:     if((ficresstdeij=fopen(fileresstde,"w"))==NULL) {
                   8389:       printf("Problem with Health Exp. and std errors resultfile: %s\n", fileresstde); exit(0);
                   8390:       fprintf(ficlog,"Problem with Health Exp. and std errors resultfile: %s\n", fileresstde); exit(0);
                   8391:     }
1.208     brouard  8392:     printf("  Computing Health Expectancies and standard errors: result on file '%s' \n", fileresstde);
                   8393:     fprintf(ficlog,"  Computing Health Expectancies and standard errors: result on file '%s' \n", fileresstde);
1.126     brouard  8394: 
1.201     brouard  8395:     strcpy(filerescve,"CVE_");
                   8396:     strcat(filerescve,fileresu);
1.126     brouard  8397:     if((ficrescveij=fopen(filerescve,"w"))==NULL) {
                   8398:       printf("Problem with Covar. Health Exp. resultfile: %s\n", filerescve); exit(0);
                   8399:       fprintf(ficlog,"Problem with Covar. Health Exp. resultfile: %s\n", filerescve); exit(0);
                   8400:     }
1.208     brouard  8401:     printf("    Computing Covar. of Health Expectancies: result on file '%s' \n", filerescve);
                   8402:     fprintf(ficlog,"    Computing Covar. of Health Expectancies: result on file '%s' \n", filerescve);
1.126     brouard  8403: 
1.201     brouard  8404:     strcpy(fileresv,"V_");
                   8405:     strcat(fileresv,fileresu);
1.126     brouard  8406:     if((ficresvij=fopen(fileresv,"w"))==NULL) {
                   8407:       printf("Problem with variance resultfile: %s\n", fileresv);exit(0);
                   8408:       fprintf(ficlog,"Problem with variance resultfile: %s\n", fileresv);exit(0);
                   8409:     }
1.208     brouard  8410:     printf("      Computing Variance-covariance of DFLEs: file '%s' ... ", fileresv);fflush(stdout);
                   8411:     fprintf(ficlog,"      Computing Variance-covariance of DFLEs: file '%s' ... ", fileresv);fflush(ficlog);
1.126     brouard  8412: 
1.145     brouard  8413:     /*for(cptcov=1,k=0;cptcov<=i1;cptcov++){
                   8414:       for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){*/
                   8415:           
                   8416:     for (k=1; k <= (int) pow(2,cptcoveff); k++){
1.208     brouard  8417:       fprintf(ficrest,"\n#****** ");
                   8418:       for(j=1;j<=cptcoveff;j++) 
                   8419:        fprintf(ficrest,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
                   8420:       fprintf(ficrest,"******\n");
                   8421:       
                   8422:       fprintf(ficresstdeij,"\n#****** ");
                   8423:       fprintf(ficrescveij,"\n#****** ");
                   8424:       for(j=1;j<=cptcoveff;j++) {
                   8425:        fprintf(ficresstdeij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
                   8426:        fprintf(ficrescveij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
                   8427:       }
                   8428:       fprintf(ficresstdeij,"******\n");
                   8429:       fprintf(ficrescveij,"******\n");
                   8430:       
                   8431:       fprintf(ficresvij,"\n#****** ");
                   8432:       for(j=1;j<=cptcoveff;j++) 
                   8433:        fprintf(ficresvij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
                   8434:       fprintf(ficresvij,"******\n");
                   8435:       
                   8436:       eij=ma3x(1,nlstate,1,nlstate,(int) bage, (int) fage);
                   8437:       oldm=oldms;savm=savms;
                   8438:       printf(" cvevsij %d, ",k);
                   8439:       fprintf(ficlog, " cvevsij %d, ",k);
                   8440:       cvevsij(eij, p, nlstate, stepm, (int) bage, (int)fage, oldm, savm, k, estepm, delti, matcov, strstart);
                   8441:       printf(" end cvevsij \n ");
                   8442:       fprintf(ficlog, " end cvevsij \n ");
                   8443:       
                   8444:       /*
                   8445:        */
                   8446:       /* goto endfree; */
                   8447:       
                   8448:       vareij=ma3x(1,nlstate,1,nlstate,(int) bage, (int) fage);
                   8449:       pstamp(ficrest);
                   8450:       
                   8451:       
                   8452:       for(vpopbased=0; vpopbased <= popbased; vpopbased++){ /* Done for vpopbased=0 and vpopbased=1 if popbased==1*/
                   8453:        oldm=oldms;savm=savms; /* ZZ Segmentation fault */
                   8454:        cptcod= 0; /* To be deleted */
                   8455:        printf("varevsij %d \n",vpopbased);
                   8456:        fprintf(ficlog, "varevsij %d \n",vpopbased);
1.209     brouard  8457:        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  8458:        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 ");
                   8459:        if(vpopbased==1)
                   8460:          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);
                   8461:        else
                   8462:          fprintf(ficrest,"the age specific period (stable) prevalences in each health state \n");
                   8463:        fprintf(ficrest,"# Age popbased mobilav e.. (std) ");
                   8464:        for (i=1;i<=nlstate;i++) fprintf(ficrest,"e.%d (std) ",i);
                   8465:        fprintf(ficrest,"\n");
                   8466:        /* printf("Which p?\n"); for(i=1;i<=npar;i++)printf("p[i=%d]=%lf,",i,p[i]);printf("\n"); */
                   8467:        epj=vector(1,nlstate+1);
                   8468:        printf("Computing age specific period (stable) prevalences in each health state \n");
                   8469:        fprintf(ficlog,"Computing age specific period (stable) prevalences in each health state \n");
                   8470:        for(age=bage; age <=fage ;age++){
1.209     brouard  8471:          prevalim(prlim, nlstate, p, age, oldm, savm, ftolpl, &ncvyear, k); /*ZZ Is it the correct prevalim */
1.208     brouard  8472:          if (vpopbased==1) {
                   8473:            if(mobilav ==0){
                   8474:              for(i=1; i<=nlstate;i++)
                   8475:                prlim[i][i]=probs[(int)age][i][k];
                   8476:            }else{ /* mobilav */ 
                   8477:              for(i=1; i<=nlstate;i++)
                   8478:                prlim[i][i]=mobaverage[(int)age][i][k];
1.126     brouard  8479:            }
1.208     brouard  8480:          }
                   8481:          
                   8482:          fprintf(ficrest," %4.0f %d %d",age, vpopbased, mobilav);
                   8483:          /* fprintf(ficrest," %4.0f %d %d %d %d",age, vpopbased, mobilav,Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]); */ /* to be done */
                   8484:          /* printf(" age %4.0f ",age); */
                   8485:          for(j=1, epj[nlstate+1]=0.;j <=nlstate;j++){
                   8486:            for(i=1, epj[j]=0.;i <=nlstate;i++) {
                   8487:              epj[j] += prlim[i][i]*eij[i][j][(int)age];
                   8488:              /*ZZZ  printf("%lf %lf ", prlim[i][i] ,eij[i][j][(int)age]);*/
                   8489:              /* printf("%lf %lf ", prlim[i][i] ,eij[i][j][(int)age]); */
1.126     brouard  8490:            }
1.208     brouard  8491:            epj[nlstate+1] +=epj[j];
                   8492:          }
                   8493:          /* printf(" age %4.0f \n",age); */
                   8494:          
                   8495:          for(i=1, vepp=0.;i <=nlstate;i++)
                   8496:            for(j=1;j <=nlstate;j++)
                   8497:              vepp += vareij[i][j][(int)age];
                   8498:          fprintf(ficrest," %7.3f (%7.3f)", epj[nlstate+1],sqrt(vepp));
                   8499:          for(j=1;j <=nlstate;j++){
                   8500:            fprintf(ficrest," %7.3f (%7.3f)", epj[j],sqrt(vareij[j][j][(int)age]));
1.126     brouard  8501:          }
1.208     brouard  8502:          fprintf(ficrest,"\n");
1.126     brouard  8503:        }
1.208     brouard  8504:       } /* End vpopbased */
                   8505:       free_ma3x(eij,1,nlstate,1,nlstate,(int) bage, (int)fage);
                   8506:       free_ma3x(vareij,1,nlstate,1,nlstate,(int) bage, (int)fage);
                   8507:       free_vector(epj,1,nlstate+1);
                   8508:       printf("done \n");fflush(stdout);
                   8509:       fprintf(ficlog,"done\n");fflush(ficlog);
                   8510:       
1.145     brouard  8511:       /*}*/
1.208     brouard  8512:     } /* End k */
1.126     brouard  8513:     free_vector(weight,1,n);
1.145     brouard  8514:     free_imatrix(Tvard,1,NCOVMAX,1,2);
1.126     brouard  8515:     free_imatrix(s,1,maxwav+1,1,n);
                   8516:     free_matrix(anint,1,maxwav,1,n); 
                   8517:     free_matrix(mint,1,maxwav,1,n);
                   8518:     free_ivector(cod,1,n);
                   8519:     free_ivector(tab,1,NCOVMAX);
                   8520:     fclose(ficresstdeij);
                   8521:     fclose(ficrescveij);
                   8522:     fclose(ficresvij);
                   8523:     fclose(ficrest);
1.208     brouard  8524:     printf("done Health expectancies\n");fflush(stdout);
                   8525:     fprintf(ficlog,"done Health expectancies\n");fflush(ficlog);
1.126     brouard  8526:     fclose(ficpar);
                   8527:   
                   8528:     /*------- Variance of period (stable) prevalence------*/   
                   8529: 
1.201     brouard  8530:     strcpy(fileresvpl,"VPL_");
                   8531:     strcat(fileresvpl,fileresu);
1.126     brouard  8532:     if((ficresvpl=fopen(fileresvpl,"w"))==NULL) {
                   8533:       printf("Problem with variance of period (stable) prevalence  resultfile: %s\n", fileresvpl);
                   8534:       exit(0);
                   8535:     }
1.208     brouard  8536:     printf("Computing Variance-covariance of period (stable) prevalence: file '%s' ...", fileresvpl);fflush(stdout);
                   8537:     fprintf(ficlog, "Computing Variance-covariance of period (stable) prevalence: file '%s' ...", fileresvpl);fflush(ficlog);
1.126     brouard  8538: 
1.145     brouard  8539:     /*for(cptcov=1,k=0;cptcov<=i1;cptcov++){
                   8540:       for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){*/
                   8541:           
                   8542:     for (k=1; k <= (int) pow(2,cptcoveff); k++){
                   8543:        fprintf(ficresvpl,"\n#****** ");
1.126     brouard  8544:        for(j=1;j<=cptcoveff;j++) 
1.200     brouard  8545:          fprintf(ficresvpl,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
1.126     brouard  8546:        fprintf(ficresvpl,"******\n");
                   8547:       
                   8548:        varpl=matrix(1,nlstate,(int) bage, (int) fage);
                   8549:        oldm=oldms;savm=savms;
1.209     brouard  8550:        varprevlim(fileres, varpl, matcov, p, delti, nlstate, stepm, (int) bage, (int) fage, oldm, savm, prlim, ftolpl, &ncvyear, k, strstart);
1.126     brouard  8551:        free_matrix(varpl,1,nlstate,(int) bage, (int)fage);
1.145     brouard  8552:       /*}*/
1.126     brouard  8553:     }
                   8554: 
                   8555:     fclose(ficresvpl);
1.208     brouard  8556:     printf("done variance-covariance of period prevalence\n");fflush(stdout);
                   8557:     fprintf(ficlog,"done variance-covariance of period prevalence\n");fflush(ficlog);
1.126     brouard  8558: 
                   8559:     /*---------- End : free ----------------*/
                   8560:     if (mobilav!=0) free_ma3x(mobaverage,1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
                   8561:     free_ma3x(probs,1,AGESUP,1,NCOVMAX, 1,NCOVMAX);
                   8562:   }  /* mle==-3 arrives here for freeing */
1.164     brouard  8563:  /* endfree:*/
1.141     brouard  8564:     free_matrix(prlim,1,nlstate,1,nlstate); /*here or after loop ? */
1.126     brouard  8565:     free_matrix(pmmij,1,nlstate+ndeath,1,nlstate+ndeath);
                   8566:     free_matrix(oldms, 1,nlstate+ndeath,1,nlstate+ndeath);
                   8567:     free_matrix(newms, 1,nlstate+ndeath,1,nlstate+ndeath);
                   8568:     free_matrix(savms, 1,nlstate+ndeath,1,nlstate+ndeath);
                   8569:     free_matrix(covar,0,NCOVMAX,1,n);
                   8570:     free_matrix(matcov,1,npar,1,npar);
1.203     brouard  8571:     free_matrix(hess,1,npar,1,npar);
1.126     brouard  8572:     /*free_vector(delti,1,npar);*/
                   8573:     free_ma3x(delti3,1,nlstate,1, nlstate+ndeath-1,1,ncovmodel); 
                   8574:     free_matrix(agev,1,maxwav,1,imx);
                   8575:     free_ma3x(param,1,nlstate,1, nlstate+ndeath-1,1,ncovmodel);
                   8576: 
1.145     brouard  8577:     free_ivector(ncodemax,1,NCOVMAX);
1.192     brouard  8578:     free_ivector(ncodemaxwundef,1,NCOVMAX);
1.145     brouard  8579:     free_ivector(Tvar,1,NCOVMAX);
                   8580:     free_ivector(Tprod,1,NCOVMAX);
                   8581:     free_ivector(Tvaraff,1,NCOVMAX);
                   8582:     free_ivector(Tage,1,NCOVMAX);
1.126     brouard  8583: 
                   8584:     free_imatrix(nbcode,0,NCOVMAX,0,NCOVMAX);
1.200     brouard  8585:     /* free_imatrix(codtab,1,100,1,10); */
1.126     brouard  8586:   fflush(fichtm);
                   8587:   fflush(ficgp);
                   8588:   
                   8589: 
                   8590:   if((nberr >0) || (nbwarn>0)){
                   8591:     printf("End of Imach with %d errors and/or %d warnings\n",nberr,nbwarn);
                   8592:     fprintf(ficlog,"End of Imach with %d errors and/or warnings %d\n",nberr,nbwarn);
                   8593:   }else{
                   8594:     printf("End of Imach\n");
                   8595:     fprintf(ficlog,"End of Imach\n");
                   8596:   }
                   8597:   printf("See log file on %s\n",filelog);
                   8598:   /*  gettimeofday(&end_time, (struct timezone*)0);*/  /* after time */
1.157     brouard  8599:   /*(void) gettimeofday(&end_time,&tzp);*/
                   8600:   rend_time = time(NULL);  
                   8601:   end_time = *localtime(&rend_time);
                   8602:   /* tml = *localtime(&end_time.tm_sec); */
                   8603:   strcpy(strtend,asctime(&end_time));
1.126     brouard  8604:   printf("Local time at start %s\nLocal time at end   %s",strstart, strtend); 
                   8605:   fprintf(ficlog,"Local time at start %s\nLocal time at end   %s\n",strstart, strtend); 
1.157     brouard  8606:   printf("Total time used %s\n", asc_diff_time(rend_time -rstart_time,tmpout));
1.126     brouard  8607: 
1.157     brouard  8608:   printf("Total time was %.0lf Sec.\n", difftime(rend_time,rstart_time));
                   8609:   fprintf(ficlog,"Total time used %s\n", asc_diff_time(rend_time -rstart_time,tmpout));
                   8610:   fprintf(ficlog,"Total time was %.0lf Sec.\n", difftime(rend_time,rstart_time));
1.126     brouard  8611:   /*  printf("Total time was %d uSec.\n", total_usecs);*/
                   8612: /*   if(fileappend(fichtm,optionfilehtm)){ */
                   8613:   fprintf(fichtm,"<br>Local time at start %s<br>Local time at end   %s<br>\n</body></html>",strstart, strtend);
                   8614:   fclose(fichtm);
                   8615:   fprintf(fichtmcov,"<br>Local time at start %s<br>Local time at end   %s<br>\n</body></html>",strstart, strtend);
                   8616:   fclose(fichtmcov);
                   8617:   fclose(ficgp);
                   8618:   fclose(ficlog);
                   8619:   /*------ End -----------*/
                   8620: 
                   8621: 
                   8622:    printf("Before Current directory %s!\n",pathcd);
1.184     brouard  8623: #ifdef WIN32
                   8624:    if (_chdir(pathcd) != 0)
                   8625:           printf("Can't move to directory %s!\n",path);
                   8626:    if(_getcwd(pathcd,MAXLINE) > 0)
                   8627: #else
1.126     brouard  8628:    if(chdir(pathcd) != 0)
1.184     brouard  8629:           printf("Can't move to directory %s!\n", path);
                   8630:    if (getcwd(pathcd, MAXLINE) > 0)
                   8631: #endif 
1.126     brouard  8632:     printf("Current directory %s!\n",pathcd);
                   8633:   /*strcat(plotcmd,CHARSEPARATOR);*/
                   8634:   sprintf(plotcmd,"gnuplot");
1.157     brouard  8635: #ifdef _WIN32
1.126     brouard  8636:   sprintf(plotcmd,"\"%sgnuplot.exe\"",pathimach);
                   8637: #endif
                   8638:   if(!stat(plotcmd,&info)){
1.158     brouard  8639:     printf("Error or gnuplot program not found: '%s'\n",plotcmd);fflush(stdout);
1.126     brouard  8640:     if(!stat(getenv("GNUPLOTBIN"),&info)){
1.158     brouard  8641:       printf("Error or gnuplot program not found: '%s' Environment GNUPLOTBIN not set.\n",plotcmd);fflush(stdout);
1.126     brouard  8642:     }else
                   8643:       strcpy(pplotcmd,plotcmd);
1.157     brouard  8644: #ifdef __unix
1.126     brouard  8645:     strcpy(plotcmd,GNUPLOTPROGRAM);
                   8646:     if(!stat(plotcmd,&info)){
1.158     brouard  8647:       printf("Error gnuplot program not found: '%s'\n",plotcmd);fflush(stdout);
1.126     brouard  8648:     }else
                   8649:       strcpy(pplotcmd,plotcmd);
                   8650: #endif
                   8651:   }else
                   8652:     strcpy(pplotcmd,plotcmd);
                   8653:   
                   8654:   sprintf(plotcmd,"%s %s",pplotcmd, optionfilegnuplot);
1.158     brouard  8655:   printf("Starting graphs with: '%s'\n",plotcmd);fflush(stdout);
1.126     brouard  8656: 
                   8657:   if((outcmd=system(plotcmd)) != 0){
1.158     brouard  8658:     printf("gnuplot command might not be in your path: '%s', err=%d\n", plotcmd, outcmd);
1.154     brouard  8659:     printf("\n Trying if gnuplot resides on the same directory that IMaCh\n");
1.152     brouard  8660:     sprintf(plotcmd,"%sgnuplot %s", pathimach, optionfilegnuplot);
1.150     brouard  8661:     if((outcmd=system(plotcmd)) != 0)
1.153     brouard  8662:       printf("\n Still a problem with gnuplot command %s, err=%d\n", plotcmd, outcmd);
1.126     brouard  8663:   }
1.158     brouard  8664:   printf(" Successful, please wait...");
1.126     brouard  8665:   while (z[0] != 'q') {
                   8666:     /* chdir(path); */
1.154     brouard  8667:     printf("\nType e to edit results with your browser, g to graph again and q for exit: ");
1.126     brouard  8668:     scanf("%s",z);
                   8669: /*     if (z[0] == 'c') system("./imach"); */
                   8670:     if (z[0] == 'e') {
1.158     brouard  8671: #ifdef __APPLE__
1.152     brouard  8672:       sprintf(pplotcmd, "open %s", optionfilehtm);
1.157     brouard  8673: #elif __linux
                   8674:       sprintf(pplotcmd, "xdg-open %s", optionfilehtm);
1.153     brouard  8675: #else
1.152     brouard  8676:       sprintf(pplotcmd, "%s", optionfilehtm);
1.153     brouard  8677: #endif
                   8678:       printf("Starting browser with: %s",pplotcmd);fflush(stdout);
                   8679:       system(pplotcmd);
1.126     brouard  8680:     }
                   8681:     else if (z[0] == 'g') system(plotcmd);
                   8682:     else if (z[0] == 'q') exit(0);
                   8683:   }
                   8684:   end:
                   8685:   while (z[0] != 'q') {
1.195     brouard  8686:     printf("\nType  q for exiting: "); fflush(stdout);
1.126     brouard  8687:     scanf("%s",z);
                   8688:   }
                   8689: }

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